Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
76 commits
Select commit Hold shift + click to select a range
8368238
fix: reject unavailable explicit models
anandgupta42 Nov 21, 2026
249d768
fix: mark model resolution guidance for upstream merges
anandgupta42 Nov 21, 2026
9193979
fix: preserve valid restored TUI selections
anandgupta42 Nov 21, 2026
036f575
test: cover CLI model precedence over agent config
anandgupta42 Nov 21, 2026
0fcfdb4
fix: reject empty explicit agent model values
anandgupta42 Nov 21, 2026
aaf5d79
fix: preserve valid session models and align config readers
anandgupta42 Nov 21, 2026
6247df2
fix: preserve shell and command-specific model execution
anandgupta42 Nov 21, 2026
55b5249
fix: preserve TUI config migration precedence
anandgupta42 Nov 21, 2026
cf7a851
fix: keep shell execution independent of model availability
anandgupta42 Nov 21, 2026
f2c1da5
fix: retain legacy TUI migration and verify shared config discovery
anandgupta42 Nov 21, 2026
67bfa15
fix: honor migrated default agent in attached runs
anandgupta42 Nov 21, 2026
889e09a
fix: validate the model used by each submission
anandgupta42 Nov 21, 2026
7a5fae9
fix: preserve TUI drafts and session model selection
anandgupta42 Nov 21, 2026
1abf265
chore: mark session model history customization
anandgupta42 Nov 21, 2026
84f3969
fix: keep picker recovery scoped to the active conversation
anandgupta42 Nov 21, 2026
d7194ce
fix: preserve the attached build agent alias
anandgupta42 Nov 21, 2026
54408c8
fix: validate pasted commands and preserve picker recovery
anandgupta42 Nov 21, 2026
1088905
fix: match command agent aliases and scope picker overrides
anandgupta42 Nov 21, 2026
7c5e531
fix: carry effective models through command execution and follow-ups
anandgupta42 Nov 21, 2026
8cc4a37
fix: keep a session picker after command history restores
anandgupta42 Nov 21, 2026
414ecc5
fix: retain draft edits made during session creation
anandgupta42 Nov 21, 2026
f7261de
fix: preserve model picks and draft mode across conversations
anandgupta42 Nov 21, 2026
1b3dcda
test: assert both command inference requests use the effective model
anandgupta42 Nov 21, 2026
57ad99b
test: exercise the production draft revision during session setup
anandgupta42 Nov 21, 2026
69548eb
fix: preserve command and prompt intent during async setup
anandgupta42 Nov 21, 2026
106ec35
fix: keep explicit effort when session history matches its model
anandgupta42 Nov 21, 2026
d5a0b6a
fix: scope model effort to its conversation
anandgupta42 Nov 21, 2026
2b6e7e2
fix: keep local submissions independent of model and catalog failures
anandgupta42 Nov 21, 2026
b950792
fix: report an unavailable async prompt model once and skip display-o…
anandgupta42 Nov 21, 2026
33898af
fix: suppress only already-reported async model errors and record aut…
anandgupta42 Nov 21, 2026
e144871
fix: track the agent list per workspace and reload catalogs on worksp…
anandgupta42 Nov 21, 2026
ab664dc
fix: report explicit subtask models, retry only gateway failures, kee…
anandgupta42 Nov 21, 2026
70992db
fix: share report-once model validation, keep 5xx retries, and test p…
anandgupta42 Nov 21, 2026
5497a16
test: wait for the subtask model error text, not the echoed model id
anandgupta42 Nov 21, 2026
fbfb838
fix: skip display-only rows in ACP restore and migrate branded TUI ke…
anandgupta42 Nov 21, 2026
32e3144
test: use the Effect instance fixtures for the plan exit and async er…
anandgupta42 Nov 21, 2026
1db0cbf
fix: load TUI config from .altimate-code directories and match loader…
anandgupta42 Nov 21, 2026
71452f8
test: run the new ACP restore tests through the Effect test fixture
anandgupta42 Nov 21, 2026
50f33a8
fix: restore ACP replies only when their parent prompt is in view, an…
anandgupta42 Nov 21, 2026
1f97aee
fix: keep restoring long agent turns whose prompt is beyond the ACP page
anandgupta42 Nov 21, 2026
a21ec26
fix: name project copies with a slug when the configured model is una…
anandgupta42 Nov 21, 2026
f11ff27
test: allow the instance-scoped async error and plan exit tests 30s o…
anandgupta42 Nov 21, 2026
0a3f7a8
fix: log why project copy naming fell back to a slug
anandgupta42 Nov 21, 2026
1a4babb
fix: keep prompt enhancement on the configured provider when its mode…
anandgupta42 Nov 21, 2026
470da1e
fix: name the agent config when a subagent model is unavailable, and …
anandgupta42 Nov 21, 2026
a4daa65
fix: check a subagent model before creating its child session and kee…
anandgupta42 Nov 21, 2026
3303316
refactor: share the unavailable-model message between session and tas…
anandgupta42 Nov 21, 2026
5d7c979
fix: keep the guided model error instead of a second send-failure toa…
anandgupta42 Nov 21, 2026
406b1ea
fix: mark the TUI send-failure guard as altimate code
anandgupta42 Nov 21, 2026
ee0a035
fix: recognise the SDK-wrapped model rejection so the TUI shows one e…
anandgupta42 Nov 21, 2026
1975131
fix: return 400 only for an unavailable model and keep the empty 200 …
anandgupta42 Nov 21, 2026
2640160
fix: keep the failed-subtask child session and relabel its model erro…
anandgupta42 Nov 21, 2026
87e06a4
fix: keep 404 and busy-session statuses on the prompt route
anandgupta42 Nov 21, 2026
4983c4b
fix: explain an empty model value and open the picker for a new user …
anandgupta42 Nov 21, 2026
cb20b9f
refactor: route the submit-time model check through a tested helper
anandgupta42 Nov 21, 2026
8080d94
feat: open the model picker when a submitted configured model is unav…
anandgupta42 Nov 21, 2026
eda34f9
fix: report a subagent or compaction model against its agent config
anandgupta42 Nov 21, 2026
d72498d
fix: scope the unavailable-model picker and advice to sources a pick …
anandgupta42 Nov 21, 2026
d3e00d4
fix: share model-error reporting and one submission-model precedence
anandgupta42 Nov 21, 2026
d2b69a8
fix: tailor unavailable-model advice to whether a pick or config edit…
anandgupta42 Nov 21, 2026
109de66
fix: keep config advice to config sources and report each model error…
anandgupta42 Nov 21, 2026
7975784
fix: check cancellation before subagent model validation and keep pro…
anandgupta42 Nov 21, 2026
5ab7583
docs: describe `markReported` as covering any error already published
anandgupta42 Nov 21, 2026
4dfa517
fix: align command model labels and document per-conversation model p…
anandgupta42 Nov 21, 2026
4f330a9
fix: share the config-source rule across server, CLI and TUI and log …
anandgupta42 Nov 21, 2026
27134fe
fix: keep the subagent model check under its own marker and scope the…
anandgupta42 Nov 21, 2026
84e6023
fix: drop an unread reported mark and scope the picker docs to the ch…
anandgupta42 Nov 21, 2026
8d26b13
fix: open the model picker when a subtask parent chat model is unavai…
anandgupta42 Nov 21, 2026
d62f59a
test: cover request, subtask and session-history sources in CLI error…
anandgupta42 Nov 21, 2026
a8ffdf6
refactor: use one name for the config-source rule and pass picker ori…
anandgupta42 Nov 21, 2026
bf30f08
test: move the configured-default-model regression onto the Effect te…
anandgupta42 Nov 21, 2026
9c70cd4
test: assert the configured default model error names its source
anandgupta42 Nov 21, 2026
70bddb7
fix: bind the subagent trace only after its model check passes
anandgupta42 Nov 21, 2026
15f231d
fix: recheck cancellation after the subagent model lookup
anandgupta42 Nov 21, 2026
6e922e0
test: pin the trace binding for an available subagent model
anandgupta42 Nov 21, 2026
9deb719
test: assert the subagent trace is bound before its prompt runs
anandgupta42 Nov 21, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions docs/docs/configure/config.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,8 @@ Configuration is loaded from multiple sources, with later sources overriding ear
!!! tip
For most projects, create a `altimate-code.json` in your project root or use the `.altimate-code/` directory for a cleaner setup.

Project files named `altimate-code.json`, `altimate-code.jsonc`, `opencode.json`, or `opencode.jsonc` are read from the project root down to the working directory. Within that layer, the nearest directory wins and the branded names override the legacy names. In the later directory-config layer (`.altimate-code/` and `.opencode/`), the legacy names load after the branded names. JSONC overrides JSON for the same name in both layers.

## Minimal Example

```json
Expand Down
2 changes: 1 addition & 1 deletion docs/docs/configure/models.md
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ altimate supports models from all configured providers. Use the `model` and `sma
}
```

The model format is `provider/model-name`.
The model format is `provider/model-name`. In `run`, sessions, and the TUI, an unavailable effective model produces an error instead of silently selecting another provider. Explicit selections include `--model`, the `model` field, agent and command configurations, and a session's recorded model. Only the selection that applies to the request is validated. The order is: a command's own model, then the command's agent, then a model in the request (`--model`), then the agent's configured model, then the session's recorded model, then the `model` field. So a resumed session keeps its model over the `model` field, but not over an agent that sets its own model. Correct that selection or choose an available model. Automatic model selection applies when there is no effective explicit selection. In the TUI, when `--model` or the `model` field sets the model, a model chosen with the picker applies to the current conversation only and does not change your config: a new conversation or a restart uses the configured model again, so update the config to make a choice permanent. Without a configured model, new conversations start on your most recent pick. When a submitted message is rejected because the configured chat model is unavailable, the TUI opens the picker so you can choose one for this conversation; a command that sets its own model shows the error without the picker, since a pick does not override it.

`small_model` handles the small background requests that are not part of the conversation, such as the session title and prompt enhancement. When it is not set, Altimate Code picks a cheap model from the same provider (Claude Haiku, Gemini Flash or GPT-5 nano when the provider lists one) and otherwise uses the chat model. A `small_model` the provider cannot serve, or does not list, fails only those requests: chat keeps working, while new sessions keep their `New session - <time>` placeholder title until a retry succeeds. Altimate Code retries the title on each of the first five messages of a session and reports every failure in telemetry. A failure shows up as a `failed to generate title` line in the log, with the provider's error, and as a `title_generation_failed` telemetry event naming the model that was asked for; correct or remove the `small_model` value to resolve it.

Expand Down
12 changes: 12 additions & 0 deletions packages/core/src/altimate-model-source.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
// altimate_change start — the single definition of a config-backed model source label.
//
// Model selection errors name where the model came from ("config (model)", 'agent "x" config (model)',
// "CLI --model", ...). Server, CLI and TUI all decide from that label whether to point at the config
// files, so the rule lives here once.
export const CONFIG_MODEL_SOURCE_SUFFIX = "config (model)"

/** Whether a source label names a config setting the user can correct. */
export function isConfigModelSource(source: string | undefined) {
return source?.endsWith(CONFIG_MODEL_SOURCE_SUFFIX) === true
}
// altimate_change end
36 changes: 27 additions & 9 deletions packages/opencode/src/acp/service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ import { ProviderV2 } from "@opencode-ai/core/provider"
import { ModelV2 } from "@opencode-ai/core/model"
import { Provider } from "@/provider/provider"
import type { Command } from "@/command"
// altimate_change start — skip display-only model rows when restoring a session
import { ModelMetadata } from "@/altimate/session/model-metadata"
import type { MessageV2 } from "@/session/message-v2"
// altimate_change end
// altimate_change start — keyless public Zen predicate (flat module)
import { isPublicZen } from "@/provider/public-zen"
// altimate_change end
Expand Down Expand Up @@ -226,7 +230,7 @@ export function make(input: {
() => input.sdk.session.messages({ directory: params.cwd, sessionID: params.sessionId }, { throwOnError: true }),
"session",
)
const restored = restoreFromMessages(messages.map((item) => item.info))
const restored = restoreFromMessages(messages)
// altimate_change start — fail closed when a legacy session has no usable model and do not pair a fallback with stale effort
const restoredModel = availableModel(snapshot, restored.model)
const model = restoredModel ?? (yield* requireDefaultModel(snapshot))
Expand Down Expand Up @@ -317,7 +321,7 @@ export function make(input: {
),
"session",
)
const restored = restoreFromMessages(messages.map((item) => item.info))
const restored = restoreFromMessages(messages)
// altimate_change start — fail closed when a resumed session has no usable model and do not pair a fallback with stale effort
const restoredModel = availableModel(snapshot, restored.model)
const model = restoredModel ?? (yield* requireDefaultModel(snapshot))
Expand Down Expand Up @@ -387,7 +391,7 @@ export function make(input: {
),
"session",
)
const sourceRestored = restoreFromMessages(sourceMessages.map((item) => item.info))
const sourceRestored = restoreFromMessages(sourceMessages)
const fallbackModel = availableModel(snapshot, sourceRestored.model) ?? (yield* requireDefaultModel(snapshot))
// altimate_change end
const forked = yield* request(
Expand All @@ -406,7 +410,7 @@ export function make(input: {
input.sdk.session.messages({ directory: params.cwd, sessionID: forked.id, limit: 20 }, { throwOnError: true }),
"session",
)
const restored = restoreFromMessages(messages.map((item) => item.info))
const restored = restoreFromMessages(messages)
// altimate_change start — fail closed when a fork has no usable model and do not pair a fallback with stale effort
const restoredModel = availableModel(snapshot, restored.model)
const model = restoredModel ?? fallbackModel
Expand Down Expand Up @@ -738,6 +742,9 @@ type SdkResponse<T> = {
}

type MessageInfo = {
// altimate_change — ids link an assistant reply to the user row that produced it
readonly id?: string
readonly parentID?: string
readonly role?: Message["role"]
readonly model?: Extract<Message, { role: "user" }>["model"]
readonly providerID?: Extract<Message, { role: "assistant" }>["providerID"]
Expand Down Expand Up @@ -1204,10 +1211,16 @@ function stableStringify(value: unknown): string {
.join(",")}}`
}

function restoreFromMessages(messages: readonly MessageInfo[]) {
const user = messages.findLast(
(message) => message.role === "user" && message.model?.providerID && message.model.modelID,
)
// altimate_change start — shell and direct MCP rows record a display-only model; restore skips them
function restoreFromMessages(items: readonly { info: MessageInfo; parts?: readonly unknown[] }[]) {
const messages = items.map((item) => item.info)
const isDisplayOnly = (item: (typeof items)[number]) =>
item.info.role === "user" && ModelMetadata.isModelMetadataOnly((item.parts ?? []) as MessageV2.Part[])
const displayOnly = new Set(items.filter(isDisplayOnly).flatMap((item) => (item.info.id ? [item.info.id] : [])))
const user = items.findLast(
(item) => item.info.role === "user" && item.info.model?.providerID && item.info.model.modelID && !isDisplayOnly(item),
)?.info
// altimate_change end
if (user?.model?.providerID && user.model.modelID) {
return {
model: { providerID: user.model.providerID as ProviderV2.ID, modelID: user.model.modelID as ModelV2.ID },
Expand All @@ -1216,7 +1229,12 @@ function restoreFromMessages(messages: readonly MessageInfo[]) {
}
}

const assistant = messages.findLast((message) => message.providerID && message.modelID)
// altimate_change — replies to display-only rows carry the same display-only model
const assistant = messages.findLast(
// Agent steps all point at one prompt that may sit beyond the fetched page, so only replies known
// to answer a display-only row are skipped.
(message) => message.providerID && message.modelID && !(message.parentID && displayOnly.has(message.parentID)),
)
if (assistant?.providerID && assistant.modelID) {
return {
model: { providerID: assistant.providerID as ProviderV2.ID, modelID: assistant.modelID as ModelV2.ID },
Expand Down
7 changes: 4 additions & 3 deletions packages/opencode/src/agent/agent.ts
Original file line number Diff line number Diff line change
Expand Up @@ -603,15 +603,16 @@ export const layer = Layer.effect(
options: {},
native: false,
}
if (value.model) {
// altimate_change start — re-brand fork ProviderID/ModelID to core ProviderV2.ID/ModelV2.ID (identity at runtime)
// altimate_change start — upstream_fix: retain an empty explicit model so resolution can reject it
if (value.model !== undefined) {
Comment thread
anandgupta42 marked this conversation as resolved.
Resolved
// Re-brand fork ProviderID/ModelID to core ProviderV2.ID/ModelV2.ID (identity at runtime).
const parsed = Provider.parseModel(value.model)
item.model = {
providerID: ProviderV2.ID.make(parsed.providerID),
modelID: ModelV2.ID.make(parsed.modelID),
}
// altimate_change end
}
// altimate_change end
item.variant = value.variant ?? item.variant
item.prompt = value.prompt ?? item.prompt
item.description = value.description ?? item.description
Expand Down
3 changes: 2 additions & 1 deletion packages/opencode/src/altimate/debug/collect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import { env as flagEnv, truthy as flagTruthy } from "@opencode-ai/core/flag/fla
import { Global } from "@opencode-ai/core/global"
import { InstallationVersion } from "@opencode-ai/core/installation/version"
import { resolveInstall } from "@/installation"
import { projectConfigNames } from "@/config/paths"
import { Telemetry } from "@/altimate/telemetry"
import { AltimateApi } from "@/altimate/api/client"
import * as Registry from "@/altimate/native/connections/registry"
Expand Down Expand Up @@ -236,7 +237,7 @@ export function configFiles(src: ConfigSources): string[] {
? []
: upwards(src.cwd, root)
.reverse()
.flatMap((d) => [path.join(d, "opencode.json"), path.join(d, "opencode.jsonc")])),
.flatMap((d) => projectConfigNames.map((name) => path.join(d, name)))),
...[...new Set(configDirs)].flatMap(inDir),
]
}
Expand Down
11 changes: 10 additions & 1 deletion packages/opencode/src/altimate/enhance-prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -88,7 +88,16 @@ export async function enhancePrompt(text: string): Promise<string> {
const timeout = setTimeout(() => controller.abort(), ENHANCE_TIMEOUT_MS)

try {
const defaultModel = await Provider.defaultModel()
// Enhancement needs only a provider; an unavailable configured model still names one.
const defaultModel = await Provider.defaultModel().catch(async (error) => {
const configured = (await Config.get()).model
if (!configured) throw error
Comment thread
anandgupta42 marked this conversation as resolved.
Resolved
log.warn("configured model unavailable; enhancing with its provider's small model", {
model: configured,
error: Provider.ModelNotFoundError.isInstance(error) ? error.name : String(error),
})
return Provider.parseModel(configured)
Comment thread
anandgupta42 marked this conversation as resolved.
Resolved
})
const model =
(await Provider.getSmallModel(defaultModel.providerID)) ??
(await Provider.getModel(defaultModel.providerID, defaultModel.modelID))
Expand Down
3 changes: 2 additions & 1 deletion packages/opencode/src/altimate/learn/project-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import path from "node:path"
import { parse } from "jsonc-parser"
import * as SafeFS from "./safe-fs"
import { Flag } from "@opencode-ai/core/flag/flag"
import { projectConfigNames } from "@/config/paths"

/**
* The highest-precedence existing project config file, from `directory` up to `root`, and its text; the default
Expand All @@ -21,7 +22,7 @@ export async function projectConfigFile(root: string, directory: string): Promis
for await (const dir of Filesystem.up({ targets: [".altimate-code", ".opencode"], start: directory, stop: root }))
directories.push(dir)
const candidates = directories.reverse().flatMap((dir) => names.map((name) => path.join(dir, name)))
for await (const file of Filesystem.up({ targets: ["opencode.jsonc", "opencode.json"], start: directory, stop: root }))
for await (const file of Filesystem.up({ targets: projectConfigNames.toReversed(), start: directory, stop: root }))
candidates.push(file)
let file = path.join(root, ".altimate-code", "altimate-code.json")
let text = "{}\n"
Expand Down
37 changes: 37 additions & 0 deletions packages/opencode/src/altimate/provider/model-hint.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,47 @@
// altimate_change - new file
import { isConfigModelSource } from "@opencode-ai/core/altimate-model-source"
//
// Extra guidance for a "Model not found" error. The Anthropic provider lost its Claude Pro/Max sign-in
// in 0.12.11, so a saved `anthropic/...` model with only that login now fails to resolve; the bare
// error gave no reason. Only a missing provider gets the hint: an Anthropic provider that is there
// with an unknown model name needs a different model, not a key.
export const modelConfigHint =
"Check the provider and model in your project config (altimate-code.json or opencode.json, including .jsonc files, at the project root or in .altimate-code/ or .opencode/) or global config (~/.config/altimate-code/)."

export function modelNotFoundHint(providerID: string | undefined, providerMissing: boolean | undefined) {
if (providerID !== "anthropic" || providerMissing !== true) return undefined
return "The Anthropic provider needs an API key. For a Claude Pro or Max plan, run /connect and pick Claude subscription."
}

/** Whether to point at the config files: a config setting chose the model, or the source is unknown. */
export function showsConfigHint(source: string | undefined) {
return source === undefined || isConfigModelSource(source)
}

export function modelNotFoundMessage(providerID: string | undefined, modelID: string | undefined, source?: string) {
const sourceHint = source ? ` (from ${source})` : ""
if (!modelID) {
const empty = providerID ? `Empty model name in "${providerID}/"${sourceHint}` : `Empty model value${sourceHint}`
// An environment variable that is not set substitutes to "", the usual cause of an empty config value.
if (isConfigModelSource(source))
return `${empty}: the model key is incomplete. If it references an environment variable such as "\${ALTIMATE_MODEL}", check that the variable is set; otherwise set a provider/model-name value or remove the key.`
return `${empty}. Use a provider/model-name value.`
}
return `Model not found: ${providerID}/${modelID}${sourceHint}`
}

// Full user-facing text for an unavailable model: the source-named line, suggestions, provider
// guidance and where to correct the config.
export function modelSelectionErrorText(data: {
providerID?: string
modelID?: string
source?: string
suggestions?: readonly string[]
providerMissing?: boolean
}) {
const message = modelNotFoundMessage(data.providerID, data.modelID, data.source)
const hint = data.suggestions?.length ? ` Did you mean: ${data.suggestions.join(", ")}?` : ""
const guidance = modelNotFoundHint(data.providerID, data.providerMissing)
const where = showsConfigHint(data.source) ? ` ${modelConfigHint}` : ""
return `${message.endsWith(".") ? message : message + "."}${hint}${guidance ? ` ${guidance}` : ""}${where}`
}
27 changes: 27 additions & 0 deletions packages/opencode/src/altimate/session/model-metadata.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import type { MessageV2 } from "../../session/message-v2"

const SHELL_MARKER = "The following tool was executed by the user"

// Shell and direct MCP commands record a model on their user row for display only; model
// resolution must skip those rows instead of treating them as a model choice.
export function isModelMetadataOnly(parts: readonly MessageV2.Part[]) {
return parts.some(
(part) =>
part.type === "text" &&
(part.metadata?.modelMetadataOnly === true || (part.synthetic === true && part.text === SHELL_MARKER)),
)
}

const reported = new WeakSet<object>()

// Record that the session already received an error event for this error (an unavailable model or an
// unknown agent), so a route that catches it does not publish it again.
export function markReported(error: unknown) {
if (typeof error === "object" && error !== null) reported.add(error)
}

export function wasReported(error: unknown) {
return typeof error === "object" && error !== null && reported.has(error)
}

export * as ModelMetadata from "./model-metadata"
40 changes: 40 additions & 0 deletions packages/opencode/src/altimate/session/model-report.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { NamedError } from "@opencode-ai/core/util/error"
import { Bus } from "../../bus"
import { Session } from "../../session"
import { Provider, validateModelSelection } from "../../provider/provider"
import type { ModelID, ProviderID } from "../../provider/schema"
import type { SessionID } from "../../session/schema"
import { modelSelectionErrorText } from "../provider/model-hint"
import { ModelMetadata } from "./model-metadata"
import { Log } from "../../util/log"

const log = Log.create({ service: "model-report" })

// Publish an error event the client relies on (the route may not publish it again); a failed publish
// must still leave a trace.
export function publishReported(sessionID: SessionID, error: InstanceType<typeof NamedError.Unknown>) {
void Bus.publish(Session.Event.Error, { sessionID, error: error.toObject() }).catch((cause) =>
log.warn("session error event not published", { sessionID, cause }),
)
}

// Publish guided text for an unavailable model once, marking the error so routes don't repeat it.
export function reportModelSelectionError(sessionID: SessionID, error: unknown) {
if (!Provider.ModelNotFoundError.isInstance(error)) return
ModelMetadata.markReported(error)
publishReported(sessionID, new NamedError.Unknown({ message: modelSelectionErrorText(error.data) }))
}

// Validate a selected model, publishing guided text once and rethrowing the same error instance.
export async function validateOrReport(
sessionID: SessionID,
model: { providerID: ProviderID; modelID: ModelID },
source: string,
) {
return validateModelSelection(model, source).catch((error) => {
reportModelSelectionError(sessionID, error)
throw error
})
}

export * as ModelReport from "./model-report"
Loading
Loading