Files
magpie/internal/provider/commandcode_plan.go
T
Junjie Zhouandmultica-agent 12d823211e provider: a multi-protocol provider's model catalog keeps every endpoint's models (#1006)
* provider: a multi-protocol provider's catalog is the union of every endpoint's models

A provider whose protocols sit at bases of their own kept only the first
list that answered, so the models of every other endpoint were nowhere in
the product: not in the agents' model lists, not in the catalog the routing
and the per-model preferences read, and not fixable by pinning a model's
protocol, which setModelAPI refuses for a model the provider does not list.
nyownm reported it as #904 and worked around it with one provider per
protocol.

fetchOne now asks every endpoint the provider speaks and merges the lists
by model id, the way fetchPerKey merges the lists of a vendor's keys: the
first list's fields stand, and an image capability both lists answer is
merged. The base kept is still the first protocol's, the one the drawer
list is fetched beside and the models are saved with. A models URL is
still asked alone, one base two protocols share is still asked once, and
a provider with no endpoint answering still fails with every URL it asked
named in the error.

Verified with go test -tags nogui ./internal/provider ./internal/catalog
and ./internal/gateway ./internal/agent, all green. TestFetchUnionsProtocolLists
and TestFetchUnionsProtocolListsWithoutChat fail on the base commit with
the single list the first protocol answered.

* provider: an endpoint that can't be asked keeps the models it listed

A provider whose protocols sit at bases of their own is asked every base
and the lists are merged, so one read that failed saved the union of the
rest as the whole list: the models of the failed base read as gone,
dropGonePicks took them out of the user's picks and stored that, and
nothing brought them back when the endpoint recovered (yetone's review of
#1006, on nyownm's #904). A read that failed says nothing about what the
vendor serves today, the rule fetchPerKey's keys already follow.

fetchOne keeps what each base listed and saves it beside the merged list,
in a new "sides" part of the catalog's live file, and a base it could not
ask takes its own part back for that fetch. What is kept is that base's own
models alone: a model the bases that answered have dropped is dropped here
too, however many of them dropped it and however many bases are down.
Keeping the whole list saved before would bring such a model back, which is
the same fault the other way round. A list saved before this kept no parts,
so a base whose part is missing keeps what no answering base lists, until
the next fetch with every base answering says which they are.

The parts are kept only where more than one base was asked: a single one
that fails is the fetch that fails, and its list is kept as it is, so a
provider of one protocol's cache is the file it was.

fetchOne answers one fetched list now — the models, the base kept for
routing, the parts — rather than three values. fetchPerKey marks the parts
with the keys that saw them, and keeps a plan's own models out of them.

Verified with go test ./internal/provider ./internal/catalog, all green,
and ./internal/gateway ./internal/agent.
TestFetchKeepsTheModelsAFailedProtocolListed,
TestFetchDropsAGoneModelWhileAnotherProtocolFails and
TestFetchKeepsTheModelsAFailedProtocolListedPerKey fail on 952d0b00 with
the model of the failed protocol taken out of the picks.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that never answered keeps nothing, and is not saved as one that listed nothing

keepDeadSides read a part missing from the saved sides as the whole list
saved before, and kept what no answering base lists from it. Two things
were wrong with that, and both were reported on #1006 (nyownm's #904):

A base in none of the saved parts is one that has never answered. The
whole list is not its own, so a model its vendor had already dropped was
kept for it, and the keepDeadSides result was saved as sides[base] —
from then on that base had a part, and the model could never be dropped
again. An Anthropic base answering 404 from the start of a provider's
life was enough: one round after the Chat base dropped a model, that
model stayed in the catalog, and dropGonePicks could not take it out of
the user's picks.

The saving is the other half of the same fault. A part is what a base
listed, so one that never answered has none, and writing an empty one
fixes the reading of "never answered" as "listed nothing" for good. Only
a part read out of the file is written back; the list saved without any
parts at all — before this kept them — is the one case where a base may
stand in for a missing part, and what it stands in for is kept for that
fetch alone, never saved as its own.

So keepDeadSides answers two lists now: the models this fetch's list is
made of, and the parts to write beside it. fetchPerKey keeps a model a
key that could not be asked at all owns to the bases that listed it,
read out of the parts saved beside the list: kept as a whole list with
no part saying where it came from it belonged to no base, and was read
as gone the first time that key answered half-way — the same permanent
deletion of a picked model, one round later and needing no new base.

Verified with go test ./internal/provider ./internal/catalog
./internal/gateway ./internal/agent, all green, and -race -count=3 over
./internal/provider with the four failures it already had.
TestFetchDropsAModelWhileAnEndpointHasNeverAnswered and
TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole fail on 6621f73e.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that answered without a model does not keep owning it

fetchPerKey gave every model kept for a key that could not be asked at all
to the bases that listed it last time, and a part there said what the
bases listed when one of them had answered this round without it (yetone's
review of #1006, nyownm's #904). With two keys where both were served a
Claude model, and the Anthropic base stopping both of them in the round
the second key was down, sides[anthropic] kept a model the base had
plainly dropped, and the fetch after that read it as a base that couldn't
be asked and held the model one round longer than it should have. It is
self-healing — the next round with the base answering settles it — and it
is the same fault c8fabd70 was written to undo, read from the other side.

sides may only say what the bases listed. A model kept for a failed key
belongs to a base that was not asked this round for any of the model's own
keys: one that was, and answered without the model, has said what it
serves today and no longer owns it. Which is per key, not per provider:
fetchOne answers which of its bases replied, which a model of the second
key alone never saw an answer from, so the base's saying nothing about it
for the first key leaves it that base's. The keys a model is kept under
are read from the list saved before, since add clears the ones of the model
it is adding.

TestFetchDropsAModelABaseStoppedServingWhileAKeyIsDown fails on c8fabd70
with the part holding claude-b, and TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole
goes on passing: the same two keys, a model only one of them sees.

Co-authored-by: multica-agent <github@multica.ai>

* provider, catalog: a page of a model list is not the list (#904)

A /v1/models that answers with has_more is one page of the vendor's
catalog. Read as the whole list, every model of a later page reads as one
the vendor has dropped, and the user's pick of it goes for good, on a
list that never said so. Such a reply is no answer: the base is treated
as one that could not be asked, which keeps what it listed last time
(#904's review of #1006).

OpenRouter's Anthropic base is not asked for the list at all. With the
Anthropic version header its /models answers with the catalog again,
twenty newest first, every id namespaced under `anthropic/`, and the
cursors of the pages after. None of those twenty is an id in OpenRouter's
own catalog, so merged they are entries of the model picker that name no
model: the long, cluttered list #904's reporter wrote of. Its Chat base
is that catalog, whole, and the fetch is one request where it was two.
The rule is OpenRouter's, by host, as the ones after it are scoped to
their vendors.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the OpenRouter rule reads the base being asked (0fb16990)

It read the Chat base's host, so a provider with a Chat base of
OpenRouter's and an Anthropic base of another vendor's had that other
base skipped: its models were in neither the union nor the sides nor the
bases that could not be asked, so no keepDeadSides path found them and
the user's picks of them went for good. `magpie provider set <id>
anthropic=<url>` reaches that shape from the CLI.

The rule is about the vendor whose base is being asked, so that is what
it now reads, together with whether the provider asks at a base of its
own besides it: an OpenRouter Anthropic base alone is still asked, its
reply being the only catalog there would otherwise be, and
catalog.fetchOne is what keeps a page of it from being read as the whole.

Five combinations of the two bases and openrouter.ai, one assertion each;
three of them fail on 0fb16990.

Co-authored-by: multica-agent <github@multica.ai>

* catalog, provider: a model list is followed to its last page, not read as a page (#1006)

A reply with has_more was refused as no answer at all, which is right for a
provider with several bases and wrong for one with a single base: Anthropic's
own preset has no other base to fall back on, so once its list passes twenty
models — about sixteen today — the fetch answered an error and no models,
where main listed the twenty of the first page, and a pick of a model on a
later page went with them. catalog.fetchOne now reads a list to its end: the
first page as the URL stands, and every page after it with limit=1000 and
the after_id the page before ended at, up to twenty pages.

Half a list is still no answer, and that is what the following ends on: a
page that fails, a list that pages without naming the id to carry on from,
one that answers the page just asked again under the same id, and one still
paging at the cap all leave the base as one that could not be asked, which
keeps what it listed last time. The rule lives in catalog.Paged, and the
Kilo gateway's list — OpenRouter's shape, which pages the same way — is paged
by it instead of refused by a guard of its own; the comment on that guard
claimed OpenRouter's /models pages, which neither api.kilo.ai nor
openrouter.ai was answering with on 2026-10-06, and now says so.

One assertion of TestFetchOpenRouterRuleOverTheFourBaseCombinations follows
the rule rather than the old count: OpenRouter's Anthropic base alone is
asked for its first page and the page after it, which is the same page
again, where before it was asked once and refused.

Tests: TestFetchFollowsThePagesOfAList, TestFetchFollowsAPageAListAnswersItsOwnWay,
TestFetchTakesAPagedListAsNoAnswerWhenAPageFails, TestFetchTakesAPagedListWithoutAnIdAsNoAnswer,
TestFetchTakesAListThatPagesWithoutEndAsNoAnswer (catalog);
TestFetchFollowsThePagesOfASingleAnthropicBase (provider, the Anthropic preset's
one base, 25 models 20 to a page) and TestKiloModelsFollowThePagesOfTheList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: OpenRouter's Anthropic base alone is asked, and refused (#1006)

The fake that stands for openrouter.ai answered every cursor with the same
twenty ids under the same last_id, so following the pages of a list stopped
where the rule of catalog.Paged says a list stops being readable, and the
single-base case looked covered: the twenty were refused and the fetch
failed. The endpoint does not answer that way. Asked with the Anthropic
version header on 2026-10-06, /api/v1/models gave those twenty with
has_more and a cursor, and under the cursor 413 more ids with has_more
false — a different set, and the end of the list. The two pages share
nothing, and following them lands deeper in the `anthropic/` namespace
rather than back at the catalog it was namespaced from: of the 433 ids, 4
are in the 466 OpenRouter serves without that header.

So the twenty were not a page to be refused but the first half of a list
that reads to the end, and the end is still not a catalog of models to
serve. The base is still asked — it is the only base there is, and refusing
to ask would leave the provider with nothing at all — and the list it
answers with is now refused as a whole, which is what the old rule did with
one page of it. It fails the fetch like any other base that could not be
asked, so the provider keeps the models it listed last time (#904).

The two replies are kept as they came, under testdata, and a test reads
them back: twenty, then 413, the cursor the first ends at, has_more true
and then false, and not one id of either page in the catalog OpenRouter
serves. The fake pages with after_id, as the endpoint does.

Tests: TestOpenRouterNamespacedPagesAreTheEndpointShape (new),
TestFetchOpenRouterRuleOverTheFourBaseCombinations (the single-base case now
asks exactly the two pages it answers with, keeps no list, and fails),
TestFetchKeepsPicksWhenAModelListIsPaginated, TestFetchDoesNotMergeOpenRouter's
NamespacedList, TestFetchOpenRouterAddsNoNamespacedModelAndKeepsPicks,
TestFetchKeepsAnotherVendorsAnthropicList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the message for a namespaced list counts nothing (#1006)

The reason a provider whose only base is OpenRouter's Anthropic one is
refused is still the one it was, and the base is still asked and refused
exactly as before: what changed is the sentence the user is left with, and
the comments around it.

That sentence counted the list it refused — "433 of them, of which 4 are
ids OpenRouter serves" — and those counts are of whatever OpenRouter's
catalog was that day, so the number a user reads is wrong tomorrow without
anyone touching it. It now says why the answer is no good and what to do
instead: give this provider OpenRouter's Chat base, which lists those
models under the ids OpenRouter serves, or type the model ids in by hand,
which is what the caller already appends to every base it could not ask.

The comments said the same counts as fact, and cited a probe file that is
not in the repository. The counts stay, marked as what was observed on
2026-10-06, and what does not move is now the point: following the pages
of the list lands deeper in the namespace, not back at the catalog it was
namespaced from. The dead file references are gone, and one test checks
that the message counts nothing at all, so a count cannot creep back in.

Tests: TestFetchOpenRouterRuleOverTheFourBaseCombinations (the message names
the Chat base and the ids to type, and holds no number but the version in
that base's path).

Co-authored-by: multica-agent <github@multica.ai>

* provider: a multi-protocol provider's catalog is the union of every endpoint's models

A provider whose protocols sit at bases of their own kept only the first
list that answered, so the models of every other endpoint were nowhere in
the product: not in the agents' model lists, not in the catalog the routing
and the per-model preferences read, and not fixable by pinning a model's
protocol, which setModelAPI refuses for a model the provider does not list.
nyownm reported it as #904 and worked around it with one provider per
protocol.

fetchOne now asks every endpoint the provider speaks and merges the lists
by model id, the way fetchPerKey merges the lists of a vendor's keys: the
first list's fields stand, and an image capability both lists answer is
merged. The base kept is still the first protocol's, the one the drawer
list is fetched beside and the models are saved with. A models URL is
still asked alone, one base two protocols share is still asked once, and
a provider with no endpoint answering still fails with every URL it asked
named in the error.

Verified with go test -tags nogui ./internal/provider ./internal/catalog
and ./internal/gateway ./internal/agent, all green. TestFetchUnionsProtocolLists
and TestFetchUnionsProtocolListsWithoutChat fail on the base commit with
the single list the first protocol answered.

Co-authored-by: multica-agent <github@multica.ai>

* provider: an endpoint that can't be asked keeps the models it listed

A provider whose protocols sit at bases of their own is asked every base
and the lists are merged, so one read that failed saved the union of the
rest as the whole list: the models of the failed base read as gone,
dropGonePicks took them out of the user's picks and stored that, and
nothing brought them back when the endpoint recovered (yetone's review of
vendor serves today, the rule fetchPerKey's keys already follow.

fetchOne keeps what each base listed and saves it beside the merged list,
in a new "sides" part of the catalog's live file, and a base it could not
ask takes its own part back for that fetch. What is kept is that base's own
models alone: a model the bases that answered have dropped is dropped here
too, however many of them dropped it and however many bases are down.
Keeping the whole list saved before would bring such a model back, which is
the same fault the other way round. A list saved before this kept no parts,
so a base whose part is missing keeps what no answering base lists, until
the next fetch with every base answering says which they are.

The parts are kept only where more than one base was asked: a single one
that fails is the fetch that fails, and its list is kept as it is, so a
provider of one protocol's cache is the file it was.

fetchOne answers one fetched list now — the models, the base kept for
routing, the parts — rather than three values. fetchPerKey marks the parts
with the keys that saw them, and keeps a plan's own models out of them.

Verified with go test ./internal/provider ./internal/catalog, all green,
and ./internal/gateway ./internal/agent.
TestFetchKeepsTheModelsAFailedProtocolListed,
TestFetchDropsAGoneModelWhileAnotherProtocolFails and
TestFetchKeepsTheModelsAFailedProtocolListedPerKey fail on 952d0b00 with
the model of the failed protocol taken out of the picks.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that never answered keeps nothing, and is not saved as one that listed nothing

keepDeadSides read a part missing from the saved sides as the whole list
saved before, and kept what no answering base lists from it. Two things
were wrong with that, and both were reported on #1006 (nyownm's #904):

A base in none of the saved parts is one that has never answered. The
whole list is not its own, so a model its vendor had already dropped was
kept for it, and the keepDeadSides result was saved as sides[base] —
from then on that base had a part, and the model could never be dropped
again. An Anthropic base answering 404 from the start of a provider's
life was enough: one round after the Chat base dropped a model, that
model stayed in the catalog, and dropGonePicks could not take it out of
the user's picks.

The saving is the other half of the same fault. A part is what a base
listed, so one that never answered has none, and writing an empty one
fixes the reading of "never answered" as "listed nothing" for good. Only
a part read out of the file is written back; the list saved without any
parts at all — before this kept them — is the one case where a base may
stand in for a missing part, and what it stands in for is kept for that
fetch alone, never saved as its own.

So keepDeadSides answers two lists now: the models this fetch's list is
made of, and the parts to write beside it. fetchPerKey keeps a model a
key that could not be asked at all owns to the bases that listed it,
read out of the parts saved beside the list: kept as a whole list with
no part saying where it came from it belonged to no base, and was read
as gone the first time that key answered half-way — the same permanent
deletion of a picked model, one round later and needing no new base.

Verified with go test ./internal/provider ./internal/catalog
./internal/gateway ./internal/agent, all green, and -race -count=3 over
./internal/provider with the four failures it already had.
TestFetchDropsAModelWhileAnEndpointHasNeverAnswered and
TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole fail on 6621f73e.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a base that answered without a model does not keep owning it

fetchPerKey gave every model kept for a key that could not be asked at all
to the bases that listed it last time, and a part there said what the
bases listed when one of them had answered this round without it (yetone's
review of #1006, nyownm's #904). With two keys where both were served a
Claude model, and the Anthropic base stopping both of them in the round
the second key was down, sides[anthropic] kept a model the base had
plainly dropped, and the fetch after that read it as a base that couldn't
be asked and held the model one round longer than it should have. It is
self-healing — the next round with the base answering settles it — and it
is the same fault c8fabd70 was written to undo, read from the other side.

sides may only say what the bases listed. A model kept for a failed key
belongs to a base that was not asked this round for any of the model's own
keys: one that was, and answered without the model, has said what it
serves today and no longer owns it. Which is per key, not per provider:
fetchOne answers which of its bases replied, which a model of the second
key alone never saw an answer from, so the base's saying nothing about it
for the first key leaves it that base's. The keys a model is kept under
are read from the list saved before, since add clears the ones of the model
it is adding.

TestFetchDropsAModelABaseStoppedServingWhileAKeyIsDown fails on c8fabd70
with the part holding claude-b, and TestFetchKeepsAModelsBaseAfterItsKeyFailedWhole
goes on passing: the same two keys, a model only one of them sees.

Co-authored-by: multica-agent <github@multica.ai>

* provider, catalog: a page of a model list is not the list (#904)

A /v1/models that answers with has_more is one page of the vendor's
catalog. Read as the whole list, every model of a later page reads as one
the vendor has dropped, and the user's pick of it goes for good, on a
list that never said so. Such a reply is no answer: the base is treated
as one that could not be asked, which keeps what it listed last time
(#904's review of #1006).

OpenRouter's Anthropic base is not asked for the list at all. With the
Anthropic version header its /models answers with the catalog again,
twenty newest first, every id namespaced under `anthropic/`, and the
cursors of the pages after. None of those twenty is an id in OpenRouter's
own catalog, so merged they are entries of the model picker that name no
model: the long, cluttered list #904's reporter wrote of. Its Chat base
is that catalog, whole, and the fetch is one request where it was two.
The rule is OpenRouter's, by host, as the ones after it are scoped to
their vendors.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the OpenRouter rule reads the base being asked (0fb16990)

It read the Chat base's host, so a provider with a Chat base of
OpenRouter's and an Anthropic base of another vendor's had that other
base skipped: its models were in neither the union nor the sides nor the
bases that could not be asked, so no keepDeadSides path found them and
the user's picks of them went for good. `magpie provider set <id>
anthropic=<url>` reaches that shape from the CLI.

The rule is about the vendor whose base is being asked, so that is what
it now reads, together with whether the provider asks at a base of its
own besides it: an OpenRouter Anthropic base alone is still asked, its
reply being the only catalog there would otherwise be, and
catalog.fetchOne is what keeps a page of it from being read as the whole.

Five combinations of the two bases and openrouter.ai, one assertion each;
three of them fail on 0fb16990.

Co-authored-by: multica-agent <github@multica.ai>

* catalog, provider: a model list is followed to its last page, not read as a page (#1006)

A reply with has_more was refused as no answer at all, which is right for a
provider with several bases and wrong for one with a single base: Anthropic's
own preset has no other base to fall back on, so once its list passes twenty
models — about sixteen today — the fetch answered an error and no models,
where main listed the twenty of the first page, and a pick of a model on a
later page went with them. catalog.fetchOne now reads a list to its end: the
first page as the URL stands, and every page after it with limit=1000 and
the after_id the page before ended at, up to twenty pages.

Half a list is still no answer, and that is what the following ends on: a
page that fails, a list that pages without naming the id to carry on from,
one that answers the page just asked again under the same id, and one still
paging at the cap all leave the base as one that could not be asked, which
keeps what it listed last time. The rule lives in catalog.Paged, and the
Kilo gateway's list — OpenRouter's shape, which pages the same way — is paged
by it instead of refused by a guard of its own; the comment on that guard
claimed OpenRouter's /models pages, which neither api.kilo.ai nor
openrouter.ai was answering with on 2026-10-06, and now says so.

One assertion of TestFetchOpenRouterRuleOverTheFourBaseCombinations follows
the rule rather than the old count: OpenRouter's Anthropic base alone is
asked for its first page and the page after it, which is the same page
again, where before it was asked once and refused.

Tests: TestFetchFollowsThePagesOfAList, TestFetchFollowsAPageAListAnswersItsOwnWay,
TestFetchTakesAPagedListAsNoAnswerWhenAPageFails, TestFetchTakesAPagedListWithoutAnIdAsNoAnswer,
TestFetchTakesAListThatPagesWithoutEndAsNoAnswer (catalog);
TestFetchFollowsThePagesOfASingleAnthropicBase (provider, the Anthropic preset's
one base, 25 models 20 to a page) and TestKiloModelsFollowThePagesOfTheList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: OpenRouter's Anthropic base alone is asked, and refused (#1006)

The fake that stands for openrouter.ai answered every cursor with the same
twenty ids under the same last_id, so following the pages of a list stopped
where the rule of catalog.Paged says a list stops being readable, and the
single-base case looked covered: the twenty were refused and the fetch
failed. The endpoint does not answer that way. Asked with the Anthropic
version header on 2026-10-06, /api/v1/models gave those twenty with
has_more and a cursor, and under the cursor 413 more ids with has_more
false — a different set, and the end of the list. The two pages share
nothing, and following them lands deeper in the `anthropic/` namespace
rather than back at the catalog it was namespaced from: of the 433 ids, 4
are in the 466 OpenRouter serves without that header.

So the twenty were not a page to be refused but the first half of a list
that reads to the end, and the end is still not a catalog of models to
serve. The base is still asked — it is the only base there is, and refusing
to ask would leave the provider with nothing at all — and the list it
answers with is now refused as a whole, which is what the old rule did with
one page of it. It fails the fetch like any other base that could not be
asked, so the provider keeps the models it listed last time (#904).

The two replies are kept as they came, under testdata, and a test reads
them back: twenty, then 413, the cursor the first ends at, has_more true
and then false, and not one id of either page in the catalog OpenRouter
serves. The fake pages with after_id, as the endpoint does.

Tests: TestOpenRouterNamespacedPagesAreTheEndpointShape (new),
TestFetchOpenRouterRuleOverTheFourBaseCombinations (the single-base case now
asks exactly the two pages it answers with, keeps no list, and fails),
TestFetchKeepsPicksWhenAModelListIsPaginated, TestFetchDoesNotMergeOpenRouter's
NamespacedList, TestFetchOpenRouterAddsNoNamespacedModelAndKeepsPicks,
TestFetchKeepsAnotherVendorsAnthropicList.

Co-authored-by: multica-agent <github@multica.ai>

* provider: the message for a namespaced list counts nothing (#1006)

The reason a provider whose only base is OpenRouter's Anthropic one is
refused is still the one it was, and the base is still asked and refused
exactly as before: what changed is the sentence the user is left with, and
the comments around it.

That sentence counted the list it refused — "433 of them, of which 4 are
ids OpenRouter serves" — and those counts are of whatever OpenRouter's
catalog was that day, so the number a user reads is wrong tomorrow without
anyone touching it. It now says why the answer is no good and what to do
instead: give this provider OpenRouter's Chat base, which lists those
models under the ids OpenRouter serves, or type the model ids in by hand,
which is what the caller already appends to every base it could not ask.

The comments said the same counts as fact, and cited a probe file that is
not in the repository. The counts stay, marked as what was observed on
2026-10-06, and what does not move is now the point: following the pages
of the list lands deeper in the namespace, not back at the catalog it was
namespaced from. The dead file references are gone, and one test checks
that the message counts nothing at all, so a count cannot creep back in.

Tests: TestFetchOpenRouterRuleOverTheFourBaseCombinations (the message names
the Chat base and the ids to type, and holds no number but the version in
that base's path).

Co-authored-by: multica-agent <github@multica.ai>

* provider: the list of a multi-protocol vendor is asked once (#1006)

The dedup added in 952d0b00 is keyed by the base URL as it is configured,
which is neither of the two things that decide whether a list is asked
again: which list URL the request goes to, and what it authenticates with.
Both of a vendor's ends were lost to it. A Chat base and the Anthropic
base of the same remote magpie are two strings, one list — GET /v1/models
— and it was fetched twice, which #1282 says a remote's test does not do.
And one base string serving Chat, Anthropic and Gemini is three requests:
the Chat request refused a 401 took the other two for lists already had,
so a vendor whose models were all there was reported as serving none.

The key is now the list URL and the authentication, in catalog.Listed, and
it gives two rules. A list URL this key has listed is not asked again by
any protocol — the answer is the answer, so …/v1 and the bare host beside
it are one request. And a request already made is not made again, but a
URL refused under one authentication is not refused under the next, so
the Gemini and Anthropic lists of a base whose Chat request was refused
are asked, each with its own. The base string is left out of the key on
purpose: Chat and Responses at one base are one request because both send
Bearer at the same URL, not because the strings match.

A base whose every list was asked already and none answered says so with
catalog.ErrAsked, which the caller reads as "nothing new here" rather
than as a second refusal to put in the message the user reads.

Tests: TestFetchAsksEachAuthenticationAtOneBase, TestFetchAsksOneListOnce
ForTwoBasesOfIt, TestFetchReportsOneRefusalForOneBaseAskedTwice.

Co-authored-by: multica-agent <github@multica.ai>

* provider: a Gemini base that fails once no longer deletes the picked model it listed

The union fetch merges a Gemini base's list like any other protocol's, but
it kept none of the fetch's bookkeeping for it: what it listed was in no
`side`, so the parts saved beside the catalog said no base listed it, and a
base that could not be asked was in no `dead` either, so `keepDeadSides`
never saw it. A picked Gemini model was therefore dropped from the user's
provider for good the first time the Gemini endpoint answered 502 or timed
out — the fault the Anthropic base of the same fetch was fixed for in
#904. A Gemini base also went uncounted in `asked`, so a two-base provider's
parts were saved on the strength of one base asked.

A Gemini base now joins `asked` before it is asked, joins `sides` and
`answered` with what it listed, and joins `dead` when it cannot be asked.
What a failed Gemini base keeps is its own models alone, so a model its list
has really dropped is still dropped from the picks.

Verified at 20ee273aaedc10ab0baf06cffbd826ddc367be3c + this commit, Go
1.26.8, darwin/arm64, under a temporary HOME with GOPATH, GOMODCACHE and
GOCACHE pinned.

Without the change (internal/provider/models.go put back):

    go test ./internal/provider -run 'TestFetchKeepsTheModelsAFailedGeminiBaseListed|TestFetchDropsAGoneGeminiModelWhileAnotherProtocolFails'
    multiproto_models_test.go:713: picks after the Gemini base failed: [gpt-a], want [gpt-a claude-b]
    multiproto_models_test.go:824: picks after the Gemini list dropped a model: [gpt-a gpt-b claude-b claude-c], want [gpt-a gpt-b claude-b]
    FAIL (exit 1)

With it:

    go test ./internal/provider -run 'TestFetchKeepsTheModelsAFailedGeminiBaseListed|TestFetchDropsAGoneGeminiModelWhileAnotherProtocolFails'
    ok (exit 0)

    go test -tags nogui ./internal/provider -count=1
    ok  github.com/yetone/magpie/internal/provider  109.187s (exit 0)

    gofmt -l internal/provider/models.go internal/provider/multiproto_models_test.go   (prints nothing)
    go vet ./internal/provider                                                       (exit 0)
    GOOS=linux go vet -tags nogui ./...                                               (exit 0)
    GOOS=windows go vet ./...                                                         (exit 0)
    go build ./...                                                                     (exit 0)
    GOOS=linux go build -tags nogui ./...                                              (exit 0)
    GOOS=windows go build ./...                                                        (exit 0)

The maintainer's own reproduction of the first failure, run on 20ee273a
before anything was changed, is the same one line and exits 1:

    --- FAIL: TestZZGeminiSideKept (0.04s)
        zz_gem_test.go:81: picks after a protocol failed: [gpt-a], want [gpt-a claude-b]

The whole-repository `go test -tags nogui ./...` was not run: the change
touches only internal/provider, and that package's full suite is green.

Co-authored-by: multica-agent <github@multica.ai>

---------

Co-authored-by: multica-agent <github@multica.ai>
2026-10-13 13:42:56 +08:00

900 lines
35 KiB
Go

package provider
// PLUGIN-SERVED (see AGENTS.md): Command Code's plan ("commandcode-plan") is
// a deprecated built-in subscription served by its plugin,
// @magpie-community/opencode-commandcode-auth, once moved onto it
// (provider.Moved; the default for a new sign-in). A moved one's sign-ins,
// models, requests and usage are all the plugin's, never this code's (only
// the move, in migrate*.go, still reads its accounts). A fix here alone
// doesn't reach those users; fix the plugin
// (github.com/magpie-community/plugins, packages/commandcode) and raise the
// mover's min in internal/provider/migrate_side.go.
// A Command Code subscription is a commandcode.ai plan (Pro, GOAT, Max,
// Ultra — every one but Go comes with API access). Signing in to it, as
// `cmd auth login` does, mints an API key for the account; that key is
// served on Command Code's Provider API (/provider/v1: Chat, Responses and
// Anthropic's Messages) and billed against the plan's own credits and its
// 5-hour and weekly limits, not as pay-as-you-go.
//
// Go has no API access: its key is only taken where the CLI itself asks,
// POST /alpha/generate, in the CLI's own format (the gateway's
// commandcode.go). Which plan an account is on is asked of billing/
// subscriptions, and kept a while (cmdPlanNow).
//
// The CLI's own account is read, never changed, from ~/.commandcode/
// auth.json. Further accounts are signed in by magpie with the CLI's own
// browser sign-in: commandcode.ai/studio/auth/cli sends the new key to a
// callback on this machine, which answers as the CLI's does; their keys
// are kept in logins.json.
//
// Its id is commandcode-plan: "commandcode" is the keyed preset's, which a
// provider added with a key from Studio may already have.
import (
"context"
"encoding/json"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/url"
"os"
"path/filepath"
"strings"
"sync"
"time"
"github.com/yetone/magpie/internal/catalog"
)
// CommandCodePlanID is the subscription's id, and its sign-in's.
const CommandCodePlanID = "commandcode-plan"
// CommandCodeMaxOutput is the most max_tokens Command Code takes at
// /alpha/generate, for any model: more is refused ("Too big: expected
// number to be <=200000 at params.max_tokens"). models.dev gives some of
// its models more (DeepSeek V4's 384000, MiniMax M3's 512000).
const CommandCodeMaxOutput = 200_000
// CommandCodeOutputOf is the most a reply of a Command Code model may be
// asked for: the model's own limit, as models.dev gives it, within
// CommandCodeMaxOutput.
func CommandCodeOutputOf(model string) int {
if n := catalog.OutputOf(model); n > 0 && n < CommandCodeMaxOutput {
return n
}
return CommandCodeMaxOutput
}
// Where Command Code's API and its sign-in page are; vars so tests can
// point them elsewhere.
var (
cmdAPI = "https://api.commandcode.ai"
cmdStudio = "https://commandcode.ai"
)
// cmdModels are the plan's best-known models, before its list is fetched.
var cmdModels = []catalog.Model{
{ID: "claude-sonnet-5", Name: "Claude Sonnet 5", Context: 1_000_000},
{ID: "claude-opus-5-5", Name: "Claude Opus 5.5", Context: 1_000_000},
{ID: "gpt-6-sol", Name: "GPT-6 Sol", Context: 1_050_000},
{ID: "deepseek/deepseek-v4-pro", Name: "DeepSeek V4 Pro", Context: 1_000_000},
{ID: "deepseek/deepseek-v4-flash", Name: "DeepSeek V4 Flash", Context: 1_000_000},
{ID: "moonshotai/Kimi-K3", Name: "Kimi K3", Context: 1_000_000},
{ID: "zai-org/GLM-5.3", Name: "GLM-5.3", Context: 1_000_000},
{ID: "MiniMaxAI/MiniMax-M3", Name: "MiniMax M3", Context: 1_000_000},
}
// cmdGoModels are the models the Go plan is let use, as the CLI's own
// table has it (1.73.0): every model its picker shows (wD, less the
// hidden) but the "premium" ones and those it blocks for Go
// (cmdGoRefused). They stand in until Command Code's list is fetched
// (cmdGoFetch), and give that list the reasoning levels and pictures it
// doesn't say.
var cmdGoModels = []catalog.Model{
{ID: "gpt-6-luna", Name: "GPT-6 Luna", Context: 1_050_000, Images: true, Efforts: []string{"low", "medium", "high", "xhigh", "max"}},
{ID: "gpt-5.6-luna", Name: "GPT-5.6 Luna", Context: 1_050_000, Images: true, Efforts: []string{"low", "medium", "high", "xhigh", "max"}},
{ID: "deepseek/deepseek-v4-pro", Name: "DeepSeek V4 Pro", Context: 1_000_000, Efforts: []string{"high", "max"}},
{ID: "deepseek/deepseek-v4-flash", Name: "DeepSeek V4 Flash", Context: 1_000_000, Efforts: []string{"high", "max"}},
{ID: "deepseek/deepseek-v4-flash-vision-exp", Name: "DeepSeek V4 Flash Vision (exp)", Context: 1_000_000, Images: true, Efforts: []string{"high", "max"}},
{ID: "deepseek/deepseek-v4-flash-fast", Name: "DeepSeek V4 Flash Fast", Context: 1_000_000, Efforts: []string{"low", "high", "max"}},
{ID: "deepseek/deepseek-v4.1-flash", Name: "DeepSeek V4.1 Flash", Context: 1_000_000, Images: true, Efforts: []string{"low", "high", "max"}},
{ID: "deepseek/deepseek-v4.1-flash-fast", Name: "DeepSeek V4.1 Flash Fast", Context: 1_000_000, Images: true, Efforts: []string{"low", "high", "max"}},
{ID: "moonshotai/Kimi-K3", Name: "Kimi K3", Context: 1_000_000, Images: true, Efforts: []string{"low", "high", "max"}},
{ID: "moonshotai/Kimi-K2.7-Code", Name: "Kimi K2.7 Code", Context: 256_000, Images: true},
{ID: "moonshotai/Kimi-K2.7-Code-Highspeed", Name: "Kimi K2.7 Code HighSpeed", Context: 262_000, Images: true},
{ID: "moonshotai/Kimi-K2.6", Name: "Kimi K2.6", Context: 256_000, Images: true},
{ID: "moonshotai/Kimi-K2.5", Name: "Kimi K2.5", Context: 256_000, Images: true},
{ID: "z-ai/glm-5.3-flash", Name: "GLM-5.3 Flash", Context: 1_048_576, Images: true, Efforts: []string{"low", "high", "max"}},
{ID: "z-ai/glm-5.3-flashx", Name: "GLM-5.3 FlashX", Context: 1_000_000, Images: true, Efforts: []string{"low", "high", "max"}},
{ID: "zai-org/GLM-5.3", Name: "GLM-5.3", Context: 1_000_000, Efforts: []string{"low", "high", "max"}},
{ID: "zai-org/GLM-5.2", Name: "GLM-5.2", Context: 1_000_000, Efforts: []string{"high", "max"}},
{ID: "zai-org/GLM-5.2-Fast", Name: "GLM-5.2 Fast", Context: 1_000_000},
{ID: "zai-org/GLM-5.1", Name: "GLM-5.1", Context: 200_000},
{ID: "zai-org/GLM-5", Name: "GLM-5", Context: 200_000},
{ID: "MiniMaxAI/MiniMax-M3", Name: "MiniMax M3", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "high"}},
{ID: "MiniMaxAI/MiniMax-M2.7", Name: "MiniMax M2.7", Context: 200_000},
{ID: "MiniMaxAI/MiniMax-M2.5", Name: "MiniMax M2.5", Context: 200_000},
{ID: "xiaomi/mimo-v2.6-pro", Name: "MiMo V2.6 Pro", Context: 1_048_576, Images: true},
{ID: "xiaomi/mimo-v2.6-flash", Name: "MiMo V2.6 Flash", Context: 1_048_576, Images: true},
{ID: "xiaomi/mimo-v2.5-pro", Name: "MiMo V2.5 Pro", Context: 1_000_000},
{ID: "xiaomi/mimo-v2.5", Name: "MiMo V2.5", Context: 1_000_000, Images: true},
{ID: "Qwen/Qwen3.8-Omni-Flash", Name: "Qwen 3.8 Omni Flash", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "xhigh"}},
{ID: "Qwen/Qwen3.8-Max-0902", Name: "Qwen 3.8 Max 0902", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "xhigh"}},
{ID: "Qwen/Qwen3.8-Max", Name: "Qwen 3.8 Max", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "xhigh"}},
{ID: "Qwen/Qwen3.8-27B", Name: "Qwen 3.8 27B", Context: 262_144, Images: true, Efforts: []string{"low", "medium", "xhigh"}},
{ID: "Qwen/Qwen3.8-Flash", Name: "Qwen 3.8 Flash", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "xhigh"}},
{ID: "Qwen/Qwen3.7-Max", Name: "Qwen 3.7 Max", Context: 1_000_000},
{ID: "Qwen/Qwen3.7-Plus", Name: "Qwen 3.7 Plus", Context: 1_000_000, Images: true},
{ID: "Qwen/Qwen3.7-Flash", Name: "Qwen 3.7 Flash", Context: 1_000_000, Images: true},
{ID: "Qwen/Qwen3.6-Max-Preview", Name: "Qwen 3.6 Max Preview", Context: 200_000},
{ID: "Qwen/Qwen3.6-Plus", Name: "Qwen 3.6 Plus", Context: 200_000, Images: true},
{ID: "meituan/LongCat-2.0", Name: "LongCat 2.0", Context: 1_048_576},
{ID: "stepfun/Step-5-Preview", Name: "Step 5 Preview", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "high"}},
{ID: "stepfun/Step-3.7-Flash", Name: "Step 3.7 Flash", Context: 256_000, Images: true},
{ID: "stepfun/Step-3.5-Flash", Name: "Step 3.5 Flash", Context: 262_144},
{ID: "tencent/hy3-paid", Name: "Tencent Hy3", Context: 262_144},
{ID: "tencent/hy4-preview", Name: "Tencent Hy4 Preview", Context: 1_048_576, Efforts: []string{"low", "medium", "high"}},
{ID: "google/gemini-3.6-flash", Name: "Gemini 3.6 Flash", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "high"}},
{ID: "google/gemini-3.5-flash-lite", Name: "Gemini 3.5 Flash Lite", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "high"}},
{ID: "nvidia/nemotron-3-ultra-550b-a55b", Name: "Nemotron 3 Ultra", Context: 1_000_000},
{ID: "thinkingmachines/inkling", Name: "Inkling", Context: 256_000, Images: true},
{ID: "thinkingmachines/inkling-small", Name: "Inkling Small", Context: 1_000_000, Images: true},
{ID: "stealth/space-bunny-alpha", Name: "Space Bunny Alpha", Context: 1_000_000, Images: true, Efforts: []string{"low", "medium", "high"}},
{ID: "stealth/pixel-canary", Name: "Pixel Canary", Context: 262_144, Images: true, Efforts: []string{"low", "medium", "xhigh"}},
{ID: "poolside/laguna-s-2.1-free", Name: "Laguna S 2.1", Context: 256_000},
{ID: "inclusionai/ling-3.0-flash-free", Name: "Ling 3.0 Flash", Context: 256_000},
{ID: "inclusionai/ling-3.0-flash-sante:free", Name: "Ling 3.0 Flash Sante", Context: 262_144},
{ID: "inclusionai/ling-3.1-flash:free", Name: "Ling 3.1 Flash", Context: 262_144, Efforts: []string{"low", "medium", "high"}},
{ID: "meta/muse-spark-1.2-contributor", Name: "Muse Spark 1.2 Contributor", Context: 1_048_576, Images: true, Efforts: []string{"low", "medium", "high", "xhigh"}},
{ID: "meta/muse-spark-1.3-contributor", Name: "Muse Spark 1.3 Contributor", Context: 1_048_576, Images: true, Efforts: []string{"low", "medium", "high", "xhigh"}},
{ID: "xai/grok-4.5", Name: "Grok 4.5", Context: 500_000, Images: true, Efforts: []string{"low", "medium", "high"}},
}
// cmdGoRefused are the models of Command Code's list the Go plan is
// refused, as the CLI's table has it (1.73.0): its "premium" ones, and
// those "individual-go" blocks —
//
// "individual-go":{allowedCategories:[qo],blockedModels:Xo=[…]}
//
// A model the table doesn't name the CLI lets any plan pick; one the plan
// hasn't after all is refused with MODEL_NOT_IN_PLAN.
var cmdGoRefused = map[string]bool{
// premium
"claude-sonnet-5": true, "claude-sonnet-4-6": true, "claude-fable-5-1": true, "claude-fable-5": true,
"claude-opus-5-5": true, "claude-opus-5": true, "claude-opus-4-8": true, "claude-opus-4-7": true,
"claude-haiku-4-5-20251001": true, "gpt-6-astra": true, "gpt-6.1-sol": true, "gpt-6-sol": true,
"gpt-5.6-terra": true, "gpt-5.5": true, "gpt-5.4": true, "gpt-5.3-codex": true, "gpt-5.4-mini": true,
"google/gemini-3.5-flash": true, "google/gemini-3.1-flash-lite": true, "sakana/fugu-ultra": true,
"meta/muse-spark-1.1": true,
// blocked for Go
"claude-sonnet-5-5": true, "gpt-5.6-sol": true, "xai/grok-4.6": true, "xai/grok-4.7": true,
"meta/muse-spark-1.2": true, "meta/muse-spark-1.3": true, "xiaomi/mimo-v2.6-pro-ultraspeed": true,
"google/gemini-3.7-flash": true, "google/gemini-3.8-flash": true,
}
// cmdGoFetch is the Go plan's models: Command Code's list, less what Go
// is refused. The list is the Provider API's, which answers without a key
// (Go's has no Provider API), and takes its reasoning levels and pictures
// from cmdGoModels.
func cmdGoFetch(ctx context.Context) ([]catalog.Model, error) {
base := cmdAPI + "/provider/v1"
ms, err := catalog.FetchURL(ctx, base+"/models", "", false, nil)
if err != nil {
return nil, err
}
var out []catalog.Model
for _, m := range catalog.Decorate(catalog.Chat(ms), cmdGoModels) {
if !cmdGoRefused[m.ID] {
out = append(out, m)
}
}
if len(out) == 0 {
return nil, errors.New("Command Code listed no models for the Go plan")
}
cmdMarkFree(out)
return out, catalog.SaveLive(CommandCodePlanID, base, out)
}
// cmdFree are the models Command Code's CLI marks FREE in its picker
// (1.73.2: badge:"free", "{name} is free and uses shared capacity"); its
// API's list doesn't say so, and Space Bunny Alpha's and Pixel Canary's
// ids name nothing free. Neither says a model is served at a discount.
var cmdFree = map[string]bool{
"stealth/space-bunny-alpha": true, "stealth/pixel-canary": true,
"poolside/laguna-s-2.1-free": true, "inclusionai/ling-3.0-flash-free": true,
"inclusionai/ling-3.0-flash-sante:free": true, "inclusionai/ling-3.1-flash:free": true,
"MiniMaxAI/MiniMax-M3-Free": true, "minimax/minimax-m3-free": true,
"minimax/minimax-m2.7-free": true, "meituan/LongCat-2.0:free": true, "tencent/Hy3": true,
}
// cmdMarkFree marks the models of ms the CLI calls free, in place.
func cmdMarkFree(ms []catalog.Model) []catalog.Model {
for i := range ms {
if cmdFree[ms[i].ID] {
ms[i].Free = true
}
}
return ms
}
func init() { cmdMarkFree(cmdGoModels) }
// cmdAuth is an account's key, as auth.json and the sign-in name it.
type cmdAuth struct {
APIKey string `json:"apiKey"`
UserID string `json:"userId,omitempty"`
UserName string `json:"userName,omitempty"`
KeyName string `json:"keyName,omitempty"`
}
// ---- the CLI's own account ----------------------------------------------------
func cmdAuthPath() string {
home, _ := os.UserHomeDir()
return filepath.Join(home, ".commandcode", "auth.json")
}
// cmdOwn is the account Command Code's CLI is signed in to; ok is false
// when it has none.
func cmdOwn() (who string, a cmdAuth, ok bool) {
if !readJSON(cmdAuthPath(), &a) || strings.TrimSpace(a.APIKey) == "" {
return "", cmdAuth{}, false
}
return cmdWho(a), a, true
}
// cmdWho names an account: its user name, or its id.
func cmdWho(a cmdAuth) string {
return firstNonEmpty(a.UserName, a.UserID, "Command Code")
}
// ---- the accounts -------------------------------------------------------------
type cmdLogin struct {
Login
auth cmdAuth
}
func cmdSaved(l savedLogin) (cmdAuth, bool) {
var a cmdAuth
if json.Unmarshal(l.Auth, &a) != nil || a.APIKey == "" {
return cmdAuth{}, false
}
return a, true
}
// cmdLogins is every Command Code account signed in, the first in use first.
func cmdLogins() []cmdLogin {
ownUser, own, hasOwn := cmdOwn()
if !hasOwn {
ownUser = ""
}
var out []cmdLogin
for _, l := range sideLogins(CommandCodePlanID, ownUser, func(l savedLogin) bool {
_, ok := cmdSaved(l)
return ok
}) {
a := own
if !l.saved.own() {
a, _ = cmdSaved(l.saved)
}
out = append(out, cmdLogin{l.Login, a})
}
return out
}
func cmdSide() []sideLogin {
var out []sideLogin
for _, l := range cmdLogins() {
out = append(out, sideLogin{Login: l.Login})
}
return out
}
func cmdLoginList() []Login { return loginsOf(cmdSide()) }
func switchCommandCodeLogin(user string) error {
return switchSideLogin(CommandCodePlanID, user, cmdSide())
}
func setCommandCodeLoginOn(user string, on bool) error {
return setSideLoginOn(CommandCodePlanID, user, on, cmdSide())
}
func forgetCommandCodeLogin(user string) error {
return forgetSideLogin(CommandCodePlanID, user, cmdSide(), nil)
}
func commandCodeAccount() (Provider, bool) {
ls := cmdLogins()
if len(ls) == 0 {
return Provider{}, false
}
return cmdProvider(ls[0].User, ls[0].Plan, ls[0].auth), true
}
// commandCodeAlsoOn is the Command Code accounts in use behind the first.
func commandCodeAlsoOn() []Provider {
var out []Provider
for _, l := range cmdLogins() {
if !l.Active && l.On {
out = append(out, cmdProvider(l.User, l.Plan, l.auth))
}
}
return out
}
func cmdProvider(who, plan string, a cmdAuth) Provider {
p := Provider{ID: CommandCodePlanID, Name: "Command Code Plan", Icon: "commandcode",
Chat: cmdAPI + "/provider/v1", Responses: cmdAPI + "/provider/v1", Anthropic: cmdAPI + "/provider",
Website: cmdStudio}
acct := &Account{Agent: CommandCodePlanID, User: who, Plan: cmdPlanKnown(a, plan)}
acct.sign = func(ctx context.Context, req *http.Request, body []byte) error {
req.Header.Del("Authorization")
req.Header.Set("Authorization", "Bearer "+a.APIKey)
req.Header.Set("x-api-key", a.APIKey)
return nil
}
acct.models = func() []catalog.Model {
if cmdPlanKnown(a, plan) == "Go" {
return cmdGoModels
}
return cmdModels
}
// the plan's list is the Provider API's, with what each model is
// served on; it is asked as a keyed provider's is. Go's key has no
// Provider API: its list is the same one, asked without it, less what
// Go is refused.
acct.fetch = func(ctx context.Context) ([]catalog.Model, error) {
if cmdPlanNow(ctx, a, plan) == "Go" {
return cmdGoFetch(ctx)
}
keyed := p
keyed.Account, keyed.Key = nil, a.APIKey
l, err := keyed.fetchOne(keyed.Via(ctx))
if err != nil {
return nil, err
}
cmdMarkFree(l.models)
return catalog.Chat(l.models), catalog.SaveLiveSides(p.ID, l.base, l.models, l.sides)
}
acct.generate = func(ctx context.Context) (string, bool) {
return a.APIKey, cmdPlanNow(ctx, a, plan) == "Go"
}
p.Account = acct
return p
}
// CommandCodeGenerate says whether p is a Command Code account on the Go
// plan, which is asked at api+"/alpha/generate" in the CLI's own format
// rather than on the Provider API, with key; ok is false for every other
// account and provider.
func CommandCodeGenerate(ctx context.Context, p Provider) (api, key string, ok bool) {
if p.Account == nil || p.Account.generate == nil {
return "", "", false
}
if key, ok = p.Account.generate(ctx); !ok {
return "", "", false
}
return cmdAPI, key, true
}
// ---- which plan ---------------------------------------------------------------
// cmdPlansSeen is each key's plan, as billing/subscriptions last said
// ("" when it couldn't be read), and when.
var cmdPlansSeen = struct {
sync.Mutex
m map[string]cmdSeen
}{m: map[string]cmdSeen{}}
type cmdSeen struct {
plan string
at time.Time
}
// How long a plan read is kept, and a failure to read it before it is
// asked again.
var (
cmdPlanKeep = 10 * time.Minute
cmdPlanRetry = time.Minute
)
// cmdRemember keeps what billing/subscriptions said of a key's plan.
func cmdRemember(key, plan string) {
cmdPlansSeen.Lock()
cmdPlansSeen.m[key] = cmdSeen{plan, time.Now()}
cmdPlansSeen.Unlock()
}
// cmdPlanKnown is the account's plan as last read, else saved (the one
// its sign-in said), asking no one.
func cmdPlanKnown(a cmdAuth, saved string) string {
cmdPlansSeen.Lock()
seen := cmdPlansSeen.m[a.APIKey]
cmdPlansSeen.Unlock()
return firstNonEmpty(seen.plan, saved)
}
// cmdPlanNow is the account's plan, read again once what was read is
// older than cmdPlanKeep; saved while it can't be read. The CLI's own
// account has none saved, so it is always asked.
func cmdPlanNow(ctx context.Context, a cmdAuth, saved string) string {
cmdPlansSeen.Lock()
seen, ok := cmdPlansSeen.m[a.APIKey]
cmdPlansSeen.Unlock()
switch {
case ok && seen.plan != "" && time.Since(seen.at) < cmdPlanKeep:
return seen.plan
case ok && seen.plan == "" && time.Since(seen.at) < cmdPlanRetry:
return saved
}
ctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
_, plan, _, _, read := cmdSubscription(ctx, a)
if !read {
plan = ""
}
cmdRemember(a.APIKey, plan)
return firstNonEmpty(plan, saved)
}
// ---- allowance ----------------------------------------------------------------
// cmdPlans names the plans as the CLI does, by their id's start, longest
// first, with the dollars of credits each gives a month (its getPlanInfo;
// "individual-pro-v1" is the old Pro, $80 of them).
var cmdPlans = []struct {
id, name string
monthly float64
}{
{"individual-provider", "Provider", 15}, {"individual-pro-v1", "Pro", 80}, {"individual-goat", "GOAT", 70},
{"individual-ultra", "Ultra", 300}, {"individual-max", "Max", 150}, {"individual-pro", "Pro", 30},
{"individual-go", "Go", 10}, {"teams-pro", "Teams Pro", 40},
}
func cmdPlanOf(id string) (name string, monthly float64) {
id = strings.ReplaceAll(strings.ToLower(id), "_", "-")
for _, p := range cmdPlans {
if strings.HasPrefix(id, p.id) {
return p.name, p.monthly
}
}
return "", 0
}
func cmdPlanName(id string) string {
name, _ := cmdPlanOf(id)
return name
}
// cmdCredits is /alpha/billing/credits as the CLI's /usage reads it
// (projectUsageView): the dollars left of the month's credits, and of the
// bought and free ones beside them, under "credits"; the plan's windows
// next to it, not in it —
//
// {"credits":{"planId":"individual-goat-monthly","monthlyCredits":41.2,
// "purchasedCredits":5,"freeCredits":0},
// "windowLimits":{"limited":true,
// "fiveHour":{"used":3.1,"cap":10,"resetAt":1790000000000},
// "weekly":{"used":12,"cap":40,"resetAt":1790400000000}},
// "sandboxMinutes":{…},"sandboxAccess":false}
//
// resetAt is in milliseconds (the CLI compares it with Date.now()); used
// and cap are only ever divided, one by the other.
type cmdWindow struct {
Used any `json:"used"`
Cap any `json:"cap"`
ResetAt any `json:"resetAt"` // unix ms (seconds or a time taken too)
}
type cmdCredits struct {
Credits struct {
PlanID string `json:"planId"`
Monthly any `json:"monthlyCredits"`
Purchased any `json:"purchasedCredits"`
Free any `json:"freeCredits"`
} `json:"credits"`
Windows *struct {
FiveHour *cmdWindow `json:"fiveHour"`
Weekly *cmdWindow `json:"weekly"`
} `json:"windowLimits"`
}
// cmdTime reads a reset time: unix seconds or milliseconds, or RFC 3339.
func cmdTime(v any) *time.Time {
if s, ok := v.(string); ok {
if t, err := time.Parse(time.RFC3339Nano, s); err == nil {
return &t
}
}
n, ok := number(v)
if !ok || n <= 0 {
return nil
}
if n < 1e12 {
n *= 1000
}
t := time.UnixMilli(int64(n))
return &t
}
// cmdWindows is the plan's 5-hour and weekly windows in a credits reply,
// those it gives a cap.
func cmdWindows(c cmdCredits) []QuotaWindow {
out := []QuotaWindow{}
if c.Windows == nil {
return out
}
for _, w := range []struct {
name string
span time.Duration
w *cmdWindow
}{{"5 hours", 5 * time.Hour, c.Windows.FiveHour}, {"Weekly", 7 * 24 * time.Hour, c.Windows.Weekly}} {
if w.w == nil {
continue
}
used, ok1 := number(w.w.Used)
limit, ok2 := number(w.w.Cap)
if !ok1 || !ok2 || limit <= 0 {
continue
}
out = append(out, QuotaWindow{Name: w.name, Used: min(100, 100*max(0, used)/limit), Span: w.span,
ResetsAt: cmdTime(w.w.ResetAt)})
}
return out
}
// cmdLeft is the dollars left on the account, the month's credits and the
// bought and free ones together (the CLI's totalRemaining), and the
// month's alone; ok is false when the reply tells none of them.
func cmdLeft(c cmdCredits) (monthly, left float64, ok bool) {
for i, v := range []any{c.Credits.Monthly, c.Credits.Purchased, c.Credits.Free} {
if n, is := number(v); is {
n = max(0, n)
if i == 0 {
monthly = n
}
left += n
ok = true
}
}
return monthly, left, ok
}
// cmdQuotaOf makes the credits reply into the plan's windows: the 5-hour
// and weekly limits, and the month's credits as one more. A card's
// Balance is shown instead of its windows — it is a key's money, not an
// allowance — so, set beside them, it hid both limits on the Usage page,
// the panel and the TUI. The dollars are a window when the plan is known,
// used of the CLI's pool (the plan's month of credits, or what is left of
// it if more, and the bought and free ones) as its /usage bar is; a reply
// with neither windows nor a plan is a Balance still.
func cmdQuotaOf(q SubscriptionQuota, c cmdCredits) SubscriptionQuota {
name, planMonthly := cmdPlanOf(c.Credits.PlanID)
if name != "" {
q.Plan = name
}
q.Windows = cmdWindows(c)
monthly, left, known := cmdLeft(c)
switch {
case !known:
case planMonthly > 0:
pool := max(planMonthly, monthly) + left - monthly
q.Windows = append(q.Windows, QuotaWindow{Name: "Credits", Used: min(100, 100*(pool-left)/pool),
Display: money("$", pool-left) + " / " + money("$", pool)})
case len(q.Windows) == 0:
q.Balance = money("$", left)
}
return q
}
func cmdQuota(ctx context.Context, l Login, a cmdAuth) SubscriptionQuota {
q := SubscriptionQuota{Provider: CommandCodePlanID, Name: "Command Code", Icon: "commandcode", Plan: l.Plan, User: l.User, Windows: []QuotaWindow{}}
// the plan is said even while the credits can't be read (Command Code
// answers 503, "Couldn't verify your credit balance just now", at times)
id, plan, until, renew, planOK := cmdSubscription(ctx, a)
var c cmdCredits
if err := accountJSON(ctx, cmdAPI+"/alpha/billing/credits", a.APIKey, nil, &c); err != nil {
q.Error = err.Error()
} else {
// billing/credits leaves the plan out: the month of credits the pool
// is made of is the subscription's plan's
if c.Credits.PlanID == "" {
c.Credits.PlanID = id
}
q = cmdQuotaOf(q, c)
}
if planOK {
q.Plan, q.Until, q.Renew = plan, until, renew
cmdRemember(a.APIKey, plan)
}
return q
}
// cmdNoPlan is the plan of an account with no subscription: its key is
// billed against the credits it bought, if any.
const cmdNoPlan = "No plan"
// cmdSubscription is the account's plan (its id, and its name), when its period ends and whether
// it renews then, as billing/subscriptions says; cmdNoPlan when it has
// none. ok is false when that can't be read.
func cmdSubscription(ctx context.Context, a cmdAuth) (id, plan string, until *time.Time, renew string, ok bool) {
var r struct {
Success *bool `json:"success"` // false when Command Code couldn't tell ("write CONNECTION_CLOSED …"), though a 200
Data *struct {
PlanID string `json:"planId"`
Status string `json:"status"`
CurrentPeriodEnd any `json:"currentPeriodEnd"`
CancelAtEnd *bool `json:"cancelAtPeriodEnd"`
} `json:"data"`
}
if accountJSON(ctx, cmdAPI+"/alpha/billing/subscriptions", a.APIKey, nil, &r) != nil || (r.Success != nil && !*r.Success) {
return "", "", nil, "", false
}
if d := r.Data; d != nil && d.PlanID != "" && d.Status != "canceled" && d.Status != "incomplete_expired" {
if d.CancelAtEnd != nil {
renew = map[bool]string{true: "off", false: "auto"}[*d.CancelAtEnd]
}
return d.PlanID, firstNonEmpty(cmdPlanName(d.PlanID), d.PlanID), cmdTime(d.CurrentPeriodEnd), renew, true
}
return "", cmdNoPlan, nil, "", true
}
func cmdLoginQuota(ctx context.Context, l Login) SubscriptionQuota {
for _, c := range cmdLogins() {
if strings.EqualFold(c.User, l.User) {
return cmdQuota(ctx, l, c.auth)
}
}
return SubscriptionQuota{Provider: CommandCodePlanID, Plan: l.Plan, Windows: []QuotaWindow{}, Error: "not signed in"}
}
// ---- signing in ---------------------------------------------------------------
// startCommandCodeSignIn is the CLI's browser sign-in: Studio asks the
// user to approve a key for this machine, then posts it (a form, or JSON
// from an older Studio) to the callback, which sends the browser on to a
// page saying it is done.
func startCommandCodeSignIn(s *signInFlow) error {
ln, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return err
}
port := ln.Addr().(*net.TCPAddr).Port
q := url.Values{}
q.Set("callback", fmt.Sprintf("http://127.0.0.1:%d/callback", port))
q.Set("state", s.state)
q.Set("mode", "redirect")
srv := &http.Server{Handler: http.HandlerFunc(s.commandCodeCallback), ReadHeaderTimeout: 10 * time.Second}
s.mu.Lock()
s.st.URL = cmdStudio + "/studio/auth/cli?" + q.Encode()
// Studio's post can't reach a magpie on a server or in Docker: a key
// made on its keys page and pasted finishes it instead
s.st.PasteKey, s.st.KeysURL = true, cmdKeysURL
s.srv = srv
s.mu.Unlock()
go func() { _ = srv.Serve(ln) }()
return nil
}
// cmdWhoamiWait is how long a sign-in waits to ask whoami again.
var cmdWhoamiWait = time.Second
// cmdOrigins are the Studio pages that may post to the callback.
var cmdOrigins = []string{"https://commandcode.ai", "https://staging.commandcode.ai"}
func (s *signInFlow) commandCodeCallback(w http.ResponseWriter, r *http.Request) {
origin := cmdOrigins[0]
for _, o := range cmdOrigins {
if r.Header.Get("Origin") == o {
origin = o
}
}
w.Header().Set("Access-Control-Allow-Origin", origin)
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
if r.Header.Get("Access-Control-Request-Private-Network") == "true" {
w.Header().Set("Access-Control-Allow-Private-Network", "true")
}
switch {
case r.Method == http.MethodOptions:
w.WriteHeader(http.StatusNoContent)
return
case r.URL.Path == "/callback/complete" && r.Method == http.MethodGet:
st := s.status()
if st.State == "done" {
signInPage(w, true, "You're signed in", fmt.Sprintf("%s is added to magpie. You can close this tab.", st.User))
} else {
signInPage(w, false, "Sign-in didn't finish", firstNonEmpty(st.Error, "Start it again from magpie."))
}
return
case r.URL.Path == "/cancel":
s.finish(SignInState{State: "canceled"})
w.WriteHeader(http.StatusNoContent)
return
case r.URL.Path != "/callback":
http.NotFound(w, r)
return
case r.Method != http.MethodPost:
w.WriteHeader(http.StatusMethodNotAllowed)
return
}
body, _ := io.ReadAll(io.LimitReader(r.Body, 10_000))
var got struct {
cmdAuth
State string `json:"state"`
Error string `json:"error"`
Desc string `json:"error_description"`
}
isJSON := strings.HasPrefix(strings.TrimSpace(strings.ToLower(r.Header.Get("Content-Type"))), "application/json")
if isJSON {
_ = json.Unmarshal(body, &got)
} else {
f, _ := url.ParseQuery(string(body))
got.APIKey, got.UserID, got.UserName, got.KeyName = f.Get("apiKey"), f.Get("userId"), f.Get("userName"), f.Get("keyName")
got.State, got.Error, got.Desc = f.Get("state"), f.Get("error"), f.Get("error_description")
}
answer := func(ok bool, msg string) {
if isJSON {
w.Header().Set("Content-Type", "application/json")
if !ok {
w.WriteHeader(http.StatusBadRequest)
}
_ = json.NewEncoder(w).Encode(map[string]any{"success": ok, "error": msg})
return
}
// as the CLI answers: on to the page that says how it went
w.Header().Set("Location", "/callback/complete?state="+url.QueryEscape(got.State))
w.Header().Set("Cache-Control", "no-store")
w.WriteHeader(http.StatusSeeOther)
}
if got.State != s.state {
// not ours: someone else's page, or a stale tab
w.WriteHeader(http.StatusForbidden)
signInPage(w, false, "This link isn't from magpie's sign-in", "Start it again from magpie.")
return
}
if s.status().State != "waiting" {
answer(false, "this sign-in is over")
return
}
if got.Error != "" {
msg := firstNonEmpty(got.Desc, got.Error)
if got.Error == "access_denied" {
msg = "the sign-in was denied"
}
s.finish(SignInState{State: "failed", Error: msg})
answer(false, msg)
return
}
if got.APIKey == "" {
answer(false, "Command Code sent back no key")
return
}
if !s.claim() {
// a key was pasted too, and that one is being kept
answer(false, "this sign-in is already finishing")
return
}
ctx, cancel := context.WithTimeout(s.via(r.Context()), 30*time.Second)
defer cancel()
// the browser comes back for its page after this: the server stays up
// a while for it, where finish would close it within a second
if err := s.commandCodeKeep(ctx, got.cmdAuth, true); err != nil {
answer(false, err.Error())
return
}
answer(true, "")
}
// commandCodeKeep names the account a key is Command Code's, keeps it beside
// the others, and finishes the sign-in. keepServer leaves the callback
// server up a while, for the browser to come back for its page.
func (s *signInFlow) commandCodeKeep(ctx context.Context, a cmdAuth, keepServer bool) error {
who, plan, err := cmdSignedIn(ctx, a)
if err != nil {
s.finish(SignInState{State: "failed", Error: err.Error()})
return err
}
a.UserName = who
auth, _ := json.Marshal(a)
ownUser, _, hasOwn := cmdOwn()
if !hasOwn {
ownUser = ""
}
if err := addSideLogin(savedLogin{Agent: CommandCodePlanID, User: who, Plan: plan, Auth: auth}, ownUser, func(savedLogin) {}); err != nil {
s.finish(SignInState{State: "failed", Error: err.Error()})
return err
}
if keepServer {
s.mu.Lock()
srv := s.srv
s.srv = nil
s.mu.Unlock()
if srv != nil {
time.AfterFunc(10*time.Second, func() { _ = srv.Close() })
}
}
s.finish(SignInState{State: "done", User: who, Plan: plan, Using: hasOwn && strings.EqualFold(ownUser, who)})
return nil
}
// cmdKeysURL is Studio's page of API keys, where one is made to paste.
var cmdKeysURL = "https://commandcode.ai/settings/keys"
// commandCodeKey finishes a sign-in with a key pasted from Studio's keys
// page, as the CLI takes one ("Authorize in browser, or paste API key
// here"). It is how a magpie the browser can't reach — on a server, in
// Docker — signs in: Studio posts the key to the callback on 127.0.0.1 in
// the background, so the page the browser ends on has nothing in its
// address to paste.
func (s *signInFlow) commandCodeKey(raw string) error {
key := strings.TrimSpace(raw)
switch {
case key == "":
return errors.New("paste an API key from Command Code's keys page")
case strings.Contains(key, "://"):
return errors.New("that's an address: Command Code sends its key in the background, so make a key on its keys page and paste that")
case strings.ContainsAny(key, " \t\r\n"):
return errors.New("that doesn't look like a Command Code API key")
}
if s.status().State != "waiting" {
return errors.New("this sign-in is over; start it again")
}
if !s.claim() {
return errors.New("this sign-in is already finishing")
}
ctx, cancel := context.WithTimeout(s.via(context.Background()), 30*time.Second)
defer cancel()
return s.commandCodeKeep(ctx, cmdAuth{APIKey: key}, false)
}
// cmdSignedIn names a new key's account with whoami, and reads its plan.
// Only whoami turning the key down (401, 403) fails the sign-in: the CLI's
// own browser sign-in keeps the key Studio posts without asking whoami at
// all, and whoami has answered a key just made with a 500, so a whoami
// that errs is asked again a few times and then passed over for the name
// Studio sent with the key.
func cmdSignedIn(ctx context.Context, a cmdAuth) (who, plan string, err error) {
var me struct {
User struct {
ID string `json:"id"`
UserName string `json:"userName"`
Name string `json:"name"`
Email string `json:"email"`
} `json:"user"`
}
for try := 0; ; try++ {
err := accountJSON(ctx, cmdAPI+"/alpha/whoami", a.APIKey, nil, &me)
var st *accountStatusError
if err == nil {
break
}
if errors.As(err, &st) && (st.status == http.StatusUnauthorized || st.status == http.StatusForbidden) {
return "", "", fmt.Errorf("Command Code didn't take the new key: %w", err)
}
if try == 2 || ctx.Err() != nil {
if firstNonEmpty(a.UserName, a.UserID) == "" {
return "", "", fmt.Errorf("Command Code couldn't say which account signed in: %w", err)
}
break
}
select {
case <-ctx.Done():
case <-time.After(cmdWhoamiWait):
}
}
who = firstNonEmpty(me.User.UserName, a.UserName, me.User.Email, me.User.ID, a.UserID)
if who == "" {
return "", "", fmt.Errorf("Command Code didn't say which account signed in")
}
if _, p, _, _, ok := cmdSubscription(ctx, a); ok {
plan = p
}
return who, plan, nil
}