Skip to content
Developer Preview

Handle errors by class

A request came back with error where you expected result. Do you send it again, show it to your user, or stop? This page gives you one small function that answers that for every error the host can send, then plays five real errors from the committed transcripts through it so you can see each answer on the wire.

The one idea to take away: every error has a data.kind, and every kind has exactly one next move. Branch on the kind, never on the message text, and the whole catalogue collapses into three classes.

The error envelope itself is described in the errors guide, and the error reference has one page per code; this is the executable version.

Two members of error.data decide what you do next: kind, always present, and retryable, present when the host wants to be explicit.

  • Retryable. Nothing was admitted, so the same command may go again, under the same commandId, after a backoff. The move is retry. overloaded and backpressured live here by default, and the SDK performs this retry for you when you pass maxAttempts. Any error whose retryable is true joins the class, whatever its kind, even a kind your table has never seen.
  • User-facing. The host answered your user’s intent with a durable no. The move is tellTheUser: show the answer, give the user their words back, and do not resend, because the same commandId gets the same answer. A new intent needs a new id. commandRejected is the archetype, with its snake_case data.reason.
  • Terminal. The request, as sent, is over, and no resend will change that. What you do instead depends on why:
    • reconnect, when the connection itself lacks something that is only granted at the handshake: capabilityRequired and experimentalRequired.
    • resync, when the position you asked from no longer exists on the host, or the answer lives on the session view rather than in this response: a notFound with reason: "missingAnchor", viewTruncated, the compaction-boundary kinds, a stale approval or prompt id, a request pre-empted by interrupted or cancelled. Reopen from what the host still serves and read the view.
    • stop, when the request violates a precondition or is a bug in your client: invalidParams, methodNotFound, internal, and the rest. Surface it, fix the request, and do not loop on it.

Here is the function, with the whole catalogue as its table. In TypeScript the table is typed over the generated ErrorKind union, so a kind the table forgets is a compile error; in Python the recipe checks the same thing at run time against the wire package’s list of known kinds.

import { MspError } from "@muse-code/sdk";
import type { ErrorKind } from "@muse-code/msp";
export type ClientMove = "retry" | "tellTheUser" | "reconnect" | "resync" | "stop";
// One row per kind. The compiler refuses this table when a kind is missing.
export const CLIENT_MOVE: Record<ErrorKind, ClientMove> = {
// Retryable: nothing was admitted; the same commandId may go again.
overloaded: "retry",
backpressured: "retry",
approvalBrokerUnavailable: "retry",
// User-facing: a durable answer to the user's intent.
commandRejected: "tellTheUser",
sessionNotFound: "tellTheUser",
sessionInUse: "tellTheUser",
sessionAmbiguous: "tellTheUser",
forkBoundaryInvalid: "tellTheUser",
skillNotFound: "tellTheUser",
marketplaceNotFound: "tellTheUser",
pluginNotFound: "tellTheUser",
marketplaceAlreadyExists: "tellTheUser",
pluginMutationsDisabled: "tellTheUser",
uploadNotFound: "tellTheUser",
outputUnavailable: "tellTheUser",
approvalAlreadyResolved: "tellTheUser",
approvalReviewerUnavailable: "tellTheUser",
userInputAlreadySettled: "tellTheUser",
userInputAnswerInvalid: "tellTheUser",
// Terminal, reconnect: granted only at the handshake.
capabilityRequired: "reconnect",
experimentalRequired: "reconnect",
// Terminal, resync: the position is gone, or the answer is on the view.
viewTruncated: "resync",
boundaryPruned: "resync",
boundaryUnusable: "resync",
noBoundary: "resync",
interrupted: "resync",
cancelled: "resync",
approvalNotFound: "resync",
approvalRequirementStale: "resync",
approvalResolving: "resync",
userInputNotFound: "resync",
// Terminal, stop: a precondition or a client bug; fix the request.
parseError: "stop",
invalidRequest: "stop",
notInitialized: "stop",
alreadyInitialized: "stop",
methodNotFound: "stop",
invalidParams: "stop",
internal: "stop",
pageEventTooLarge: "stop",
outputResultTooLarge: "stop",
inputTooLarge: "stop",
notFound: "stop", // a missing view anchor becomes "resync" below
sessionNotLoaded: "stop",
sessionStreamMismatch: "stop",
computerUseUnavailable: "stop",
approvalChoiceInvalid: "stop",
};
export function classify(error: MspError): ClientMove {
// An explicit retryable from the host outranks the table.
if (error.retryable === true) return "retry";
if (error.kind === "notFound" && error.data["reason"] === "missingAnchor") return "resync";
// A newer host can send a kind this table has never seen: terminal until
// you learn it, unless the host marked it retryable above.
const known: Readonly<Partial<Record<string, ClientMove>>> = CLIENT_MOVE;
const move = known[error.kind] ?? "stop";
return move === "retry" && error.retryable === false ? "stop" : move;
}

Two rows deserve a word. notFound covers a run, an item, a subscription or a view anchor; only the anchor case is a resync, which is why the function reads data.reason before it reads the table. And approvalBrokerUnavailable sits with the retryable pair because the host marks it so: the approval stays pending while you retry.

The recipe behind this page spawns a canned host on five committed transcripts and sends the request each one records. Every arm asserts the kind, the code, the members the kind promises, and the move the function returns. Here is each answer as it crosses the wire. One class is taught and not played: no committed transcript produces overloaded or backpressured, and you do not write that retry yourself, because Connection.command retries both under the same commandId with a jittered backoff when you pass maxAttempts, as the backpressure guide and the retry page describe.

The client never asked for userShell at the handshake, then calls a method that needs it:

{"dir":"client","raw":"{\"jsonrpc\":\"2.0\",\"id\":\"a1\",\"method\":\"session/userShell\",\"params\":{\"sessionId\":\"0198f0aa-1111-7000-8000-0000000000aa\",\"commandId\":\"018f6a24-9999-7bbb-8ccc-00000000feed\",\"commandText\":\"git status\"}}"}
{"dir":"server","raw":"{\"error\":{\"code\":-32010,\"data\":{\"capability\":\"userShell\",\"kind\":\"capabilityRequired\",\"retryable\":false},\"message\":\"session/userShell requires the userShell capability\"},\"id\":\"a1\",\"jsonrpc\":\"2.0\"}"}

capabilityRequired is terminal for this connection, and data.capability names what was missing. Grants happen only at the handshake, so the move is reconnect: spawn again and ask for the capability this time.

import { MspError, MuseClient } from "@muse-code/sdk";
try {
await msp.connection.command("session/userShell", { sessionId, commandText: "git status" }, { maxAttempts: 1 });
} catch (error) {
if (!(error instanceof MspError) || classify(error) !== "reconnect") throw error;
// Granted only at the handshake: spawn a client that asks for it.
const capability = String(error.data["capability"]);
const granted = await MuseClient.spawn({
args: ["serve"],
clientInfo: { name: "my_app", version: "1.0.0" },
capabilities: { requestedCapabilities: [capability] },
});
}

A client resumes with a cursor it made up, or kept from another host:

{"dir":"client","raw":"{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"session/resume\",\"params\":{\"commandId\":\"0198f0ab-8888-7000-8000-0000000000c4\",\"sessionId\":\"0198f0aa-1111-7000-8000-0000000000aa\",\"cursor\":\"v11:0198f0aa-2222-7000-8000-0000000000bb:9\"}}"}
{"dir":"server","raw":"{\"jsonrpc\":\"2.0\",\"id\":9,\"error\":{\"code\":-32011,\"message\":\"this cursor is not valid on this host; reopen without a cursor: session/resume, or a forward view/page if session/resume is unavailable\",\"data\":{\"kind\":\"notFound\",\"reason\":\"missingAnchor\",\"sessionId\":\"0198f0aa-1111-7000-8000-0000000000aa\"}}}"}

notFound with reason: "missingAnchor" is the one notFound that means your position, not your reference, is wrong. The move is resync: resume the same session without a cursor and let the host serve the view from its own earliest point.

A client comes back after a long absence with a cursor the host has since compacted past:

{"dir":"client","raw":"{\"jsonrpc\":\"2.0\",\"id\":9,\"method\":\"session/resume\",\"params\":{\"commandId\":\"0198f0ab-8888-7000-8000-0000000000c3\",\"sessionId\":\"0198f0aa-1111-7000-8000-0000000000aa\",\"cursor\":\"v11:0198f0aa-1111-7000-8000-0000000000aa:3\"}}"}
{"dir":"server","raw":"{\"jsonrpc\":\"2.0\",\"id\":9,\"error\":{\"code\":-32040,\"message\":\"requested range predates the retained view\",\"data\":{\"kind\":\"viewTruncated\",\"sessionId\":\"0198f0aa-1111-7000-8000-0000000000aa\",\"earliestCursor\":\"v11:0198f0aa-1111-7000-8000-0000000000aa:200\"}}}"}

viewTruncated carries data.earliestCursor, the oldest position the host can still serve. The move is resync again, and this time the error says where from: drop what you cached before that cursor and resume from it. One handler covers both cursor answers:

try {
await msp.connection.command("session/resume", { sessionId, cursor }, { maxAttempts: 1 });
} catch (error) {
if (!(error instanceof MspError) || classify(error) !== "resync") throw error;
// Resume from what the host still serves: its earliest cursor when it
// names one, otherwise from the beginning.
const earliest = error.data["earliestCursor"];
await msp.connection.command(
"session/resume",
typeof earliest === "string" ? { sessionId, cursor: earliest } : { sessionId },
{ maxAttempts: 1 },
);
}

The user pauses a goal in a session that has none:

{"dir":"client","raw":"{\"jsonrpc\":\"2.0\",\"id\":3,\"method\":\"goal/pause\",\"params\":{\"sessionId\":\"0198f0aa-1111-7000-8000-0000000000aa\",\"commandId\":\"018f6a22-400f-7000-8000-00000000d00f\"}}"}
{"dir":"server","raw":"{\"jsonrpc\":\"2.0\",\"id\":3,\"error\":{\"code\":-32030,\"message\":\"goal/pause command 018f6a22-400f-7000-8000-00000000d00f rejected: missing_goal\",\"data\":{\"kind\":\"commandRejected\",\"commandId\":\"018f6a22-400f-7000-8000-00000000d00f\",\"reason\":\"missing_goal\",\"retryable\":false}}}"}

commandRejected is the user-facing class in one frame: data.reason is a stable snake_case word, retryable is false, and replaying the same commandId answers the same rejection. The move is tellTheUser: say that there is no goal to pause, and leave the composer as it was. The retry page shows how a durable rejection retires a pending entry and hands the input back.

A failure that is not a request error at all

Section titled “A failure that is not a request error at all”

The last arm sends a turn/start that the host accepts, and the failure arrives later, on the session view:

{"dir":"server","raw":"{\"emittedAtMs\":1754592400000,\"jsonrpc\":\"2.0\",\"method\":\"turn/completed\",\"params\":{\"error\":{\"kind\":\"modelError\",\"message\":\"model failed after 3 attempts: provider returned 503 service_unavailable\",\"retryable\":true},\"reason\":\"model failed after 3 attempts: provider returned 503 service_unavailable\",\"sessionId\":\"018f7294-0000-7000-8000-5f0e73500000\",\"sourceRange\":{\"first\":{\"id\":\"018f7294-0000-7000-8000-5f0e73500113\",\"sequence\":15},\"last\":{\"id\":\"018f7294-0000-7000-8000-5f0e73500113\",\"sequence\":15},\"stream\":{\"id\":\"018f7294-0000-7000-8000-5f0e73500000\",\"kind\":\"session\"}},\"terminal\":\"failed\",\"turnId\":\"018f7294-0000-7000-8000-5f0e73500105\",\"viewCursor\":\"v11:018f7294-0000-7000-8000-5f0e73500000:9\"}}"}

Nothing here is an error response. The request was acknowledged, the turn ran, and the model failed. Mid-turn failures surface as a turn/completed with terminal: "failed" and a settled error object, so your error handling has two layers: the typed request errors above, and turn terminals on the view. The terminal’s error.retryable is the hint, and the move is a new turn with a new commandId, because the failed turn is over:

{"dir":"client","raw":"{\"id\":4,\"jsonrpc\":\"2.0\",\"method\":\"turn/start\",\"params\":{\"commandId\":\"018f7294-0000-7000-8000-5f0e73500114\",\"input\":[{\"text\":\"try again\",\"type\":\"text\"}],\"sessionId\":\"018f7294-0000-7000-8000-5f0e73500000\"}}"}
{"dir":"server","raw":"{\"id\":4,\"jsonrpc\":\"2.0\",\"result\":{\"commandId\":\"018f7294-0000-7000-8000-5f0e73500114\",\"disposition\":\"started\",\"startedNewTurn\":true,\"status\":\"accepted\",\"turnId\":\"018f7294-0000-7000-8000-5f0e73500114\"}}"}
msp.connection.onNotification((notification) => {
if (notification.method !== "turn/completed") return;
const params = notification.params ?? {};
if (params["terminal"] !== "failed") return;
const error = params["error"] as { kind?: string; retryable?: boolean } | undefined;
if (error?.retryable === true) {
// The turn is over; the retry is a NEW turn under a NEW commandId.
offerRetry(params["turnId"]);
} else {
showFailure(error?.kind);
}
});

The recipe plays exactly that: the first turn fails with modelError and retryable: true; the second, a new intent under a new id, completes.

You need Node 20 or newer and the SDK your own application depends on, npm install @muse-code/sdk. This recipe never spawns a real host, so an installed muse is not part of it. The recipe programs live in the SDK repository:

Terminal window
git clone https://github.com/meta-models/muse-code-sdk
cd muse-code-sdk
npm ci && npm run build --workspace @muse-code/sdk
npm run recipes --workspace @muse-code/sdk-cookbook -- --only handle-errors-by-class

This recipe replays committed transcripts through a canned host, so it needs no credentials and no model. The canned host is a conformance fixture that is not published yet, so the command above reports the recipe as needing a host it cannot find. Until that fixture ships, the verified program on this page is the complete source of truth. The recipes that need only a real muse host, the fingerprint check, surviving a host crash and switching models mid-session, run end to end today.

One detail in that source is test plumbing rather than guidance: the recipe passes each transcript’s recorded commandId explicitly, because the canned host matches the frames it is sent against the ones it recorded. Against a real host the SDK mints every commandId, and the function never reads it.

The runnable source for this page is published in full, comments and all, as the handle-errors-by-class example. It is the source that runs, not a retelling of it: it is executed end to end on every change to this area, and every docs build checks the wire frames above against the committed transcripts, so this page cannot drift.