diff --git a/docs/src/content/docs/connect/models.mdx b/docs/src/content/docs/connect/models.mdx index c308b79fd..bf04f0320 100644 --- a/docs/src/content/docs/connect/models.mdx +++ b/docs/src/content/docs/connect/models.mdx @@ -69,7 +69,7 @@ If a model request stops your task, the failure message links to **Settings > Mo Nod checks your selected model with a tiny request when you choose it, including choosing it again, and when you start Nod. While a model's last request failed, **Settings > Models** shows the provider's reason beside its connection and chat shows it above the message box, before you send anything. -After a model fails a request, automatic work stops using that model on that connection. This includes background checks, background helpers and cache warming, and recurring schedules skip their runs. A one-time schedule still runs and reports the failure. Errors Nod retries on its own, such as an overload, and a conversation too long for the model's context don't count. Nod tries automatic work again after 2 minutes, and each further failure waits longer: 6, 18, 54 and 162 minutes, then 6 hours at most. A request that succeeds clears that model's failure. When a failing model works again, the connection's other paused models try again too. Requests you start always go through, and so does work that continues after you approve, sign in, pay, hand back the browser or connect an app. The failure survives a restart, and other connections stay available. +After a model fails a request, automatic work stops using that model on that connection. This includes background checks, background helpers and cache warming, and recurring schedules skip their runs. A one-time schedule still runs and reports the failure. Errors Nod retries on its own, such as an overload, and a conversation too long for the model's context don't count. Nod tries automatic work again after 2 minutes, and each further failure waits longer: 6, 18, 54 and 162 minutes, then 6 hours at most. A request that succeeds clears that model's failure. When a failing model works again, the connection's other paused models try again too. Requests you start always go through, and so does work that continues after you approve, sign in, pay, hand back the browser or connect an app. The failure survives a restart, and other connections stay available. With [backup models](#backup-models), an automatic turn starts on the first backup that isn't paused instead. A recurring schedule then skips its run only when its model is paused and its connection needs attention, or no connected backup that can stand in is unpaused. The exception is a key or sign-in the service rejects with HTTP 401, for example because it expired or was revoked. The connection then shows **Needs attention** and Nod stops sending requests through it, including yours. If it's your selected connection, chat asks you to reconnect. Add the key again or reconnect in **Manage**. A connection set in the server settings doesn't show **Needs attention**: change its key there and [apply the change](/deploy/configuration/#apply-configuration-changes). @@ -277,10 +277,20 @@ You can also tell Nod, for example "Run my schedules on the light model" or "Use A change applies from the next turn; work that's already running keeps its model until then. Checking what Nod may do, writing the questions it asks you and reading your answers always use your model. If a model you chose for some work is no longer available, that work fails with the reason instead of switching models, and **Settings > Models** shows it as unavailable so you can choose another. Removing a connection returns the work that used it to its default: the model for its kind of work, else your model. An audio model's **Text support** label names its companion from the same connection. Requests without recordings use that companion; follow-ups that still include recordings use the audio model. Both use the smaller context and output limits of the pair. Your saved model choice stays unchanged. -If a model request fails, Nod doesn't switch to another connection on its own; the notice above the chat box offers one when you have it. Nod retries a temporary provider error up to three times, waiting 4, 8 and 16 seconds. Temporary errors include an overload, a rate limit, and, for hosted providers, a request that gets no response within 90 seconds of being sent, cache warming included. Requests to a model server you run have no such limit, because local models can take minutes to start answering. +Without [backup models](#backup-models), a failed model request doesn't move to another connection; the notice above the chat box offers one when you have it. Nod retries a temporary provider error up to three times, waiting 4, 8 and 16 seconds, or once when you have backups. Temporary errors include an overload, a rate limit, and, for hosted providers, a request that gets no response within 90 seconds of being sent, cache warming included. Requests to a model server you run have no such limit, because local models can take minutes to start answering. Background work, such as memory upkeep, uses a smaller model from the same connection when it has one, such as `gpt-6-luna` or `claude-haiku-5-5`. Otherwise it uses your model or, for an audio model, its text companion. The short line about your request in the app's chat status line uses only that smaller model. Without one, or without a known price for it, Nod skips the line. Background work and checks use the lightest reasoning their model offers: off, minimal, low or medium in that order, or the model's first effort level if it offers none of these. +## Backup models + +Chat, tasks, schedules and work Nod starts on its own can continue on up to three backup models when their model can't answer. In **Settings > Models**, the sentence **If it's busy or unavailable, Nod tries …** lists them. Select a backup to replace it or choose **No backup** to remove it, and select **Add a backup model** to add one. The list starts empty, and Nod never adds a backup on its own, so your conversations only reach providers you chose. + +When a request fails before the model starts answering, it continues on the next backup. An error Nod retries on its own, such as an overload, a rate limit or a timeout, moves on after one retry. An error the provider returns before it starts answering, such as a used-up quota or an invalid request, moves on at once. A refusal from the model and a conversation too long for your model, which Nod compacts as usual, don't move, and your **Stop** ends the turn. A backup that can't read the conversation's images or hold all of it is skipped, and so is a paused one in automatic work. When your model's connection needs attention, for example after a rejected key, Nod asks you to fix it rather than switching. + +The rest of the turn, including its helpers, continues on the backup, and the next turn starts on your model again. The status line names the backup that took over, such as "Gemini 3.8 Flash failed, so this used GPT-6 Luna". Usage shows each attempt with the model that ran and its cost, and backups count toward the same check-in and monthly limit. A backup billed through a plan counts at its API price estimate. When every model fails, the error names each one and the provider's reason. Audio requests that include a recording stay on the audio model. Recalling memory for your message uses the same backups and moves on after one failed request. Checks, such as the action checker, and other memory upkeep keep their own model. + +A backup that is the model a kind of work already uses is skipped for that work. **Settings > Models** marks a backup that is your chat model; it can still stand in for schedules or work Nod starts on its own when they use another model. + ## Models with a small context window For a context window below 65,536 tokens, Nod uses short instructions and loads one detailed tool at a time. The `apps` tool for connected apps and the `send_message` tool for delivering results stay available; MCP server tools load when needed. It reads guides, saved memory and older messages when needed. Large tool results stay in workspace files, with a short preview in the conversation. diff --git a/docs/src/content/docs/how-it-works/agent-runtime.md b/docs/src/content/docs/how-it-works/agent-runtime.md index 372d6ff89..7554eb7eb 100644 --- a/docs/src/content/docs/how-it-works/agent-runtime.md +++ b/docs/src/content/docs/how-it-works/agent-runtime.md @@ -292,7 +292,7 @@ Nod keeps two things apart: Live status covers work you started, including chat requests, tasks, replies, and work that continues after you answer or approve something. Scheduled runs show their live activity on their cards in **Scheduled**. Email event checks stay quiet, and a task Nod starts on its own shows its line on its card only. The turn state and tool events determine whether Nod is working. The model can supply an activity description. -Nod derives live activity from the current work. For longer work and activity changes, a brief description arrives with a tool call, without a separate status action or model request. Quick replies and simple actions need no description. The description excludes internal tool names, reasoning, generic busy text, private details and completion claims. Nod does not start helpers to write activity descriptions. Its only separate model request for live status is the request line described below. Text the model writes before a tool call becomes the step when that call starts streaming, not after the call's arguments finish. When the model streams a reasoning summary whose block starts with a bold heading, the runtime records that heading as a `thought` event, and the line shows the newest step or thought; thoughts never appear in a task's activity list. When Pi retries a failed model request, the runtime records a `retry` event that names the model and the attempt, such as "Gemini 3.8 Flash failed, trying again (1 of 3)". The line shows it until any later event of that turn. Without either, a task's card falls back to the task's saved progress. When a running tool has a label but no description, the line says **Using** followed by that label. The label can name a website, connected app, MCP server, or local files; examples include **Using Gmail**, **Using Slack**, and **Using local files**. A known tool without such a label shows a fixed description of its kind of work, such as **Running code**, **Running a command**, **Reading files**, **Searching the web** or **Working with helpers**. A web search with a query shows **Searching** and its first query in quotes instead, and a page read shows **Reading** and its site. With a description, the label follows it after a dot. Other tools keep the rotating word. While the model works and nothing has happened for a minute, the line says **Waiting for** and the selected model's name. Otherwise it shows a rotating word, such as **Joining the dots…**, or the request line in its place. Screen readers hear **Working…**. A task's card shows **Working…** while its turn waits to start; the chat's line shows the rotating word from the moment you send. The chat's line follows only the chat session's turn, apart from owner messages that go to a task, described below. Each task's card shows its own. After a quiet minute it adds how long nothing has happened. A description written before the owner's newest message stops counting once Nod reads that message. You can still stop active work from the composer. The status is computed in [`src/server/activity.ts`](https://github.com/n8n-io/nod/blob/main/src/server/activity.ts), and the runtime records steps in [`src/runtime/index.ts`](https://github.com/n8n-io/nod/blob/main/src/runtime/index.ts). +Nod derives live activity from the current work. For longer work and activity changes, a brief description arrives with a tool call, without a separate status action or model request. Quick replies and simple actions need no description. The description excludes internal tool names, reasoning, generic busy text, private details and completion claims. Nod does not start helpers to write activity descriptions. Its only separate model request for live status is the request line described below. Text the model writes before a tool call becomes the step when that call starts streaming, not after the call's arguments finish. When the model streams a reasoning summary whose block starts with a bold heading, the runtime records that heading as a `thought` event, and the line shows the newest step or thought; thoughts never appear in a task's activity list. When Pi retries a failed model request, the runtime records a `retry` event that names the model and the attempt, such as "Gemini 3.8 Flash failed, trying again (1 of 3)". When a [backup model](/connect/models/#backup-models) takes over, it records one more, such as "Gemini 3.8 Flash failed, so this used GPT-6 Luna". The line shows it until any later event of that turn. Without either, a task's card falls back to the task's saved progress. When a running tool has a label but no description, the line says **Using** followed by that label. The label can name a website, connected app, MCP server, or local files; examples include **Using Gmail**, **Using Slack**, and **Using local files**. A known tool without such a label shows a fixed description of its kind of work, such as **Running code**, **Running a command**, **Reading files**, **Searching the web** or **Working with helpers**. A web search with a query shows **Searching** and its first query in quotes instead, and a page read shows **Reading** and its site. With a description, the label follows it after a dot. Other tools keep the rotating word. While the model works and nothing has happened for a minute, the line says **Waiting for** and the selected model's name. Otherwise it shows a rotating word, such as **Joining the dots…**, or the request line in its place. Screen readers hear **Working…**. A task's card shows **Working…** while its turn waits to start; the chat's line shows the rotating word from the moment you send. The chat's line follows only the chat session's turn, apart from owner messages that go to a task, described below. Each task's card shows its own. After a quiet minute it adds how long nothing has happened. A description written before the owner's newest message stops counting once Nod reads that message. You can still stop active work from the composer. The status is computed in [`src/server/activity.ts`](https://github.com/n8n-io/nod/blob/main/src/server/activity.ts), and the runtime records steps in [`src/runtime/index.ts`](https://github.com/n8n-io/nod/blob/main/src/runtime/index.ts). The request line fills the time before Nod names its own step. About a second after an owner message to the main chat in Nod web or desktop, a small model writes one short line about the request, such as "Checking the weather in Brno". It is the selected connection's small model, the same one task classification uses. A message that the chat's running turn takes in while it works gets its own line the same way, about a second after Nod picks it up. For an answer to Nod's question, it also gets that question as context. The line takes the rotating word's place until Nod's own step, a reasoning heading or a retry replaces it, and an active tool's label shows beside it meanwhile. It is never posted as a message, never reaches the main model and never claims a result. Messages to a task, confirmation replies, and schedule, event and proactive work get none, and neither do Telegram and WhatsApp. Nod skips it past the monthly limit, when the small model has no known price, or when no small model is set up. Each line is one small model request, recorded in Usage and model analytics like other auxiliary requests. It is not included in conversation traces. diff --git a/docs/src/content/docs/how-it-works/memory.md b/docs/src/content/docs/how-it-works/memory.md index 3eadfc0c5..d208a0d85 100644 --- a/docs/src/content/docs/how-it-works/memory.md +++ b/docs/src/content/docs/how-it-works/memory.md @@ -64,7 +64,7 @@ flowchart TD rank --> answer[Pi answers, streaming as it writes]:::go ``` -The memory model selects existing notes. It can connect an indirect question to a preference or possession. It expands search terms with related concepts and source names, then ranks the returned messages. The server accepts only note paths and message IDs from the supplied records. Model-written facts do not enter this evidence packet or memory. +The memory model selects existing notes. It can connect an indirect question to a preference or possession. It expands search terms with related concepts and source names, then ranks the returned messages. The server accepts only note paths and message IDs from the supplied records. Model-written facts do not enter this evidence packet or memory. When the memory model fails a request and you have [backup models](/connect/models/#backup-models), this selection moves to the next one. For this selection, Nod sends at most 4,000 characters of the current request and 1,200 characters from each of up to six recent owner messages to the memory model. Long messages keep their beginning and end with an omission marker between them. Full messages remain available through conversation search when the task needs their contents. diff --git a/docs/src/content/docs/how-it-works/threads-and-turns.md b/docs/src/content/docs/how-it-works/threads-and-turns.md index 3aeafdcda..305d4dc30 100644 --- a/docs/src/content/docs/how-it-works/threads-and-turns.md +++ b/docs/src/content/docs/how-it-works/threads-and-turns.md @@ -151,7 +151,7 @@ The main **Stop** control aborts running turns, cancels queued and waiting turns An aborted database transaction stops waiting for a free connection at once. If the pool supplies a connection later, Nod closes it without running the transaction. -Turns and tool calls are never retried. Pi retries a model request that fails with a temporary provider error up to three times with backoff, and leaves the failed attempt out of the model context. A request to a hosted provider that gets no response within 90 seconds counts as a temporary error. Any other error, or a restart during execution, ends the turn `failed`. When an agent model request fails, the error identifies the model and provider and keeps the provider's specific reason, HTTP status and error codes when supplied. This includes any retry delay or limit source the provider reports. Nod does not replace a quota or rate limit with a generic billing warning. It removes secrets and limits the displayed error to 2,000 characters. Structured errors show their messages and error metadata without unrelated response fields. Diagnostic logs retain the provider error with known secrets removed. For work you started (a chat turn, a task, a reply to a task, or work that continues after you answer or approve), Nod posts the error in the main chat or as a reply to the task's message, and a restart posts an interruption notice instead. A model failure is posted as the plain error, because the model that failed can't write it, and names another connection you can switch to when one is set up. When a request to a hosted provider found no network (`ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`, `EHOSTUNREACH` or `ENETDOWN`), the error names the provider and says Nod couldn't reach it because the computer had no internet connection, with that code. The provider's raw error stays in the diagnostic logs. The error and the notice above the chat box leave out the switch and the **Settings → Models** link, unless the notice is still showing an earlier model problem; the notice still offers **Try again**. An OpenAI-compatible, Azure OpenAI or Amazon Bedrock connection keeps the usual error and link, because its address or Region may be wrong or its server stopped. A provider whose adapter reports no transport cause, such as Google's, also keeps them. In the desktop app's local assistant, a schedule run or a task Nod started that fails this way also says that scheduled tasks need the computer awake and online, and links to [running Nod on a server](/deploy/self-host/). A schedule run's own model failure also carries a run track that the server writes from the run's record: due and start times, skipped runs, the cause and code, the next run and the schedule revision the run started with, which **Run now** sends. See [Schedules](/use/schedules/#keep-nod-running). Other errors are written by the model, or posted as the plain error when the model can't write them. A failed schedule run, or a task Nod started, posts the error naming that work; an event turn posts nothing. Errors also show in **Usage**, and a schedule's in its run history. The session's next turn receives the error as `previousFailure`, so Nod can work around it or tell you what to fix. When a turn's model request fails, a provider refusal included, Nod removes what that request added since the last answered one, such as your message or a tool result, from the session's model context, so the session doesn't send it again. A tool call whose result was removed is marked with an unknown outcome, so Nod checks before it runs that call again. Your message stays in the chat, and the saved transcript keeps everything removed. A restart keeps saved task sessions and waiting questions. +Turns and tool calls are never retried. Pi retries a model request that fails with a temporary provider error up to three times with backoff, and leaves the failed attempt out of the model context. With [backup models](/connect/models/#backup-models), Pi retries a temporary error once, and a request that fails before the model answers then continues on the next backup. A refusal doesn't move. A request to a hosted provider that gets no response within 90 seconds counts as a temporary error. Any other error, or a restart during execution, ends the turn `failed`. When an agent model request fails, the error identifies the model and provider and keeps the provider's specific reason, HTTP status and error codes when supplied. This includes any retry delay or limit source the provider reports. Nod does not replace a quota or rate limit with a generic billing warning. It removes secrets and limits the displayed error to 2,000 characters. Structured errors show their messages and error metadata without unrelated response fields. Diagnostic logs retain the provider error with known secrets removed. For work you started (a chat turn, a task, a reply to a task, or work that continues after you answer or approve), Nod posts the error in the main chat or as a reply to the task's message, and a restart posts an interruption notice instead. A model failure is posted as the plain error, because the model that failed can't write it, and names another connection you can switch to when one is set up. When a request to a hosted provider found no network (`ENOTFOUND`, `EAI_AGAIN`, `ENETUNREACH`, `EHOSTUNREACH` or `ENETDOWN`), the error names the provider and says Nod couldn't reach it because the computer had no internet connection, with that code. The provider's raw error stays in the diagnostic logs. The error and the notice above the chat box leave out the switch and the **Settings → Models** link, unless the notice is still showing an earlier model problem; the notice still offers **Try again**. An OpenAI-compatible, Azure OpenAI or Amazon Bedrock connection keeps the usual error and link, because its address or Region may be wrong or its server stopped. A provider whose adapter reports no transport cause, such as Google's, also keeps them. In the desktop app's local assistant, a schedule run or a task Nod started that fails this way also says that scheduled tasks need the computer awake and online, and links to [running Nod on a server](/deploy/self-host/). A schedule run's own model failure also carries a run track that the server writes from the run's record: due and start times, skipped runs, the cause and code, the next run and the schedule revision the run started with, which **Run now** sends. See [Schedules](/use/schedules/#keep-nod-running). Other errors are written by the model, or posted as the plain error when the model can't write them. A failed schedule run, or a task Nod started, posts the error naming that work; an event turn posts nothing. Errors also show in **Usage**, and a schedule's in its run history. The session's next turn receives the error as `previousFailure`, so Nod can work around it or tell you what to fix. When a turn's model request fails, a provider refusal included, Nod removes what that request added since the last answered one, such as your message or a tool result, from the session's model context, so the session doesn't send it again. A tool call whose result was removed is marked with an unknown outcome, so Nod checks before it runs that call again. Your message stays in the chat, and the saved transcript keeps everything removed. A restart keeps saved task sessions and waiting questions. When a turn that carries your message fails at the model provider, that turn is _withdrawn_. When you cancel work with **Stop**, `/stop`, a task's **Stop** or reset, the whole request is withdrawn: the stopped turn and the earlier turns it continues in that session, such as the turn that asked you a question or for a sign-in. A waiting turn that a later turn had already replaced isn't. Work that carries none of your words, such as an app check, has nothing to withdraw. When Nod stops tasks for you with `task stop`, or cancels a turn for another reason, nothing is withdrawn. diff --git a/src/ports/agent.ts b/src/ports/agent.ts index 2b141a899..98f4ac759 100644 --- a/src/ports/agent.ts +++ b/src/ports/agent.ts @@ -351,6 +351,7 @@ export type AgentEvent = | { type: 'text_delta'; text: string } | { type: 'thinking'; title: string } | { type: 'retry'; model: string; attempt: number; attempts: number } + | { type: 'fallback'; from: string; to: string } | { type: 'final'; text: string } | ModelUsageObservation | { type: 'error'; message: string; contextExhausted?: boolean }; diff --git a/src/ports/models.ts b/src/ports/models.ts index 0c5b8456a..bccfe8570 100644 --- a/src/ports/models.ts +++ b/src/ports/models.ts @@ -68,6 +68,7 @@ export interface ModelDefinition { } export interface ModelAccess { + connectionId?: string; provider: ModelProvider; method: ModelMethod; definition: ModelDefinition; diff --git a/src/providers/pi/audio.ts b/src/providers/pi/audio.ts index 61467c52c..38de2dc4b 100644 --- a/src/providers/pi/audio.ts +++ b/src/providers/pi/audio.ts @@ -26,6 +26,12 @@ export function readsNativeAudio(model: { provider: string; id: string; api: str ); } +export function hasNativeAudio(context: Context) { + return context.messages.some( + (message) => message.role === 'user' && Boolean((message as AudioMessage)[filesKey]), + ); +} + export function audioMessage(text: string, images: AgentImage[], audio: AgentAudioInput) { const details = detailsSchema.parse({ id: randomUUID(), recordedAt: Date.now(), ...audio }); return { diff --git a/src/providers/pi/fallback.ts b/src/providers/pi/fallback.ts new file mode 100644 index 000000000..745d34717 --- /dev/null +++ b/src/providers/pi/fallback.ts @@ -0,0 +1,246 @@ +import { + clampThinkingLevel, + createAssistantMessageEventStream, + isContextOverflow, + isRetryableAssistantError, + type Api, + type AssistantMessage, + type AssistantMessageEvent, + type Context, + type Model, + type SimpleStreamOptions, +} from '@earendil-works/pi-ai'; +import { estimateTokens } from '@earendil-works/pi-coding-agent'; +import type { ModelAccess } from '../../ports/models.ts'; +import type { createPiModelRuntime } from './models.ts'; +import { hasNativeAudio, readsNativeAudio } from './audio.ts'; + +type Connection = Awaited>; +type Stream = Connection['runtime']['streamSimple']; + +export function modelKey(access: ModelAccess) { + return `${access.connectionId ?? access.provider}/${access.method}/${access.definition.choice.id}`; +} + +function fits(choice: ModelAccess['definition']['choice'], context: Context) { + const images = context.messages.some( + (message) => + Array.isArray(message.content) && message.content.some((part) => part.type === 'image'), + ); + if (images && !choice.images) return false; + const tokens = + context.messages.reduce((total, message) => total + estimateTokens(message as never), 0) + + (context.systemPrompt?.length ?? 0) / 4; + return !choice.contextWindow || tokens < choice.contextWindow * 0.9; +} + +function failedRequest( + model: Pick, 'api' | 'provider' | 'id'>, + error: unknown, + aborted: boolean, +): AssistantMessage { + return { + role: 'assistant', + content: [], + api: model.api, + provider: model.provider, + model: model.id, + usage: { + input: 0, + output: 0, + cacheRead: 0, + cacheWrite: 0, + totalTokens: 0, + cost: { input: 0, output: 0, cacheRead: 0, cacheWrite: 0, total: 0 }, + }, + stopReason: aborted ? 'aborted' : 'error', + errorMessage: error instanceof Error ? error.message : String(error), + timestamp: Date.now(), + }; +} + +export function failedBeforeAnswer(message: AssistantMessage, phase: string | undefined) { + return ( + message.stopReason === 'error' && (isRetryableAssistantError(message) || phase !== 'stream') + ); +} + +export function createTurnFallback(options: { + primary: { access: ModelAccess; connection: Connection; stream: Stream }; + backups: ModelAccess[]; + start: number; + automatic: boolean; + connect(access: ModelAccess): Promise; + retrying(): boolean; + shared(): number; + switched(at: number): void; + moved(from: number, to: number): void; + failed(message: AssistantMessage): void; +}) { + const candidates: Array<{ access: ModelAccess; connection?: Promise }> = [ + { access: options.primary.access, connection: Promise.resolve(options.primary.connection) }, + ...options.backups.map((access) => ({ access })), + ]; + const ready = new Map([[0, options.primary.connection]]); + const ranOn = new WeakMap>(); + const tried: string[] = []; + let at = Math.min(options.start, candidates.length - 1); + let serving = 0; + + function move(next: number) { + at = next; + options.switched(at); + } + + async function open( + index: number, + target: Model, + context: Context, + streamOptions: SimpleStreamOptions | undefined, + ) { + if (index === 0) + return { + connection: options.primary.connection, + model: target, + upstream: options.primary.stream(target, context, streamOptions), + }; + const candidate = candidates[index]!; + const { choice } = candidate.access.definition; + if (!fits(choice, context)) + throw new Error(`${choice.name} can't take this conversation, so Nod didn't try it.`); + candidate.connection ??= options.connect(candidate.access); + const connection = await candidate.connection; + ready.set(index, connection); + if (options.automatic) await candidate.access.prepareRequest?.(connection.model.id, true); + const { apiKey: _, headers: __, env: ___, ...rest } = streamOptions ?? {}; + const level = clampThinkingLevel(connection.model, candidate.access.effort); + return { + connection, + model: connection.model, + upstream: connection.runtime.streamSimple(connection.model, context, { + ...rest, + reasoning: level === 'off' ? undefined : level, + } as SimpleStreamOptions), + }; + } + + const movesOn = (message: AssistantMessage, index: number, connection: Connection) => + failedBeforeAnswer(message, connection.requestFacts?.(message)?.requestPhase) && + (index > 0 || !isContextOverflow(message, connection.model.contextWindow ?? 0)) && + (!isRetryableAssistantError(message) || !options.retrying()); + + return { + stream(target: Model, context: Context, streamOptions?: SimpleStreamOptions) { + if ( + (streamOptions?.maxTokens === 1 && streamOptions.maxRetries === 0) || + target.api === 'pi-virtual' || + (readsNativeAudio(target) && hasNativeAudio(context)) + ) + return options.primary.stream(target, context, streamOptions); + const out = createAssistantMessageEventStream(); + const stopped = () => Boolean(streamOptions?.signal?.aborted); + void (async () => { + at = Math.max(at, Math.min(options.shared(), candidates.length - 1)); + for (;;) { + const index = at; + const { access } = candidates[index]!; + const last = index + 1 >= candidates.length; + let sent = false; + let reason: string; + try { + const opened = await open(index, target, context, streamOptions); + const { model } = opened; + const held: AssistantMessageEvent[] = []; + let failure: AssistantMessage | undefined; + for await (const event of opened.upstream) { + if (!sent && event.type === 'start') { + held.push(event); + continue; + } + if ( + !sent && + !last && + event.type === 'error' && + !stopped() && + movesOn(event.error, index, opened.connection) + ) { + failure = event.error; + break; + } + if (!sent && event.type !== 'error' && index !== serving) { + options.moved(serving, index); + serving = index; + } + if (!sent) for (const item of held.splice(0)) out.push(item); + sent = true; + out.push(event); + } + if (!failure) { + const result = await opened.upstream.result(); + ranOn.set(result, model); + if (result.stopReason !== 'error' && result.stopReason !== 'aborted') + tried.length = 0; + out.end(result); + return; + } + ranOn.set(failure, model); + options.failed(failure); + reason = failure.errorMessage?.trim() || 'The provider gave no reason.'; + } catch (error) { + if (stopped() || last || sent) { + const result = failedRequest( + index + ? { api: target.api, provider: access.provider, id: access.definition.choice.id } + : target, + error, + stopped(), + ); + out.push({ + type: 'error', + reason: result.stopReason === 'aborted' ? 'aborted' : 'error', + error: result, + }); + out.end(result); + return; + } + reason = error instanceof Error ? error.message : String(error); + } + tried.push(`${access.provider} / ${access.definition.choice.id}: ${reason}`); + move(index + 1); + } + })(); + return out; + }, + describe(message: AssistantMessage) { + if (message.stopReason !== 'error' || !tried.length) return undefined; + return [ + ...tried, + `${message.provider} / ${message.model}: ${message.errorMessage?.trim() || 'The provider gave no reason.'}`, + ].join('; then '); + }, + method(provider: string, model: string) { + const index = [at, ...candidates.keys()].find((index) => { + const { access } = candidates[index]!; + return ( + access.provider === provider && + [access.definition.choice.id, access.textModel?.definition.choice.id].includes(model) + ); + }); + return candidates[index ?? at]!.access.method; + }, + model(usage: { provider: string; model: string }) { + const exact = ranOn.get(usage); + if (exact) return exact; + for (const connection of [ready.get(at), ...ready.values()]) { + const found = + connection?.model.provider === usage.provider && connection.model.id === usage.model + ? connection.model + : connection?.runtime.getModel(usage.provider, usage.model); + if (found) return found; + } + return undefined; + }, + current: () => candidates[at]!.access.definition.choice.name, + switched: () => at > 0, + }; +} diff --git a/src/providers/pi/index.ts b/src/providers/pi/index.ts index 3f9721d72..9295edf6b 100644 --- a/src/providers/pi/index.ts +++ b/src/providers/pi/index.ts @@ -34,14 +34,15 @@ import { type ResourceLoader, type ToolDefinition, } from '@earendil-works/pi-coding-agent'; -import { createPiModelRuntime, localModelSilenceMs } from './models.ts'; +import { createPiModelRuntime } from './models.ts'; +import { createTurnFallback, modelKey } from './fallback.ts'; import { modelContext } from './context.ts'; import { createContextOutput, toolOutputReference } from './context-output.ts'; import { audioContext, audioEntries, audioMessage, readsNativeAudio } from './audio.ts'; import { piModelTrace } from './traces.ts'; import type { ModelTraces } from '../../ports/traces.ts'; import type { ModelAccess } from '../../ports/models.ts'; -import type { Agent } from '../../ports/agent.ts'; +import type { Agent, AgentEvent } from '../../ports/agent.ts'; import { closeInterruptedCalls, completeAssistantMessage, @@ -231,7 +232,7 @@ function stableRequestCache( return (pi: ExtensionAPI) => { pi.on('before_provider_request', ({ payload }) => { const request = payload as CachedRequest | null; - if (!request || !Array.isArray(request.messages)) return; + if (!request?.system || !Array.isArray(request.messages)) return; if (Array.isArray(request.system) && request.system.filter((b) => b.cache_control).length > 1) return; const prefixes = [...new Set(cached.stable ?? [])].sort((a, b) => a.length - b.length); @@ -444,9 +445,25 @@ function completeAssistantMessages(pi: ExtensionAPI) { const tokenRateLimit = /\b(?:tokens? per (?:minute|day)|[tr]p[md])\b/i; +function planBilled(event: AgentEvent): AgentEvent { + return event.type === 'model_usage' + ? { ...event, costUsd: null, estimateUsd: event.costUsd, costSource: 'unavailable' } + : event.type === 'provider_usage' + ? { + ...event, + usage: { + ...event.usage, + costUsd: null, + estimateUsd: event.usage.costUsd, + pricing: 'unavailable', + }, + } + : event; +} + export function createPiAgent(options: { provider: string; - resolve?: (choice?: ModelSelection) => Promise; + resolve?: (choice?: ModelSelection) => Promise; model?: string; apiKey?: string; sessionRoot: string; @@ -461,41 +478,51 @@ export function createPiAgent(options: { >(); let disposed = false; const warming = new Map Promise>(); + const turnModels = new Map(); return { async open(input) { if (disposed) throw new Error('The agent service has stopped.'); - const access = await options.resolve?.(input.model); - if (input.automatic) - await access?.prepareRequest?.( - access.textModel?.definition.choice.id ?? access.definition.choice.id, - true, + const resolved = await options.resolve?.(input.model); + const [access, ...backups] = resolved === undefined ? [] : [resolved].flat(); + const chain = access ? [access, ...backups] : []; + const shared = () => + Math.max( + 0, + chain.findIndex((item) => modelKey(item) === turnModels.get(input.turnId)), ); + let start = shared(); + if (input.automatic && access) { + let failure: unknown; + for (; start < chain.length; start++) { + const item = chain[start]!; + try { + await item.prepareRequest?.( + item.textModel?.definition.choice.id ?? item.definition.choice.id, + true, + ); + break; + } catch (error) { + failure ??= error; + } + } + if (start === chain.length) throw failure; + } if (!access && !options.apiKey) throw new Error('Configure the selected model provider to enable the assistant.'); - if (access?.method === 'subscription') { + let billing = (_provider: string, _model: string) => access?.method; + if (chain.some((item) => item.method === 'subscription')) { const observe = input.onEvent; input = { ...input, onEvent: (event) => observe( - event.type === 'model_usage' - ? { - ...event, - costUsd: null, - estimateUsd: event.costUsd, - costSource: 'unavailable', - } + (event.type === 'model_usage' + ? billing(event.provider, event.model) : event.type === 'provider_usage' - ? { - ...event, - usage: { - ...event.usage, - costUsd: null, - estimateUsd: event.usage.costUsd, - pricing: 'unavailable', - }, - } - : event, + ? billing(event.usage.provider, event.usage.model ?? '') + : undefined) === 'subscription' + ? planBilled(event) + : event, ), }; } @@ -505,34 +532,34 @@ export function createPiAgent(options: { await warming.get(directory)?.(); await mkdir(directory, { recursive: true, mode: 0o700 }); const traces = options.traces; + const runtimeOptions: Parameters[1] = { + automatic: input.automatic, + trace: + traces && + ((call) => { + if (traces.active()) + traces.record( + piModelTrace( + call, + { + source: 'agent', + session_id: input.sessionId, + turn_id: input.turnId, + run_id: input.runId, + ...(input.parentRunId ? { parent_run_id: input.parentRunId } : {}), + }, + input.ownerContext, + ), + ); + }), + reportCacheUsage: (usage) => + input.onEvent({ + type: 'provider_usage', + usage: { ...usage, turnId: input.turnId }, + }), + }; const connection = access - ? await createPiModelRuntime(access, { - automatic: input.automatic, - trace: - traces && - ((call) => { - if (traces.active()) - traces.record( - piModelTrace( - call, - { - source: 'agent', - session_id: input.sessionId, - turn_id: input.turnId, - run_id: input.runId, - ...(input.parentRunId ? { parent_run_id: input.parentRunId } : {}), - }, - input.ownerContext, - ), - ); - }), - readAudio: input.readAudio, - reportCacheUsage: (usage) => - input.onEvent({ - type: 'provider_usage', - usage: { ...usage, turnId: input.turnId }, - }), - }) + ? await createPiModelRuntime(access, { ...runtimeOptions, readAudio: input.readAudio }) : undefined; const runtime = connection ? connection.runtime @@ -662,6 +689,36 @@ export function createPiAgent(options: { runtime.streamSimple = (target, context, options) => stream(target, context, { ...options, cacheRetention: 'long' }); } + const fallback = + access && connection && backups.length + ? createTurnFallback({ + primary: { access, connection, stream: runtime.streamSimple.bind(runtime) }, + backups, + start, + automatic: Boolean(input.automatic), + connect: (backup) => createPiModelRuntime(backup, runtimeOptions), + shared, + switched: (at) => turnModels.set(input.turnId, modelKey(chain[at]!)), + retrying: () => { + const retry = settings.getRetrySettings(); + return retry.enabled && session.retryAttempt < retry.maxRetries; + }, + moved: (from, to) => + input.onEvent({ + type: 'fallback', + from: chain[from]!.definition.choice.name, + to: chain[to]!.definition.choice.name, + }), + failed: (message) => { + const usage = observeUsage(message); + if (usage) input.onEvent({ ...usage, pricingSignature: usagePricing(message) }); + }, + }) + : undefined; + if (fallback) { + runtime.streamSimple = fallback.stream; + billing = fallback.method; + } if (restart) manager.appendCompaction( 'Earlier checks are saved outside this context. Use the current request and fresh source reads.', @@ -769,8 +826,7 @@ export function createPiAgent(options: { transport: 'sse', steeringMode: 'all', cacheWarming: input.keepWarm ? 'idle' : 'streaming', - retry: { baseDelayMs: 4000 }, - ...(access?.provider === 'compatible' ? { httpIdleTimeoutMs: localModelSilenceMs } : {}), + retry: { baseDelayMs: 4000, ...(backups.length ? { maxRetries: 1 } : {}) }, }); const extensionLoader = new DefaultResourceLoader({ cwd: input.workspace.path, @@ -923,6 +979,7 @@ export function createPiAgent(options: { }), (pi: ExtensionAPI) => pi.on('cache_warming_decision', async () => { + if (fallback?.switched()) return { action: 'stop' as const }; try { await access?.prepareRequest?.(connection?.textModel?.id ?? model.id, true); } catch { @@ -1176,7 +1233,8 @@ export function createPiAgent(options: { { id: string; started: number; error?: string; requests: AssistantMessage[] } | undefined; const auxiliarySeen = new Set(manager.getEntries().map((entry) => entry.id)); const usagePricing = (usage: { provider: string; model: string } | undefined) => { - const target = usage && runtime.getModel(usage.provider, usage.model); + const target = + usage && (fallback?.model(usage) ?? runtime.getModel(usage.provider, usage.model)); return modelPricingSignature(target?.cost, target?.api); }; const observeUsage = createPiUsageTracker({ @@ -1255,7 +1313,7 @@ export function createPiAgent(options: { if (event.type === 'auto_retry_start') input.onEvent({ type: 'retry', - model: (session.model ?? model).name, + model: fallback?.current() ?? (session.model ?? model).name, attempt: event.attempt, attempts: event.maxAttempts, }); @@ -1307,7 +1365,9 @@ export function createPiAgent(options: { if (event.message.stopReason === 'error') input.onEvent({ type: 'error', - message: `${event.message.provider} / ${event.message.model}: ${event.message.errorMessage?.trim() || 'The provider gave no reason.'}`, + message: + fallback?.describe(event.message) ?? + `${event.message.provider} / ${event.message.model}: ${event.message.errorMessage?.trim() || 'The provider gave no reason.'}`, ...(overflow ? { contextExhausted: true } : {}), }); if (event.message.stopReason === 'stop') { @@ -1346,6 +1406,7 @@ export function createPiAgent(options: { active.delete(session); }; const dispose = async () => { + if (!input.parentRunId) turnModels.delete(input.turnId); if (disposed || !input.keepWarm || session.cacheWarmingStatus?.state === 'inactive') return close(); idle = true; diff --git a/src/providers/pi/memory-curator.ts b/src/providers/pi/memory-curator.ts index af7bc3a93..4d4609023 100644 --- a/src/providers/pi/memory-curator.ts +++ b/src/providers/pi/memory-curator.ts @@ -9,7 +9,8 @@ import { } from '@earendil-works/pi-ai'; import { ModelRuntime } from '@earendil-works/pi-coding-agent'; import { retryAssistantCall } from '@earendil-works/pi-ai/utils/retry'; -import { createPiModelRuntime, localModelSilenceMs } from './models.ts'; +import { createPiModelRuntime } from './models.ts'; +import { failedBeforeAnswer } from './fallback.ts'; import type { ModelAccess } from '../../ports/models.ts'; import { lightestEffort, modelPricingSignature } from '../../shared/models.ts'; import type { MemoryCurator } from '../../ports/memory-curator.ts'; @@ -81,7 +82,8 @@ function json(text: string) { export function createPiMemoryCurator(options: { provider: string; - resolve?: () => Promise; + resolve?: () => Promise; + retry?: boolean; configured?: () => boolean; model?: string; lightest?: boolean; @@ -91,8 +93,8 @@ export function createPiMemoryCurator(options: { estimateAnthropicRequestUsd?: (model: Model, body: RequestInit['body']) => number | null; }): MemoryCurator { let loaded: ReturnType | undefined; - async function load(automatic: boolean) { - const access = await options.resolve?.(); + async function load(automatic: boolean, resolved: ModelAccess | ModelAccess[] | undefined) { + const access = [resolved ?? []].flat()[0]; if (options.resolve && !access) throw new Error('The selected model is unavailable.'); if (access) await access.prepareRequest?.( @@ -144,13 +146,32 @@ export function createPiMemoryCurator(options: { report, ) { signal?.throwIfAborted(); + const candidates = await options.resolve?.(); + if (Array.isArray(candidates) && candidates.length > 1) + for (const [index, access] of candidates.entries()) { + const last = index === candidates.length - 1; + try { + return await createPiMemoryCurator({ + ...options, + resolve: async () => access, + retry: last, + }).curate( + { task, instructions, input, responseSchema, images, automatic }, + signal, + report, + ); + } catch (error) { + if (last || signal?.aborted || (error as { movesOn?: boolean }).movesOn === false) + throw error; + } + } const traceTurnId = crypto.randomUUID(); const bounded = task === 'classify' || task === 'attention' || task === 'check' || task === 'activity'; const turnBound = signal !== undefined && ['review', 'access', 'skill', 'remember'].includes(task); if (options.resolve) loaded = undefined; - loaded ??= load(automatic).catch((error) => { + loaded ??= load(automatic, candidates).catch((error) => { loaded = undefined; throw error; }); @@ -240,9 +261,6 @@ export function createPiMemoryCurator(options: { maxTokens: bounded ? 512 : task === 'ideas' ? 2048 : 8192, ...(sessionId ? { sessionId } : {}), ...(bounded ? { maxRetries: 0, timeoutMs: 10_000 } : {}), - ...(turnBound && model.provider === 'compatible' - ? { timeoutMs: localModelSilenceMs } - : {}), reasoning: effort === 'off' ? undefined : effort, }); } finally { @@ -295,7 +313,7 @@ export function createPiMemoryCurator(options: { const reply = await retryAssistantCall( complete, { - enabled: task !== 'vision' && task !== 'ideas' && !bounded, + enabled: options.retry !== false && task !== 'vision' && task !== 'ideas' && !bounded, maxRetries: 2, baseDelayMs: 250, }, @@ -325,6 +343,7 @@ export function createPiMemoryCurator(options: { const status = [...(reply.errorMessage ?? '').matchAll(/\(HTTP (\d{3})\)/g)].at(-1)?.[1]; throw Object.assign( new Error(`${label} Task: ${task}. Model: ${model.provider}/${model.id}.${detail}`), + { movesOn: failedBeforeAnswer(reply, requestFacts?.(reply)?.requestPhase) }, status ? { providerStatus: Number(status), diff --git a/src/providers/pi/models.ts b/src/providers/pi/models.ts index f796ee43c..e4714750f 100644 --- a/src/providers/pi/models.ts +++ b/src/providers/pi/models.ts @@ -1277,6 +1277,7 @@ export async function createPiModelRuntime( signal: options?.signal ? AbortSignal.any([options.signal, silence.signal]) : silence.signal, maxTokens: output, maxRetries: 0, + ...(access.provider === 'compatible' ? { timeoutMs: localModelSilenceMs } : {}), onResponse: async (response, model) => { phase = 'response'; status = response.status; diff --git a/src/runtime/index.ts b/src/runtime/index.ts index e038da1ee..46c48e9c0 100644 --- a/src/runtime/index.ts +++ b/src/runtime/index.ts @@ -278,6 +278,7 @@ export function createAgentRuntime(dependencies: { let completed = false; let lastReply = ''; let lastPresentation = ''; + let fallbackNoted: string | undefined; let checkInSpent = context.checkIn?.spentUsd ?? 0; let checkInPlan = context.checkIn?.planUsd ?? 0; let checkInBlocked = false; @@ -1232,6 +1233,14 @@ export function createAgentRuntime(dependencies: { ); void pendingReplies.catch(() => {}); } + if (event.type === 'fallback' && event.to !== fallbackNoted) { + fallbackNoted = event.to; + const note = `${event.from} failed, so this used ${event.to}.`; + pendingReplies = pendingReplies.then(() => + context.emit('retry', note, { execution }).catch(() => {}), + ); + void pendingReplies.catch(() => {}); + } if (event.type === 'message_start') { completeStream(); streamId = randomUUID(); diff --git a/src/server/composition.ts b/src/server/composition.ts index b72b5bcfc..6ca2a027b 100644 --- a/src/server/composition.ts +++ b/src/server/composition.ts @@ -260,6 +260,7 @@ export interface ApplicationAdapters { keepAwake?: KeepAwake; localFilesHome?: string; memoryCurator?: MemoryCurator; + recallCurator?: MemoryCurator; classificationCurator?: MemoryCurator; imageCurator?: MemoryCurator; onboardingCurator?: MemoryCurator; @@ -510,7 +511,7 @@ export function createDefaultAdapters( }, models, agent: createPiAgent({ - resolve: (choice) => models.resolve(false, choice), + resolve: (choice) => models.candidates(choice), provider, model, sessionRoot: join(dataRoot, 'sessions'), @@ -617,6 +618,14 @@ export function createDefaultAdapters( integrationBrowser, keyStore, memoryCurator: modelCurator, + recallCurator: createPiMemoryCurator({ + get provider() { + return models.current.provider; + }, + resolve: () => models.candidates(undefined, true), + configured: () => models.configured, + traces, + }), trustCurator: createPiMemoryCurator({ get provider() { return models.current.provider; @@ -1072,7 +1081,12 @@ async function initializeApplication( } : undefined, }); - const memoryRecall = createMemoryRecall({ pool, ownerId, memory, curator }); + const memoryRecall = createMemoryRecall({ + pool, + ownerId, + memory, + curator: adapters.recallCurator ? ledger.curator(adapters.recallCurator) : curator, + }); const writingStyle = createWritingStyleLearning({ memory, curator }); let channels: Awaited> | undefined; const communication = createCommunication({ diff --git a/src/server/model-store.ts b/src/server/model-store.ts index c57f6dcc3..3f5532c1c 100644 --- a/src/server/model-store.ts +++ b/src/server/model-store.ts @@ -26,6 +26,7 @@ export interface ModelState { selection: ModelSelection | null; selectionSet: boolean; routes: ModelRoutes; + backups: ModelSelection[]; hostId: string; } @@ -69,16 +70,19 @@ export function createDatabaseModelStore(options: { selection: ModelSelection | null; selection_set: boolean; routes: ModelRoutes | null; + backups: ModelSelection[] | null; host_id: string; - }>('SELECT selection,selection_set,routes,host_id FROM model_settings WHERE owner_id=$1', [ - ownerId, - ]) + }>( + 'SELECT selection,selection_set,routes,backups,host_id FROM model_settings WHERE owner_id=$1', + [ownerId], + ) ).rows[0]; return { connections, selection: settings?.selection ?? null, selectionSet: settings?.selection_set ?? false, routes: settings?.routes ?? {}, + backups: settings?.backups ?? [], hostId: settings.host_id, }; } @@ -94,7 +98,8 @@ export function createDatabaseModelStore(options: { ALTER TABLE model_connections ADD COLUMN IF NOT EXISTS request_failures jsonb NOT NULL DEFAULT '{}'; CREATE TABLE IF NOT EXISTS model_settings(owner_id text PRIMARY KEY,selection jsonb,selection_set boolean NOT NULL DEFAULT false); ALTER TABLE model_settings ADD COLUMN IF NOT EXISTS host_id uuid NOT NULL DEFAULT gen_random_uuid(); - ALTER TABLE model_settings ADD COLUMN IF NOT EXISTS routes jsonb NOT NULL DEFAULT '{}';`); + ALTER TABLE model_settings ADD COLUMN IF NOT EXISTS routes jsonb NOT NULL DEFAULT '{}'; + ALTER TABLE model_settings ADD COLUMN IF NOT EXISTS backups jsonb NOT NULL DEFAULT '[]';`); await database.query( 'INSERT INTO model_settings(owner_id) VALUES($1) ON CONFLICT DO NOTHING', [ownerId], @@ -161,6 +166,11 @@ export function createDatabaseModelStore(options: { ownerId, JSON.stringify(state.routes), ]); + if (JSON.stringify(state.backups) !== JSON.stringify(previous.backups)) + await client.query('UPDATE model_settings SET backups=$2 WHERE owner_id=$1', [ + ownerId, + JSON.stringify(state.backups), + ]); signal?.throwIfAborted(); return result; }; diff --git a/src/server/models.ts b/src/server/models.ts index 663060bd6..afc4bf8d5 100644 --- a/src/server/models.ts +++ b/src/server/models.ts @@ -108,7 +108,11 @@ function modelPricing(model: ModelDefinition): ModelChoice['pricing'] { }; } +const auxiliaryEffort = (efforts: ModelChoice['efforts']) => + efforts.find((level) => ['off', 'low', 'medium'].includes(level)) ?? efforts[0]; + export const modelRouteInput = z.union([modelSelectionInput, z.literal('light'), z.null()]); +export const modelBackupsInput = z.array(modelSelectionInput).max(3); export interface WorkOrigin { kind: WorkKind; @@ -375,6 +379,7 @@ export function createModelService(options: { let initialized = false; let selection: ModelSelection | null = null; let routes: ModelRoutes = {}; + let backups: ModelSelection[] = []; let starting: Promise = Promise.resolve(); const pendingControllers = new Set(); let closed = false; @@ -466,6 +471,7 @@ export function createModelService(options: { }); selection = state.selection; routes = state.routes; + backups = state.backups; checkSelection(state); options.changed?.(); } @@ -621,6 +627,25 @@ export function createModelService(options: { if (definition) return { row, definition }; } } + function usableBackups(connectionId: string | undefined, modelId: string) { + const seen = new Set([`${connectionId}:${modelId}`]); + return backups.flatMap((item) => { + const row = rows.find((candidate) => candidate.id === item.connectionId); + const definition = + row?.status === 'connected' + ? row.models.find( + (model) => + model.choice.id === item.modelId && + !model.choice.audio && + model.choice.efforts.length > 0, + ) + : undefined; + const key = `${item.connectionId}:${item.modelId}`; + if (!row || !definition || seen.has(key)) return []; + seen.add(key); + return [{ row, definition, item }]; + }); + } function classificationModel(otherConnections = false) { const selected = selection && { ...selection }; const current = rows.find((row) => row.id === selected?.connectionId); @@ -1215,8 +1240,22 @@ export function createModelService(options: { paused(origin: WorkOrigin) { try { const { selection: work } = service.workModel(origin); - const row = rows.find((item) => item.id === work.connectionId); - return requested(row, work.modelId).some((id) => (row?.retry?.[id] ?? 0) > Date.now()); + const paused = (choice: ModelSelection) => { + const row = rows.find((item) => item.id === choice.connectionId); + return requested(row, choice.modelId).some((id) => (row?.retry?.[id] ?? 0) > Date.now()); + }; + const usable = (choice: ModelSelection) => { + try { + return Boolean(chosen(false, choice)); + } catch { + return false; + } + }; + return ( + paused(work) && + (!usable(work) || + usableBackups(work.connectionId, work.modelId).every(({ item }) => paused(item))) + ); } catch { return false; } @@ -1224,16 +1263,20 @@ export function createModelService(options: { async automaticRequestsAllowed(origin: WorkOrigin, auxiliary = false) { try { const work = service.workModel(origin); - for (const access of [ - await service.resolve(false, work.selection), - ...(auxiliary ? [await service.resolve(true)] : []), - ]) { - await access.prepareRequest?.( - access.textModel?.definition.choice.id ?? access.definition.choice.id, - true, - ); - } - return true; + const takes = async (access: ModelAccess) => { + try { + await access.prepareRequest?.( + access.textModel?.definition.choice.id ?? access.definition.choice.id, + true, + ); + return true; + } catch { + return false; + } + }; + for (const access of await service.candidates(work.selection)) + if (await takes(access)) return !auxiliary || (await takes(await service.resolve(true))); + return false; } catch { return false; } @@ -1306,6 +1349,48 @@ export function createModelService(options: { selection: { ...work.selection, effort: defaultEffort(row.provider, definition.choice) }, }; }, + async candidates( + choice: ModelSelection | null = selection, + auxiliary = false, + ): Promise { + const primary = await service.resolve(auxiliary, choice); + return [ + primary, + ...usableBackups(primary.connectionId, primary.definition.choice.id).map( + ({ row, definition, item }): ModelAccess => ({ + connectionId: row.id, + provider: row.provider, + method: row.method, + definition, + effort: auxiliary + ? auxiliaryEffort(definition.choice.efforts) + : definition.choice.efforts.includes(item.effort) + ? item.effort + : defaultEffort(row.provider, definition.choice), + ...requestAccess(row), + needsReconnect: (credential) => + needsReconnect(row.id, { models: row.models, credential }), + }), + ), + ]; + }, + async setBackups(value: ModelSelection[]) { + const list = modelBackupsInput.parse(value); + await store.change((state) => { + const key = (choice: ModelSelection) => + `${choice.connectionId}:${choice.modelId}:${choice.effort}`; + const saved = new Set(state.backups.map(key)); + const seen = new Set(); + state.backups = list.filter((choice) => { + if (!saved.has(key(choice))) textChoice(state.connections, choice); + const model = `${choice.connectionId}:${choice.modelId}`; + if (seen.has(model)) return false; + seen.add(model); + return true; + }); + }); + await reload(); + }, async setRoute( lane: ModelLane, value: ModelRoute | null, @@ -1368,6 +1453,7 @@ export function createModelService(options: { selection, ...(selectionIssue ? { selectionIssue } : {}), routes, + backups, light: lightModel(), ...(unpriced ? { unpricedPreparationModel: unpriced } : {}), }; @@ -1381,6 +1467,9 @@ export function createModelService(options: { ); if (!state.connections.some((row) => row.id === state.selection?.connectionId)) state.selection = null; + state.backups = state.backups.filter((choice) => + state.connections.some((row) => row.id === choice.connectionId), + ); for (const row of state.connections) { try { if (!credential(row)) row.status = 'reconnect'; @@ -1522,6 +1611,7 @@ export function createModelService(options: { ([, route]) => route === 'light' || route?.connectionId !== id, ), ); + state.backups = state.backups.filter((choice) => choice.connectionId !== id); return { row, selectionCleared }; }); if (removed.selectionCleared) @@ -1616,13 +1706,11 @@ export function createModelService(options: { ): Promise { const { selected, row, definition, companion } = chosen(auxiliary, choice); return { + connectionId: row.id, provider: row.provider, method: row.method, definition, - effort: auxiliary - ? (definition.choice.efforts.find((level) => ['off', 'low', 'medium'].includes(level)) ?? - definition.choice.efforts[0]) - : selected.effort, + effort: auxiliary ? auxiliaryEffort(definition.choice.efforts) : selected.effort, ...(companion ? { textModel: { @@ -1682,6 +1770,11 @@ export function createModelService(options: { await service.select(modelSelectionInput.parse(request.body)); return service.view(); }); + routes.put('/api/models/backups', async (request) => { + const input = z.object({ backups: modelBackupsInput }).strict().parse(request.body); + await service.setBackups(input.backups); + return service.view(); + }); routes.put('/api/models/routes', async (request) => { const input = z .object({ lane: z.enum(['schedule', 'background']), route: modelRouteInput }) diff --git a/src/shared/model-quota.ts b/src/shared/model-quota.ts index a10d85db2..a81d4e267 100644 --- a/src/shared/model-quota.ts +++ b/src/shared/model-quota.ts @@ -83,12 +83,15 @@ function readFailure(text: string) { return { start, end, reasons }; } -export function modelFailureReason(text: string) { +export function modelFailureReason(text: string): string { const { start, end, reasons } = readFailure(text); - if (!reasons.length) return text; + if (start === -1 || end <= start) return text; const rest = reasons.reduce( (value, reason) => value.replace(` (${reason})`, ''), text.slice(end + 1), ); - return `${text.slice(0, start)}${[...new Set(reasons)].join('; ')}${rest}`; + const head = reasons.length + ? `${text.slice(0, start)}${[...new Set(reasons)].join('; ')}` + : text.slice(0, end + 1); + return `${head}${modelFailureReason(rest)}`; } diff --git a/src/shared/models.ts b/src/shared/models.ts index d9ff3e2cf..a5cdb7c9e 100644 --- a/src/shared/models.ts +++ b/src/shared/models.ts @@ -255,6 +255,7 @@ export interface ModelsResponse { selection: ModelSelection | null; selectionIssue?: ModelIssue; routes: ModelRoutes; + backups: ModelSelection[]; light: ModelSelection | null; unpricedPreparationModel?: string; } diff --git a/src/web/components/model-choices.tsx b/src/web/components/model-choices.tsx index ba2985e03..4b989b56b 100644 --- a/src/web/components/model-choices.tsx +++ b/src/web/components/model-choices.tsx @@ -1,3 +1,4 @@ +import { Fragment } from 'react'; import type { Schedule, Task } from '../../shared/contracts'; import { canReuseWorkCost, @@ -76,6 +77,23 @@ function laneTarget( }; } +function backupTarget(data: ModelsResponse, index: number): ModelTarget { + const list = data.backups ?? []; + return { + title: index < list.length ? `Backup model ${index + 1}` : 'Add a backup model', + value: list[index] ?? null, + defaults: index < list.length ? [{ value: null, label: 'No backup', model: null }] : [], + save: (choice) => { + const next = [...list]; + if (choice && choice !== 'light') next[index] = choice; + else next.splice(index, 1); + return saved('/api/models/backups', { backups: next }, (result) => + pageDataCache.update('/api/models', () => result), + ); + }, + }; +} + function scheduleTarget( data: ModelsResponse, schedule: Schedule, @@ -162,6 +180,7 @@ export function ModelSentences() { const data = models.data; if (!data) return null; const chat = modelOf(data, data.selection); + const backups = data.backups ?? []; const lane = (kind: ModelLane) => { const value = data.routes?.[kind]; const light = value === 'light' && data.light && modelOf(data, data.light); @@ -223,6 +242,30 @@ export function ModelSentences() { /> .

+ {chat && ( +

+ If it’s busy or unavailable, Nod tries{' '} + {backups.length + ? backups.map((choice, index) => ( + + {index ? ', then ' : ''} + + + )) + : 'no other model'} + . +

+ )}

Schedules use {lane('schedule')}.

Work Nod starts on its own uses {lane('background')}.

{ownSchedules.map((schedule) => ( @@ -250,6 +293,16 @@ export function ModelSentences() {

))} + {chat && backups.length < 3 && ( +

+ +

+ )} {chat?.audio && (

{chat.textModelName ? `Text support: ${chat.textModelName}` : 'Text model unavailable'} diff --git a/tests/accounts.test.ts b/tests/accounts.test.ts index 428bd0980..76185feeb 100644 --- a/tests/accounts.test.ts +++ b/tests/accounts.test.ts @@ -4452,7 +4452,13 @@ describe('model connections', { skip: !process.env.TEST_DATABASE_URL }, () => { ); assert.equal((await f.database.query('SELECT * FROM vault_app_grants')).rowCount, 0); const removed = await f.create('fixture-environment-owner', backend, modelEnvironment({})); - assert.deepEqual(removed.view(), { connections: [], selection: null, routes: {}, light: null }); + assert.deepEqual(removed.view(), { + connections: [], + selection: null, + routes: {}, + backups: [], + light: null, + }); await assert.rejects(removed.resolve()); for (const access of captured) assert.equal(await access.read(), undefined); }); @@ -5875,6 +5881,109 @@ describe('model connections', { skip: !process.env.TEST_DATABASE_URL }, () => { assert.doesNotMatch(JSON.stringify(settings()), /fixture-|connectionId|modelId/); }); + test('backup models are only the ones the owner picks, in order, and survive a restart', async (t) => { + const f = await fixture(t); + const { createServer } = await import('node:http'); + const { createPiModelBackend } = await import('../src/providers/pi/models.ts'); + const server = createServer((_request, response) => { + response.writeHead(200, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ data: [{ id: 'fixture-local' }] })); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise((resolve) => server.close(() => resolve()))); + const address = `http://127.0.0.1:${(server.address() as import('node:net').AddressInfo).port}`; + const backend = createPiModelBackend({ + fetch: async (input, init) => + String(input).startsWith('https://') + ? Response.json({ data: ['gpt-6.1-sol', 'gpt-6-luna'].map((id) => ({ id })) }) + : fetch(input, init), + }); + const ownerId = 'fixture-backup-owner'; + const owner = await f.create(ownerId, backend); + const local = await owner.addEndpoint(`${address}/v1`); + await owner.addKey('openai', 'fixture-backup-openai-key'); + await owner.addKey('openai', 'fixture-backup-openai-key', { region: 'eu' }); + const openai = owner.view().connections.filter((row) => row.provider === 'openai'); + const eu = openai.find((row) => row.label.includes('Europe'))!; + const global = openai.find((row) => row !== eu)!; + const luna = eu.models.find((model) => model.id === 'gpt-6-luna')!; + await owner.select({ connectionId: local, modelId: 'fixture-local', effort: 'off' }); + assert.deepEqual(owner.view().backups, []); + assert.deepEqual((await f.create(ownerId, backend)).view().backups, []); + + await owner.setBackups([ + { connectionId: eu.id, modelId: luna.id, effort: luna.efforts.at(-1)! }, + { connectionId: global.id, modelId: 'gpt-6.1-sol', effort: 'high' }, + ]); + const restarted = await f.create(ownerId, backend); + assert.deepEqual(restarted.view().backups, [ + { connectionId: eu.id, modelId: 'gpt-6-luna', effort: luna.efforts.at(-1) }, + { connectionId: global.id, modelId: 'gpt-6.1-sol', effort: 'high' }, + ]); + assert.deepEqual( + (await restarted.candidates()).map((access) => access.definition.choice.id), + ['fixture-local', 'gpt-6-luna', 'gpt-6.1-sol'], + ); + const { createHash } = await import('node:crypto'); + const [selected] = await restarted.candidates(); + const credentialTag = createHash('sha256') + .update(JSON.stringify(await selected!.read())) + .digest('hex'); + const failure = { credentialTag, reason: 'Synthetic key rejected.', failures: 1 }; + const pause = (status: string) => + f.database.query('UPDATE model_connections SET status=$2, request_failures=$3 WHERE id=$1', [ + local, + status, + JSON.stringify({ 'fixture-local': { ...failure, retryAt: Date.now() + 60_000 } }), + ]); + const schedule = { kind: 'schedule' as const }; + await pause('reconnect'); + const broken = await f.create(ownerId, backend); + assert.equal(broken.paused(schedule), true); + await assert.rejects(broken.candidates(), /OpenAI-compatible connection/); + await pause('connected'); + assert.equal((await f.create(ownerId, backend)).paused(schedule), false); + await f.database.query("UPDATE model_connections SET request_failures='{}' WHERE id=$1", [ + local, + ]); + + await restarted.select({ connectionId: global.id, modelId: 'gpt-6.1-sol', effort: 'high' }); + await restarted.setBackups([ + { connectionId: global.id, modelId: 'gpt-6.1-sol', effort: 'high' }, + { connectionId: eu.id, modelId: 'gpt-6.1-sol', effort: 'high' }, + { connectionId: local, modelId: 'fixture-local', effort: 'off' }, + ]); + assert.deepEqual( + (await restarted.candidates()).map((access) => [ + access.connectionId, + access.definition.choice.id, + ]), + [ + [global.id, 'gpt-6.1-sol'], + [eu.id, 'gpt-6.1-sol'], + [local, 'fixture-local'], + ], + ); + await assert.rejects( + restarted.setBackups([{ connectionId: local, modelId: 'fixture-missing', effort: 'off' }]), + /Choose an available text model/, + ); + const retired = { connectionId: local, modelId: 'fixture-retired', effort: 'off' as const }; + const sol = { connectionId: global.id, modelId: 'gpt-6.1-sol', effort: 'high' as const }; + await f.database.query('UPDATE model_settings SET backups=$2 WHERE owner_id=$1', [ + ownerId, + JSON.stringify([retired]), + ]); + const stale = await f.create(ownerId, backend); + await stale.setBackups([retired, sol]); + assert.deepEqual(stale.view().backups, [retired, sol]); + await stale.setBackups([sol]); + assert.deepEqual(stale.view().backups, [sol]); + await stale.setBackups([]); + const again = await f.create(ownerId, backend); + assert.deepEqual(again.view().backups, []); + }); + test('OpenAI-compatible servers connect from Models or server settings, and keep their key out of storage', async (t) => { const f = await fixture(t); const { createServer } = await import('node:http'); diff --git a/tests/pi.test.ts b/tests/pi.test.ts index b95fc2cf6..46c58e993 100644 --- a/tests/pi.test.ts +++ b/tests/pi.test.ts @@ -1,5 +1,5 @@ import { lightestEffort, type ModelSelection } from '../src/shared/models.ts'; -import type { Context } from '@earendil-works/pi-ai'; +import type { Context, UserMessage } from '@earendil-works/pi-ai'; import type { ModelAccess } from '../src/ports/models.ts'; import { createPiModelBackend, createPiModelRuntime } from '../src/providers/pi/models.ts'; import type { Presentation } from '../src/shared/presentation.ts'; @@ -10386,6 +10386,426 @@ test('model HTTP failures keep their response status within each request and ret assert.ok(reports.every(({ status }) => status === 'failed')); }); +async function fallbackServer(t: TestContext, answer: (model: string) => number) { + const { createServer } = await import('node:http'); + const requests: string[] = []; + const server = createServer((request, response) => { + const parts: Buffer[] = []; + request.on('data', (part) => parts.push(part)); + request.on('end', () => { + const { model } = JSON.parse(Buffer.concat(parts).toString()) as { model: string }; + requests.push(model); + const status = answer(model); + if (status !== 200) { + response.writeHead(status, { 'content-type': 'application/json' }); + response.end(JSON.stringify({ error: { message: 'Synthetic failure.' } })); + return; + } + response.writeHead(200, { 'content-type': 'text/event-stream' }); + response.end( + `data: ${JSON.stringify({ + id: `fixture-${model}`, + choices: [ + { index: 0, delta: { content: `Answer from ${model}.` }, finish_reason: 'stop' }, + ], + usage: { prompt_tokens: 10, completion_tokens: 5, total_tokens: 15 }, + })}\n\ndata: [DONE]\n\n`, + ); + }); + }); + await new Promise((resolve) => server.listen(0, '127.0.0.1', resolve)); + t.after(() => new Promise((resolve) => server.close(() => resolve()))); + const url = `http://127.0.0.1:${(server.address() as import('node:net').AddressInfo).port}/v1`; + const access = (id: string, cost = 1): ModelAccess => { + const value = smallContextAccess('compatible', id, 131_072); + const pricing = { input: cost, output: cost, cacheRead: 0, cacheWrite: 0 }; + value.definition = { + choice: { ...value.definition.choice, pricing }, + spec: { ...value.definition.spec, baseUrl: url, cost: pricing }, + }; + value.read = async () => ({ type: 'endpoint', url, key: 'fixture-key' }); + return { ...value, connectionId: `fixture-${id}` }; + }; + return { requests, access }; +} + +test('a busy work model gets one retry, then the same request continues on a backup, and a running helper follows', async (t) => { + const { modelPricingSignature } = await import('../src/shared/models.ts'); + const directory = await mkdtemp(join(tmpdir(), 'nod-fallback-turn-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const { requests, access } = await fallbackServer(t, (model) => + model === 'fixture-backup' ? 200 : 503, + ); + const agent = createPiAgent({ + provider: 'compatible', + resolve: async () => [access('fixture-primary'), access('fixture-backup', 5)], + sessionRoot: directory, + createSession: async (options) => { + options?.settingsManager?.applyOverrides({ retry: { baseDelayMs: 1, maxAgentDelayMs: 1 } }); + return createAgentSession(options); + }, + }); + t.after(() => agent.dispose()); + const execution = fakeExecution(randomUUID()); + const open = (extra: object, events: AgentEvent[]) => + agent.open({ + ...execution, + ...extra, + ...sandbox, + systemPrompt: 'Synthetic fixture', + tools: [], + shouldStop: () => false, + onEvent: (event) => events.push(event), + }); + const events: AgentEvent[] = []; + const main = await open({}, events); + const helper = await open( + { sessionId: randomUUID(), runId: randomUUID(), parentRunId: execution.runId }, + [], + ); + await main.prompt('Synthetic question.', []); + assert.deepEqual(requests, ['fixture-primary', 'fixture-primary', 'fixture-backup']); + assert.deepEqual( + events.filter((event) => event.type === 'fallback'), + [{ type: 'fallback', from: 'fixture-primary', to: 'fixture-backup' }], + ); + const usage = events.flatMap((event) => (event.type === 'model_usage' ? [event] : [])); + assert.deepEqual( + usage.map(({ model, status }) => [model, status]), + [ + ['fixture-primary', 'failed'], + ['fixture-primary', 'failed'], + ['fixture-backup', 'succeeded'], + ], + ); + assert.equal( + usage.at(-1)!.pricingSignature, + modelPricingSignature( + { input: 5, output: 5, cacheRead: 0, cacheWrite: 0 }, + 'openai-completions', + ), + ); + assert.ok(events.some((event) => event.type === 'final' && /fixture-backup/.test(event.text))); + + requests.length = 0; + await helper.prompt('Synthetic helper question.', []); + await helper.dispose(); + await main.dispose(); + assert.deepEqual(requests, ['fixture-backup']); +}); + +test('a turn fallback moves on after Pi gives up or at once on request errors, never after output, on a refusal, a Stop or the selected model overflowing, and sends a backup no primary credentials', async () => { + const { createTurnFallback } = await import('../src/providers/pi/fallback.ts'); + const errors: Record = { + busy: '503 Service Unavailable (HTTP 503)', + quota: '429 insufficient_quota: You exceeded your current quota (HTTP 429)', + overflow: 'prompt is too long: 213462 tokens > 131072 maximum', + partial: '503 Service Unavailable (HTTP 503)', + stop: '503 Service Unavailable (HTTP 503)', + refusal: 'The model declined to answer.', + }; + const model = (id: string) => + ({ + provider: 'compatible', + id, + api: 'openai-completions', + input: ['text'], + contextWindow: 131_072, + }) as never; + const choice = (id: string, provider: 'openai' | 'compatible', paused = false): ModelAccess => ({ + provider, + method: 'api_key', + effort: 'off', + read: async () => undefined, + ...(paused + ? { + prepareRequest: async () => { + throw new Error(`${id} is paused.`); + }, + } + : {}), + definition: { + choice: { + id, + name: id, + efforts: ['off'], + images: id === 'fixture-last', + contextWindow: 131_072, + }, + spec: {}, + }, + }); + const setup = (script: Record>, stop?: AbortController) => { + const calls: Array<{ id: string; timeoutMs?: number; credentials: boolean }> = []; + let retrying = false; + const phases = new WeakMap(); + const connection = (id: string) => ({ + model: model(id), + requestFacts: (message: object) => phases.get(message), + runtime: { + streamSimple: ( + _target: never, + _context: never, + options?: { timeoutMs?: number; apiKey?: string; headers?: object }, + ) => { + calls.push({ + id, + timeoutMs: options?.timeoutMs, + credentials: Boolean(options?.apiKey || options?.headers), + }); + const outcome = script[id]!.shift(); + if (outcome === 'stop') stop?.abort(); + const message = { + ...fauxAssistantMessage(outcome ? '' : `Answer from ${id}.`), + provider: 'compatible', + model: id, + api: 'openai-completions', + ...(outcome ? { stopReason: 'error' as const, errorMessage: errors[outcome] } : {}), + } as AssistantMessage; + phases.set(message, { requestPhase: outcome === 'refusal' ? 'stream' : 'response' }); + const stream = createAssistantMessageEventStream(); + if (outcome === 'partial') + stream.push({ type: 'text_delta', contentIndex: 0, delta: 'Part', partial: message }); + stream.push( + outcome + ? { type: 'error', reason: 'error', error: message } + : { type: 'done', reason: 'stop', message }, + ); + stream.end(message); + return stream; + }, + }, + }); + const work = connection('fixture-work'); + const moved: Array<[number, number]> = []; + const fallback = createTurnFallback({ + primary: { + access: choice('fixture-work', 'openai'), + connection: work as never, + stream: work.runtime.streamSimple as never, + }, + backups: [ + choice('fixture-first', 'openai'), + choice('fixture-paused', 'openai', true), + choice('fixture-last', 'compatible'), + ], + start: 0, + automatic: true, + connect: async (backup) => connection(backup.definition.choice.id) as never, + retrying: () => retrying, + shared: () => 0, + switched: () => {}, + moved: (from, to) => moved.push([from, to]), + failed: () => {}, + }); + const send = (retry: boolean, signal?: AbortSignal, content?: UserMessage['content']) => { + retrying = retry; + return fallback + .stream( + work.model, + { messages: content ? [{ role: 'user', content, timestamp: 1 }] : [] }, + { timeoutMs: 1234, signal, apiKey: 'fixture-work-key', headers: { 'x-work': '1' } }, + ) + .result(); + }; + return { calls, moved, fallback, send }; + }; + + const moving = setup({ + 'fixture-work': ['busy', 'busy'], + 'fixture-first': [undefined, 'quota'], + 'fixture-last': [undefined], + }); + assert.equal((await moving.send(true)).stopReason, 'error'); + assert.equal((await moving.send(false)).stopReason, 'stop'); + assert.equal((await moving.send(true)).stopReason, 'stop'); + assert.deepEqual(moving.calls, [ + { id: 'fixture-work', timeoutMs: 1234, credentials: true }, + { id: 'fixture-work', timeoutMs: 1234, credentials: true }, + { id: 'fixture-first', timeoutMs: 1234, credentials: false }, + { id: 'fixture-first', timeoutMs: 1234, credentials: false }, + { id: 'fixture-last', timeoutMs: 1234, credentials: false }, + ]); + assert.deepEqual(moving.moved, [ + [0, 1], + [1, 3], + ]); + + const pictured = setup({ 'fixture-work': ['quota'], 'fixture-last': [undefined] }); + const image = [{ type: 'image' as const, data: 'AA==', mimeType: 'image/png' }]; + assert.equal((await pictured.send(true, undefined, image)).stopReason, 'stop'); + assert.deepEqual( + pictured.calls.map(({ id }) => id), + ['fixture-work', 'fixture-last'], + ); + + const crowded = setup({ + 'fixture-work': ['busy'], + 'fixture-first': ['overflow'], + 'fixture-last': [undefined], + }); + assert.equal((await crowded.send(false)).stopReason, 'stop'); + assert.deepEqual( + crowded.calls.map(({ id }) => id), + ['fixture-work', 'fixture-first', 'fixture-last'], + ); + + for (const outcome of ['overflow', 'partial', 'stop', 'refusal']) { + const stop = new AbortController(); + const staying = setup({ 'fixture-work': [outcome] }, stop); + assert.equal((await staying.send(false, stop.signal)).stopReason, 'error'); + assert.equal(staying.fallback.switched(), false, outcome); + assert.deepEqual( + staying.calls.map(({ id }) => id), + ['fixture-work'], + ); + } +}); + +test('a turn fallback moves a text-only request off a native-audio model and prices each attempt with the model that served it', async () => { + const { createTurnFallback } = await import('../src/providers/pi/fallback.ts'); + const busy = '503 Service Unavailable (HTTP 503)'; + const connection = (provider: string, id: string, input: number, failing: boolean) => { + const model = { + provider, + id, + api: 'openai-completions', + input: ['text'], + contextWindow: 131_072, + cost: { input, output: input, cacheRead: 0, cacheWrite: 0 }, + }; + return { + model, + runtime: { + streamSimple: () => { + const message = { + ...fauxAssistantMessage(failing ? '' : 'Synthetic answer.'), + provider, + model: id, + api: 'openai-completions', + ...(failing ? { stopReason: 'error' as const, errorMessage: busy } : {}), + } as AssistantMessage; + const stream = createAssistantMessageEventStream(); + stream.push( + failing + ? { type: 'error', reason: 'error', error: message } + : { type: 'done', reason: 'stop', message }, + ); + stream.end(message); + return stream; + }, + getModel: () => undefined, + }, + }; + }; + const choice = (provider: 'openai' | 'compatible', id: string): ModelAccess => ({ + provider, + method: 'api_key', + effort: 'off', + read: async () => undefined, + definition: { + choice: { id, name: id, efforts: ['off'], images: false, contextWindow: 131_072 }, + spec: {}, + }, + }); + for (const [provider, id] of [ + ['openai', 'gpt-audio-1.5'], + ['compatible', 'fixture-shared'], + ] as const) { + const work = connection(provider, id, 1, true); + const fallback = createTurnFallback({ + primary: { + access: choice(provider, id), + connection: work as never, + stream: work.runtime.streamSimple as never, + }, + backups: [choice('compatible', 'fixture-shared')], + start: 0, + automatic: false, + connect: async () => connection('compatible', 'fixture-shared', 5, false) as never, + retrying: () => false, + shared: () => 0, + switched: () => {}, + moved: () => {}, + failed: () => {}, + }); + const result = await fallback + .stream(work.model as never, { + messages: [{ role: 'user', content: 'Synthetic question.', timestamp: 1 }], + }) + .result(); + assert.equal(result.stopReason, 'stop'); + assert.equal(fallback.model(result)?.cost.input, 5); + } +}); + +test('an automatic turn starts on the first model that takes automatic requests, or fails with the first reason', async (t) => { + const directory = await mkdtemp(join(tmpdir(), 'nod-fallback-paused-')); + t.after(() => rm(directory, { recursive: true, force: true })); + const { requests, access } = await fallbackServer(t, () => 200); + const turn = async (refused: string[]) => { + const refusing = (id: string): ModelAccess => ({ + ...access(id), + prepareRequest: async (_id, automatic) => { + if (automatic && refused.includes(id)) throw new Error(`Synthetic ${id} is paused.`); + return async () => {}; + }, + }); + const agent = createPiAgent({ + provider: 'compatible', + resolve: async () => [refusing('fixture-primary'), refusing('fixture-backup')], + sessionRoot: directory, + }); + t.after(() => agent.dispose()); + const session = await agent.open({ + ...fakeExecution(randomUUID()), + ...sandbox, + automatic: true, + systemPrompt: 'Synthetic fixture', + tools: [], + shouldStop: () => false, + onEvent: () => {}, + }); + await session.prompt('Synthetic question.', []); + await session.dispose(); + }; + await turn(['fixture-primary']); + assert.deepEqual(requests, ['fixture-backup']); + requests.length = 0; + await assert.rejects( + turn(['fixture-primary', 'fixture-backup']), + /Synthetic fixture-primary is paused/, + ); + assert.deepEqual(requests, []); +}); + +test('recall moves to the next backup after one failed request and reports every attempt', async (t) => { + const { requests, access } = await fallbackServer(t, (model) => + model === 'fixture-backup' ? 200 : 503, + ); + const usage: string[] = []; + const recall = (models: string[]) => + createPiMemoryCurator({ + provider: 'compatible', + resolve: async () => models.map((id) => access(id)), + }).curate( + { task: 'recall', instructions: 'Synthetic recall.', input: {} }, + undefined, + (event) => usage.push(`${event.model}:${event.status}`), + ); + assert.equal(await recall(['fixture-primary', 'fixture-backup']), null); + assert.deepEqual(requests, ['fixture-primary', 'fixture-backup']); + assert.deepEqual(usage, ['fixture-primary:failed', 'fixture-backup:succeeded']); + requests.length = 0; + await assert.rejects(recall(['fixture-primary', 'fixture-other']), /fixture-other/); + assert.deepEqual(requests, [ + 'fixture-primary', + 'fixture-other', + 'fixture-other', + 'fixture-other', + ]); +}); + test('action review failures identify the task, model, provider, and bounded provider reason', async (t) => { const { createServer } = await import('node:http'); const { InMemoryCredentialStore } = await import('@earendil-works/pi-ai'); diff --git a/tests/thread.test.ts b/tests/thread.test.ts index a65862620..d164d5dcb 100644 --- a/tests/thread.test.ts +++ b/tests/thread.test.ts @@ -11461,6 +11461,24 @@ test( reason: /You requested 65536 tokens, but can only afford 2048\./, code: /HTTP 402.*weight_exceeds_budget/, }, + { + prompt: 'model-backups-failed-fixture', + error: + prefix + + ['Primary', 'Backup'] + .map((name) => + JSON.stringify({ + error: { + code: 402, + message: `${name} credits used up.`, + detail: 'synthetic-private-provider-detail', + }, + }), + ) + .join('; then compatible / fixture-backup: '), + reason: /Primary credits used up\..*Backup credits used up\./, + code: /fixture-backup: HTTP 402; Backup credits used up\./, + }, { prompt: 'model-plain-quota-fixture', error: prefix + 'quota_exceeded', diff --git a/tests/usage-time-zone.test.ts b/tests/usage-time-zone.test.ts index 29c294b6c..8fc8813c7 100644 --- a/tests/usage-time-zone.test.ts +++ b/tests/usage-time-zone.test.ts @@ -113,7 +113,13 @@ test('Usage uses the computer time zone for activity and opened logs', async (t) ['/api/trust', view], [ '/api/models', - { connections: [], selection: null, routes: {}, light: null } satisfies ModelsResponse, + { + connections: [], + selection: null, + routes: {}, + backups: [], + light: null, + } satisfies ModelsResponse, ], ['/api/vault/activity', vault], ['/api/vault', []],