Skip to content

Linger is An Open-Source Personal Agent That Runs Fully on Your PC. We aim to break Big Tech’s grip on AI by bringing powerful local AI to everyday computers through efficient model–harness co-design, so everyone can run their own.

feat: switch a Computer's model source, with bring-your-own-key endpoints

LeoXingb8b23e5de3b6
diff --git a/apps/computer/local-daemon/README.md b/apps/computer/local-daemon/README.md
index a2db925e..da2de5d4 100644
--- a/apps/computer/local-daemon/README.md
+++ b/apps/computer/local-daemon/README.md
@@ -157,6 +157,18 @@ model.
passed through as `localmodels` reports it; the endpoint keeps only the
loaded engine's `base_url`.
+## Model source
+
+`internal/localmodels/source.go` runs `localmodels source status|check|models|apply`
+for `execute` commands of kind `model_source`, on their own goroutine so they
+never block Operation commands; `apply` is serialized. A BYOK key reaches the
+tool on stdin, never in argv or logs. `localmodels` writes
+`<state>/model-source.json`; the Daemon only adds the `runtime_paths` that the
+same `apply` reported. It re-reads the file on every discovery tick to overlay
+the Runtimes' environment (`OverlayEnvironment`) and executable paths
+(`OverlayRuntimePaths`), and under BYOK lists only the BYOK model in each
+Runtime's catalog.
+
## Codex models cache
Signed in with ChatGPT, Codex blocks its first `thread/start` on a 4–5 s
diff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go
index 3ee8887a..f3378a0e 100644
--- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go
+++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main.go
@@ -12,6 +12,7 @@ import (
"os/signal"
"path/filepath"
"runtime"
+ "slices"
"sort"
"strings"
"sync"
@@ -130,14 +131,32 @@ func run(args []string) (resultErr error) {
} else if removed > 0 {
slog.Info("pruned abandoned Operation temp directories", "removed", removed, "bytes_freed", bytesFreed)
}
- providerEnvironment := runtimeProviderEnvironment(environment, computer.GatewayToken, computer.CodexAuthFile)
- discovered, err := provider.Discover(context.Background(), provider.DiscoveryOptions{
- ConfiguredPaths: computer.RuntimePaths,
- Runtimes: computer.EnabledRuntimes,
- PreferredRuntime: computer.PreferredRuntime,
- RuntimeHomeRoot: filepath.Join(computer.StateDirectory, "runtime-homes"),
- Environment: providerEnvironment,
- })
+ baseProviderEnvironment := runtimeProviderEnvironment(environment, computer.GatewayToken, computer.CodexAuthFile)
+ var localModelsStateDir string
+ if computer.LocalModels != nil {
+ localModelsStateDir = computer.LocalModels.StateDirectory
+ }
+ currentProviderEnvironment := func() map[string]string {
+ return localmodels.OverlayEnvironment(baseProviderEnvironment, localModelsStateDir)
+ }
+ currentDiscoveryOptions := func() provider.DiscoveryOptions {
+ return provider.DiscoveryOptions{
+ ConfiguredPaths: localmodels.OverlayRuntimePaths(computer.RuntimePaths, localModelsStateDir),
+ Runtimes: computer.EnabledRuntimes,
+ PreferredRuntime: computer.PreferredRuntime,
+ RuntimeHomeRoot: filepath.Join(computer.StateDirectory, "runtime-homes"),
+ Environment: currentProviderEnvironment(),
+ }
+ }
+ discover := func(ctx context.Context, options provider.DiscoveryOptions) (provider.DiscoveryResult, error) {
+ result, err := provider.Discover(ctx, options)
+ if err == nil {
+ result.Diagnostics = byokRuntimeCatalogs(result.Diagnostics, localmodels.ReadOverlay(localModelsStateDir))
+ }
+ return result, err
+ }
+ providerEnvironment := currentProviderEnvironment()
+ discovered, err := discover(context.Background(), currentDiscoveryOptions())
if err != nil {
return err
}
@@ -285,6 +304,7 @@ func run(args []string) (resultErr error) {
// full Runtime discovery.
runtimeRefresh := make(chan struct{}, 1)
var localDaemon *daemon.Daemon
+ var controller *controlController
var localModelsTool *localmodels.Tool
if tool := computer.LocalModels; tool != nil {
localModelsTool = &localmodels.Tool{
@@ -292,9 +312,10 @@ func run(args []string) (resultErr error) {
StateDirectory: tool.StateDirectory, BaseDirectory: tool.BaseDirectory,
}
}
+ jobDir := filepath.Join(computer.StateDirectory, "local-models", "jobs")
localModels := localmodels.New(localmodels.Options{
- Tool: localModelsTool, Environment: providerEnvironment,
- JobDirectory: filepath.Join(computer.StateDirectory, "local-models", "jobs"),
+ Tool: localModelsTool, Environment: baseProviderEnvironment,
+ JobDirectory: jobDir,
// The library publishes only from Act and Refresh, which the Daemon
// calls once it runs.
Publish: func(snapshot wire.LocalModelsSnapshot) { localDaemon.PublishLocalModels(snapshot) },
@@ -306,6 +327,40 @@ func run(args []string) (resultErr error) {
},
})
defer localModels.Close()
+ applyDiscovered := func(publishCtx context.Context, next provider.DiscoveryResult) error {
+ logRuntimeDiagnostics(next.Diagnostics)
+ nextProviders, nextRuntimes := providerInstallations(next, currentProviderEnvironment())
+ providerCatalog.Replace(nextProviders)
+ if controller != nil {
+ controller.UpdateDiagnostics(next.Diagnostics)
+ }
+ return inventory.publish(publishCtx, nextRuntimes, next.Diagnostics)
+ }
+ var nodePath string
+ if toolInstallation != nil {
+ nodePath = toolInstallation.NodePath
+ }
+ modelSource := localmodels.NewModelSource(localmodels.ModelSourceOptions{
+ Tool: localModelsTool,
+ Environment: baseProviderEnvironment,
+ JobDirectory: jobDir,
+ NodePath: nodePath,
+ OnApplied: func(applyCtx context.Context) map[string][]localmodels.RuntimeModelOption {
+ localModels.Refresh(applyCtx)
+ var catalogs map[string][]localmodels.RuntimeModelOption
+ if next, discoverErr := discover(applyCtx, currentDiscoveryOptions()); discoverErr == nil {
+ if pubErr := applyDiscovered(applyCtx, next); pubErr != nil {
+ slog.Warn("model_source.runtime_publish_failed", "error", pubErr)
+ }
+ catalogs = runtimeModelCatalogs(next.Diagnostics)
+ }
+ select {
+ case runtimeRefresh <- struct{}{}:
+ default:
+ }
+ return catalogs
+ },
+ })
codexModelSessions := &provider.CodexSessions{Root: filepath.Join(computer.StateDirectory, "model-invoke", "codex-sessions")}
localDaemon, err = daemon.New(daemon.Options{
ComputerID: computer.ComputerID, DisplayName: computer.DisplayName,
@@ -330,6 +385,7 @@ func run(args []string) (resultErr error) {
CLICredentials: cliCredentials,
TeamHubCLIBin: teamhubBin,
LocalModels: localModels,
+ ModelSource: modelSource,
ModelInvoker: provider.ModelInvoker{
TempBase: operationTempBase,
ClaudeConfigRoot: filepath.Join(computer.StateDirectory, "model-invoke", "claude", ".claude"),
@@ -369,7 +425,7 @@ func run(args []string) (resultErr error) {
})
localDaemon.SetSelfUpdater(updates)
}
- controller := &controlController{
+ controller = &controlController{
daemon: localDaemon, assignments: assignmentStore, diagnostics: discovered.Diagnostics,
services: managedServices, computerID: computer.ComputerID,
capacity: computer.MaxConcurrentOperations,
@@ -395,14 +451,10 @@ func run(args []string) (resultErr error) {
monitorDone := make(chan error, 1)
go func() {
monitorDone <- provider.MonitorRuntimeDiagnostics(ctx, provider.RuntimeMonitorOptions{
- Initial: discovered,
- Discovery: provider.DiscoveryOptions{
- ConfiguredPaths: computer.RuntimePaths,
- Runtimes: computer.EnabledRuntimes,
- PreferredRuntime: computer.PreferredRuntime,
- RuntimeHomeRoot: filepath.Join(computer.StateDirectory, "runtime-homes"),
- Environment: providerEnvironment,
- },
+ Initial: discovered,
+ Discovery: currentDiscoveryOptions(),
+ Discover: discover,
+ ResolveDiscovery: currentDiscoveryOptions,
RefreshInterval: 15 * time.Second,
FullRefreshEveryTicks: 4,
FullRefreshAllowed: func() bool {
@@ -413,11 +465,7 @@ func run(args []string) (resultErr error) {
},
Refresh: runtimeRefresh,
OnChanged: func(next provider.DiscoveryResult) error {
- logRuntimeDiagnostics(next.Diagnostics)
- nextProviders, nextRuntimes := providerInstallations(next, providerEnvironment)
- providerCatalog.Replace(nextProviders)
- controller.UpdateDiagnostics(next.Diagnostics)
- return inventory.publish(ctx, nextRuntimes, next.Diagnostics)
+ return applyDiscovered(ctx, next)
},
OnError: func(err error) {
slog.Warn("Runtime diagnostic refresh failed", "error", err)
@@ -774,3 +822,40 @@ func logRuntimeDiagnostics(diagnostics []provider.RuntimeDiagnostic) {
slog.Info("runtime.diagnostic", attributes...)
}
}
+
+// runtimeModelCatalogs keys each Runtime's discovered models by its type, so a
+// model-source switch can pick the model its Agents run next.
+func runtimeModelCatalogs(diagnostics []provider.RuntimeDiagnostic) map[string][]localmodels.RuntimeModelOption {
+ catalogs := make(map[string][]localmodels.RuntimeModelOption, len(diagnostics))
+ for _, diagnostic := range diagnostics {
+ models := make([]localmodels.RuntimeModelOption, 0, len(diagnostic.Models))
+ for _, model := range diagnostic.Models {
+ models = append(models, localmodels.RuntimeModelOption{
+ ID: model.ID, AllowedReasoningEffort: model.AllowedReasoningEffort,
+ DefaultReasoningEffort: model.DefaultReasoningEffort, IsDefault: model.IsDefault,
+ })
+ }
+ catalogs[diagnostic.Type] = models
+ }
+ return catalogs
+}
+
+// byokRuntimeCatalogs shows a BYOK source as the one model the person entered.
+// The Runtime's own catalog names the gateway route instead, and Claude also
+// lists aliases that all resolve to it.
+func byokRuntimeCatalogs(diagnostics []provider.RuntimeDiagnostic, source *localmodels.OverlayState) []provider.RuntimeDiagnostic {
+ if source == nil || source.Mode != "byok" || source.RuntimeModel == "" || source.ModelLabel == "" {
+ return diagnostics
+ }
+ shaped := append([]provider.RuntimeDiagnostic(nil), diagnostics...)
+ for index, diagnostic := range shaped {
+ i := slices.IndexFunc(diagnostic.Models, func(model provider.RuntimeModel) bool { return model.ID == source.RuntimeModel })
+ if i < 0 {
+ continue
+ }
+ model := diagnostic.Models[i]
+ model.Label, model.IsDefault = source.ModelLabel, true
+ shaped[index].Models = []provider.RuntimeModel{model}
+ }
+ return shaped
+}
diff --git a/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go b/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go
index 2e525bf2..5630d534 100644
--- a/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go
+++ b/apps/computer/local-daemon/cmd/linger-computer-daemon/main_test.go
@@ -7,6 +7,7 @@ import (
"os"
"os/exec"
"path/filepath"
+ "reflect"
"runtime"
"slices"
"strings"
@@ -15,6 +16,7 @@ import (
"github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/computerconfig"
"github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/assignment"
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/localmodels"
"github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/provider"
)
@@ -233,3 +235,30 @@ func TestProviderInstallationsKeepDiscoveredContextWindows(t *testing.T) {
t.Fatalf("context windows = %v", windows)
}
}
+
+func TestByokRuntimeCatalogsShowTheEnteredModel(t *testing.T) {
+ diagnostics := []provider.RuntimeDiagnostic{
+ {Type: "claude", Models: []provider.RuntimeModel{
+ {ID: "default", Label: "Default", IsDefault: true},
+ {ID: "localmodels-byok", Label: "localmodels-byok"},
+ }},
+ {Type: "codex", Models: []provider.RuntimeModel{{ID: "gpt-5", Label: "gpt-5", IsDefault: true}}},
+ }
+ byok := &localmodels.OverlayState{Mode: "byok", RuntimeModel: "localmodels-byok", ModelLabel: "vendor/model"}
+
+ shaped := byokRuntimeCatalogs(diagnostics, byok)
+ if want := []provider.RuntimeModel{{ID: "localmodels-byok", Label: "vendor/model", IsDefault: true}}; !reflect.DeepEqual(shaped[0].Models, want) {
+ t.Fatalf("Claude models = %+v, want %+v", shaped[0].Models, want)
+ }
+ if !reflect.DeepEqual(shaped[1].Models, diagnostics[1].Models) {
+ t.Fatalf("a Runtime without the BYOK route changed: %+v", shaped[1].Models)
+ }
+ if len(diagnostics[0].Models) != 2 || diagnostics[0].Models[1].Label != "localmodels-byok" {
+ t.Fatalf("input diagnostics were modified: %+v", diagnostics[0].Models)
+ }
+ for _, source := range []*localmodels.OverlayState{nil, {Mode: "local", RuntimeModel: "localmodels-byok", ModelLabel: "x"}} {
+ if got := byokRuntimeCatalogs(diagnostics, source); len(got[0].Models) != 2 {
+ t.Fatalf("source %+v reshaped the catalog: %+v", source, got[0].Models)
+ }
+ }
+}
diff --git a/apps/computer/local-daemon/internal/daemon/connection.go b/apps/computer/local-daemon/internal/daemon/connection.go
index 9a196b84..e2ed7d74 100644
--- a/apps/computer/local-daemon/internal/daemon/connection.go
+++ b/apps/computer/local-daemon/internal/daemon/connection.go
@@ -287,6 +287,17 @@ func (d *Daemon) handleConnectionCommand(ctx, connectionCtx context.Context, str
slog.Warn("local_models.outcome_not_sent", "error", err)
}
}()
+ case protocol.CommandCapabilityModelSource:
+ if !d.welcomeSeen || command.ConnectionEpoch != d.connectionEpoch {
+ return errors.New("Model source command uses a stale connection epoch")
+ }
+ // Probing endpoints or mounting Bifrost can take seconds; Operation
+ // commands must not wait behind them.
+ go func() {
+ if err := d.handleModelSourceCommand(connectionCtx, stream, command); err != nil {
+ slog.Warn("model_source.outcome_not_sent", "error", err)
+ }
+ }()
case protocol.CommandOperationCancel:
if !dispatch.followOperation(command, func() error { return d.handleOperationCancel(command) }) {
if err := d.handleOperationCancel(command); err != nil {
diff --git a/apps/computer/local-daemon/internal/daemon/daemon.go b/apps/computer/local-daemon/internal/daemon/daemon.go
index 441df6b2..04141f55 100644
--- a/apps/computer/local-daemon/internal/daemon/daemon.go
+++ b/apps/computer/local-daemon/internal/daemon/daemon.go
@@ -67,6 +67,8 @@ type Options struct {
// LocalModels runs owner-chosen localmodels library actions; nil
// refuses each with TOOL_NOT_INSTALLED.
LocalModels LocalModelLibrary
+ // ModelSource inspects, tests and switches the Computer's active model source.
+ ModelSource ModelSourceManager
}
type OperationResolver interface {
@@ -138,6 +140,7 @@ type Daemon struct {
modelInvokeMu sync.Mutex
modelInvokes map[string]*modelInvoke
localModels LocalModelLibrary
+ modelSource ModelSourceManager
// localModelsMu orders runner.local_models sends with their revision.
localModelsMu sync.Mutex
localModelsRevision uint64
@@ -234,6 +237,7 @@ func New(options Options) (*Daemon, error) {
modelInvoker: options.ModelInvoker,
modelInvokes: make(map[string]*modelInvoke),
localModels: options.LocalModels,
+ modelSource: options.ModelSource,
contextDispatchLimit: defaultContextDispatchLimit,
retryDelay: defaultRetryDelay(options.RetryDelay),
stableConnection: stableGatewayConnection,
diff --git a/apps/computer/local-daemon/internal/daemon/model_source.go b/apps/computer/local-daemon/internal/daemon/model_source.go
new file mode 100644
index 00000000..af289e97
--- /dev/null
+++ b/apps/computer/local-daemon/internal/daemon/model_source.go
@@ -0,0 +1,176 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "log/slog"
+ "time"
+
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/linger/transport"
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/localmodels"
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/protocol"
+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"
+)
+
+// ModelSourceManager inspects, probes and switches this Computer's active
+// model source (local models, native subscriptions, or BYOK on Bifrost).
+type ModelSourceManager interface {
+ Status(ctx context.Context) (wire.ModelSourceStatus, error)
+ TestByok(ctx context.Context, runtime string, input wire.ByokConfigInput) (wire.ByokTestResult, error)
+ ListByokModels(ctx context.Context, input wire.ByokConfigInput) (wire.ByokModelList, error)
+ Apply(ctx context.Context, apply localmodels.ModelSourceApply) (wire.ModelSourceStatus, error)
+}
+
+func (d *Daemon) handleModelSourceCommand(ctx context.Context, stream transport.Stream, command protocol.Command) error {
+ var request wire.CapabilityModelSource
+ if err := json.Unmarshal(command.Payload, &request); err != nil {
+ return errors.New("invalid model source command")
+ }
+ expiresAt, err := time.Parse(time.RFC3339Nano, request.ExpiresAt)
+ if err != nil {
+ return errors.New("invalid model source command expiry")
+ }
+ sendFailed := func(code, message string, retryable bool) error {
+ frame := wire.CapabilityModelSourceFailed{
+ ProtocolVersion: request.ProtocolVersion,
+ CommandID: request.CommandID,
+ RunnerID: request.RunnerID,
+ TenantID: request.TenantID,
+ OwnerActorID: request.OwnerActorID,
+ ConnectionEpoch: request.ConnectionEpoch,
+ ExpiresAt: request.ExpiresAt,
+ Type: wire.TypeExecuted,
+ Kind: wire.KindModelSource,
+ Action: request.Action,
+ Outcome: wire.OutcomeFailed,
+ Error: wire.AgentRunnerError{
+ Code: code,
+ Message: message,
+ Retryable: retryable,
+ },
+ }
+ payload, marshalErr := json.Marshal(frame)
+ if marshalErr != nil {
+ return marshalErr
+ }
+ return stream.Send(ctx, protocol.Event{
+ Type: protocol.EventCapabilityModelSourceFailed,
+ ProtocolVersion: command.ProtocolVersion,
+ CommandID: command.CommandID,
+ RunnerID: command.RunnerID,
+ TenantID: request.TenantID,
+ OwnerActorID: request.OwnerActorID,
+ ConnectionEpoch: command.ConnectionEpoch,
+ SentAt: time.Now().UTC(),
+ Payload: payload,
+ })
+ }
+
+ switch {
+ case request.RunnerID != d.computerID || !d.ownedBy(request.TenantID, request.OwnerActorID):
+ return sendFailed("MODEL_SOURCE_FORBIDDEN", "This Computer does not belong to the owner.", false)
+ case !expiresAt.After(time.Now()):
+ return sendFailed("MODEL_SOURCE_EXPIRED", "The model source request expired; try again.", true)
+ case request.Runtime != "" && !d.runtimeEnabled(request.Runtime):
+ return sendFailed("RUNTIME_NOT_ENABLED", "The selected AI runtime is not enabled on this Computer.", false)
+ case d.modelSource == nil:
+ return sendFailed(localmodels.CodeToolNotInstalled, "The localmodels tool is not installed on this Computer.", false)
+ }
+
+ commandCtx, cancel := context.WithDeadline(ctx, expiresAt)
+ defer cancel()
+
+ var status *wire.ModelSourceStatus
+ var testResult *wire.ByokTestResult
+ var modelList *wire.ByokModelList
+ var actionErr error
+
+ switch request.Action {
+ case "status":
+ res, err := d.modelSource.Status(commandCtx)
+ if err != nil {
+ actionErr = err
+ } else {
+ status = &res
+ }
+ case "test":
+ if request.Byok == nil || request.Runtime == "" {
+ return sendFailed("BYOK_INVALID_CONFIG", "A BYOK endpoint and its AI runtime are required.", false)
+ }
+ res, err := d.modelSource.TestByok(commandCtx, request.Runtime, *request.Byok)
+ if err != nil {
+ actionErr = err
+ } else {
+ testResult = &res
+ }
+ case "models":
+ if request.Byok == nil {
+ return sendFailed("BYOK_INVALID_CONFIG", "A BYOK endpoint is required.", false)
+ }
+ res, err := d.modelSource.ListByokModels(commandCtx, *request.Byok)
+ if err != nil {
+ actionErr = err
+ } else {
+ modelList = &res
+ }
+ case "apply":
+ if request.Mode == "" {
+ return sendFailed("MODEL_SOURCE_INVALID", "Target model source mode is required.", false)
+ }
+ res, err := d.modelSource.Apply(commandCtx, localmodels.ModelSourceApply{
+ Mode: request.Mode,
+ Runtime: request.Runtime,
+ LocalModelID: request.LocalModelID,
+ Byok: request.Byok,
+ })
+ if err != nil {
+ actionErr = err
+ } else {
+ status = &res
+ }
+ default:
+ return sendFailed("MODEL_SOURCE_INVALID", "Unsupported model source action.", false)
+ }
+
+ if actionErr != nil {
+ var typed *localmodels.ModelSourceError
+ if errors.As(actionErr, &typed) {
+ return sendFailed(typed.Code, typed.Message, typed.Retryable)
+ }
+ slog.Warn("model_source.command_failed", "action", request.Action)
+ return sendFailed(localmodels.CodeToolFailed, "Could not complete the model source action on this Computer.", true)
+ }
+
+ frame := wire.CapabilityModelSourceSucceeded{
+ ProtocolVersion: request.ProtocolVersion,
+ CommandID: request.CommandID,
+ RunnerID: request.RunnerID,
+ TenantID: request.TenantID,
+ OwnerActorID: request.OwnerActorID,
+ ConnectionEpoch: request.ConnectionEpoch,
+ ExpiresAt: request.ExpiresAt,
+ Type: wire.TypeExecuted,
+ Kind: wire.KindModelSource,
+ Action: request.Action,
+ Outcome: wire.OutcomeSucceeded,
+ Status: status,
+ TestResult: testResult,
+ ModelList: modelList,
+ }
+ payload, err := json.Marshal(frame)
+ if err != nil {
+ return err
+ }
+ return stream.Send(ctx, protocol.Event{
+ Type: protocol.EventCapabilityModelSourceSucceeded,
+ ProtocolVersion: command.ProtocolVersion,
+ CommandID: command.CommandID,
+ RunnerID: command.RunnerID,
+ TenantID: request.TenantID,
+ OwnerActorID: request.OwnerActorID,
+ ConnectionEpoch: command.ConnectionEpoch,
+ SentAt: time.Now().UTC(),
+ Payload: payload,
+ })
+}
diff --git a/apps/computer/local-daemon/internal/daemon/model_source_test.go b/apps/computer/local-daemon/internal/daemon/model_source_test.go
new file mode 100644
index 00000000..80bb3495
--- /dev/null
+++ b/apps/computer/local-daemon/internal/daemon/model_source_test.go
@@ -0,0 +1,150 @@
+package daemon
+
+import (
+ "context"
+ "encoding/json"
+ "testing"
+ "time"
+
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/localmodels"
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/protocol"
+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"
+)
+
+type fakeModelSourceManager struct {
+ deadline time.Time
+ lastApply localmodels.ModelSourceApply
+}
+
+func (f *fakeModelSourceManager) Status(ctx context.Context) (wire.ModelSourceStatus, error) {
+ f.deadline, _ = ctx.Deadline()
+ return wire.ModelSourceStatus{
+ Mode: "subscription",
+ Runtime: "claude",
+ RuntimeModel: "",
+ Byok: wire.ByokSummary{Configured: false, KeySaved: false},
+ }, nil
+}
+
+func (f *fakeModelSourceManager) TestByok(ctx context.Context, _ string, input wire.ByokConfigInput) (wire.ByokTestResult, error) {
+ f.deadline, _ = ctx.Deadline()
+ return wire.ByokTestResult{
+ Ok: true,
+ Protocol: "openai-chat",
+ BaseURL: input.BaseURL,
+ ModelID: input.ModelID,
+ ContextWindow: 128000,
+ }, nil
+}
+
+func (f *fakeModelSourceManager) ListByokModels(ctx context.Context, input wire.ByokConfigInput) (wire.ByokModelList, error) {
+ f.deadline, _ = ctx.Deadline()
+ return wire.ByokModelList{BaseURL: input.BaseURL, Models: []wire.ByokModelListModelsItem{{ID: "vendor/model"}}}, nil
+}
+
+func (f *fakeModelSourceManager) Apply(ctx context.Context, apply localmodels.ModelSourceApply) (wire.ModelSourceStatus, error) {
+ f.deadline, _ = ctx.Deadline()
+ f.lastApply = apply
+ return wire.ModelSourceStatus{
+ Mode: apply.Mode,
+ Runtime: apply.Runtime,
+ RuntimeModel: "localmodels-byok",
+ GatewayURL: "http://127.0.0.1:43120",
+ Byok: wire.ByokSummary{Configured: true, KeySaved: true, Protocol: "openai-chat", BaseURL: "https://api.example.com/v1", ModelID: "gpt-5.4"},
+ }, nil
+}
+
+func TestHandleModelSourceCommandValidatesOwnerExpiryAndActions(t *testing.T) {
+ manager := &fakeModelSourceManager{}
+ d := &Daemon{
+ computerID: "comp-1",
+ protocolVersion: protocol.Version,
+ modelSource: manager,
+ owners: []ComputerOwner{{TenantID: "tenant-1", OwnerActorID: "owner-1"}},
+ }
+ expires := time.Now().Add(time.Minute).UTC().Truncate(time.Millisecond)
+ stream := &browserEventStream{}
+
+ // 1. Status succeeds for the Computer's owner.
+ statusCmd, _ := json.Marshal(wire.CapabilityModelSource{
+ ProtocolVersion: protocol.Version,
+ CommandID: "cmd-status",
+ RunnerID: "comp-1",
+ TenantID: "tenant-1",
+ OwnerActorID: "owner-1",
+ ConnectionEpoch: 1,
+ ExpiresAt: expires.Format(time.RFC3339Nano),
+ Type: wire.TypeExecute,
+ Kind: wire.KindModelSource,
+ Action: "status",
+ })
+ if err := d.handleModelSourceCommand(t.Context(), stream, protocol.Command{
+ Type: protocol.CommandCapabilityModelSource, CommandID: "cmd-status", RunnerID: "comp-1", ConnectionEpoch: 1, Payload: statusCmd,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if len(stream.events) != 1 || stream.events[0].Type != protocol.EventCapabilityModelSourceSucceeded {
+ t.Fatalf("expected succeeded event, got %+v", stream.events)
+ }
+ if !manager.deadline.Equal(expires) {
+ t.Fatalf("expected command deadline %v, got %v", expires, manager.deadline)
+ }
+
+ // 2. Apply succeeds and returns updated ModelSourceStatus.
+ applyCmd, _ := json.Marshal(wire.CapabilityModelSource{
+ ProtocolVersion: protocol.Version,
+ CommandID: "cmd-apply",
+ RunnerID: "comp-1",
+ TenantID: "tenant-1",
+ OwnerActorID: "owner-1",
+ ConnectionEpoch: 1,
+ ExpiresAt: expires.Format(time.RFC3339Nano),
+ Type: wire.TypeExecute,
+ Kind: wire.KindModelSource,
+ Action: "apply",
+ Mode: "byok",
+ Runtime: "claude",
+ Byok: &wire.ByokConfigInput{
+ BaseURL: "https://api.example.com/v1",
+ APIKey: "sk-secret",
+ ModelID: "gpt-5.4",
+ },
+ })
+ if err := d.handleModelSourceCommand(t.Context(), stream, protocol.Command{
+ Type: protocol.CommandCapabilityModelSource, CommandID: "cmd-apply", RunnerID: "comp-1", ConnectionEpoch: 1, Payload: applyCmd,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if len(stream.events) != 2 || stream.events[1].Type != protocol.EventCapabilityModelSourceSucceeded {
+ t.Fatalf("expected apply succeeded event, got %+v", stream.events)
+ }
+ var succeeded wire.CapabilityModelSourceSucceeded
+ if err := json.Unmarshal(stream.events[1].Payload, &succeeded); err != nil {
+ t.Fatal(err)
+ }
+ if succeeded.Status == nil || succeeded.Status.Mode != "byok" || succeeded.Status.RuntimeModel != "localmodels-byok" {
+ t.Fatalf("unexpected apply status payload: %+v", succeeded.Status)
+ }
+
+ // 3. Another actor is rejected with MODEL_SOURCE_FORBIDDEN.
+ intruderCmd, _ := json.Marshal(wire.CapabilityModelSource{
+ ProtocolVersion: protocol.Version,
+ CommandID: "cmd-intruder",
+ RunnerID: "comp-1",
+ TenantID: "tenant-1",
+ OwnerActorID: "other-actor",
+ ConnectionEpoch: 1,
+ ExpiresAt: expires.Format(time.RFC3339Nano),
+ Type: wire.TypeExecute,
+ Kind: wire.KindModelSource,
+ Action: "status",
+ })
+ if err := d.handleModelSourceCommand(t.Context(), stream, protocol.Command{
+ Type: protocol.CommandCapabilityModelSource, CommandID: "cmd-intruder", RunnerID: "comp-1", ConnectionEpoch: 1, Payload: intruderCmd,
+ }); err != nil {
+ t.Fatal(err)
+ }
+ if len(stream.events) != 3 || stream.events[2].Type != protocol.EventCapabilityModelSourceFailed {
+ t.Fatalf("expected failed event for intruder, got %+v", stream.events)
+ }
+}
diff --git a/apps/computer/local-daemon/internal/linger/transport/gateway.go b/apps/computer/local-daemon/internal/linger/transport/gateway.go
index 3eede2e4..e0b2906c 100644
--- a/apps/computer/local-daemon/internal/linger/transport/gateway.go
+++ b/apps/computer/local-daemon/internal/linger/transport/gateway.go
@@ -143,6 +143,7 @@ var agentShapes = map[string]func() wire.Shape{
"CapabilityBrowserConnect": func() wire.Shape { return &wire.CapabilityBrowserConnect{} },
"CapabilityComputerPermission": func() wire.Shape { return &wire.CapabilityComputerPermission{} },
"CapabilityLocalModelsExecute": func() wire.Shape { return &wire.CapabilityLocalModelsExecute{} },
+ "CapabilityModelSource": func() wire.Shape { return &wire.CapabilityModelSource{} },
"OperationPrepare": func() wire.Shape { return &wire.OperationPrepare{} },
"ProviderPrepare": func() wire.Shape { return &wire.ProviderPrepare{} },
"SessionCompact": func() wire.Shape { return &wire.SessionCompact{} },
@@ -271,7 +272,8 @@ func decodeGatewayCommand(encoded []byte) (protocol.Command, error) {
protocol.CommandComputerToolCall,
protocol.CommandDebugInspect, protocol.CommandAgentCLICredentialPut,
protocol.CommandCapabilitySkillsScan, protocol.CommandCapabilityBrowserConnect,
- protocol.CommandCapabilityComputerPermission, protocol.CommandCapabilityLocalModels:
+ protocol.CommandCapabilityComputerPermission, protocol.CommandCapabilityLocalModels,
+ protocol.CommandCapabilityModelSource:
// Their handlers decode the generated shape from the frame itself.
command.Payload = append(json.RawMessage(nil), encoded...)
}
@@ -428,6 +430,7 @@ func (s *gatewayStream) Send(ctx context.Context, event protocol.Event) error {
event.Type == protocol.EventCapabilityBrowserConnected || event.Type == protocol.EventCapabilityBrowserFailed ||
event.Type == protocol.EventCapabilityComputerPermissionSucceeded || event.Type == protocol.EventCapabilityComputerPermissionFailed ||
event.Type == protocol.EventCapabilityLocalModelsAccepted || event.Type == protocol.EventCapabilityLocalModelsRefused ||
+ event.Type == protocol.EventCapabilityModelSourceSucceeded || event.Type == protocol.EventCapabilityModelSourceFailed ||
event.Type == protocol.EventLocalModels ||
event.Type == protocol.EventProviderPrepared || event.Type == protocol.EventSessionCompacted ||
event.Type == protocol.EventModelInvoked || event.Type == protocol.EventComputerToolResult:
diff --git a/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go b/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go
index 46027fc9..59292340 100644
--- a/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go
+++ b/apps/computer/local-daemon/internal/linger/transport/runner_wire_contract_test.go
@@ -118,7 +118,7 @@ func TestRunnerWireContractFixtures(t *testing.T) {
for _, kind := range []string{protocol.CommandRunnerWelcome, protocol.CommandRunnerReconciled, protocol.CommandRegistrationSnapshot,
protocol.CommandAgentRunnerEnsure, protocol.CommandAgentRunnerRemove, protocol.CommandAgentCLICredentialPut,
protocol.CommandDebugInspect, protocol.CommandCapabilitySkillsScan, protocol.CommandCapabilityBrowserConnect,
- protocol.CommandCapabilityComputerPermission, protocol.CommandCapabilityLocalModels, protocol.CommandOperationPrepare, protocol.CommandOperationStart, protocol.CommandOperationInput,
+ protocol.CommandCapabilityComputerPermission, protocol.CommandCapabilityLocalModels, protocol.CommandCapabilityModelSource, protocol.CommandOperationPrepare, protocol.CommandOperationStart, protocol.CommandOperationInput,
protocol.CommandOperationCancel, protocol.CommandOperationAck, protocol.CommandProviderPrepare,
protocol.CommandSessionCompact, protocol.CommandModelInvoke, protocol.CommandModelInvokeCancel,
protocol.CommandComputerToolCall} {
@@ -236,6 +236,8 @@ func runnerWireDaemonEvents(t *testing.T) []protocol.Event {
capability(protocol.EventCapabilityComputerPermissionFailed, "computer_permission", "failed", map[string]any{"action": "relaunch", "error": failure})
capability(protocol.EventCapabilityLocalModelsAccepted, "local_models", "accepted", map[string]any{"action": "download", "model_id": "qwen3-4b:Q4_K_M"})
capability(protocol.EventCapabilityLocalModelsRefused, "local_models", "refused", map[string]any{"action": "refresh", "refusal": map[string]any{"code": "TOOL_NOT_INSTALLED"}})
+ capability(protocol.EventCapabilityModelSourceSucceeded, "model_source", "succeeded", map[string]any{"action": "test", "test_result": map[string]any{"ok": true, "protocol": "anthropic", "base_url": "https://api.example.com", "model_id": "vendor/model", "context_window": 200000}})
+ capability(protocol.EventCapabilityModelSourceFailed, "model_source", "failed", map[string]any{"action": "apply", "error": failure})
appendEvent(protocol.EventLocalModels, map[string]any{"type": "runner.local_models", "protocol_version": "2", "runner_id": "computer-1", "sent_at": "2026-10-28T00:00:00Z", "revision": 1, "local_models": map[string]any{"available": false, "reason": map[string]any{"code": "TOOL_NOT_INSTALLED"}, "observed_at": "2026-10-28T00:00:00Z", "pools": []any{}, "models": []any{}}})
appendEvent(protocol.EventOperationPrepared, map[string]any{"prepare_command_id": "prepare-1", "prepared": true, "outcome": "ready", "duration_ms": 1})
appendEvent(protocol.EventOperationAccepted, map[string]any{"runner_pid": 123})
diff --git a/apps/computer/local-daemon/internal/localmodels/fake_tool_test.go b/apps/computer/local-daemon/internal/localmodels/fake_tool_test.go
index cd21e1a2..ea965530 100644
--- a/apps/computer/local-daemon/internal/localmodels/fake_tool_test.go
+++ b/apps/computer/local-daemon/internal/localmodels/fake_tool_test.go
@@ -43,6 +43,9 @@ type fakeLine struct {
func runFakeTool(args []string) int {
state := os.Getenv("LOCALMODELS_STATE")
+ if len(args) >= 6 && strings.Join(args[:5], " ") == "-P -s -m localmodels source" {
+ return runFakeSourceTool(state, args[5:])
+ }
if len(args) < 6 || strings.Join(args[:5], " ") != "-P -s -m localmodels library" {
fmt.Fprintln(os.Stderr, "unexpected invocation", args)
return 3
diff --git a/apps/computer/local-daemon/internal/localmodels/source.go b/apps/computer/local-daemon/internal/localmodels/source.go
new file mode 100644
index 00000000..00c45356
--- /dev/null
+++ b/apps/computer/local-daemon/internal/localmodels/source.go
@@ -0,0 +1,712 @@
+package localmodels
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "maps"
+ "os"
+ "os/exec"
+ "path/filepath"
+ "slices"
+ "strings"
+ "sync"
+ "time"
+
+ "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/process"
+ localworkspace "github.com/simplexai-labs/linger/apps/computer/local-daemon/internal/workspace"
+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"
+)
+
+const (
+ modelSourceSchema = "localmodels.model-source/v1"
+ modelSourceStatusSchema = "localmodels.model-source-status/v1"
+ modelSourceCheckSchema = "localmodels.byok-check/v1"
+ modelSourceModelsSchema = "localmodels.byok-models/v1"
+
+ defaultModelSourceTimeout = 3 * time.Minute
+ defaultByokTestTimeout = 45 * time.Second
+)
+
+// ModelSourceError carries a structured error code and message from localmodels
+// source operations without exposing local file paths or credentials.
+type ModelSourceError struct {
+ Code string
+ Message string
+ Retryable bool
+}
+
+func (e *ModelSourceError) Error() string { return e.Message }
+
+// ModelSourceApply describes one model-source switch requested by the Computer owner.
+type ModelSourceApply struct {
+ Mode string
+ Runtime string
+ LocalModelID string
+ Byok *wire.ByokConfigInput
+}
+
+// OverlayState is the active model-source profile persisted by localmodels in
+// <state_dir>/model-source.json.
+type OverlayState struct {
+ Mode string
+ Runtime string
+ RuntimeModel string
+ // ModelLabel names the model the source serves, as the person entered it.
+ ModelLabel string
+ GatewayURL string
+ Environment map[string]string
+ RuntimePaths map[string]string
+}
+
+type storedModelSourceFile struct {
+ Schema string `json:"schema"`
+ Mode string `json:"mode"`
+ Runtime string `json:"runtime"`
+ RuntimeModel string `json:"runtime_model"`
+ ModelLabel string `json:"model_label"`
+ GatewayURL *string `json:"gateway_url"`
+ Environment map[string]string `json:"environment"`
+ RuntimePaths map[string]string `json:"runtime_paths"`
+}
+
+var allowedOverlayEnvKeys = []string{"CODEX_HOME", "CLAUDE_CONFIG_DIR", "PI_CODING_AGENT_DIR"}
+
+// ReadOverlay reads the persisted model-source.json from stateDir, returning
+// nil when absent or invalid so callers preserve existing behavior.
+func ReadOverlay(stateDir string) *OverlayState {
+ if stateDir == "" {
+ return nil
+ }
+ raw, err := readBounded(filepath.Join(stateDir, "model-source.json"), 64*1024)
+ if err != nil {
+ return nil
+ }
+ var doc storedModelSourceFile
+ if err := json.Unmarshal(raw, &doc); err != nil {
+ return nil
+ }
+ if doc.Schema != modelSourceSchema ||
+ !slices.Contains([]string{"local", "subscription", "byok"}, doc.Mode) ||
+ !slices.Contains([]string{"claude", "codex", "pi"}, doc.Runtime) {
+ return nil
+ }
+ env := make(map[string]string)
+ for _, key := range allowedOverlayEnvKeys {
+ if value := strings.TrimSpace(doc.Environment[key]); value != "" && filepath.IsAbs(value) {
+ env[key] = filepath.Clean(value)
+ }
+ }
+ paths := make(map[string]string)
+ for _, rt := range []string{"claude", "codex", "pi"} {
+ if value := strings.TrimSpace(doc.RuntimePaths[rt]); value != "" && filepath.IsAbs(value) {
+ paths[rt] = filepath.Clean(value)
+ }
+ }
+ gatewayURL := ""
+ if doc.GatewayURL != nil {
+ gatewayURL = strings.TrimSpace(*doc.GatewayURL)
+ }
+ return &OverlayState{
+ Mode: doc.Mode,
+ Runtime: doc.Runtime,
+ RuntimeModel: strings.TrimSpace(doc.RuntimeModel),
+ ModelLabel: strings.TrimSpace(doc.ModelLabel),
+ GatewayURL: gatewayURL,
+ Environment: env,
+ RuntimePaths: paths,
+ }
+}
+
+func isManagedGatewayProfilePath(stateDir, candidate string) bool {
+ if stateDir == "" || candidate == "" {
+ return false
+ }
+ cleaned := filepath.Clean(candidate)
+ for _, sub := range []string{"gateway-home", "byok-home"} {
+ prefix := filepath.Clean(filepath.Join(stateDir, sub))
+ if cleaned == prefix || strings.HasPrefix(cleaned, prefix+string(filepath.Separator)) {
+ return true
+ }
+ }
+ return false
+}
+
+// OverlayEnvironment computes the effective Runtime discovery/execution
+// environment by applying stateDir/model-source.json over base without
+// restarting the Daemon.
+func OverlayEnvironment(base map[string]string, stateDir string) map[string]string {
+ result := maps.Clone(base)
+ if result == nil {
+ result = make(map[string]string)
+ }
+ overlay := ReadOverlay(stateDir)
+ if overlay == nil {
+ return result
+ }
+ for _, key := range allowedOverlayEnvKeys {
+ if isManagedGatewayProfilePath(stateDir, result[key]) {
+ delete(result, key)
+ }
+ }
+ if overlay.Mode == "subscription" {
+ return result
+ }
+ if len(overlay.Environment) > 0 {
+ if _, managedClaude := overlay.Environment["CLAUDE_CONFIG_DIR"]; managedClaude {
+ // Claude prefers its process environment to its settings, so an endpoint
+ // or key inherited from the Daemon's shell would bypass the source's profile.
+ for _, name := range localworkspace.ClaudeAuthEnvironmentNames {
+ delete(result, name)
+ }
+ }
+ for key, value := range overlay.Environment {
+ result[key] = value
+ }
+ return result
+ }
+ if overlay.Mode == "local" && stateDir != "" {
+ piProfile := filepath.Join(stateDir, "gateway-home", ".pi", "agent")
+ if info, err := os.Stat(piProfile); err == nil && info.IsDir() {
+ result["PI_CODING_AGENT_DIR"] = piProfile
+ }
+ }
+ return result
+}
+
+// OverlayRuntimePaths supplements configured Runtime executable paths with
+// managed Runtimes under <home>/runtime/harness/bin or recorded in model-source.json.
+func OverlayRuntimePaths(configured map[string]string, stateDir string) map[string]string {
+ result := maps.Clone(configured)
+ if result == nil {
+ result = make(map[string]string)
+ }
+ if overlay := ReadOverlay(stateDir); overlay != nil {
+ for rt, exe := range overlay.RuntimePaths {
+ if current := result[rt]; current == "" {
+ if info, err := os.Stat(exe); err == nil && info.Mode().IsRegular() {
+ result[rt] = exe
+ }
+ }
+ }
+ }
+ if stateDir != "" {
+ binDir := filepath.Clean(filepath.Join(stateDir, "..", "..", "harness", "bin"))
+ for _, rt := range []string{"claude", "codex", "pi"} {
+ if result[rt] != "" {
+ continue
+ }
+ candidate := filepath.Join(binDir, rt)
+ if info, err := os.Stat(candidate); err == nil && info.Mode().IsRegular() {
+ result[rt] = candidate
+ }
+ }
+ }
+ return result
+}
+
+// ModelSourceOptions configures a ModelSource controller.
+type ModelSourceOptions struct {
+ Tool *Tool
+ Environment map[string]string
+ JobDirectory string
+ HarnessRoot string
+ NodePath string
+ StatusTimeout time.Duration
+ TestTimeout time.Duration
+ ApplyTimeout time.Duration
+ // OnApplied runs synchronously after Apply mutates model-source.json or
+ // local models so Runtime discovery and library snapshots update before
+ // Apply returns to the caller. It returns each Runtime's model catalog as
+ // that discovery found it, nil when discovery failed.
+ OnApplied func(context.Context) map[string][]RuntimeModelOption
+}
+
+// RuntimeModelOption is one model a Runtime offers, as Runtime discovery
+// reports it.
+type RuntimeModelOption struct {
+ ID string
+ AllowedReasoningEffort []string
+ DefaultReasoningEffort string
+ IsDefault bool
+}
+
+// ModelSource inspects, tests and switches the Computer's active model source
+// (local models, native subscriptions, or BYOK mounted on Bifrost).
+type ModelSource struct {
+ tool *Tool
+ environment map[string]string
+ jobDirectory string
+ harnessRoot string
+ nodePath string
+ statusTimeout time.Duration
+ testTimeout time.Duration
+ applyTimeout time.Duration
+ onApplied func(context.Context) map[string][]RuntimeModelOption
+ mu sync.Mutex
+}
+
+// NewModelSource constructs a ModelSource controller for the given localmodels Tool.
+func NewModelSource(options ModelSourceOptions) *ModelSource {
+ harnessRoot := options.HarnessRoot
+ if harnessRoot == "" && options.Tool != nil && options.Tool.StateDirectory != "" {
+ harnessRoot = filepath.Clean(filepath.Join(options.Tool.StateDirectory, "..", "..", "harness"))
+ }
+ statusTimeout := options.StatusTimeout
+ if statusTimeout <= 0 {
+ statusTimeout = defaultStatusTimeout
+ }
+ testTimeout := options.TestTimeout
+ if testTimeout <= 0 {
+ testTimeout = defaultByokTestTimeout
+ }
+ applyTimeout := options.ApplyTimeout
+ if applyTimeout <= 0 {
+ applyTimeout = defaultModelSourceTimeout
+ }
+ return &ModelSource{
+ tool: options.Tool,
+ environment: maps.Clone(options.Environment),
+ jobDirectory: options.JobDirectory,
+ harnessRoot: harnessRoot,
+ nodePath: options.NodePath,
+ statusTimeout: statusTimeout,
+ testTimeout: testTimeout,
+ applyTimeout: applyTimeout,
+ onApplied: options.OnApplied,
+ }
+}
+
+type byokStdinPayload struct {
+ BaseURL string `json:"baseUrl"`
+ APIKey string `json:"apiKey,omitempty"`
+ ModelID string `json:"modelId"`
+ ContextWindow *uint64 `json:"contextWindow,omitempty"`
+ ReuseSavedKey *bool `json:"reuseSavedKey,omitempty"`
+}
+
+func encodeByokStdin(input *wire.ByokConfigInput) ([]byte, error) {
+ if input == nil {
+ return nil, nil
+ }
+ return json.Marshal(byokStdinPayload{
+ BaseURL: input.BaseURL,
+ APIKey: input.APIKey,
+ ModelID: input.ModelID,
+ ContextWindow: input.ContextWindow,
+ ReuseSavedKey: input.ReuseSavedKey,
+ })
+}
+
+type sourceStatusDocument struct {
+ Schema string `json:"schema"`
+ Mode string `json:"mode"`
+ Runtime string `json:"runtime"`
+ RuntimeModel string `json:"runtime_model"`
+ GatewayURL *string `json:"gateway_url"`
+ Environment map[string]string `json:"environment"`
+ RuntimePaths map[string]string `json:"runtime_paths"`
+ Byok wire.ByokSummary `json:"byok"`
+ OK *bool `json:"ok,omitempty"`
+ Code string `json:"code,omitempty"`
+ Message string `json:"message,omitempty"`
+}
+
+// Status reads the Computer's current model source and redacted BYOK summary.
+func (m *ModelSource) Status(ctx context.Context) (wire.ModelSourceStatus, error) {
+ if m.tool == nil || !m.tool.installed() {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: CodeToolNotInstalled,
+ Message: "The localmodels tool is not installed on this Computer.",
+ }
+ }
+ runCtx, cancel := context.WithTimeout(ctx, m.statusTimeout)
+ defer cancel()
+ args := []string{"-P", "-s", "-m", "localmodels", "source", "status", "--base-dir", m.tool.BaseDirectory, "--json"}
+ if m.harnessRoot != "" {
+ args = append(args, "--harness-root", m.harnessRoot)
+ }
+ stdout, exitCode, err := m.runTool(runCtx, "source_status", args, nil)
+ if err != nil {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: CodeToolFailed,
+ Message: "Could not read model source status on this Computer.",
+ Retryable: true,
+ }
+ }
+ if exitCode != 0 {
+ return wire.ModelSourceStatus{}, parseToolFailure(stdout, CodeToolFailed, "Could not read model source status on this Computer.")
+ }
+ return parseSourceStatus(stdout)
+}
+
+// TestByok probes a BYOK upstream endpoint for runtime, finding the wire
+// format and address it answers, without persisting credentials or mutating
+// the active model source.
+func (m *ModelSource) TestByok(ctx context.Context, runtime string, input wire.ByokConfigInput) (wire.ByokTestResult, error) {
+ if !slices.Contains([]string{"claude", "codex", "pi"}, runtime) {
+ return wire.ByokTestResult{}, &ModelSourceError{
+ Code: "MODEL_SOURCE_INVALID",
+ Message: "Unsupported AI runtime.",
+ }
+ }
+ var doc struct {
+ Protocol string `json:"protocol"`
+ BaseURL string `json:"base_url"`
+ ModelID string `json:"model_id"`
+ ContextWindow uint64 `json:"context_window"`
+ }
+ if err := m.runEndpointCommand(ctx, input, modelSourceCheckSchema, &doc, "check", "--runtime", runtime); err != nil {
+ return wire.ByokTestResult{}, err
+ }
+ return wire.ByokTestResult{
+ Ok: true,
+ Protocol: doc.Protocol,
+ BaseURL: doc.BaseURL,
+ ModelID: doc.ModelID,
+ ContextWindow: doc.ContextWindow,
+ }, nil
+}
+
+// ListByokModels lists the models a BYOK endpoint serves without persisting
+// credentials.
+func (m *ModelSource) ListByokModels(ctx context.Context, input wire.ByokConfigInput) (wire.ByokModelList, error) {
+ var list wire.ByokModelList
+ if err := m.runEndpointCommand(ctx, input, modelSourceModelsSchema, &list, "models"); err != nil {
+ return wire.ByokModelList{}, err
+ }
+ return list, nil
+}
+
+// runEndpointCommand runs a read-only `localmodels source` command against a
+// BYOK endpoint, its API key on stdin, and decodes its document into result.
+func (m *ModelSource) runEndpointCommand(ctx context.Context, input wire.ByokConfigInput, schema string, result any, verb string, flags ...string) error {
+ if m.tool == nil || !m.tool.installed() {
+ return &ModelSourceError{
+ Code: CodeToolNotInstalled,
+ Message: "The localmodels tool is not installed on this Computer.",
+ }
+ }
+ stdin, err := encodeByokStdin(&input)
+ if err != nil {
+ return &ModelSourceError{
+ Code: "BYOK_INVALID_CONFIG",
+ Message: "BYOK configuration is invalid.",
+ }
+ }
+ runCtx, cancel := context.WithTimeout(ctx, m.testTimeout)
+ defer cancel()
+ args := append([]string{"-P", "-s", "-m", "localmodels", "source", verb, "--config-stdin", "--json"}, flags...)
+ stdout, exitCode, runErr := m.runTool(runCtx, "source_"+verb, args, stdin)
+ if runErr != nil {
+ return &ModelSourceError{
+ Code: "BYOK_CHECK_TIMEOUT",
+ Message: "Timed out while reaching the BYOK endpoint.",
+ Retryable: true,
+ }
+ }
+ var outcome struct {
+ Schema string `json:"schema"`
+ OK bool `json:"ok"`
+ Code string `json:"code"`
+ Message string `json:"message"`
+ }
+ if json.Unmarshal(stdout, &outcome) != nil || (outcome.OK && json.Unmarshal(stdout, result) != nil) {
+ return &ModelSourceError{
+ Code: CodeToolFailed,
+ Message: "The BYOK endpoint check returned an unreadable response.",
+ Retryable: true,
+ }
+ }
+ if exitCode != 0 || !outcome.OK || outcome.Schema != schema {
+ code := outcome.Code
+ if code == "" {
+ code = "BYOK_CHECK_FAILED"
+ }
+ msg := strings.TrimSpace(outcome.Message)
+ if msg == "" {
+ msg = "Could not reach the BYOK endpoint."
+ }
+ return &ModelSourceError{
+ Code: code,
+ Message: clip(msg, 500),
+ Retryable: code == "BYOK_UNREACHABLE",
+ }
+ }
+ return nil
+}
+
+// Apply switches the Computer's active model source (unloading local models or
+// mounting BYOK on Bifrost as needed) and triggers synchronous Runtime refresh.
+func (m *ModelSource) Apply(ctx context.Context, apply ModelSourceApply) (wire.ModelSourceStatus, error) {
+ if m.tool == nil || !m.tool.installed() {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: CodeToolNotInstalled,
+ Message: "The localmodels tool is not installed on this Computer.",
+ }
+ }
+ if !slices.Contains([]string{"local", "subscription", "byok"}, apply.Mode) {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: "MODEL_SOURCE_INVALID",
+ Message: "Unsupported model source mode.",
+ }
+ }
+ if apply.Runtime != "" && !slices.Contains([]string{"claude", "codex", "pi"}, apply.Runtime) {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: "MODEL_SOURCE_INVALID",
+ Message: "Unsupported AI runtime.",
+ }
+ }
+ if apply.LocalModelID != "" && !ValidModelID(apply.LocalModelID) {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: "MODEL_UNKNOWN",
+ Message: "Invalid local model identifier.",
+ }
+ }
+ stdin, err := encodeByokStdin(apply.Byok)
+ if err != nil {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: "BYOK_INVALID_CONFIG",
+ Message: "BYOK configuration is invalid.",
+ }
+ }
+
+ m.mu.Lock()
+ defer m.mu.Unlock()
+
+ runCtx, cancel := context.WithTimeout(ctx, m.applyTimeout)
+ defer cancel()
+ args := []string{
+ "-P", "-s", "-m", "localmodels", "source", "apply",
+ "--mode", apply.Mode,
+ "--base-dir", m.tool.BaseDirectory,
+ "--json",
+ }
+ if apply.Runtime != "" {
+ args = append(args, "--runtime", apply.Runtime)
+ }
+ if apply.LocalModelID != "" {
+ args = append(args, "--model", apply.LocalModelID)
+ }
+ if m.harnessRoot != "" {
+ args = append(args, "--harness-root", m.harnessRoot)
+ }
+ if node := m.resolveNodePath(); node != "" {
+ args = append(args, "--node", node)
+ }
+ if len(stdin) > 0 {
+ args = append(args, "--config-stdin")
+ }
+ stdout, exitCode, runErr := m.runTool(runCtx, "source_apply", args, stdin)
+ if runErr != nil {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: CodeToolFailed,
+ Message: "Model source switch timed out or could not run on this Computer.",
+ Retryable: true,
+ }
+ }
+ if exitCode != 0 {
+ return wire.ModelSourceStatus{}, parseToolFailure(stdout, CodeToolFailed, "Could not switch model source on this Computer.")
+ }
+ status, err := parseSourceStatus(stdout)
+ if err != nil {
+ return wire.ModelSourceStatus{}, err
+ }
+ // Persist runtime_paths discovered by source apply into model-source.json so
+ // OverlayRuntimePaths can resolve newly installed managed runtimes immediately.
+ m.persistRuntimePaths(stdout)
+ var catalogs map[string][]RuntimeModelOption
+ if m.onApplied != nil {
+ catalogs = m.onApplied(runCtx)
+ }
+ status.RuntimeModel, status.ReasoningEffort = agentRuntimeModel(status.Runtime, status.RuntimeModel, catalogs[status.Runtime])
+ return status, nil
+}
+
+// agentRuntimeModel picks the model the Computer's Agents run after a switch:
+// the target model when the Runtime's catalog offers it, else the catalog's
+// default, else its first entry. A Runtime without a catalog runs the target
+// model, or its host default under the id Agent Service and TeamHub use for
+// it. The effort is the model's default, else its first allowed one, because
+// a model that offers efforts needs one.
+func agentRuntimeModel(runtime, target string, catalog []RuntimeModelOption) (string, string) {
+ if len(catalog) == 0 {
+ if target != "" {
+ return target, ""
+ }
+ return runtime + "-default", ""
+ }
+ index := slices.IndexFunc(catalog, func(model RuntimeModelOption) bool { return target != "" && model.ID == target })
+ if index < 0 {
+ index = max(0, slices.IndexFunc(catalog, func(model RuntimeModelOption) bool { return model.IsDefault }))
+ }
+ model := catalog[index]
+ effort := model.DefaultReasoningEffort
+ if effort == "" && len(model.AllowedReasoningEffort) > 0 {
+ effort = model.AllowedReasoningEffort[0]
+ }
+ return model.ID, effort
+}
+
+func (m *ModelSource) persistRuntimePaths(stdout []byte) {
+ if m.tool == nil || m.tool.StateDirectory == "" {
+ return
+ }
+ var doc sourceStatusDocument
+ if err := json.Unmarshal(stdout, &doc); err != nil || len(doc.RuntimePaths) == 0 {
+ return
+ }
+ stateFile := filepath.Join(m.tool.StateDirectory, "model-source.json")
+ raw, err := readBounded(stateFile, 64*1024)
+ if err != nil {
+ return
+ }
+ var current map[string]any
+ if err := json.Unmarshal(raw, &current); err != nil {
+ return
+ }
+ current["runtime_paths"] = doc.RuntimePaths
+ encoded, err := json.MarshalIndent(current, "", " ")
+ if err != nil {
+ return
+ }
+ tmp := stateFile + ".paths.tmp"
+ if err := os.WriteFile(tmp, append(encoded, '\n'), 0o600); err != nil {
+ return
+ }
+ _ = os.Rename(tmp, stateFile)
+}
+
+func (m *ModelSource) resolveNodePath() string {
+ if m.nodePath != "" {
+ return m.nodePath
+ }
+ if pathVal := m.environment["PATH"]; pathVal != "" {
+ for _, dir := range filepath.SplitList(pathVal) {
+ candidate := filepath.Join(dir, "node")
+ if info, err := os.Stat(candidate); err == nil && info.Mode().IsRegular() {
+ return candidate
+ }
+ }
+ }
+ if found, err := exec.LookPath("node"); err == nil {
+ return found
+ }
+ return ""
+}
+
+func parseSourceStatus(stdout []byte) (wire.ModelSourceStatus, error) {
+ var doc sourceStatusDocument
+ if err := json.Unmarshal(stdout, &doc); err != nil || doc.Schema != modelSourceStatusSchema {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: CodeToolFailed,
+ Message: "Model source status output did not match its contract.",
+ Retryable: true,
+ }
+ }
+ if !slices.Contains([]string{"local", "subscription", "byok"}, doc.Mode) ||
+ !slices.Contains([]string{"claude", "codex", "pi"}, doc.Runtime) {
+ return wire.ModelSourceStatus{}, &ModelSourceError{
+ Code: CodeToolFailed,
+ Message: "Model source status reported an unknown mode or runtime.",
+ Retryable: true,
+ }
+ }
+ status := wire.ModelSourceStatus{
+ Mode: doc.Mode,
+ Runtime: doc.Runtime,
+ RuntimeModel: doc.RuntimeModel,
+ Byok: doc.Byok,
+ }
+ if doc.GatewayURL != nil && *doc.GatewayURL != "" {
+ status.GatewayURL = *doc.GatewayURL
+ }
+ return status, nil
+}
+
+func parseToolFailure(stdout []byte, fallbackCode, fallbackMessage string) error {
+ var errDoc struct {
+ Code string `json:"code"`
+ Message string `json:"message"`
+ Detail string `json:"detail"`
+ }
+ if err := json.Unmarshal(stdout, &errDoc); err == nil {
+ code := strings.TrimSpace(errDoc.Code)
+ if code == "" {
+ code = fallbackCode
+ }
+ msg := strings.TrimSpace(errDoc.Message)
+ if msg == "" {
+ msg = strings.TrimSpace(errDoc.Detail)
+ }
+ if msg == "" {
+ msg = fallbackMessage
+ }
+ return &ModelSourceError{
+ Code: code,
+ Message: clip(msg, 500),
+ Retryable: code == "BYOK_UNREACHABLE" || code == "NETWORK_UNAVAILABLE",
+ }
+ }
+ return &ModelSourceError{Code: fallbackCode, Message: fallbackMessage, Retryable: true}
+}
+
+// runTool executes localmodels with stdout in a temporary file and stderr on
+// the null device (not pipes), matching Library.runOnce so a Bifrost gateway
+// child spawned by source apply survives after the CLI process exits.
+func (m *ModelSource) runTool(ctx context.Context, label string, args []string, stdin []byte) ([]byte, int, error) {
+ dir := m.jobDirectory
+ if dir == "" {
+ dir = os.TempDir()
+ } else if err := os.MkdirAll(dir, 0o700); err != nil {
+ return nil, -1, err
+ }
+ stdout, err := os.CreateTemp(dir, "model-source-*.out")
+ if err != nil {
+ return nil, -1, err
+ }
+ defer func() { _ = os.Remove(stdout.Name()) }()
+
+ cmd := exec.Command(m.tool.Python, args...)
+ cmd.Dir = m.tool.ModuleDirectory
+ values := make(map[string]string, len(m.environment)+4)
+ for key, value := range m.environment {
+ switch strings.ToUpper(key) {
+ case "PYTHONHOME", "PYTHONSTARTUP", "PYTHONINSPECT", "PYTHONPATH", "LOCALMODELS_STATE":
+ continue
+ }
+ values[key] = value
+ }
+ values["PYTHONPATH"] = m.tool.ModuleDirectory
+ values["LOCALMODELS_STATE"] = m.tool.StateDirectory
+ values["PYTHONNOUSERSITE"] = "1"
+ values["PYTHONDONTWRITEBYTECODE"] = "1"
+ cmd.Env = make([]string, 0, len(values))
+ for key, value := range values {
+ cmd.Env = append(cmd.Env, key+"="+value)
+ }
+ if len(stdin) > 0 {
+ cmd.Stdin = bytes.NewReader(stdin)
+ }
+ cmd.Stdout = stdout
+ process.Prepare(cmd)
+ startErr := cmd.Start()
+ _ = stdout.Close()
+ if startErr != nil {
+ return nil, -1, startErr
+ }
+ exited := make(chan error, 1)
+ go func() { exited <- cmd.Wait() }()
+ select {
+ case <-exited:
+ case <-ctx.Done():
+ _ = cmd.Process.Kill()
+ <-exited
+ return nil, -1, errors.Join(fmt.Errorf("%s cancelled", label), context.Cause(ctx))
+ }
+ exitCode := cmd.ProcessState.ExitCode()
+ output, readErr := readBounded(stdout.Name(), maxEventLine)
+ return output, exitCode, readErr
+}
diff --git a/apps/computer/local-daemon/internal/localmodels/source_test.go b/apps/computer/local-daemon/internal/localmodels/source_test.go
new file mode 100644
index 00000000..ac1d3951
--- /dev/null
+++ b/apps/computer/local-daemon/internal/localmodels/source_test.go
@@ -0,0 +1,266 @@
+package localmodels
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ wire "github.com/simplexai-labs/linger/contracts-go/runnergateway"
+)
+
+func runFakeSourceTool(state string, args []string) int {
+ verb := args[0]
+ stdinBytes, _ := io.ReadAll(os.Stdin)
+ _ = os.WriteFile(filepath.Join(state, "source-args.txt"), []byte(strings.Join(args, " ")), 0o600)
+ _ = os.WriteFile(filepath.Join(state, "source-stdin.json"), stdinBytes, 0o600)
+ out, err := os.ReadFile(filepath.Join(state, "source-"+verb+".json"))
+ if err != nil {
+ return 1
+ }
+ _, _ = os.Stdout.Write(out)
+ if codeBytes, err := os.ReadFile(filepath.Join(state, "source-"+verb+"-exit")); err == nil {
+ if strings.TrimSpace(string(codeBytes)) == "2" {
+ return 2
+ }
+ }
+ return 0
+}
+
+func TestOverlayEnvironmentSwitchesCleanlyBetweenByokLocalAndSubscription(t *testing.T) {
+ stateDir := t.TempDir()
+ byokClaude := filepath.Join(stateDir, "byok-home", ".claude")
+ byokCodex := filepath.Join(stateDir, "byok-home", ".codex")
+ gatewayPi := filepath.Join(stateDir, "gateway-home", ".pi", "agent")
+ if err := os.MkdirAll(gatewayPi, 0o700); err != nil {
+ t.Fatal(err)
+ }
+
+ base := map[string]string{
+ "HOME": "/Users/test",
+ "CLAUDE_CONFIG_DIR": filepath.Join(stateDir, "gateway-home", ".claude"),
+ "PI_CODING_AGENT_DIR": gatewayPi,
+ "ANTHROPIC_BASE_URL": "http://shell-gateway.example",
+ "ANTHROPIC_AUTH_TOKEN": "shell-token",
+ }
+
+ // Without model-source.json, base environment is preserved unchanged.
+ unchanged := OverlayEnvironment(base, stateDir)
+ if unchanged["PI_CODING_AGENT_DIR"] != gatewayPi {
+ t.Fatalf("expected initial gateway Pi profile preserved, got %v", unchanged)
+ }
+
+ // Switching to BYOK replaces gateway-home overrides with byok-home profiles.
+ writeModelSourceJSON(t, stateDir, map[string]any{
+ "schema": modelSourceSchema,
+ "mode": "byok",
+ "runtime": "claude",
+ "runtime_model": "localmodels-byok",
+ "gateway_url": "http://127.0.0.1:43120",
+ "environment": map[string]string{
+ "CLAUDE_CONFIG_DIR": byokClaude,
+ "CODEX_HOME": byokCodex,
+ },
+ })
+ byokEnv := OverlayEnvironment(base, stateDir)
+ if byokEnv["CLAUDE_CONFIG_DIR"] != byokClaude || byokEnv["CODEX_HOME"] != byokCodex {
+ t.Fatalf("expected byok-home environment overrides, got %v", byokEnv)
+ }
+ if _, hasStalePi := byokEnv["PI_CODING_AGENT_DIR"]; hasStalePi {
+ t.Fatalf("expected stale gateway-home PI_CODING_AGENT_DIR removed, got %v", byokEnv)
+ }
+ if _, inherited := byokEnv["ANTHROPIC_BASE_URL"]; inherited || byokEnv["ANTHROPIC_AUTH_TOKEN"] != "" {
+ t.Fatalf("expected the shell's Claude endpoint dropped under the BYOK profile, got %v", byokEnv)
+ }
+
+ // Switching to Subscription strips both gateway-home and byok-home overrides
+ // so native ~/.claude and ~/.codex credentials take effect without restart.
+ baseWithByok := map[string]string{
+ "HOME": "/Users/test",
+ "CLAUDE_CONFIG_DIR": byokClaude,
+ "CODEX_HOME": byokCodex,
+ "ANTHROPIC_BASE_URL": "http://shell-gateway.example",
+ }
+ writeModelSourceJSON(t, stateDir, map[string]any{
+ "schema": modelSourceSchema,
+ "mode": "subscription",
+ "runtime": "claude",
+ "runtime_model": "",
+ "gateway_url": nil,
+ "environment": map[string]string{},
+ })
+ subEnv := OverlayEnvironment(baseWithByok, stateDir)
+ if _, ok := subEnv["CLAUDE_CONFIG_DIR"]; ok {
+ t.Fatalf("expected CLAUDE_CONFIG_DIR stripped in subscription mode, got %v", subEnv)
+ }
+ if _, ok := subEnv["CODEX_HOME"]; ok {
+ t.Fatalf("expected CODEX_HOME stripped in subscription mode, got %v", subEnv)
+ }
+ if subEnv["ANTHROPIC_BASE_URL"] != "http://shell-gateway.example" {
+ t.Fatalf("expected the user's own Claude endpoint kept for subscriptions, got %v", subEnv)
+ }
+}
+
+func TestModelSourceStatusTestAndApplyKeepSecretsOnStdin(t *testing.T) {
+ ft := newFakeTool(t)
+ if err := os.WriteFile(filepath.Join(ft.state, "model-source.json"), []byte(`{"schema":"localmodels.model-source/v1","mode":"subscription","runtime":"claude","runtime_model":"","gateway_url":null,"environment":{}}`), 0o600); err != nil {
+ t.Fatal(err)
+ }
+ appliedCalls := 0
+ ms := NewModelSource(ModelSourceOptions{
+ Tool: &ft.tool,
+ Environment: map[string]string{"LOCALMODELS_FAKE_TOOL": "1"},
+ JobDirectory: filepath.Join(t.TempDir(), "jobs"),
+ NodePath: "/usr/local/bin/node",
+ OnApplied: func(context.Context) map[string][]RuntimeModelOption {
+ appliedCalls++
+ return map[string][]RuntimeModelOption{"codex": {
+ {ID: "gpt-5.5", IsDefault: true},
+ {ID: "localmodels-byok", AllowedReasoningEffort: []string{"low", "high"}, DefaultReasoningEffort: "high"},
+ }}
+ },
+ })
+
+ _ = os.WriteFile(filepath.Join(ft.state, "source-check.json"), []byte(`{
+ "schema": "localmodels.byok-check/v1",
+ "ok": true,
+ "protocol": "openai-responses",
+ "base_url": "https://api.example.com/v1",
+ "model_id": "gpt-5.4",
+ "context_window": 200000
+ }`), 0o600)
+
+ testRes, err := ms.TestByok(t.Context(), "codex", wire.ByokConfigInput{
+ BaseURL: "https://api.example.com/v1",
+ APIKey: "sk-never-in-argv",
+ ModelID: "gpt-5.4",
+ })
+ if err != nil {
+ t.Fatalf("TestByok error: %v", err)
+ }
+ if !testRes.Ok || testRes.ContextWindow != 200000 || testRes.ModelID != "gpt-5.4" {
+ t.Fatalf("unexpected TestByok result: %+v", testRes)
+ }
+ recordedArgs, _ := os.ReadFile(filepath.Join(ft.state, "source-args.txt"))
+ if strings.Contains(string(recordedArgs), "sk-never-in-argv") || !strings.Contains(string(recordedArgs), "--runtime codex") {
+ t.Fatalf("check argv = %s, want the Runtime and no API key", string(recordedArgs))
+ }
+ recordedStdin, _ := os.ReadFile(filepath.Join(ft.state, "source-stdin.json"))
+ if !strings.Contains(string(recordedStdin), `"apiKey":"sk-never-in-argv"`) {
+ t.Fatalf("expected API key on stdin JSON, got: %s", string(recordedStdin))
+ }
+
+ _ = os.WriteFile(filepath.Join(ft.state, "source-apply.json"), []byte(`{
+ "schema": "localmodels.model-source-status/v1",
+ "mode": "byok",
+ "runtime": "codex",
+ "runtime_model": "localmodels-byok",
+ "gateway_url": "http://127.0.0.1:43120",
+ "environment": {"CODEX_HOME": "/tmp/byok/.codex"},
+ "runtime_paths": {"codex": "/tmp/codex"},
+ "byok": {
+ "configured": true,
+ "protocol": "openai-responses",
+ "base_url": "https://api.example.com/v1",
+ "model_id": "gpt-5.4",
+ "context_window": 200000,
+ "key_saved": true
+ }
+ }`), 0o600)
+
+ status, err := ms.Apply(t.Context(), ModelSourceApply{
+ Mode: "byok",
+ Runtime: "codex",
+ Byok: &wire.ByokConfigInput{
+ BaseURL: "https://api.example.com/v1",
+ APIKey: "sk-never-in-argv",
+ ModelID: "gpt-5.4",
+ },
+ })
+ if err != nil {
+ t.Fatalf("Apply error: %v", err)
+ }
+ if status.Mode != "byok" || status.Runtime != "codex" || status.RuntimeModel != "localmodels-byok" ||
+ status.ReasoningEffort != "high" || !status.Byok.KeySaved {
+ t.Fatalf("unexpected Apply status: %+v", status)
+ }
+ if appliedCalls != 1 {
+ t.Fatalf("expected OnApplied called synchronously once, got %d", appliedCalls)
+ }
+
+ // Verify structured error propagation on failure.
+ _ = os.WriteFile(filepath.Join(ft.state, "source-check.json"), []byte(`{
+ "schema": "localmodels.byok-check/v1",
+ "ok": false,
+ "code": "BYOK_UPSTREAM_REJECTED",
+ "message": "Upstream endpoint returned HTTP 401."
+ }`), 0o600)
+ _ = os.WriteFile(filepath.Join(ft.state, "source-check-exit"), []byte("2"), 0o600)
+ _, err = ms.TestByok(t.Context(), "pi", wire.ByokConfigInput{
+ BaseURL: "https://api.example.com/v1",
+ ModelID: "gpt-5.4",
+ })
+ var sourceErr *ModelSourceError
+ if !errors.As(err, &sourceErr) || sourceErr.Code != "BYOK_UPSTREAM_REJECTED" {
+ t.Fatalf("expected BYOK_UPSTREAM_REJECTED error, got %v", err)
+ }
+
+ _ = os.WriteFile(filepath.Join(ft.state, "source-models.json"), []byte(`{
+ "schema": "localmodels.byok-models/v1",
+ "ok": true,
+ "base_url": "https://api.example.com",
+ "models": [{"id": "alpha", "name": null, "context_window": null}, {"id": "zeta", "name": "Zeta", "context_window": 200000}]
+ }`), 0o600)
+ list, err := ms.ListByokModels(t.Context(), wire.ByokConfigInput{BaseURL: "https://api.example.com/v1", APIKey: "sk-list"})
+ if err != nil || list.BaseURL != "https://api.example.com" || len(list.Models) != 2 ||
+ list.Models[1].Name != "Zeta" || list.Models[1].ContextWindow == nil || *list.Models[1].ContextWindow != 200000 {
+ t.Fatalf("ListByokModels = %+v, %v", list, err)
+ }
+ recordedArgs, _ = os.ReadFile(filepath.Join(ft.state, "source-args.txt"))
+ if !strings.HasPrefix(string(recordedArgs), "models --config-stdin") || strings.Contains(string(recordedArgs), "sk-list") {
+ t.Fatalf("models argv = %s", recordedArgs)
+ }
+}
+
+func writeModelSourceJSON(t *testing.T, stateDir string, payload map[string]any) {
+ t.Helper()
+ encoded, err := json.Marshal(payload)
+ if err != nil {
+ t.Fatal(err)
+ }
+ if err := os.WriteFile(filepath.Join(stateDir, "model-source.json"), encoded, 0o600); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestAgentRuntimeModelPrefersTargetThenCatalogDefault(t *testing.T) {
+ catalog := []RuntimeModelOption{
+ {ID: "opus", AllowedReasoningEffort: []string{"low", "max"}},
+ {ID: "default", IsDefault: true, AllowedReasoningEffort: []string{"medium"}, DefaultReasoningEffort: "medium"},
+ {ID: "localmodels-byok"},
+ }
+ for _, test := range []struct {
+ name, runtime, target string
+ catalog []RuntimeModelOption
+ model, effort string
+ }{
+ {name: "target offered", runtime: "claude", target: "localmodels-byok", catalog: catalog, model: "localmodels-byok"},
+ {name: "target missing", runtime: "claude", target: "gone", catalog: catalog, model: "default", effort: "medium"},
+ {name: "no target", runtime: "claude", catalog: catalog, model: "default", effort: "medium"},
+ {name: "first allowed effort", runtime: "claude", target: "opus", catalog: catalog, model: "opus", effort: "low"},
+ {name: "no default", runtime: "codex", catalog: catalog[2:], model: "localmodels-byok"},
+ {name: "no catalog keeps target", runtime: "pi", target: "localmodels/qwen", model: "localmodels/qwen"},
+ {name: "no catalog no target", runtime: "codex", model: "codex-default"},
+ } {
+ t.Run(test.name, func(t *testing.T) {
+ model, effort := agentRuntimeModel(test.runtime, test.target, test.catalog)
+ if model != test.model || effort != test.effort {
+ t.Fatalf("agentRuntimeModel = %q, %q; want %q, %q", model, effort, test.model, test.effort)
+ }
+ })
+ }
+}
diff --git a/apps/computer/local-daemon/internal/protocol/types.go b/apps/computer/local-daemon/internal/protocol/types.go
index 02de2ef1..9841d2e4 100644
--- a/apps/computer/local-daemon/internal/protocol/types.go
+++ b/apps/computer/local-daemon/internal/protocol/types.go
@@ -125,6 +125,7 @@ const (
CommandCapabilityBrowserConnect = wire.TypeExecute + ":" + wire.KindBrowserConnect
CommandCapabilityComputerPermission = wire.TypeExecute + ":" + wire.KindComputerPermission
CommandCapabilityLocalModels = wire.TypeExecute + ":" + wire.KindLocalModels
+ CommandCapabilityModelSource = wire.TypeExecute + ":" + wire.KindModelSource
CommandSessionCompact = wire.TypeExecute + ":" + wire.KindSessionCompact
CommandModelInvoke = wire.TypeExecute + ":" + wire.KindModelInvoke
CommandComputerToolCall = wire.TypeExecute + ":" + wire.KindComputerTool
@@ -158,6 +159,8 @@ const (
EventCapabilityComputerPermissionFailed = wire.TypeExecuted + ":" + wire.KindComputerPermission + ":" + wire.OutcomeFailed
EventCapabilityLocalModelsAccepted = wire.TypeExecuted + ":" + wire.KindLocalModels + ":" + wire.OutcomeAccepted
EventCapabilityLocalModelsRefused = wire.TypeExecuted + ":" + wire.KindLocalModels + ":" + wire.OutcomeRefused
+ EventCapabilityModelSourceSucceeded = wire.TypeExecuted + ":" + wire.KindModelSource + ":" + wire.OutcomeSucceeded
+ EventCapabilityModelSourceFailed = wire.TypeExecuted + ":" + wire.KindModelSource + ":" + wire.OutcomeFailed
EventSessionCompacted = wire.TypeExecuted + ":" + wire.KindSessionCompact
EventModelInvoked = wire.TypeExecuted + ":" + wire.KindModelInvoke
EventComputerToolResult = wire.TypeExecuted + ":" + wire.KindComputerTool
diff --git a/apps/computer/local-daemon/internal/provider/runtime_monitor.go b/apps/computer/local-daemon/internal/provider/runtime_monitor.go
index 5ca6f51f..f45d70db 100644
--- a/apps/computer/local-daemon/internal/provider/runtime_monitor.go
+++ b/apps/computer/local-daemon/internal/provider/runtime_monitor.go
@@ -11,8 +11,11 @@ import (
)
type RuntimeMonitorOptions struct {
- Initial DiscoveryResult
- Discovery DiscoveryOptions
+ Initial DiscoveryResult
+ Discovery DiscoveryOptions
+ // ResolveDiscovery returns the live DiscoveryOptions when Runtime profile
+ // environments or executable paths can change without restarting the Daemon.
+ ResolveDiscovery func() DiscoveryOptions
RefreshInterval time.Duration
FullRefreshEveryTicks int
OnChanged func(DiscoveryResult) error
@@ -34,7 +37,16 @@ func MonitorRuntimeDiagnostics(ctx context.Context, options RuntimeMonitorOption
if options.RefreshInterval <= 0 || options.FullRefreshEveryTicks < 1 || options.OnChanged == nil {
return errors.New("Runtime diagnostic monitor options are invalid")
}
+ resolveDiscovery := func() DiscoveryOptions {
+ if options.ResolveDiscovery != nil {
+ return options.ResolveDiscovery()
+ }
+ return options.Discovery
+ }
current := options.Initial
+ activeDiscovery := resolveDiscovery()
+ prevEnv := maps.Clone(activeDiscovery.Environment)
+ prevPaths := maps.Clone(activeDiscovery.ConfiguredPaths)
transientFailures := make(map[string]int)
authenticationFailures := make(map[string]int)
discover := options.Discover
@@ -53,13 +65,17 @@ func MonitorRuntimeDiagnostics(ctx context.Context, options RuntimeMonitorOption
case <-options.Refresh:
requested = true
}
+ activeDiscovery = resolveDiscovery()
+ envChanged := !maps.Equal(prevEnv, activeDiscovery.Environment) || !maps.Equal(prevPaths, activeDiscovery.ConfiguredPaths)
var next DiscoveryResult
var err error
- if (requested || tick%options.FullRefreshEveryTicks == 0 || runtimeExecutablesChanged(current.Diagnostics)) &&
+ if (requested || envChanged || tick%options.FullRefreshEveryTicks == 0 || runtimeExecutablesChanged(current.Diagnostics)) &&
(options.FullRefreshAllowed == nil || options.FullRefreshAllowed()) {
- next, err = discover(ctx, options.Discovery)
+ next, err = discover(ctx, activeDiscovery)
if err == nil {
requested = false
+ prevEnv = maps.Clone(activeDiscovery.Environment)
+ prevPaths = maps.Clone(activeDiscovery.ConfiguredPaths)
for _, diagnostic := range next.Diagnostics {
if diagnostic.Status == "ready" {
delete(authenticationFailures, diagnostic.Type)
@@ -68,7 +84,7 @@ func MonitorRuntimeDiagnostics(ctx context.Context, options RuntimeMonitorOption
next = retainReadyRuntimesDuringTransientFailures(current, next, transientFailures)
}
} else {
- next, err = refreshRuntimeAuthentication(ctx, current, options.Discovery, tick%options.FullRefreshEveryTicks == 0)
+ next, err = refreshRuntimeAuthentication(ctx, current, activeDiscovery, tick%options.FullRefreshEveryTicks == 0)
if err == nil {
if options.RuntimeBusy != nil && options.RuntimeBusy() {
next = retainReadyRuntimesDuringInconclusiveProbes(current, next)
@@ -83,7 +99,7 @@ func MonitorRuntimeDiagnostics(ctx context.Context, options RuntimeMonitorOption
}
return err
}
- if sameRuntimeDiagnostics(current.Diagnostics, next.Diagnostics) {
+ if !envChanged && sameRuntimeDiagnostics(current.Diagnostics, next.Diagnostics) {
// Retain internal probe provenance even when the public status did not
// change; only this provenance permits a safe auth-only recovery.
current = next
diff --git a/apps/computer/local-daemon/internal/workspace/claude_auth_environment.go b/apps/computer/local-daemon/internal/workspace/claude_auth_environment.go
index 65e486fb..8472aa1b 100644
--- a/apps/computer/local-daemon/internal/workspace/claude_auth_environment.go
+++ b/apps/computer/local-daemon/internal/workspace/claude_auth_environment.go
@@ -9,6 +9,17 @@ import (
"path/filepath"
)
+// ClaudeAuthEnvironmentNames are the variables that choose Claude's endpoint,
+// credentials and models.
+var ClaudeAuthEnvironmentNames = []string{
+ "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_MODEL",
+ "CLAUDE_CODE_OAUTH_TOKEN",
+ "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME",
+ "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME",
+ "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME",
+ "ANTHROPIC_DEFAULT_FABLE_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL_NAME",
+}
+
// ClaudeSourceEnvironment returns a copy of environment with the
// authentication and model variables the user's Claude settings declare, as
// a managed Claude process sees them; explicit values win.
@@ -57,14 +68,7 @@ func inheritClaudeAuthEnvironment(source string, environment map[string]string)
return errors.New("Claude local settings env must be a JSON object")
}
inherited := make(map[string]string)
- for _, name := range []string{
- "ANTHROPIC_API_KEY", "ANTHROPIC_AUTH_TOKEN", "ANTHROPIC_BASE_URL", "ANTHROPIC_MODEL",
- "CLAUDE_CODE_OAUTH_TOKEN",
- "ANTHROPIC_DEFAULT_HAIKU_MODEL", "ANTHROPIC_DEFAULT_HAIKU_MODEL_NAME",
- "ANTHROPIC_DEFAULT_SONNET_MODEL", "ANTHROPIC_DEFAULT_SONNET_MODEL_NAME",
- "ANTHROPIC_DEFAULT_OPUS_MODEL", "ANTHROPIC_DEFAULT_OPUS_MODEL_NAME",
- "ANTHROPIC_DEFAULT_FABLE_MODEL", "ANTHROPIC_DEFAULT_FABLE_MODEL_NAME",
- } {
+ for _, name := range ClaudeAuthEnvironmentNames {
encoded, present := values[name]
if !present {
continue
diff --git a/apps/computer/package.json b/apps/computer/package.json
index 71e6e78e..8e251e4b 100644
--- a/apps/computer/package.json
+++ b/apps/computer/package.json
@@ -1,6 +1,6 @@
{
"name": "@linger/computer",
- "version": "0.53.0",
+ "version": "0.54.0",
"description": "Local Computer: resident Daemon, control CLI, and Runner Gateway transport.",
"private": true,
"type": "module",
diff --git a/apps/computer/tests/runner-wire-contract.test.ts b/apps/computer/tests/runner-wire-contract.test.ts
index 291ef747..f6df0aeb 100644
--- a/apps/computer/tests/runner-wire-contract.test.ts
+++ b/apps/computer/tests/runner-wire-contract.test.ts
@@ -154,6 +154,14 @@ const agentFrames = [
model_id: "qwen3-4b:Q4_K_M",
unload_first: ["gemma3-4b:Q4_K_M"],
},
+ {
+ type: "execute",
+ kind: "model_source",
+ ...localCapability,
+ action: "test",
+ runtime: "claude",
+ byok: { base_url: "https://api.example.com/v1", model_id: "vendor/model" },
+ },
{
type: "prepare",
target: "operation",
diff --git a/apps/desktop/src/main/local-server.ts b/apps/desktop/src/main/local-server.ts
index 400793e3..b2e9a48a 100644
--- a/apps/desktop/src/main/local-server.ts
+++ b/apps/desktop/src/main/local-server.ts
@@ -69,6 +69,7 @@ import {
savedProviderKeys,
type ProviderKeyChanges,
} from "./provider-keys.js";
+import type { SetupByokCheck, SetupByokConfig } from "../shared/setup.js";
// The pinned linger source this build installs, written by the release build:
// downloaded from `url` (or a mirror of it), or bundled in the app at `file`.
@@ -149,6 +150,8 @@ export interface Transfer {
export interface LocalServerPlan {
// "local" runs tasks on an inference model deployed on this computer.
readonly runtime: "recommended" | "codex" | "claude" | "pi" | "local";
+ // Optional BYOK configuration mounted onto local Bifrost.
+ readonly byok?: SetupByokConfig;
// Provider keys edited on the page, saved before the installer runs.
readonly keys?: ProviderKeyChanges;
}
@@ -274,6 +277,7 @@ export interface LocalServerStatus {
readonly origin?: string;
// While the "signin" step waits for the person.
readonly signIn?: RuntimeSignIn;
+ readonly byokCheck?: SetupByokCheck;
// Where this installation moved the data of the earlier Simplex app,
// which it could not upgrade.
readonly legacyBackup?: string;
@@ -426,12 +430,14 @@ export class LocalServerModule implements Module {
#offDaemon: (() => void) | undefined;
#daemonFailure: string | undefined;
#signIn: RuntimeSignIn | undefined;
+ #byokCheck: SetupByokCheck | undefined;
#legacyBackup: string | undefined;
// The installer that runs the sign-in, and what the person asked for
// while the step waits.
#signInInstaller: InstallerApi | undefined;
#signInWake: (() => void) | undefined;
#switchTo: LocalRuntime | undefined;
+ #switchByok: SetupByokConfig | undefined;
#opened: string | undefined;
#serverCheck:
| { readonly at: number; readonly ok: Promise<boolean> }
@@ -532,6 +538,7 @@ export class LocalServerModule implements Module {
},
...(this.#origin ? { origin: this.#origin } : {}),
...(this.#signIn ? { signIn: this.#signIn } : {}),
+ ...(this.#byokCheck ? { byokCheck: this.#byokCheck } : {}),
...(this.#legacyBackup ? { legacyBackup: this.#legacyBackup } : {}),
};
}
@@ -625,6 +632,78 @@ export class LocalServerModule implements Module {
this.inspect();
}
+ async checkByok(byok: SetupByokConfig): Promise<void> {
+ if (this.#byokCheck?.state === "checking") return;
+ this.#byokCheck = { state: "checking" };
+ this.#ctx?.bus.emit("local-server.changed");
+ const home = this.#location ?? this.#home;
+ try {
+ const output = await new Promise<string>((resolve, reject) => {
+ const child = spawn(
+ process.execPath,
+ [this.#installerScript(), "--home", home, "--check-byok"],
+ {
+ stdio: ["pipe", "pipe", "pipe"],
+ windowsHide: true,
+ env: {
+ ...process.env,
+ ELECTRON_RUN_AS_NODE: "1",
+ LINGER_HOME: home,
+ },
+ signal: AbortSignal.timeout(45_000),
+ },
+ );
+ let last = "";
+ createInterface({ input: child.stdout }).on("line", (line) => {
+ if (line.trim()) last = line;
+ });
+ child.once("error", reject);
+ child.once("close", () => resolve(last));
+ child.stdin.end(JSON.stringify(byok));
+ });
+ const parsed = JSON.parse(output) as {
+ ok?: unknown;
+ protocol?: unknown;
+ modelId?: unknown;
+ contextWindow?: unknown;
+ message?: unknown;
+ };
+ if (
+ parsed.ok === true &&
+ (parsed.protocol === "openai-chat" ||
+ parsed.protocol === "openai-responses" ||
+ parsed.protocol === "anthropic")
+ ) {
+ this.#byokCheck = {
+ state: "ready",
+ protocol: parsed.protocol,
+ modelId: String(parsed.modelId ?? byok.modelId),
+ contextWindow:
+ typeof parsed.contextWindow === "number"
+ ? parsed.contextWindow
+ : 131_072,
+ };
+ } else {
+ this.#byokCheck = {
+ state: "failed",
+ message:
+ typeof parsed.message === "string" && parsed.message
+ ? parsed.message
+ : "Could not verify BYOK endpoint.",
+ };
+ }
+ } catch (error) {
+ this.#byokCheck = {
+ state: "failed",
+ message:
+ error instanceof Error
+ ? error.message
+ : "Could not verify BYOK endpoint.",
+ };
+ }
+ this.#ctx?.bus.emit("local-server.changed");
+ }
+
async #inspect(
signal: AbortSignal,
onDownload: (download: Transfer) => void,
@@ -853,18 +932,34 @@ export class LocalServerModule implements Module {
);
// Changed keys reach the services only when the installation runs
// again, even after one that finished.
- let job = await runInstaller(plan, keysChanged);
+ let job = await runInstaller(plan, keysChanged || Boolean(plan.byok));
// The runtime is installed but has no sign-in here: the server would
// never create the Another Me, so ask for it now. Another runtime
// reruns the installation for it.
for (;;) {
- const switchTo = job.signInRequired
+ const nextChoice = job.signInRequired
? await this.#awaitSignIn(installer, signal)
: undefined;
- if (!switchTo) break;
+ if (!nextChoice) break;
this.#endSignIn();
this.#step = "services";
- job = await runInstaller({ ...plan, runtime: switchTo }, true);
+ job =
+ typeof nextChoice === "string"
+ ? await runInstaller(
+ {
+ runtime: nextChoice,
+ ...(plan.keys ? { keys: plan.keys } : {}),
+ },
+ true,
+ )
+ : await runInstaller(
+ {
+ runtime: nextChoice.byok.runtime,
+ byok: nextChoice.byok,
+ ...(plan.keys ? { keys: plan.keys } : {}),
+ },
+ true,
+ );
}
// The desktop's Computer runs the runtime this installer set up, with
// its profile, rather than whatever its PATH finds.
@@ -955,14 +1050,16 @@ export class LocalServerModule implements Module {
async #awaitSignIn(
installer: InstallerApi,
signal: AbortSignal,
- ): Promise<LocalRuntime | undefined> {
+ ): Promise<LocalRuntime | { readonly byok: SetupByokConfig } | undefined> {
const runtime =
setupRuntime((await installer.runtime()).setupChoice) ?? "pi";
this.#signInInstaller = installer;
this.#switchTo = undefined;
+ this.#switchByok = undefined;
try {
for (;;) {
signal.throwIfAborted();
+ if (this.#switchByok) return { byok: this.#switchByok };
if (this.#switchTo) return this.#switchTo;
const login = await installer.runtimeLogin();
if (login.state === "ready") {
@@ -1195,6 +1292,12 @@ export class LocalServerModule implements Module {
this.#signInWake?.();
}
+ switchToByok(byok: SetupByokConfig): void {
+ if (!this.#signInInstaller) return;
+ this.#switchByok = byok;
+ this.#signInWake?.();
+ }
+
async openSignInPage(): Promise<void> {
const url = this.#signIn?.url;
if (url && new URL(url).protocol === "https:")
@@ -2626,8 +2729,9 @@ export class InstallerApi {
`/api/jobs/${encodeURIComponent(latest.id)}/cancel`,
{},
);
- const setupChoice =
- plan.runtime === "local"
+ const setupChoice = plan.byok
+ ? plan.byok.runtime
+ : plan.runtime === "local"
? "local-models"
: plan.runtime === "recommended"
? await this.#json<{ recommendation?: string }>("/api/setup").then(
@@ -2640,6 +2744,7 @@ export class InstallerApi {
job = await this.#json<Job>("/api/jobs", {
instance: LOCAL_INSTANCE,
...(setupChoice ? { setupChoice } : {}),
+ ...(plan.byok ? { byok: plan.byok } : {}),
});
}
// The person chose the local model after seeing what it needs, so its
diff --git a/apps/desktop/src/main/setup-command.test.ts b/apps/desktop/src/main/setup-command.test.ts
index 6f7c7204..b863cd4a 100644
--- a/apps/desktop/src/main/setup-command.test.ts
+++ b/apps/desktop/src/main/setup-command.test.ts
@@ -57,6 +57,42 @@ describe("parseSetupCommand", () => {
expect(
parseSetupCommand({ op: "local.signin.switch", runtime: "claude" }),
).toEqual({ op: "local.signin.switch", runtime: "claude" });
+ expect(
+ parseSetupCommand({
+ op: "local.byok.check",
+ byok: {
+ baseUrl: " https://api.example.com/v1 ",
+ apiKey: "sk-test",
+ modelId: " gpt-5.4 ",
+ runtime: "claude",
+ },
+ }),
+ ).toEqual({
+ op: "local.byok.check",
+ byok: {
+ baseUrl: "https://api.example.com/v1",
+ apiKey: "sk-test",
+ modelId: "gpt-5.4",
+ runtime: "claude",
+ },
+ });
+ expect(
+ parseSetupCommand({
+ op: "local.signin.byok",
+ byok: {
+ baseUrl: "https://api.anthropic.com",
+ modelId: "claude-sonnet-4-6",
+ runtime: "pi",
+ },
+ }),
+ ).toEqual({
+ op: "local.signin.byok",
+ byok: {
+ baseUrl: "https://api.anthropic.com",
+ modelId: "claude-sonnet-4-6",
+ runtime: "pi",
+ },
+ });
});
it("takes provider keys with local.start, trimmed, and nothing else", () => {
diff --git a/apps/desktop/src/main/setup-command.ts b/apps/desktop/src/main/setup-command.ts
index 3f84e25f..942fa16a 100644
--- a/apps/desktop/src/main/setup-command.ts
+++ b/apps/desktop/src/main/setup-command.ts
@@ -9,6 +9,18 @@ const providerKey = z
.trim()
.regex(/^[A-Za-z0-9._~+/=:-]{0,512}$/, "Invalid key");
+const byokConfig = z
+ .object({
+ baseUrl: z.string().trim().min(1).max(2048),
+ apiKey: z.string().max(4096).optional(),
+ modelId: z
+ .string()
+ .trim()
+ .regex(/^[-a-zA-Z0-9_./:@]{1,256}$/, "Invalid model ID"),
+ runtime: z.enum(["claude", "codex", "pi"]),
+ })
+ .strict();
+
const setupCommand = z.discriminatedUnion("op", [
z
.object({ op: z.literal("server.set"), serverUrl: z.string().max(2048) })
@@ -19,6 +31,7 @@ const setupCommand = z.discriminatedUnion("op", [
runtime: z
.enum(["recommended", "codex", "claude", "pi", "local"])
.optional(),
+ byok: byokConfig.optional(),
keys: z
.object({
composio: providerKey.optional(),
@@ -27,6 +40,12 @@ const setupCommand = z.discriminatedUnion("op", [
.optional(),
})
.strict(),
+ z
+ .object({
+ op: z.literal("local.byok.check"),
+ byok: byokConfig,
+ })
+ .strict(),
z.object({ op: z.literal("local.recheck") }).strict(),
z.object({ op: z.literal("local.location.pick") }).strict(),
z.object({ op: z.literal("local.location.reset") }).strict(),
@@ -44,6 +63,12 @@ const setupCommand = z.discriminatedUnion("op", [
runtime: z.enum(["codex", "claude", "pi"]),
})
.strict(),
+ z
+ .object({
+ op: z.literal("local.signin.byok"),
+ byok: byokConfig,
+ })
+ .strict(),
z.object({ op: z.literal("local.account.show"), on: z.boolean() }).strict(),
z.object({ op: z.literal("local.account.copy") }).strict(),
z.object({ op: z.literal("local.account.reveal") }).strict(),
diff --git a/apps/desktop/src/main/setup-window.ts b/apps/desktop/src/main/setup-window.ts
index 0c226dd7..c271160a 100644
--- a/apps/desktop/src/main/setup-window.ts
+++ b/apps/desktop/src/main/setup-window.ts
@@ -229,13 +229,19 @@ export class SetupWindowModule implements Module {
case "local.start": {
const local = ctx.get<LocalServerModule>("LocalServer");
const plan = {
- runtime: command.runtime ?? "recommended",
+ runtime: command.byok
+ ? command.byok.runtime
+ : (command.runtime ?? "recommended"),
+ ...(command.byok ? { byok: command.byok } : {}),
...(command.keys ? { keys: command.keys } : {}),
} as const;
// The page follows progress through state; a failure shows there too.
void local.begin(plan).catch(() => undefined);
return;
}
+ case "local.byok.check":
+ await ctx.get<LocalServerModule>("LocalServer").checkByok(command.byok);
+ return;
case "local.recheck":
ctx.get<LocalServerModule>("LocalServer").recheck();
return;
@@ -270,6 +276,9 @@ export class SetupWindowModule implements Module {
.get<LocalServerModule>("LocalServer")
.switchRuntime(command.runtime);
return;
+ case "local.signin.byok":
+ ctx.get<LocalServerModule>("LocalServer").switchToByok(command.byok);
+ return;
case "local.account.show":
await this.#account?.show(command.on);
return;
diff --git a/apps/desktop/src/shared/setup.ts b/apps/desktop/src/shared/setup.ts
index d6dc1975..ef61ef8d 100644
--- a/apps/desktop/src/shared/setup.ts
+++ b/apps/desktop/src/shared/setup.ts
@@ -49,6 +49,8 @@ export interface SetupLocalServer {
};
// While the "signin" step shows: the AI runtime's own sign-in.
readonly signIn?: SetupRuntimeSignIn;
+ // Latest BYOK endpoint check requested from the setup page.
+ readonly byokCheck?: SetupByokCheck;
// Once installed: the owner account, for signing in again after logging
// out.
readonly account?: SetupLocalAccount;
@@ -57,6 +59,29 @@ export interface SetupLocalServer {
readonly legacyBackup?: string;
}
+export type SetupByokProtocol =
+ | "openai-chat"
+ | "openai-responses"
+ | "anthropic";
+
+export interface SetupByokConfig {
+ readonly baseUrl: string;
+ readonly apiKey?: string;
+ readonly modelId: string;
+ readonly runtime: "claude" | "codex" | "pi";
+}
+
+export type SetupByokCheck =
+ | { readonly state: "idle" | "checking" }
+ | {
+ readonly state: "ready";
+ // The wire format the endpoint answered, found by the check.
+ readonly protocol: SetupByokProtocol;
+ readonly modelId: string;
+ readonly contextWindow: number;
+ }
+ | { readonly state: "failed"; readonly message: string };
+
// The owner account in the installation's local-account.json. The password
// is present only while the person chose to show it; error says why the
// file could not be read.
@@ -199,8 +224,13 @@ export type SetupCommand =
| {
readonly op: "local.start";
readonly runtime?: SetupLocalRuntime;
+ readonly byok?: SetupByokConfig;
readonly keys?: SetupProviderKeys;
}
+ | {
+ readonly op: "local.byok.check";
+ readonly byok: SetupByokConfig;
+ }
// Checks this computer for a local model again.
| { readonly op: "local.recheck" }
// Picks the install folder with the system picker, or goes back to the
@@ -217,6 +247,10 @@ export type SetupCommand =
readonly op: "local.signin.switch";
readonly runtime: "codex" | "claude" | "pi";
}
+ | {
+ readonly op: "local.signin.byok";
+ readonly byok: SetupByokConfig;
+ }
// The finished install's account: show or hide the password, copy it to
// the clipboard, or show its file in the file manager.
| { readonly op: "local.account.show"; readonly on: boolean }
diff --git a/apps/desktop/src/shell/setup-page.test.ts b/apps/desktop/src/shell/setup-page.test.ts
index cfb4a051..a837c6bc 100644
--- a/apps/desktop/src/shell/setup-page.test.ts
+++ b/apps/desktop/src/shell/setup-page.test.ts
@@ -282,13 +282,25 @@ describe("setup page Quick Install recommendation", () => {
);
expect($("local-recheck").hidden).toBe(false);
$("local-customize").click();
+ // Subscription is active by default when the local model is on hold;
+ // selecting Local model reveals the held card and disables Install.
+ expect($("subscription-row").hidden).toBe(false);
+ expect($("local-row").hidden).toBe(true);
+ document
+ .querySelector<HTMLButtonElement>(
+ '[data-plan="source"] [data-value="local"]',
+ )!
+ .click();
expect($("local-row").hidden).toBe(false);
+ expect($("subscription-row").hidden).toBe(true);
+ expect($("byok-row").hidden).toBe(true);
expect($("local-model-name").textContent).toBe("qwen3-8b");
expect($("local-sub").textContent).toBe(
"On hold: close other programs, then Check again.",
);
expect(($("local-model") as HTMLButtonElement).disabled).toBe(true);
expect($("local-model").getAttribute("aria-checked")).toBe("false");
+ expect(($("local-install") as HTMLButtonElement).disabled).toBe(true);
$("local-recheck").click();
await vi.waitFor(() =>
expect(run).toHaveBeenCalledWith({ op: "local.recheck" }),
@@ -331,6 +343,11 @@ describe("setup page Quick Install recommendation", () => {
);
expect($("local-recheck").hidden).toBe(false);
$("local-customize").click();
+ document
+ .querySelector<HTMLButtonElement>(
+ '[data-plan="source"] [data-value="local"]',
+ )!
+ .click();
expect($("local-sub").textContent).toBe(
"On hold: 12.7 GB memory needed, 2.7 GB free",
);
@@ -406,14 +423,20 @@ describe("setup page Quick Install recommendation", () => {
"welcome",
);
$("local-customize").click();
+ const source = (value: string) =>
+ document.querySelector<HTMLButtonElement>(
+ `[data-plan="source"] [data-value="${value}"]`,
+ )!;
const option = (value: string) =>
document.querySelector<HTMLButtonElement>(
`[data-plan="runtime"] [data-value="${value}"]`,
)!;
option("recommended").click();
push(welcome(capable));
- expect(option("recommended").hidden).toBe(true);
- expect(option("pi").getAttribute("aria-checked")).toBe("true");
+ expect(source("local").getAttribute("aria-checked")).toBe("true");
+ expect($("local-row").hidden).toBe(false);
+ expect($("subscription-row").hidden).toBe(true);
+ expect($("byok-row").hidden).toBe(true);
expect($("local-model").getAttribute("aria-checked")).toBe("true");
$("local-install").click();
await vi.waitFor(() =>
@@ -421,24 +444,32 @@ describe("setup page Quick Install recommendation", () => {
);
});
- it("marks the recommendation under Customize and installs the person's choice", async () => {
+ it("marks the recommendation under Customize and keeps model sources mutually exclusive", async () => {
const { run } = await openPage(welcome(capable), "welcome");
$("local-customize").click();
+ const source = (value: string) =>
+ document.querySelector<HTMLButtonElement>(
+ `[data-plan="source"] [data-value="${value}"]`,
+ )!;
const option = (value: string) =>
document.querySelector<HTMLButtonElement>(
`[data-plan="runtime"] [data-value="${value}"]`,
)!;
- expect(option("pi").dataset.recommended).toBe("true");
- expect(option("pi").getAttribute("aria-checked")).toBe("true");
- expect(option("codex").dataset.recommended).toBe("false");
- expect(option("recommended").hidden).toBe(true);
- expect($("runtime-sub").textContent).toBe("Recommended: Pi.");
+ expect(source("local").dataset.recommended).toBe("true");
+ expect(source("local").getAttribute("aria-checked")).toBe("true");
+ expect(source("subscription").dataset.recommended).toBe("false");
+ expect($("local-row").hidden).toBe(false);
+ expect($("subscription-row").hidden).toBe(true);
+ expect($("byok-row").hidden).toBe(true);
expect($("local-sub").textContent).toContain(
"Recommended for this computer",
);
expect($("local-model").getAttribute("aria-checked")).toBe("true");
+ source("subscription").click();
+ expect($("local-row").hidden).toBe(true);
+ expect($("subscription-row").hidden).toBe(false);
+ expect($("byok-row").hidden).toBe(true);
option("claude").click();
- expect($("local-model").getAttribute("aria-checked")).toBe("false");
expect($("local-install-label").textContent).toBe("Install");
$("local-install").click();
await vi.waitFor(() =>
@@ -452,69 +483,125 @@ describe("setup page Quick Install recommendation", () => {
"Recommended for this computer: Local model + Pi",
);
});
- it("offers the local model only with the Pi runtime", async () => {
- const { run } = await openPage(welcome(capable), "welcome");
- // Quick Install follows the tool's pick: Pi with the local model.
- expect($("plan-summary").textContent).toBe(
- "Recommended for this computer: Local model + Pi",
- );
- $("local-customize").click();
- const option = (value: string) =>
- document.querySelector<HTMLButtonElement>(
- `[data-plan="runtime"] [data-value="${value}"]`,
- )!;
- const local = $("local-model") as HTMLButtonElement;
- expect(local.getAttribute("aria-disabled")).toBe("false");
- expect(local.hasAttribute("aria-describedby")).toBe(false);
- expect($("local-pi-only").hidden).toBe(true);
- for (const runtime of ["codex", "claude"]) {
- option(runtime).click();
- // Greyed, still focusable, and it says why.
- expect(local.getAttribute("aria-checked")).toBe("false");
- expect(local.getAttribute("aria-disabled")).toBe("true");
- expect(local.disabled).toBe(false);
- expect(local.getAttribute("aria-describedby")).toBe("local-pi-only");
- expect($("local-pi-only").hidden).toBe(false);
- expect($("local-pi-only").textContent).toBe(
- "Local models are only available with the Pi runtime.",
- );
- // Clicking or pressing it does not pick it, nor switch the runtime.
- local.click();
- expect(local.getAttribute("aria-checked")).toBe("false");
- expect(option(runtime).getAttribute("aria-checked")).toBe("true");
- }
- // Pi alone: the local model is off until chosen again.
- option("pi").click();
- expect(local.getAttribute("aria-disabled")).toBe("false");
- expect($("local-pi-only").hidden).toBe(true);
- expect(local.getAttribute("aria-checked")).toBe("false");
- local.click();
- expect(local.getAttribute("aria-checked")).toBe("true");
- $("local-install").click();
- await vi.waitFor(() =>
- expect(installed(run)).toEqual([{ op: "local.start", runtime: "local" }]),
- );
- });
- it("keeps a held local model on hold with Pi and says Pi is needed otherwise", async () => {
- await openPage(welcome(held), "welcome");
+ it("configures BYOK across all runtimes with tooltip, Check, and secret scrubbing", async () => {
+ const { run, push } = await openPage(welcome(small), "welcome");
$("local-customize").click();
- const local = $("local-model") as HTMLButtonElement;
- // Codex is the tool's pick here.
- expect(local.disabled).toBe(true);
- expect($("local-pi-only").hidden).toBe(false);
+ const byokSource = document.querySelector<HTMLButtonElement>(
+ '[data-plan="source"] [data-value="byok"]',
+ )!;
+ expect(byokSource.getAttribute("aria-describedby")).toBe("byok-tip-text");
+ expect($("byok-tip-text").textContent).toContain("Bring Your Own Key");
+ byokSource.click();
+ expect($("byok-row").hidden).toBe(false);
+ expect($("local-row").hidden).toBe(true);
+ expect($("subscription-row").hidden).toBe(true);
+ expect(($("local-install") as HTMLButtonElement).disabled).toBe(true);
+
document
.querySelector<HTMLButtonElement>(
- '[data-plan="runtime"] [data-value="pi"]',
+ '[data-byok="runtime"] [data-value="codex"]',
)!
.click();
- expect($("local-pi-only").hidden).toBe(true);
- expect(local.getAttribute("aria-disabled")).toBe("false");
- // Pi does not lift the hold: the model still waits for free memory.
- expect(local.disabled).toBe(true);
- expect($("local-sub").textContent).toBe(
- "On hold: close other programs, then Check again.",
+ const urlInput = $("byok-url") as HTMLInputElement;
+ const keyInput = $("byok-key") as HTMLInputElement;
+ const modelInput = $("byok-model") as HTMLInputElement;
+ urlInput.value = "https://api.example.com/v1";
+ urlInput.dispatchEvent(new Event("input"));
+ keyInput.value = "sk-top-secret";
+ keyInput.dispatchEvent(new Event("input"));
+ modelInput.value = "gpt-5.4";
+ modelInput.dispatchEvent(new Event("input"));
+
+ expect(($("local-install") as HTMLButtonElement).disabled).toBe(false);
+ expect($("plan-summary").textContent).toBe("BYOK · Codex · gpt-5.4");
+
+ $("byok-check").click();
+ await vi.waitFor(() =>
+ expect(run).toHaveBeenCalledWith({
+ op: "local.byok.check",
+ byok: {
+ runtime: "codex",
+ baseUrl: "https://api.example.com/v1",
+ apiKey: "sk-top-secret",
+ modelId: "gpt-5.4",
+ },
+ }),
+ );
+ const checkedState = welcome(small);
+ push({
+ ...checkedState,
+ localServer: {
+ ...checkedState.localServer,
+ byokCheck: {
+ state: "ready",
+ protocol: "openai-responses",
+ modelId: "gpt-5.4",
+ contextWindow: 200_000,
+ },
+ },
+ });
+ expect($("byok-status").textContent).toBe(
+ "Ready · gpt-5.4 (200k context) through OpenAI Responses",
+ );
+
+ $("local-install").click();
+ await vi.waitFor(() => {
+ expect(installed(run)).toEqual([
+ {
+ op: "local.start",
+ runtime: "codex",
+ byok: {
+ runtime: "codex",
+ baseUrl: "https://api.example.com/v1",
+ apiKey: "sk-top-secret",
+ modelId: "gpt-5.4",
+ },
+ },
+ ]);
+ expect(keyInput.value).toBe("");
+ });
+ });
+
+ it("offers Use BYOK instead inside the runtime OAuth sign-in modal", async () => {
+ const base = state("installing");
+ const { run } = await openPage({
+ ...base,
+ localServer: {
+ ...base.localServer,
+ steps: ["prepare", "services", "signin", "connect", "agents"],
+ step: "signin",
+ signIn: { runtime: "claude", state: "required" },
+ },
+ });
+ expect($("runtime-signin").hidden).toBe(false);
+ expect($("runtime-signin-byok").hidden).toBe(true);
+ $("runtime-signin-byok-toggle").click();
+ expect($("runtime-signin-byok").hidden).toBe(false);
+ const url = $("signin-byok-url") as HTMLInputElement;
+ const key = $("signin-byok-key") as HTMLInputElement;
+ const model = $("signin-byok-model") as HTMLInputElement;
+ url.value = "https://api.anthropic.com";
+ url.dispatchEvent(new Event("input"));
+ key.value = "sk-ant-fallback";
+ key.dispatchEvent(new Event("input"));
+ model.value = "claude-sonnet-4-6";
+ model.dispatchEvent(new Event("input"));
+ $("runtime-signin-byok").dispatchEvent(
+ new Event("submit", { cancelable: true }),
+ );
+ await vi.waitFor(() =>
+ expect(run).toHaveBeenCalledWith({
+ op: "local.signin.byok",
+ byok: {
+ runtime: "claude",
+ baseUrl: "https://api.anthropic.com",
+ apiKey: "sk-ant-fallback",
+ modelId: "claude-sonnet-4-6",
+ },
+ }),
);
+ expect(key.value).toBe("");
});
});
diff --git a/apps/desktop/src/shell/setup.html b/apps/desktop/src/shell/setup.html
index 12887665..dd13c3f1 100644
--- a/apps/desktop/src/shell/setup.html
+++ b/apps/desktop/src/shell/setup.html
@@ -659,6 +659,128 @@
overflow: hidden;
padding: 0 4px 10px;
}
+ .fold[data-open="true"] > div {
+ overflow: visible;
+ }
+ .choice[hidden],
+ .byok-box[hidden],
+ .signin-byok[hidden] {
+ display: none !important;
+ }
+ .byok-tip-btn {
+ position: relative;
+ }
+ .byok-tooltip {
+ position: absolute;
+ bottom: calc(100% + 8px);
+ right: 0;
+ z-index: 30;
+ width: 248px;
+ padding: 8px 10px;
+ border-radius: 9px;
+ background: #1f1f1d;
+ color: #f7f7f4;
+ font-size: 11.5px;
+ font-weight: 450;
+ line-height: 1.4;
+ text-align: left;
+ white-space: normal;
+ box-shadow: 0 10px 24px -8px rgba(20, 20, 16, 0.45);
+ opacity: 0;
+ pointer-events: none;
+ transform: translateY(3px);
+ transition:
+ opacity 150ms ease,
+ transform 150ms ease;
+ }
+ .byok-tip-btn:hover .byok-tooltip,
+ .byok-tip-btn:focus-visible .byok-tooltip {
+ opacity: 1;
+ transform: translateY(0);
+ }
+ .choice.byok-box {
+ flex-direction: column;
+ align-items: stretch;
+ gap: 10px;
+ }
+ .byok-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ }
+ .byok-row label {
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 500;
+ }
+ .byok-grid {
+ display: grid;
+ gap: 7px;
+ }
+ .byok-grid input,
+ .signin-byok input,
+ .signin-byok select {
+ width: 100%;
+ height: 30px;
+ padding: 0 10px;
+ border: 1px solid #e2e2dc;
+ border-radius: 8px;
+ background: #fafaf8;
+ color: var(--ink);
+ font: inherit;
+ font-size: 12px;
+ }
+ .byok-grid input:focus,
+ .signin-byok input:focus,
+ .signin-byok select:focus {
+ outline: none;
+ border-color: var(--ink);
+ background: #fff;
+ }
+ .byok-actions {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 10px;
+ }
+ .byok-status {
+ flex: 1;
+ color: var(--faint);
+ font-size: 11.5px;
+ line-height: 1.35;
+ }
+ .byok-status[data-state="ready"] {
+ color: #2b7a3d;
+ }
+ .byok-status[data-state="failed"] {
+ color: var(--error);
+ }
+ .choice.optional-keys {
+ display: block;
+ }
+ .choice.optional-keys summary {
+ cursor: pointer;
+ color: var(--muted);
+ font-size: 12px;
+ font-weight: 500;
+ list-style: none;
+ }
+ .choice.optional-keys summary::-webkit-details-marker {
+ display: none;
+ }
+ .choice.optional-keys[open] summary {
+ margin-bottom: 8px;
+ color: var(--ink);
+ }
+ .signin-byok {
+ display: grid;
+ gap: 8px;
+ margin-top: 10px;
+ padding-top: 10px;
+ border-top: 1px solid #ecece7;
+ text-align: left;
+ }
.choices,
.panel {
border: 1px solid rgba(20, 20, 16, 0.07);
@@ -1167,6 +1289,22 @@
border-radius: 8px;
font: inherit;
}
+ .signin-byok {
+ display: grid;
+ gap: 7px;
+ margin-top: 8px;
+ padding-top: 10px;
+ border-top: 1px solid var(--line);
+ }
+ .signin-byok .seg {
+ width: 100%;
+ }
+ .signin-byok .seg button {
+ flex: 1;
+ }
+ .signin-byok input {
+ width: 100%;
+ }
.diagnostics {
display: flex;
flex-wrap: wrap;
@@ -1409,35 +1547,44 @@
<div class="choices">
<div class="choice">
<div class="text">
- <strong>AI runtime</strong
- ><span class="sub" id="runtime-sub">Runs your tasks.</span>
+ <strong>Model source</strong
+ ><span class="sub" id="source-sub"
+ >Where your agents get their models.</span
+ >
</div>
<div
class="seg"
role="radiogroup"
- aria-label="AI runtime"
- data-plan="runtime"
+ aria-label="Model source"
+ data-plan="source"
>
<span class="knob"></span>
- <button type="button" role="radio" data-value="recommended">
- Auto
+ <button type="button" role="radio" data-value="local">
+ Local model
</button>
- <button type="button" role="radio" data-value="codex">
- Codex
+ <button type="button" role="radio" data-value="subscription">
+ Subscription
</button>
- <button type="button" role="radio" data-value="claude">
- Claude Code
+ <button
+ type="button"
+ role="radio"
+ data-value="byok"
+ class="byok-tip-btn"
+ aria-describedby="byok-tip-text"
+ >
+ BYOK
+ <span class="byok-tooltip" id="byok-tip-text" role="tooltip"
+ >Bring Your Own Key — Connect your own OpenAI-compatible
+ or Anthropic API endpoint, key, and model through Linger's
+ local Bifrost gateway.</span
+ >
</button>
- <button type="button" role="radio" data-value="pi">Pi</button>
</div>
</div>
<div class="choice local" id="local-row" hidden>
<div class="text">
<strong>Local model</strong
- ><span class="sub" id="local-sub"></span
- ><span class="sub" id="local-pi-only" hidden
- >Local models are only available with the Pi runtime.</span
- >
+ ><span class="sub" id="local-sub"></span>
</div>
<button
type="button"
@@ -1451,12 +1598,91 @@
><small id="local-model-needs"></small>
</button>
</div>
- <div class="choice provider-keys">
+ <div class="choice" id="subscription-row" hidden>
<div class="text">
- <strong>API keys</strong
- ><span class="sub"
- >Optional. Composio connects apps; turn on voice inside the
- app. Keys stay on this computer.</span
+ <strong>AI runtime</strong
+ ><span class="sub" id="runtime-sub">Runs your tasks.</span>
+ </div>
+ <div
+ class="seg"
+ role="radiogroup"
+ aria-label="AI runtime"
+ data-plan="runtime"
+ >
+ <span class="knob"></span>
+ <button type="button" role="radio" data-value="recommended">
+ Auto
+ </button>
+ <button type="button" role="radio" data-value="codex">
+ Codex
+ </button>
+ <button type="button" role="radio" data-value="claude">
+ Claude Code
+ </button>
+ </div>
+ </div>
+ <div class="choice byok-box" id="byok-row" hidden>
+ <div class="byok-row">
+ <label>AI runtime</label>
+ <div
+ class="seg"
+ role="radiogroup"
+ aria-label="BYOK runtime"
+ data-byok="runtime"
+ >
+ <span class="knob"></span>
+ <button type="button" role="radio" data-value="claude">
+ Claude Code
+ </button>
+ <button type="button" role="radio" data-value="codex">
+ Codex
+ </button>
+ <button type="button" role="radio" data-value="pi">
+ Pi
+ </button>
+ </div>
+ </div>
+ <div class="byok-grid">
+ <input
+ id="byok-url"
+ type="url"
+ autocomplete="off"
+ spellcheck="false"
+ aria-label="BYOK endpoint URL"
+ placeholder="Endpoint URL (https://… or http://192.168.…)"
+ />
+ <input
+ id="byok-key"
+ type="password"
+ autocomplete="off"
+ spellcheck="false"
+ aria-label="BYOK API key"
+ placeholder="API key (stored privately on this computer)"
+ />
+ <input
+ id="byok-model"
+ type="text"
+ autocomplete="off"
+ spellcheck="false"
+ aria-label="BYOK model ID"
+ placeholder="Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)"
+ />
+ </div>
+ <div class="byok-actions">
+ <span class="byok-status" id="byok-status">
+ Mounted on local Bifrost for all runtimes.
+ </span>
+ <button type="button" class="change" id="byok-check">
+ Check
+ </button>
+ </div>
+ </div>
+ <details class="choice optional-keys" id="optional-keys">
+ <summary>App integrations (optional)</summary>
+ <div class="text">
+ <span class="sub"
+ >Composio connects apps; turn on voice inside the app. Keys
+ stay on this computer.</span
>
</div>
<div class="keys">
@@ -1477,7 +1703,7 @@
</button>
</div>
<p class="keys-note" id="keys-note"></p>
- </div>
+ </details>
<div class="choice">
<div class="text">
<strong>Install location</strong
@@ -1582,6 +1808,13 @@
>
Use a different runtime
</button>
+ <button
+ class="link quiet"
+ id="runtime-signin-byok-toggle"
+ type="button"
+ >
+ Use BYOK instead
+ </button>
<button
class="link quiet"
id="runtime-signin-logs"
@@ -1601,6 +1834,39 @@
Pi
</button>
</div>
+ <form class="signin-byok" id="runtime-signin-byok" hidden>
+ <input
+ id="signin-byok-url"
+ type="url"
+ autocomplete="off"
+ spellcheck="false"
+ aria-label="Sign-in BYOK endpoint URL"
+ placeholder="Endpoint URL (https://… or http://192.168.…)"
+ />
+ <input
+ id="signin-byok-key"
+ type="password"
+ autocomplete="off"
+ spellcheck="false"
+ aria-label="Sign-in BYOK API key"
+ placeholder="API key (stored privately on this computer)"
+ />
+ <input
+ id="signin-byok-model"
+ type="text"
+ autocomplete="off"
+ spellcheck="false"
+ aria-label="Sign-in BYOK model ID"
+ placeholder="Model ID (e.g. gpt-5.4 or claude-sonnet-4-6)"
+ />
+ <button
+ class="secondary"
+ id="runtime-signin-byok-submit"
+ type="submit"
+ >
+ Continue with BYOK
+ </button>
+ </form>
</div>
<div class="row" id="runtime-signin-busy">
<button class="link quiet" id="runtime-signin-open" type="button">
@@ -2019,15 +2285,47 @@
const models = state.localServer.localModels;
const pick = models.state === "checked" && models.recommendation;
if (pick === "local-models" && models.eligible && models.model)
- return { runtime: "pi", localModel: true };
- if (pick && pick !== "local-models" && RUNTIMES[pick])
- return { runtime: pick, localModel: false };
- return { runtime: "recommended", localModel: false };
+ return { source: "local", runtime: "pi", localModel: true };
+ if (pick === "codex" || pick === "claude")
+ return { source: "subscription", runtime: pick, localModel: false };
+ return {
+ source: "subscription",
+ runtime: "recommended",
+ localModel: false,
+ };
};
let plan;
// Whether the person changed the plan; until then it follows defaults().
let picked = false;
+ let pickedAutoBeforeCheck = false;
let customizing = false;
+ const emptyByok = () => ({
+ runtime: "claude",
+ baseUrl: "",
+ apiKey: "",
+ modelId: "",
+ });
+ let byok = emptyByok();
+ let signInByokOpen = false;
+ let signInByok = {
+ baseUrl: "",
+ apiKey: "",
+ modelId: "",
+ };
+ const byokProtocolLabels = {
+ anthropic: "Anthropic Messages",
+ "openai-chat": "OpenAI Chat Completions",
+ "openai-responses": "OpenAI Responses",
+ };
+ const trimByok = (value, runtime) => {
+ const apiKey = value.apiKey.trim();
+ return {
+ runtime,
+ baseUrl: value.baseUrl.trim(),
+ ...(apiKey ? { apiKey } : {}),
+ modelId: value.modelId.trim(),
+ };
+ };
// Provider keys typed or removed here ("" removes the saved one); kept
// only in the inputs and sent once with Install.
let keys = {};
@@ -2220,6 +2518,7 @@
$("runtime-signin").hidden = !open;
if (!open) {
otherRuntimes = false;
+ signInByokOpen = false;
$("runtime-signin-trouble").open = false;
return;
}
@@ -2230,7 +2529,7 @@
const pi = sign.runtime === "pi";
$("runtime-signin-title").textContent = "Sign in to " + name;
$("runtime-signin-lead").textContent = pi
- ? "Pi needs a model provider. Run pi in a terminal to sign in; setup continues by itself."
+ ? "Pi needs a model provider. Run pi in a terminal to sign in, or use BYOK below; setup continues by itself."
: "Your agents run on " +
name +
". Authorize it with " +
@@ -2249,6 +2548,9 @@
$("runtime-signin-logs").hidden = !failed;
$("runtime-signin-runtimes").hidden = !otherRuntimes && !pi;
$("runtime-signin-other").hidden = pi;
+ $("runtime-signin-byok").hidden = !signInByokOpen;
+ $("runtime-signin-byok-submit").disabled =
+ busy || !signInByok.baseUrl.trim() || !signInByok.modelId.trim();
for (const option of document.querySelectorAll("[data-switch]")) {
option.hidden = option.dataset.switch === sign.runtime;
option.disabled = busy;
@@ -2262,6 +2564,7 @@
? "If your browser didn't open, choose Open browser again, then paste the code the page shows."
: "If your browser didn't open, choose Open browser again.";
$("runtime-signin-paste").hidden = !sign.acceptsCode;
+ requestAnimationFrame(placeKnobs);
};
const renderLocal = (busy) => {
@@ -2269,12 +2572,10 @@
const recommended = defaults();
// Auto, picked before the check named a pick, means that pick; once
// it is known Auto no longer shows.
- if (
- picked &&
- plan.runtime === "recommended" &&
- recommended.runtime !== "recommended"
- )
+ if (pickedAutoBeforeCheck && recommended.runtime !== "recommended") {
picked = false;
+ pickedAutoBeforeCheck = false;
+ }
if (!picked) plan = recommended;
// The local model is offered only once this computer is known to
// serve it; until then its row does not show.
@@ -2301,14 +2602,22 @@
size(free.vramFreeBytes) +
" is free"
: "");
- if (!model) plan.localModel = false;
+ plan.localModel = plan.source === "local" && !!model;
const custom = !isDefaultPlan(local);
// Quick Install waits for the check, so it installs what it shows.
const checking = models.state === "checking";
- const known = recommended.runtime !== "recommended";
+ const known =
+ recommended.source === "local" ||
+ recommended.runtime !== "recommended";
const following = JSON.stringify(plan) === JSON.stringify(recommended);
const named = (choice) =>
- choice.localModel ? "Local model + Pi" : RUNTIMES[choice.runtime];
+ choice.source === "local"
+ ? "Local model + Pi"
+ : choice.source === "byok"
+ ? ["BYOK", RUNTIMES[byok.runtime], byok.modelId.trim()]
+ .filter(Boolean)
+ .join(" · ")
+ : RUNTIMES[choice.runtime];
$("welcome-lead").textContent = local.available
? "Runs on this computer, just for you. Takes a few minutes."
: "Connect this computer to your team's Linger.";
@@ -2336,19 +2645,19 @@
$("local-install-label").innerHTML = label;
document.querySelector('[data-step="welcome"]').dataset.customizing =
String(customizing && local.available);
- $("local-install").disabled ||= checking;
+ const byokIncomplete =
+ plan.source === "byok" &&
+ (!byok.baseUrl.trim() || !byok.modelId.trim());
+ const localUnavailable = plan.source === "local" && !model;
+ $("local-install").disabled ||=
+ checking || byokIncomplete || localUnavailable;
$("local-install").dataset.busy = String(checking);
$("local-install").setAttribute("aria-busy", String(checking));
$("plan-summary").textContent = checking
? "Finding the best setup for this computer"
: following && known
? "Recommended for this computer: " + named(plan)
- : [
- RUNTIMES[plan.runtime] || "Best AI runtime",
- plan.localModel && "Local model",
- ]
- .filter(Boolean)
- .join(" · ");
+ : named(plan) || "Best AI runtime";
// Why, in the localmodels tool's facts and words.
$("plan-why").textContent = fetching
? transferParts(fetching).join(" · ")
@@ -2417,10 +2726,17 @@
}
$("keys-note").textContent = "Applies when the installation runs.";
const shown = model || held;
- const runtime =
- plan.runtime === "recommended" ? recommended.runtime : plan.runtime;
- const piOnly = !!shown && runtime !== "pi";
- $("local-row").hidden = !shown;
+ $("source-sub").textContent =
+ recommended.source === "local"
+ ? "Recommended: Local model on this computer."
+ : known
+ ? "Recommended: Subscription (" +
+ RUNTIMES[recommended.runtime] +
+ ")."
+ : "Choose how your agents run.";
+ $("local-row").hidden = plan.source !== "local";
+ $("subscription-row").hidden = plan.source !== "subscription";
+ $("byok-row").hidden = plan.source !== "byok";
$("local-model").hidden = !shown;
$("local-recheck").hidden = !held || !local.available;
$("local-recheck").disabled = busy;
@@ -2435,8 +2751,8 @@
: "On hold: close other programs, then Check again."
: [
recommended.localModel
- ? "Recommended for this computer"
- : "Runs your tasks on this computer",
+ ? "Recommended for this computer · Runs on Pi via Bifrost"
+ : "Runs your tasks on this computer via Pi",
models.gpu,
]
.filter(Boolean)
@@ -2451,39 +2767,78 @@
]
.filter(Boolean)
.join(" · ");
- $("local-model").setAttribute(
- "aria-checked",
- String(plan.localModel),
- );
+ $("local-model").setAttribute("aria-checked", String(!!model));
$("local-model").disabled = busy || !model;
- // The local model runs only behind Pi: with another runtime it
- // stays focusable, greyed and says so, but does not toggle.
- $("local-pi-only").hidden = !piOnly;
- $("local-model").setAttribute("aria-disabled", String(piOnly));
- if (piOnly)
- $("local-model").setAttribute("aria-describedby", "local-pi-only");
- else $("local-model").removeAttribute("aria-describedby");
+ } else {
+ $("local-sub").textContent = checking
+ ? "Checking this computer…"
+ : models.reasons?.[0]?.message ||
+ "No local model fits this computer.";
}
- $("runtime-sub").textContent = known
+ const subKnown =
+ recommended.source === "subscription" &&
+ recommended.runtime !== "recommended";
+ $("runtime-sub").textContent = subKnown
? "Recommended: " + RUNTIMES[recommended.runtime] + "."
- : plan.localModel
- ? "Pi + local model."
- : "Runs your tasks.";
+ : "Sign in with your ChatGPT or Claude subscription.";
for (const seg of document.querySelectorAll("[data-plan]"))
for (const option of seg.querySelectorAll("button")) {
+ const field = seg.dataset.plan;
const value = option.dataset.value;
- option.setAttribute(
- "aria-checked",
- String(plan[seg.dataset.plan] === value),
- );
- // With the tool's pick known, it is marked and Auto is not
- // needed.
- option.hidden = known && value === "recommended";
- option.dataset.recommended = String(
- known && value === recommended.runtime,
- );
+ if (field === "source") {
+ option.setAttribute(
+ "aria-checked",
+ String(plan.source === value),
+ );
+ option.dataset.recommended = String(
+ known && value === recommended.source,
+ );
+ option.disabled = busy;
+ } else {
+ const subPick =
+ plan.runtime === "pi"
+ ? subKnown
+ ? recommended.runtime
+ : "recommended"
+ : plan.runtime;
+ option.setAttribute("aria-checked", String(subPick === value));
+ option.hidden = subKnown && value === "recommended";
+ option.dataset.recommended = String(
+ subKnown && value === recommended.runtime,
+ );
+ option.disabled = busy;
+ }
+ }
+ for (const seg of document.querySelectorAll("[data-byok]"))
+ for (const option of seg.querySelectorAll("button")) {
+ const field = seg.dataset.byok;
+ const value = option.dataset.value;
+ option.setAttribute("aria-checked", String(byok[field] === value));
option.disabled = busy;
}
+ $("byok-check").disabled =
+ busy || !byok.baseUrl.trim() || !byok.modelId.trim();
+ const byokCheck = local.byokCheck;
+ if (byokCheck?.state === "checking") {
+ $("byok-status").textContent = "Checking endpoint…";
+ $("byok-status").dataset.tone = "";
+ } else if (byokCheck?.state === "ready") {
+ $("byok-status").textContent =
+ "Ready · " +
+ byokCheck.modelId +
+ " (" +
+ Math.round(byokCheck.contextWindow / 1000) +
+ "k context) through " +
+ byokProtocolLabels[byokCheck.protocol];
+ $("byok-status").dataset.tone = "ok";
+ } else if (byokCheck?.state === "failed") {
+ $("byok-status").textContent = byokCheck.message;
+ $("byok-status").dataset.tone = "err";
+ } else {
+ $("byok-status").textContent =
+ "Mounted on local Bifrost for all runtimes.";
+ $("byok-status").dataset.tone = "";
+ }
requestAnimationFrame(placeKnobs);
// Installing. A restart after a reboot shows here as starting.
@@ -2801,11 +3156,22 @@
});
// The install runs on its own; this window follows its progress.
const install = async () => {
+ const byokPayload =
+ plan.source === "byok" ? trimByok(byok, byok.runtime) : undefined;
+ const runtime =
+ plan.source === "local"
+ ? "local"
+ : plan.source === "byok"
+ ? byok.runtime
+ : plan.runtime === "pi"
+ ? "recommended"
+ : plan.runtime;
const ok = await run(
{
op: "local.start",
// The installer sets up Pi with the local model for "local".
- runtime: plan.localModel ? "local" : plan.runtime,
+ runtime,
+ ...(byokPayload ? { byok: byokPayload } : {}),
...(customizing && Object.keys(keys).length ? { keys } : {}),
},
"local-error",
@@ -2839,6 +3205,31 @@
otherRuntimes = !otherRuntimes;
render();
});
+ $("runtime-signin-byok-toggle").addEventListener("click", () => {
+ signInByokOpen = !signInByokOpen;
+ render();
+ });
+ for (const [id, field] of [
+ ["signin-byok-url", "baseUrl"],
+ ["signin-byok-key", "apiKey"],
+ ["signin-byok-model", "modelId"],
+ ])
+ $(id).addEventListener("input", () => {
+ signInByok = { ...signInByok, [field]: $(id).value };
+ render();
+ });
+ $("runtime-signin-byok").addEventListener("submit", async (event) => {
+ event.preventDefault();
+ const runtime = state.localServer.signIn?.runtime ?? "claude";
+ if (!signInByok.baseUrl.trim() || !signInByok.modelId.trim()) return;
+ const payload = trimByok(signInByok, runtime);
+ $("signin-byok-key").value = "";
+ signInByok = { ...signInByok, apiKey: "" };
+ await run(
+ { op: "local.signin.byok", byok: payload },
+ "runtime-signin-error",
+ );
+ });
$("runtime-signin-logs").addEventListener("click", () =>
run({ op: "logs.open" }, "runtime-signin-error"),
);
@@ -2883,6 +3274,10 @@
);
const clearKeys = () => {
keys = {};
+ byok = { ...byok, apiKey: "" };
+ $("byok-key").value = "";
+ signInByok = { ...signInByok, apiKey: "" };
+ $("signin-byok-key").value = "";
for (const input of document.querySelectorAll("[data-key]")) {
input.value = "";
input.type = "password";
@@ -2922,6 +3317,10 @@
customizing = !customizing;
if (!customizing) {
picked = false;
+ pickedAutoBeforeCheck = false;
+ byok = emptyByok();
+ $("byok-url").value = "";
+ $("byok-model").value = "";
clearKeys();
const location = state.localServer.location;
if (location.custom || location.error)
@@ -2933,11 +3332,61 @@
for (const option of seg.querySelectorAll("button"))
option.addEventListener("click", () => {
picked = true;
- plan = { ...plan, [seg.dataset.plan]: option.dataset.value };
- // Another runtime than Pi does not run the local model.
- if (plan.runtime !== "pi") plan.localModel = false;
+ const field = seg.dataset.plan;
+ const value = option.dataset.value;
+ pickedAutoBeforeCheck =
+ field === "runtime" &&
+ value === "recommended" &&
+ state.localServer.localModels.state === "checking";
+ if (field === "source") {
+ const rec = defaults();
+ plan = {
+ ...plan,
+ source: value,
+ runtime:
+ value === "local"
+ ? "pi"
+ : plan.runtime === "pi"
+ ? rec.source === "subscription"
+ ? rec.runtime
+ : "recommended"
+ : plan.runtime,
+ localModel: value === "local",
+ };
+ } else {
+ plan = {
+ ...plan,
+ source: "subscription",
+ runtime: value,
+ localModel: false,
+ };
+ }
+ render();
+ });
+ for (const seg of document.querySelectorAll("[data-byok]"))
+ for (const option of seg.querySelectorAll("button"))
+ option.addEventListener("click", () => {
+ picked = true;
+ byok = { ...byok, [seg.dataset.byok]: option.dataset.value };
render();
});
+ for (const [id, field] of [
+ ["byok-url", "baseUrl"],
+ ["byok-key", "apiKey"],
+ ["byok-model", "modelId"],
+ ])
+ $(id).addEventListener("input", () => {
+ picked = true;
+ byok = { ...byok, [field]: $(id).value };
+ render();
+ });
+ $("byok-check").addEventListener("click", () => {
+ if (!byok.baseUrl.trim() || !byok.modelId.trim()) return;
+ run(
+ { op: "local.byok.check", byok: trimByok(byok, byok.runtime) },
+ "local-error",
+ );
+ });
$("location-change").addEventListener("click", () =>
run({ op: "local.location.pick" }),
);
@@ -2945,10 +3394,9 @@
run({ op: "local.recheck" }, "local-error"),
);
$("local-model").addEventListener("click", () => {
- // Only Pi runs the local model; choose Pi first.
- if ($("local-model").getAttribute("aria-disabled") === "true") return;
+ if ($("local-model").disabled) return;
picked = true;
- plan = { ...plan, localModel: !plan.localModel };
+ plan = { ...plan, source: "local", runtime: "pi", localModel: true };
render();
});
$("open").addEventListener("click", () => run({ op: "finish" }));
diff --git a/apps/linger-installer/src/main.ts b/apps/linger-installer/src/main.ts
index 0865a4b7..b99d8abd 100644
--- a/apps/linger-installer/src/main.ts
+++ b/apps/linger-installer/src/main.ts
@@ -15,6 +15,7 @@ export function parseInstallerArguments(args: string[]) {
noOpen?: boolean;
resume?: boolean;
inspect?: boolean;
+ checkByok?: boolean;
userKeys?: boolean;
migrate?: boolean;
stop?: boolean;
@@ -35,6 +36,10 @@ export function parseInstallerArguments(args: string[]) {
options.inspect = true;
continue;
}
+ if (flag === "--check-byok") {
+ options.checkByok = true;
+ continue;
+ }
if (flag === "--migrate") {
options.migrate = true;
continue;
@@ -74,6 +79,7 @@ export function parseInstallerArguments(args: string[]) {
if (
!options.sourceRepo &&
!options.inspect &&
+ !options.checkByok &&
!options.userKeys &&
!options.migrate &&
!options.stop
@@ -222,6 +228,27 @@ async function userKeys(options: ReturnType<typeof parseInstallerArguments>) {
process.exit("error" in outcome ? 1 : 0),
);
}
+async function checkByok(options: ReturnType<typeof parseInstallerArguments>) {
+ let input = "";
+ for await (const chunk of process.stdin) input += String(chunk);
+ const { checkByokEndpoint, validateByokConfiguration } =
+ await import("@linger/local-installation/byok-source");
+ try {
+ const config = validateByokConfiguration(JSON.parse(input));
+ const result = await checkByokEndpoint(
+ options.home,
+ config,
+ AbortSignal.timeout(45_000),
+ );
+ process.stdout.write(`${JSON.stringify(result)}\n`, () => process.exit(0));
+ } catch (error) {
+ const message =
+ error instanceof Error ? error.message : "Could not check BYOK endpoint.";
+ process.stdout.write(`${JSON.stringify({ ok: false, message })}\n`, () =>
+ process.exit(1),
+ );
+ }
+}
// Headless stop for the desktop's uninstall: the outcome as one JSON line on
// stdout. The uninstall waits for it, so it ends on its own after a while.
async function stopInstallation(
@@ -324,6 +351,7 @@ if (
process.exit(0),
);
else if (options?.userKeys) await userKeys(options);
+ else if (options?.checkByok) await checkByok(options);
else if (options?.inspect) await inspect(options);
else if (options?.resume) await resume(options);
else if (options) await serve(options).catch(failedToStart);
diff --git a/apps/linger-installer/src/server/instance-runtime.ts b/apps/linger-installer/src/server/instance-runtime.ts
index 0ba145c6..2324b8c0 100644
--- a/apps/linger-installer/src/server/instance-runtime.ts
+++ b/apps/linger-installer/src/server/instance-runtime.ts
@@ -1,6 +1,7 @@
import path from "node:path";
import { loadInstance } from "@linger/local-installation/instance";
import { localModelsEnvironment } from "@linger/local-installation/local-models";
+import { readByokEnvironment } from "@linger/local-installation/byok-source";
import {
LOCALMODELS_TOOL_ENVIRONMENT,
localmodelsComputerTool,
@@ -33,9 +34,11 @@ export async function instanceRuntime(
const value = await loadInstance({ name, home });
if (!value) return undefined;
const setupChoice = await readSetupChoice({ name, home });
+ const byok = await readByokEnvironment(home);
const found: Record<string, string | undefined> = {
...(await managedRuntimeEnvironment(home, value.root)),
...(await localModelsEnvironment(value)),
+ ...(byok?.mode === "byok" ? byok.environment : {}),
...localmodelsToolEnvironment(
await localmodelsComputerTool(home, pinnedToolSource()),
),
diff --git a/apps/linger-installer/src/server/jobs.ts b/apps/linger-installer/src/server/jobs.ts
index 0d9ccad6..84165a33 100644
--- a/apps/linger-installer/src/server/jobs.ts
+++ b/apps/linger-installer/src/server/jobs.ts
@@ -203,6 +203,7 @@ export class JobManager {
input.password,
input.model?.apiKey,
input.runtimeModel?.apiKey,
+ input.byok?.apiKey,
])
if (secret) clean = clean.split(secret).join("[hidden]");
clean = clean
diff --git a/apps/linger-installer/src/server/server.ts b/apps/linger-installer/src/server/server.ts
index a1a70ffc..9822efb7 100644
--- a/apps/linger-installer/src/server/server.ts
+++ b/apps/linger-installer/src/server/server.ts
@@ -12,11 +12,13 @@ import { JobManager, type RunInstallation } from "./jobs.js";
import { privateDirectory, privateWrite } from "./storage.js";
import {
instanceName,
+ validateByok,
validateInput,
validateModel,
validateLocalModelsAuthority,
} from "./validation.js";
import { checkModel, openLocalTarget } from "./platform.js";
+import { checkByokEndpoint } from "@linger/local-installation/byok-source";
import { checkRuntimeModel } from "@linger/local-installation/managed-codex";
export interface ServerOptions {
home: string;
@@ -410,6 +412,16 @@ export async function startInstallerServer(options: ServerOptions) {
}
return;
}
+ if (url.pathname === "/api/byok/check" && method === "POST") {
+ const byok = validateByok(await body(req));
+ const checked = await checkByokEndpoint(
+ options.home,
+ byok,
+ AbortSignal.timeout(45_000),
+ );
+ json(res, 200, checked);
+ return;
+ }
if (url.pathname === "/api/runtime-login" && method === "DELETE") {
json(
res,
diff --git a/apps/linger-installer/src/server/validation.test.ts b/apps/linger-installer/src/server/validation.test.ts
index 0c8bc69d..a78c7ae7 100644
--- a/apps/linger-installer/src/server/validation.test.ts
+++ b/apps/linger-installer/src/server/validation.test.ts
@@ -1,5 +1,5 @@
import { expect, test } from "vitest";
-import { validateInput } from "./validation.js";
+import { validateByok, validateInput } from "./validation.js";
test("accepts separate local model approval and explicit replan inputs", () => {
const localModelsApproval = "a".repeat(64);
expect(
@@ -54,3 +54,46 @@ test.each([
])("rejects malformed selection or consent %#", (options) => {
expect(() => validateInput({ instance: "default", ...options })).toThrow();
});
+
+test("validates BYOK check and installation inputs", () => {
+ expect(
+ validateByok({
+ baseUrl: "https://api.openai.com/v1/",
+ apiKey: "sk-test",
+ modelId: "gpt-5.4",
+ runtime: "codex",
+ }),
+ ).toMatchObject({
+ baseUrl: "https://api.openai.com/v1",
+ modelId: "gpt-5.4",
+ runtime: "codex",
+ });
+ expect(
+ validateInput({
+ instance: "default",
+ setupChoice: "claude",
+ byok: {
+ baseUrl: "https://api.anthropic.com",
+ apiKey: "sk-ant-test",
+ modelId: "claude-sonnet-4-6",
+ },
+ }),
+ ).toMatchObject({
+ setupChoice: "claude",
+ byok: {
+ baseUrl: "https://api.anthropic.com",
+ modelId: "claude-sonnet-4-6",
+ runtime: "claude",
+ },
+ });
+ expect(() =>
+ validateInput({
+ instance: "default",
+ setupChoice: "local-models",
+ byok: {
+ baseUrl: "https://api.openai.com/v1",
+ modelId: "gpt-5.4",
+ },
+ }),
+ ).toThrow();
+});
diff --git a/apps/linger-installer/src/server/validation.ts b/apps/linger-installer/src/server/validation.ts
index b196010d..44f13864 100644
--- a/apps/linger-installer/src/server/validation.ts
+++ b/apps/linger-installer/src/server/validation.ts
@@ -1,6 +1,12 @@
+import { validateByokConfiguration } from "@linger/local-installation/byok-source";
import type { components } from "@linger/wire-contracts/linger-installer/types";
type Input = components["schemas"]["InstallationInput"];
type Model = components["schemas"]["ModelConfiguration"];
+type Byok = components["schemas"]["ByokConfiguration"];
+
+export function validateByok(value: unknown): Byok {
+ return validateByokConfiguration(value);
+}
function object(value: unknown): Record<string, unknown> {
if (!value || typeof value !== "object" || Array.isArray(value))
throw new Error("Invalid input");
@@ -80,6 +86,7 @@ export function validateInput(value: unknown): Input {
"computerName",
"model",
"runtimeModel",
+ "byok",
"preparation",
]);
instanceName(input.instance);
@@ -155,5 +162,17 @@ export function validateInput(value: unknown): Input {
throw new Error("Invalid computer name");
if (input.model !== undefined) validateModel(input.model);
if (input.runtimeModel !== undefined) validateModel(input.runtimeModel);
+ if (input.byok !== undefined) {
+ if (input.setupChoice === "local-models")
+ throw new Error("BYOK cannot be combined with local-models setupChoice");
+ const byok = validateByok(input.byok);
+ input.byok =
+ byok.runtime === undefined &&
+ (input.setupChoice === "codex" ||
+ input.setupChoice === "claude" ||
+ input.setupChoice === "pi")
+ ? { ...byok, runtime: input.setupChoice }
+ : byok;
+ }
return input as Input;
}
diff --git a/apps/linger-installer/src/web/App.tsx b/apps/linger-installer/src/web/App.tsx
index 049cfbb1..2632ef96 100644
--- a/apps/linger-installer/src/web/App.tsx
+++ b/apps/linger-installer/src/web/App.tsx
@@ -3,8 +3,9 @@ import { RuntimeSignIn } from "./RuntimeSignIn.js";
import { InstallationProgress } from "./InstallationProgress.js";
import {
SetupChoicePanel,
+ type ByokConfiguration,
+ type PanelChoice,
type SetupReport,
- type SetupChoice,
} from "./SetupChoicePanel.js";
import {
authenticate,
@@ -45,7 +46,7 @@ export function App() {
const [ready, setReady] = useState(false);
const [environment, setEnvironment] = useState<EnvironmentReport>();
const [setup, setSetup] = useState<SetupReport>();
- const [choice, setChoice] = useState<SetupChoice>();
+ const [choice, setChoice] = useState<PanelChoice>();
const [config, setConfig] = useState<InstallerConfig>();
const [job, setJob] = useState<InstallationJob>();
const [login, setLogin] = useState<LoginInformation>();
@@ -230,14 +231,17 @@ export function App() {
active = false;
};
}, [finished, jobId]);
- async function install() {
+ async function install(byok?: ByokConfiguration) {
if (!choice) return;
+ const setupChoice =
+ choice === "byok" ? (byok?.runtime ?? "claude") : choice;
await perform(async () => {
setSkipped(false);
setJob(
await request<InstallationJob>("/jobs", {
instance: config?.instance ?? "default",
- setupChoice: choice,
+ setupChoice,
+ ...(byok ? { byok } : {}),
}),
);
});
@@ -331,7 +335,7 @@ export function App() {
report={setup}
choice={choice}
onChange={setChoice}
- onInstall={() => void install()}
+ onInstall={(byok) => void install(byok)}
disabled={!choice || Boolean(blocker) || busy}
blocker={blocker?.detail}
/>
diff --git a/apps/linger-installer/src/web/SetupChoicePanel.tsx b/apps/linger-installer/src/web/SetupChoicePanel.tsx
index b7b8bb4f..c0fd50e4 100644
--- a/apps/linger-installer/src/web/SetupChoicePanel.tsx
+++ b/apps/linger-installer/src/web/SetupChoicePanel.tsx
@@ -1,6 +1,16 @@
+import { useState } from "react";
import type { components } from "@linger/wire-contracts/linger-installer/types";
+import { request } from "./api.js";
export type SetupReport = components["schemas"]["SetupReport"];
export type SetupChoice = components["schemas"]["SetupChoice"];
+export type ByokConfiguration = components["schemas"]["ByokConfiguration"];
+type ByokCheckReport = components["schemas"]["ByokCheckReport"];
+const byokProtocolLabels: Record<ByokCheckReport["protocol"], string> = {
+ anthropic: "Anthropic Messages",
+ "openai-chat": "OpenAI Chat Completions",
+ "openai-responses": "OpenAI Responses",
+};
+export type PanelChoice = SetupChoice | "byok";
export function bytes(value: number | null | undefined): string {
if (value == null) return "—";
const units = ["B", "KiB", "MiB", "GiB", "TiB"];
@@ -19,22 +29,57 @@ export function SetupChoicePanel({
blocker,
}: {
report: SetupReport;
- choice?: SetupChoice;
- onChange: (choice: SetupChoice) => void;
- onInstall: () => void;
+ choice?: PanelChoice;
+ onChange: (choice: PanelChoice) => void;
+ onInstall: (byok?: ByokConfiguration) => void;
disabled: boolean;
blocker?: string;
}) {
+ const [byokRuntime, setByokRuntime] =
+ useState<NonNullable<ByokConfiguration["runtime"]>>("claude");
+ const [baseUrl, setBaseUrl] = useState("");
+ const [apiKey, setApiKey] = useState("");
+ const [modelId, setModelId] = useState("");
+ const [checking, setChecking] = useState(false);
+ const [checkNote, setCheckNote] = useState("");
+ const isByok = choice === "byok";
const selected =
choice === "local-models"
? report.localModels.estimate
- : report.runtimes.find((r) => r.choice === choice)?.estimate;
- const label =
- choice === "local-models"
+ : !isByok
+ ? report.runtimes.find((r) => r.choice === choice)?.estimate
+ : undefined;
+ const label = isByok
+ ? "BYOK"
+ : choice === "local-models"
? report.localModels.estimate.model || "Local models"
: choice
? { codex: "Codex", claude: "Claude Code", pi: "Pi" }[choice]
: "";
+ const buildByok = (): ByokConfiguration => ({
+ baseUrl: baseUrl.trim(),
+ ...(apiKey.trim() ? { apiKey: apiKey.trim() } : {}),
+ modelId: modelId.trim(),
+ runtime: byokRuntime,
+ });
+ async function checkByok() {
+ if (!baseUrl.trim() || !modelId.trim()) return;
+ setChecking(true);
+ setCheckNote("Checking endpoint…");
+ try {
+ const report = await request<ByokCheckReport>("/byok/check", buildByok());
+ setCheckNote(
+ `Ready · ${report.modelId} (${Math.round(report.contextWindow / 1000)}k context) through ${byokProtocolLabels[report.protocol]}`,
+ );
+ } catch (error) {
+ setCheckNote(
+ error instanceof Error ? error.message : "BYOK endpoint check failed.",
+ );
+ } finally {
+ setChecking(false);
+ }
+ }
+ const byokIncomplete = isByok && (!baseUrl.trim() || !modelId.trim());
return (
<section className="setup-choice" aria-label={"Deployment plan"}>
<p className="recommended-plan">
@@ -112,12 +157,104 @@ export function SetupChoicePanel({
</label>
);
})}
+ <label
+ className={`setup-option ${isByok ? "selected" : ""}`}
+ title="Bring Your Own Key — Connect your own OpenAI-compatible or Anthropic API endpoint, key, and model through Linger's local Bifrost gateway."
+ >
+ <input
+ type="radio"
+ name="setup-choice"
+ value="byok"
+ checked={isByok}
+ onChange={() => onChange("byok")}
+ />
+ <span>
+ <strong>{"BYOK"}</strong>
+ <small>
+ {
+ "Bring Your Own Key · Mounted on local Bifrost for all runtimes"
+ }
+ </small>
+ </span>
+ </label>
</div>
</div>
+ {isByok && (
+ <div className="byok-panel">
+ <label>
+ {"AI runtime"}
+ <select
+ value={byokRuntime}
+ onChange={(event) => {
+ setByokRuntime(
+ event.target.value as NonNullable<
+ ByokConfiguration["runtime"]
+ >,
+ );
+ // The runtime decides which API format is tried first.
+ setCheckNote("");
+ }}
+ >
+ <option value="claude">Claude Code</option>
+ <option value="codex">Codex</option>
+ <option value="pi">Pi</option>
+ </select>
+ </label>
+ <label>
+ {"Endpoint URL"}
+ <input
+ type="url"
+ value={baseUrl}
+ onChange={(event) => setBaseUrl(event.target.value)}
+ placeholder="https://api.example.com/v1"
+ maxLength={2048}
+ />
+ </label>
+ <label>
+ {"API key"}
+ <input
+ type="password"
+ autoComplete="off"
+ value={apiKey}
+ onChange={(event) => setApiKey(event.target.value)}
+ placeholder="Stored privately on this computer"
+ maxLength={4096}
+ />
+ </label>
+ <label>
+ {"Model ID"}
+ <input
+ value={modelId}
+ onChange={(event) => setModelId(event.target.value)}
+ placeholder="gpt-5.4 or claude-sonnet-4-6"
+ maxLength={256}
+ />
+ </label>
+ <div className="byok-check-row">
+ <button
+ type="button"
+ className="button compact"
+ disabled={checking || byokIncomplete}
+ onClick={() => void checkByok()}
+ >
+ {checking ? "Checking…" : "Check"}
+ </button>
+ {checkNote && <span role="status">{checkNote}</span>}
+ </div>
+ </div>
+ )}
<button
className="button primary deploy-action"
- disabled={disabled}
- onClick={onInstall}
+ disabled={disabled || byokIncomplete}
+ onClick={() => {
+ if (isByok) {
+ const payload = buildByok();
+ setApiKey("");
+ onInstall(payload);
+ } else {
+ onInstall();
+ }
+ }}
>
{"Install Linger"}
</button>
diff --git a/apps/node-services/src/agent/AGENTS.md b/apps/node-services/src/agent/AGENTS.md
index e0d0ee75..a417c027 100644
--- a/apps/node-services/src/agent/AGENTS.md
+++ b/apps/node-services/src/agent/AGENTS.md
@@ -116,6 +116,13 @@ take precedence.
`expires_at` (at most 30 seconds; the Daemon never answers after that
deadline, so the outcome is unknown, not refused), or
`LOCAL_COMPUTER_OFFLINE`.
+- A Computer's model source is the Daemon's too
+ (`runner-gateway/runner-local-capabilities.ts`, `modelSource`). Agent Service
+ sends `execute` `model_source` only to Computer 0.54.0 or later
+ (`FIRST_MODEL_SOURCE_COMPUTER_VERSION`), because an older one closes the
+ connection on a kind it cannot decode, and maps the Computer's refusals in
+ `executor/http/local-computer-http.ts`. A BYOK key stays inside the request
+ and the envelope; it is never logged, stored or returned.
- Default unit, integration, and fixture smoke tests use deterministic adapters
and do not call a live model provider. Explicitly named live suites such as
`smoke:local-runner:live` may use an authenticated provider and must remain
diff --git a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
index 739cdfa1..9304d0e6 100644
--- a/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
+++ b/apps/node-services/src/agent/executor/http/agent-manager-http-server.ts
@@ -28,6 +28,7 @@ import {
LocalComputerHttpError,
registerLocalComputerCompatibilityRoutes,
registerLocalComputerModelRoutes,
+ registerLocalComputerModelSourceRoutes,
registerLocalComputerPermissionRoutes,
} from "./local-computer-http.js";
import {
@@ -651,6 +652,7 @@ const createAgentManagerHttpApp = <TRuntimeSettings>(
registerLocalComputerCompatibilityRoutes(app, handlers);
registerLocalComputerPermissionRoutes(app, handlers);
registerLocalComputerModelRoutes(app, handlers);
+ registerLocalComputerModelSourceRoutes(app, handlers);
app.notFound((context) =>
writeProtocolError(context, 404, "not_found", "Not found"),
diff --git a/apps/node-services/src/agent/executor/http/local-computer-http.ts b/apps/node-services/src/agent/executor/http/local-computer-http.ts
index 52a94017..59e8d1b9 100644
--- a/apps/node-services/src/agent/executor/http/local-computer-http.ts
+++ b/apps/node-services/src/agent/executor/http/local-computer-http.ts
@@ -1,5 +1,6 @@
import { type Context, Hono } from "hono";
import * as AgentManagementRoutes from "@linger/wire-contracts/node-services-internal/server";
+import type { ByokConfigInput } from "@linger/wire-contracts/runner-gateway/types";
import {
LocalComputerBusyError,
LocalComputerHasAgentsError,
@@ -8,10 +9,12 @@ import {
LocalComputerOfflineError,
LocalBrowserConnectionError,
LocalComputerPermissionError,
+ LocalModelSourceError,
LocalSkillOperationError,
type LocalBrowserConnectionCommand,
type LocalComputerPermissionCommand,
type LocalComputerManagement,
+ type LocalModelSourceCommand,
} from "../../runner-gateway/local-computer-management.js";
import {
LocalModelsActionTimeoutError,
@@ -47,6 +50,10 @@ export interface LocalComputerRouteHandlers {
getLocalComputerPermissions(context: Context): Promise<Response> | Response;
actOnLocalComputerPermission(context: Context): Promise<Response> | Response;
actOnLocalComputerModels(context: Context): Promise<Response> | Response;
+ getLocalComputerModelSource(context: Context): Promise<Response> | Response;
+ applyLocalComputerModelSource(context: Context): Promise<Response> | Response;
+ testLocalComputerByok(context: Context): Promise<Response> | Response;
+ listLocalComputerByokModels(context: Context): Promise<Response> | Response;
}
export const createLocalComputerRouteHandlers = (options: {
@@ -216,8 +223,346 @@ export const createLocalComputerRouteHandlers = (options: {
throw localModelsRequestError(error);
}
},
+ getLocalComputerModelSource: async (context) => {
+ const management = requireModelSourceManagement(
+ options.localComputerManagement,
+ );
+ try {
+ const { status } = await management.modelSource({
+ tenantId: options.pathId(context, "tenantId"),
+ ownerActorId: options.pathId(context, "ownerActorId"),
+ computerId: options.pathId(context, "computerId"),
+ action: "status",
+ signal: context.req.raw.signal,
+ });
+ if (!status) {
+ throw new LocalComputerHttpError(
+ 502,
+ "MODEL_SOURCE_EMPTY",
+ "Local Computer returned no model source status",
+ );
+ }
+ return writeJson(context, 200, status);
+ } catch (error) {
+ throw modelSourceRequestError(error);
+ }
+ },
+ applyLocalComputerModelSource: async (context) => {
+ const management = requireModelSourceManagement(
+ options.localComputerManagement,
+ );
+ const body = parseModelSourceApplyCommand(
+ await options.readJsonBody(context),
+ );
+ try {
+ const { status } = await management.modelSource({
+ tenantId: options.pathId(context, "tenantId"),
+ ownerActorId: options.pathId(context, "ownerActorId"),
+ computerId: options.pathId(context, "computerId"),
+ action: "apply",
+ mode: body.mode,
+ ...(body.runtime ? { runtime: body.runtime } : {}),
+ ...(body.local_model_id ? { localModelId: body.local_model_id } : {}),
+ ...(body.byok ? { byok: body.byok } : {}),
+ signal: context.req.raw.signal,
+ });
+ if (!status) {
+ throw new LocalComputerHttpError(
+ 502,
+ "MODEL_SOURCE_EMPTY",
+ "Local Computer returned no model source status",
+ );
+ }
+ return writeJson(context, 200, status);
+ } catch (error) {
+ throw modelSourceRequestError(error);
+ }
+ },
+ testLocalComputerByok: async (context) => {
+ const management = requireModelSourceManagement(
+ options.localComputerManagement,
+ );
+ const { runtime, byok } = parseByokTestRequest(
+ await options.readJsonBody(context),
+ );
+ try {
+ const { testResult } = await management.modelSource({
+ tenantId: options.pathId(context, "tenantId"),
+ ownerActorId: options.pathId(context, "ownerActorId"),
+ computerId: options.pathId(context, "computerId"),
+ action: "test",
+ runtime,
+ byok,
+ signal: context.req.raw.signal,
+ });
+ if (!testResult) {
+ throw new LocalComputerHttpError(
+ 502,
+ "BYOK_CHECK_EMPTY",
+ "Local Computer returned no BYOK check result",
+ );
+ }
+ return writeJson(context, 200, testResult);
+ } catch (error) {
+ throw modelSourceRequestError(error);
+ }
+ },
+ listLocalComputerByokModels: async (context) => {
+ const management = requireModelSourceManagement(
+ options.localComputerManagement,
+ );
+ const byok = parseByokEndpointInput(await options.readJsonBody(context));
+ try {
+ const { modelList } = await management.modelSource({
+ tenantId: options.pathId(context, "tenantId"),
+ ownerActorId: options.pathId(context, "ownerActorId"),
+ computerId: options.pathId(context, "computerId"),
+ action: "models",
+ byok,
+ signal: context.req.raw.signal,
+ });
+ if (!modelList) {
+ throw new LocalComputerHttpError(
+ 502,
+ "BYOK_MODELS_EMPTY",
+ "Local Computer returned no BYOK model list",
+ );
+ }
+ return writeJson(context, 200, modelList);
+ } catch (error) {
+ throw modelSourceRequestError(error);
+ }
+ },
});
+const requireModelSourceManagement = (
+ management: LocalComputerManagement | undefined,
+): LocalComputerManagement &
+ Required<Pick<LocalComputerManagement, "modelSource">> => {
+ const available = requireLocalComputerManagement(management);
+ if (!available.modelSource) {
+ throw new LocalComputerHttpError(
+ 503,
+ "MODEL_SOURCE_UNAVAILABLE",
+ "Model source management is unavailable",
+ );
+ }
+ return available as LocalComputerManagement &
+ Required<Pick<LocalComputerManagement, "modelSource">>;
+};
+
+const BYOK_MODEL_ID_PATTERN = /^[-a-zA-Z0-9_./:@]{1,256}$/u;
+
+// Never include the request body in the error; it carries the API key.
+const parseByokInput = (value: unknown): ByokConfigInput => {
+ if (
+ !isRecord(value) ||
+ Object.keys(value).some(
+ (key) =>
+ ![
+ "base_url",
+ "api_key",
+ "model_id",
+ "context_window",
+ "reuse_saved_key",
+ ].includes(key),
+ ) ||
+ typeof value.base_url !== "string" ||
+ value.base_url.trim().length === 0 ||
+ value.base_url.length > 2048 ||
+ typeof value.model_id !== "string" ||
+ !BYOK_MODEL_ID_PATTERN.test(value.model_id.trim()) ||
+ (value.api_key !== undefined &&
+ (typeof value.api_key !== "string" || value.api_key.length > 4096)) ||
+ (value.context_window !== undefined &&
+ (!Number.isSafeInteger(value.context_window) ||
+ Number(value.context_window) < 1 ||
+ Number(value.context_window) > 2_147_483_647)) ||
+ (value.reuse_saved_key !== undefined &&
+ typeof value.reuse_saved_key !== "boolean")
+ ) {
+ throw new LocalComputerHttpError(
+ 400,
+ "BYOK_INVALID_CONFIG",
+ "BYOK configuration is invalid",
+ );
+ }
+ return {
+ base_url: value.base_url.trim(),
+ ...(value.api_key !== undefined ? { api_key: value.api_key } : {}),
+ model_id: value.model_id.trim(),
+ ...(value.context_window !== undefined
+ ? { context_window: Number(value.context_window) }
+ : {}),
+ ...(value.reuse_saved_key !== undefined
+ ? { reuse_saved_key: value.reuse_saved_key }
+ : {}),
+ };
+};
+
+// Never include the request body in the error; it carries the API key.
+const parseByokEndpointInput = (value: unknown): ByokConfigInput => {
+ if (
+ !isRecord(value) ||
+ Object.keys(value).some(
+ (key) => !["base_url", "api_key", "reuse_saved_key"].includes(key),
+ ) ||
+ typeof value.base_url !== "string" ||
+ value.base_url.trim().length === 0 ||
+ value.base_url.length > 2048 ||
+ (value.api_key !== undefined &&
+ (typeof value.api_key !== "string" || value.api_key.length > 4096)) ||
+ (value.reuse_saved_key !== undefined &&
+ typeof value.reuse_saved_key !== "boolean")
+ ) {
+ throw new LocalComputerHttpError(
+ 400,
+ "BYOK_INVALID_CONFIG",
+ "BYOK endpoint is invalid",
+ );
+ }
+ return {
+ base_url: value.base_url.trim(),
+ ...(value.api_key !== undefined ? { api_key: value.api_key } : {}),
+ ...(value.reuse_saved_key !== undefined
+ ? { reuse_saved_key: value.reuse_saved_key }
+ : {}),
+ };
+};
+
+const isModelSourceRuntime = (
+ value: unknown,
+): value is NonNullable<LocalModelSourceCommand["runtime"]> =>
+ value === "claude" || value === "codex" || value === "pi";
+
+const parseByokTestRequest = (
+ value: unknown,
+): {
+ readonly runtime: NonNullable<LocalModelSourceCommand["runtime"]>;
+ readonly byok: ByokConfigInput;
+} => {
+ if (
+ !isRecord(value) ||
+ Object.keys(value).some((key) => !["runtime", "byok"].includes(key)) ||
+ !isModelSourceRuntime(value.runtime)
+ ) {
+ throw new LocalComputerHttpError(
+ 400,
+ "BYOK_INVALID_CONFIG",
+ "BYOK configuration is invalid",
+ );
+ }
+ return { runtime: value.runtime, byok: parseByokInput(value.byok) };
+};
+
+interface ModelSourceApplyBody {
+ readonly mode: NonNullable<LocalModelSourceCommand["mode"]>;
+ readonly runtime?: LocalModelSourceCommand["runtime"];
+ readonly local_model_id?: string;
+ readonly byok?: ByokConfigInput;
+}
+
+const parseModelSourceApplyCommand = (value: unknown): ModelSourceApplyBody => {
+ if (
+ !isRecord(value) ||
+ Object.keys(value).some(
+ (key) => !["mode", "runtime", "local_model_id", "byok"].includes(key),
+ ) ||
+ (value.mode !== "local" &&
+ value.mode !== "subscription" &&
+ value.mode !== "byok") ||
+ (value.runtime !== undefined && !isModelSourceRuntime(value.runtime)) ||
+ (value.local_model_id !== undefined &&
+ !isLocalModelId(value.local_model_id))
+ ) {
+ throw new LocalComputerHttpError(
+ 400,
+ "MODEL_SOURCE_INVALID",
+ "Model source command is invalid",
+ );
+ }
+ return {
+ mode: value.mode,
+ ...(value.runtime !== undefined ? { runtime: value.runtime } : {}),
+ ...(value.local_model_id !== undefined
+ ? { local_model_id: value.local_model_id }
+ : {}),
+ ...(value.byok !== undefined ? { byok: parseByokInput(value.byok) } : {}),
+ };
+};
+
+const modelSourceRequestError = (error: unknown): Error => {
+ if (error instanceof LocalComputerNotFoundError) {
+ return new LocalComputerHttpError(
+ 404,
+ "LOCAL_COMPUTER_NOT_FOUND",
+ error.message,
+ );
+ }
+ if (error instanceof LocalComputerOfflineError) {
+ return new LocalComputerHttpError(
+ 503,
+ "LOCAL_COMPUTER_OFFLINE",
+ error.message,
+ );
+ }
+ if (error instanceof LocalComputerCapabilityError) {
+ return new LocalComputerHttpError(
+ 409,
+ "MODEL_SOURCE_UNSUPPORTED",
+ error.message,
+ );
+ }
+ if (error instanceof LocalModelSourceError) {
+ if (
+ error.code === "MODEL_SOURCE_TIMEOUT" ||
+ error.code === "BYOK_CHECK_TIMEOUT"
+ ) {
+ return new LocalComputerHttpError(503, error.code, error.message);
+ }
+ if (
+ error.code === "BYOK_INVALID_CONFIG" ||
+ error.code === "MODEL_SOURCE_INVALID" ||
+ error.code === "MODEL_UNKNOWN"
+ ) {
+ return new LocalComputerHttpError(400, error.code, error.message);
+ }
+ if (
+ error.code === "RUNTIME_NOT_ENABLED" ||
+ error.code === "TOOL_NOT_INSTALLED"
+ ) {
+ return new LocalComputerHttpError(409, error.code, error.message);
+ }
+ return new LocalComputerHttpError(502, error.code, error.message);
+ }
+ return error instanceof Error
+ ? error
+ : new Error("Model source operation failed");
+};
+
+export function registerLocalComputerModelSourceRoutes(
+ app: Hono,
+ handlers: Pick<
+ LocalComputerRouteHandlers,
+ | "getLocalComputerModelSource"
+ | "applyLocalComputerModelSource"
+ | "testLocalComputerByok"
+ | "listLocalComputerByokModels"
+ >,
+): void {
+ const basePath =
+ "/v1/tenants/:tenantId/owners/:ownerActorId/local-computers/:computerId/model-source";
+ const testPath = `${basePath}/test`;
+ const modelsPath = `${basePath}/models`;
+ app.get(basePath, handlers.getLocalComputerModelSource);
+ app.post(basePath, handlers.applyLocalComputerModelSource);
+ app.all(basePath, (context) => methodNotAllowed(context, "GET, POST"));
+ app.post(testPath, handlers.testLocalComputerByok);
+ app.all(testPath, (context) => methodNotAllowed(context, "POST"));
+ app.post(modelsPath, handlers.listLocalComputerByokModels);
+ app.all(modelsPath, (context) => methodNotAllowed(context, "POST"));
+}
+
const computerPermissions = async (
options: {
readonly localComputerManagement: LocalComputerManagement | undefined;
diff --git a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts b/apps/node-services/src/agent/runner-gateway/local-computer-management.ts
index 57b8b8ea..fe7932d8 100644
--- a/apps/node-services/src/agent/runner-gateway/local-computer-management.ts
+++ b/apps/node-services/src/agent/runner-gateway/local-computer-management.ts
@@ -5,7 +5,11 @@ import type {
} from "./runner-local-models.js";
import type {
BrowserConnectionStatus,
+ ByokConfigInput,
+ ByokModelList,
+ ByokTestResult,
ComputerPermissionStatus,
+ ModelSourceStatus,
} from "@linger/wire-contracts/runner-gateway/types";
export type LocalRuntimeType = "claude" | "codex" | "pi";
@@ -32,6 +36,9 @@ export const FIRST_SERVICE_FEATURES_COMPUTER_VERSION = "0.52.0";
// The first release that decodes a cancel for one model_invoke. An older
// Computer closes the connection on it, so its calls are never swapped out.
export const FIRST_MODEL_INVOKE_CANCEL_COMPUTER_VERSION = "0.53.0";
+// The first release that runs `model_source` commands. An older Computer
+// closes the connection on a command kind it cannot decode.
+export const FIRST_MODEL_SOURCE_COMPUTER_VERSION = "0.54.0";
const COMPUTER_RELEASE_VERSION = /^(0|[1-9]\d*)\.(0|[1-9]\d*)\.(0|[1-9]\d*)$/;
@@ -142,6 +149,12 @@ export interface LocalComputerManagement {
command: LocalModelActionCommand,
): Promise<LocalModelActionAck>;
+ modelSource?(command: LocalModelSourceCommand): Promise<{
+ readonly status?: ModelSourceStatus;
+ readonly testResult?: ByokTestResult;
+ readonly modelList?: ByokModelList;
+ }>;
+
/** Returns the placed model as the connected Computer reports it. */
requireLocalPlacement(
requirement: LocalPlacementRequirement,
@@ -351,6 +364,30 @@ export class LocalComputerPermissionError extends Error {
}
}
+export interface LocalModelSourceCommand {
+ readonly tenantId: string;
+ readonly ownerActorId: string;
+ readonly computerId: string;
+ readonly action: "status" | "test" | "models" | "apply";
+ readonly mode?: "local" | "subscription" | "byok";
+ readonly runtime?: LocalRuntimeType;
+ readonly localModelId?: string;
+ readonly byok?: ByokConfigInput;
+ readonly signal?: AbortSignal;
+}
+
+/** The Computer rejected a model-source command or did not answer. */
+export class LocalModelSourceError extends Error {
+ constructor(
+ readonly code: string,
+ message: string,
+ readonly retryable: boolean,
+ ) {
+ super(message);
+ this.name = "LocalModelSourceError";
+ }
+}
+
export class LocalComputerHasAgentsError extends Error {
readonly code = "local_computer_has_agents";
diff --git a/apps/node-services/src/agent/runner-gateway/runner-connections.ts b/apps/node-services/src/agent/runner-gateway/runner-connections.ts
index 14ff367a..95422b39 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-connections.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-connections.ts
@@ -656,6 +656,12 @@ export class RunnerConnections {
this.owners.capabilities().receivePermissionOutcome(connection, envelope);
return;
}
+ if (envelope.type === "executed" && envelope.kind === "model_source") {
+ this.owners
+ .capabilities()
+ .receiveModelSourceOutcome(connection, envelope);
+ return;
+ }
if (envelope.type === "executed" && envelope.kind === "computer_tool") {
this.owners.computerTools().receive(connection, envelope);
return;
diff --git a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
index d50771cf..09f55731 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-gateway.ts
@@ -16,6 +16,7 @@ import {
type LocalBrowserConnectionStatus,
type LocalComputerPermissionCommand,
type LocalComputerPermissionStatus,
+ type LocalModelSourceCommand,
type LocalPlacementRequirement,
type LocalReasoningEffort,
type LocalRuntimeModelDefinition,
@@ -338,6 +339,10 @@ export class RunnerGateway
return this.#localModels.act(command);
}
+ async modelSource(command: LocalModelSourceCommand) {
+ return this.#capabilities.modelSource(command);
+ }
+
async runLocalComputerMutation<T>(
computerId: string,
operation: () => Promise<T>,
diff --git a/apps/node-services/src/agent/runner-gateway/runner-local-capabilities.ts b/apps/node-services/src/agent/runner-gateway/runner-local-capabilities.ts
index ef56fbdd..1383caab 100644
--- a/apps/node-services/src/agent/runner-gateway/runner-local-capabilities.ts
+++ b/apps/node-services/src/agent/runner-gateway/runner-local-capabilities.ts
@@ -1,26 +1,35 @@
import type {
+ ByokModelList,
+ ByokTestResult,
CapabilityBrowserConnected,
CapabilityBrowserFailed,
CapabilityComputerPermissionFailed,
CapabilityComputerPermissionSucceeded,
+ CapabilityModelSourceFailed,
+ CapabilityModelSourceSucceeded,
CapabilitySkillsScanned,
DaemonToAgentEnvelope,
+ ModelSourceStatus,
} from "@linger/wire-contracts/runner-gateway/types";
import {
RUNNER_GATEWAY_PROTOCOL_VERSION,
parseAgentToDaemonEnvelope,
} from "@linger/wire-contracts/runner-gateway/validator";
import {
+ FIRST_MODEL_SOURCE_COMPUTER_VERSION,
+ isComputerVersionAtLeast,
LocalBrowserConnectionError,
LocalComputerCapabilityError,
LocalComputerNotFoundError,
LocalComputerOfflineError,
LocalComputerPermissionError,
+ LocalModelSourceError,
LocalSkillOperationError,
type LocalBrowserConnectionCommand,
type LocalBrowserConnectionStatus,
type LocalComputerPermissionCommand,
type LocalComputerPermissionStatus,
+ type LocalModelSourceCommand,
type LocalSkillScanCommand,
type LocalSkillScanResult,
} from "./local-computer-management.js";
@@ -73,6 +82,20 @@ export class RunnerLocalCapabilities {
}
>();
+ readonly #modelSourceWaiters = new Map<
+ string,
+ {
+ readonly connection: ConnectedRunner;
+ readonly tenantId: string;
+ readonly ownerActorId: string;
+ readonly action: LocalModelSourceCommand["action"];
+ readonly resolve: (
+ outcome: CapabilityModelSourceSucceeded | CapabilityModelSourceFailed,
+ ) => void;
+ readonly reject: (error: unknown) => void;
+ }
+ >();
+
constructor(
private readonly context: RunnerGatewayContext,
private readonly owners: Pick<RunnerGatewayControllers, "connections">,
@@ -279,7 +302,112 @@ export class RunnerLocalCapabilities {
return result.status;
}
- /** Fails every browser and permission command still waiting on this connection. */
+ /**
+ * Sends one model-source status, test, models, or apply command to the Computer.
+ * API keys stay strictly inside the transient envelope and are never logged,
+ * stored, or echoed back.
+ */
+ async modelSource(command: LocalModelSourceCommand): Promise<{
+ readonly status?: ModelSourceStatus;
+ readonly testResult?: ByokTestResult;
+ readonly modelList?: ByokModelList;
+ }> {
+ command.signal?.throwIfAborted();
+ const connection = this.owners
+ .connections()
+ .getConnection(command.computerId);
+ if (!isServingConnection(connection)) {
+ throw new LocalComputerOfflineError();
+ }
+ if (
+ connection.tenantOwners.get(command.tenantId) !== command.ownerActorId
+ ) {
+ throw new LocalComputerNotFoundError();
+ }
+ if (
+ !isComputerVersionAtLeast(
+ connection.hello.daemon_version,
+ FIRST_MODEL_SOURCE_COMPUTER_VERSION,
+ )
+ ) {
+ throw new LocalComputerCapabilityError(
+ "Local Computer must be upgraded to switch model sources",
+ );
+ }
+ const timeoutMs =
+ command.action === "apply"
+ ? MODEL_SOURCE_APPLY_TIMEOUT_MS
+ : MODEL_SOURCE_STATUS_TIMEOUT_MS;
+ const commandId = this.context.createId();
+ const envelope = parseAgentToDaemonEnvelope({
+ type: "execute",
+ kind: "model_source",
+ protocol_version: RUNNER_GATEWAY_PROTOCOL_VERSION,
+ command_id: commandId,
+ runner_id: command.computerId,
+ tenant_id: command.tenantId,
+ owner_actor_id: command.ownerActorId,
+ connection_epoch: connection.connectionEpoch,
+ expires_at: new Date(Date.now() + timeoutMs).toISOString(),
+ action: command.action,
+ ...(command.mode ? { mode: command.mode } : {}),
+ ...(command.runtime ? { runtime: command.runtime } : {}),
+ ...(command.localModelId ? { local_model_id: command.localModelId } : {}),
+ ...(command.byok ? { byok: command.byok } : {}),
+ });
+ const signal = command.signal;
+ let onAbort: (() => void) | undefined;
+ let timer: ReturnType<typeof setTimeout> | undefined;
+ const outcome = new Promise<
+ CapabilityModelSourceSucceeded | CapabilityModelSourceFailed
+ >((resolve, reject) => {
+ timer = setTimeout(() => {
+ reject(
+ new LocalModelSourceError(
+ "MODEL_SOURCE_TIMEOUT",
+ "Local Computer did not answer the model source command",
+ true,
+ ),
+ );
+ }, timeoutMs);
+ timer.unref();
+ onAbort = () => reject(signal?.reason);
+ signal?.addEventListener("abort", onAbort, { once: true });
+ this.#modelSourceWaiters.set(commandId, {
+ connection,
+ tenantId: command.tenantId,
+ ownerActorId: command.ownerActorId,
+ action: command.action,
+ resolve,
+ reject,
+ });
+ });
+ let result: CapabilityModelSourceSucceeded | CapabilityModelSourceFailed;
+ try {
+ [, result] = await Promise.all([
+ this.owners.connections().sendToCurrentRunner(envelope),
+ outcome,
+ ]);
+ } finally {
+ clearTimeout(timer);
+ if (onAbort) signal?.removeEventListener("abort", onAbort);
+ this.#modelSourceWaiters.delete(commandId);
+ }
+ if (result.outcome === "failed") {
+ throw new LocalModelSourceError(
+ result.error.code,
+ result.error.message,
+ result.error.retryable,
+ );
+ }
+ return {
+ ...(result.status ? { status: result.status } : {}),
+ ...(result.test_result ? { testResult: result.test_result } : {}),
+ ...(result.model_list ? { modelList: result.model_list } : {}),
+ };
+ }
+
+ /** Fails every browser, permission, and model-source command waiting on this connection. */
rejectConnectionWaiters(connection: ConnectedRunner): void {
for (const [commandId, waiter] of this.#browserWaiters) {
if (waiter.connection !== connection) continue;
@@ -291,6 +419,11 @@ export class RunnerLocalCapabilities {
this.#permissionWaiters.delete(commandId);
waiter.reject(new LocalComputerOfflineError());
}
+ for (const [commandId, waiter] of this.#modelSourceWaiters) {
+ if (waiter.connection !== connection) continue;
+ this.#modelSourceWaiters.delete(commandId);
+ waiter.reject(new LocalComputerOfflineError());
+ }
}
async scanLocalSkills(
@@ -496,6 +629,35 @@ export class RunnerLocalCapabilities {
waiter.resolve(envelope);
}
+ receiveModelSourceOutcome(
+ connection: ConnectedRunner,
+ envelope: CapabilityModelSourceSucceeded | CapabilityModelSourceFailed,
+ ): void {
+ if (
+ envelope.connection_epoch !== connection.connectionEpoch ||
+ connection.tenantOwners.get(envelope.tenant_id) !==
+ envelope.owner_actor_id
+ ) {
+ throw new RunnerGatewayProtocolError(
+ "Runner model source outcome identity mismatch",
+ );
+ }
+ const waiter = this.#modelSourceWaiters.get(envelope.command_id);
+ if (!waiter) return;
+ if (
+ waiter.connection !== connection ||
+ waiter.tenantId !== envelope.tenant_id ||
+ waiter.ownerActorId !== envelope.owner_actor_id ||
+ waiter.action !== envelope.action
+ ) {
+ throw new RunnerGatewayProtocolError(
+ "Runner model source command identity mismatch",
+ );
+ }
+ this.#modelSourceWaiters.delete(envelope.command_id);
+ waiter.resolve(envelope);
+ }
+
rejectLocalSkillWaiters(runnerId: string): void {
for (const [commandId, waiters] of this.#localSkillWaiters) {
for (const waiter of [...waiters]) {
@@ -517,6 +679,8 @@ const BROWSER_CONNECTION_TIMEOUT_MS = 60_000;
// A prompt can hold the Computer briefly while macOS shows its dialog; the
// Computer itself gives Desktop 10 s per step.
const COMPUTER_PERMISSION_TIMEOUT_MS = 30_000;
+const MODEL_SOURCE_STATUS_TIMEOUT_MS = 45_000;
+const MODEL_SOURCE_APPLY_TIMEOUT_MS = 180_000;
const requireLocalSkillScan = (
outcome: LocalSkillOutcome,
diff --git a/apps/node-services/tests/agent/executor/http/local-computer-model-source-http.test.ts b/apps/node-services/tests/agent/executor/http/local-computer-model-source-http.test.ts
new file mode 100644
index 00000000..b2a1bda1
--- /dev/null
+++ b/apps/node-services/tests/agent/executor/http/local-computer-model-source-http.test.ts
@@ -0,0 +1,233 @@
+import { Hono } from "hono";
+import { describe, expect, it, vi } from "vitest";
+import {
+ createLocalComputerRouteHandlers,
+ LocalComputerHttpError,
+ registerLocalComputerModelSourceRoutes,
+} from "../../../../src/agent/executor/http/local-computer-http.js";
+import {
+ LocalComputerOfflineError,
+ LocalModelSourceError,
+ type LocalComputerManagement,
+ type LocalModelSourceCommand,
+} from "../../../../src/agent/runner-gateway/local-computer-management.js";
+
+const secretKey = "sk-top-secret-never-echo-or-log";
+const basePath =
+ "/v1/tenants/tenant-1/owners/actor-1/local-computers/computer-1/model-source";
+
+const sampleStatus = {
+ mode: "byok",
+ runtime: "claude",
+ runtime_model: "localmodels-byok",
+ gateway_url: "http://127.0.0.1:43120",
+ byok: {
+ configured: true,
+ protocol: "anthropic",
+ base_url: "https://api.anthropic.com",
+ model_id: "claude-sonnet-4-6",
+ context_window: 200_000,
+ key_saved: true,
+ },
+} as const;
+
+function buildTestApp(
+ modelSource: (command: LocalModelSourceCommand) => Promise<{
+ readonly status?: typeof sampleStatus;
+ readonly testResult?: {
+ readonly ok: boolean;
+ readonly protocol: "anthropic";
+ readonly base_url: string;
+ readonly model_id: string;
+ readonly context_window: number;
+ };
+ readonly modelList?: {
+ readonly base_url: string;
+ readonly models: readonly {
+ readonly id: string;
+ readonly name?: string;
+ readonly context_window?: number;
+ }[];
+ };
+ }>,
+) {
+ const handlers = createLocalComputerRouteHandlers({
+ localComputerManagement: {
+ modelSource,
+ } as unknown as LocalComputerManagement,
+ pathId: (context, name) => context.req.param(name) ?? "",
+ readJsonBody: (context) => context.req.json(),
+ });
+ const app = new Hono();
+ registerLocalComputerModelSourceRoutes(app, handlers);
+ app.onError((error, context) =>
+ error instanceof LocalComputerHttpError
+ ? context.json(
+ { code: error.errorCode, message: error.message },
+ error.status,
+ )
+ : context.json({ code: "internal" }, 500),
+ );
+ return app;
+}
+
+describe("Agent Management model-source routes", () => {
+ it("reads model-source status and returns redacted BYOK summary", async () => {
+ const fn = vi.fn(async () => ({ status: sampleStatus }));
+ const res = await buildTestApp(fn).request(basePath);
+ expect(res.status).toBe(200);
+ expect(await res.json()).toEqual(sampleStatus);
+ expect(fn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ tenantId: "tenant-1",
+ ownerActorId: "actor-1",
+ computerId: "computer-1",
+ action: "status",
+ }),
+ );
+ });
+
+ it("forwards BYOK test and apply without echoing the API key", async () => {
+ const fn = vi.fn(async (cmd: LocalModelSourceCommand) =>
+ cmd.action === "test"
+ ? {
+ testResult: {
+ ok: true,
+ protocol: "anthropic" as const,
+ base_url: "https://api.anthropic.com",
+ model_id: "claude-sonnet-4-6",
+ context_window: 200_000,
+ },
+ }
+ : { status: sampleStatus },
+ );
+ const app = buildTestApp(fn);
+
+ const testRes = await app.request(`${basePath}/test`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ runtime: "claude",
+ byok: {
+ base_url: "https://api.anthropic.com",
+ api_key: secretKey,
+ model_id: "claude-sonnet-4-6",
+ },
+ }),
+ });
+ expect(testRes.status).toBe(200);
+ const testText = await testRes.text();
+ expect(testText).not.toContain(secretKey);
+ expect(fn).toHaveBeenCalledWith(
+ expect.objectContaining({ action: "test", runtime: "claude" }),
+ );
+
+ const applyRes = await app.request(basePath, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ mode: "byok",
+ runtime: "claude",
+ byok: {
+ base_url: "https://api.anthropic.com",
+ api_key: secretKey,
+ model_id: "claude-sonnet-4-6",
+ },
+ }),
+ });
+ expect(applyRes.status).toBe(200);
+ expect(await applyRes.text()).not.toContain(secretKey);
+ });
+
+ it("lists a BYOK endpoint's models from the address and key alone", async () => {
+ const modelList = {
+ base_url: "https://gateway.example.com/anthropic",
+ models: [{ id: "glm-5", name: "GLM 5", context_window: 131_072 }],
+ };
+ const fn = vi.fn(async () => ({ modelList }));
+ const app = buildTestApp(fn);
+
+ const res = await app.request(`${basePath}/models`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ base_url: " https://gateway.example.com/v1 ",
+ api_key: secretKey,
+ }),
+ });
+ expect(res.status).toBe(200);
+ const text = await res.text();
+ expect(text).not.toContain(secretKey);
+ expect(JSON.parse(text)).toEqual(modelList);
+ expect(fn).toHaveBeenCalledWith(
+ expect.objectContaining({
+ action: "models",
+ byok: {
+ base_url: "https://gateway.example.com/v1",
+ api_key: secretKey,
+ },
+ }),
+ );
+
+ const withModel = await app.request(`${basePath}/models`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ base_url: "https://gateway.example.com/v1",
+ model_id: "glm-5",
+ }),
+ });
+ expect(withModel.status).toBe(400);
+ expect(fn).toHaveBeenCalledTimes(1);
+ });
+
+ it("maps invalid input, offline computer, and upstream rejection without leaking secrets", async () => {
+ const fn = vi.fn(async () => {
+ throw new LocalModelSourceError(
+ "BYOK_UPSTREAM_REJECTED",
+ "Upstream endpoint returned HTTP 401.",
+ false,
+ );
+ });
+ const app = buildTestApp(fn);
+
+ const badRes = await app.request(`${basePath}/test`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ runtime: "gemini",
+ byok: {
+ base_url: "https://api.example.com",
+ api_key: secretKey,
+ model_id: "gpt-5.4",
+ },
+ }),
+ });
+ expect(badRes.status).toBe(400);
+ expect(await badRes.text()).not.toContain(secretKey);
+ expect(fn).not.toHaveBeenCalled();
+
+ const upstreamRes = await app.request(`${basePath}/test`, {
+ method: "POST",
+ headers: { "content-type": "application/json" },
+ body: JSON.stringify({
+ runtime: "pi",
+ byok: {
+ base_url: "https://api.anthropic.com",
+ api_key: secretKey,
+ model_id: "claude-sonnet-4-6",
+ },
+ }),
+ });
+ expect(upstreamRes.status).toBe(502);
+ expect(await upstreamRes.json()).toEqual({
+ code: "BYOK_UPSTREAM_REJECTED",
+ message: "Upstream endpoint returned HTTP 401.",
+ });
+
+ const offlineApp = buildTestApp(async () => {
+ throw new LocalComputerOfflineError();
+ });
+ expect((await offlineApp.request(basePath)).status).toBe(503);
+ });
+});
diff --git a/apps/node-services/tests/agent/runner-gateway/runner-gateway-model-source.test.ts b/apps/node-services/tests/agent/runner-gateway/runner-gateway-model-source.test.ts
new file mode 100644
index 00000000..a493c050
--- /dev/null
+++ b/apps/node-services/tests/agent/runner-gateway/runner-gateway-model-source.test.ts
@@ -0,0 +1,105 @@
+import type {
+ AgentToDaemonEnvelope,
+ CapabilityModelSource,
+} from "@linger/wire-contracts/runner-gateway/types";
+import { afterEach, describe, expect, it, vi } from "vitest";
+
+import { LocalComputerCapabilityError } from "../../../src/agent/runner-gateway/local-computer-management.js";
+import { type RunnerGatewayConnection } from "../../../src/agent/runner-gateway/runner-gateway.js";
+import { createTestRunnerGateway } from "../test-support/runner-gateway.js";
+import { runtimeDiagnostics } from "./runtime-diagnostics-fixture.js";
+import {
+ CURRENT_RUNNER_CAPABILITIES,
+ currentRunnerIdentity,
+} from "../test-support/runner-capabilities.js";
+
+const connections: RunnerGatewayConnection[] = [];
+afterEach(() => {
+ for (const connection of connections.splice(0)) connection.disconnect();
+});
+
+const connect = async (daemonVersion: string) => {
+ const gateway = createTestRunnerGateway({ heartbeatIntervalMs: 60_000 });
+ const sent: AgentToDaemonEnvelope[] = [];
+ const connection = await gateway.acceptConnection(
+ {
+ runnerId: "computer-local",
+ credentialGeneration: 0,
+ tenantOwners: [{ tenantId: "tenant-1", ownerActorId: "actor-1" }],
+ },
+ {
+ type: "runner.hello",
+ platform: "darwin",
+ protocol_version: "2",
+ daemon_version: daemonVersion,
+ ...currentRunnerIdentity(),
+ capabilities: [...CURRENT_RUNNER_CAPABILITIES],
+ runner_id: "computer-local",
+ display_name: "Alice's Mac",
+ connection_nonce: "nonce-1",
+ sent_at: new Date().toISOString(),
+ runtimes: ["codex"],
+ runtime_diagnostics: runtimeDiagnostics(),
+ workspace_grants: [],
+ agent_runners: [],
+ active_operations: [],
+ },
+ {
+ send: vi.fn(async (envelope: AgentToDaemonEnvelope) => {
+ sent.push(envelope);
+ }),
+ close: vi.fn(),
+ },
+ );
+ connections.push(connection);
+ return { gateway, connection, sent };
+};
+
+const isModelSourceCommand = (
+ frame: AgentToDaemonEnvelope,
+): frame is CapabilityModelSource =>
+ frame.type === "execute" && frame.kind === "model_source";
+
+const target = {
+ computerId: "computer-local",
+ tenantId: "tenant-1",
+ ownerActorId: "actor-1",
+} as const;
+
+describe("Runner Gateway model source", () => {
+ it.each(["dev", "0.54.0"])(
+ "sends the command to Computer %s",
+ async (version) => {
+ const { gateway, connection, sent } = await connect(version);
+ const reading = gateway.modelSource({ ...target, action: "status" });
+ await vi.waitFor(() =>
+ expect(sent.some(isModelSourceCommand)).toBe(true),
+ );
+ const request = sent.find(isModelSourceCommand);
+ if (!request) throw new Error("Missing model source command");
+ await connection.receive({
+ type: "executed",
+ kind: "model_source",
+ outcome: "succeeded",
+ protocol_version: request.protocol_version,
+ command_id: request.command_id,
+ runner_id: request.runner_id,
+ tenant_id: request.tenant_id,
+ owner_actor_id: request.owner_actor_id,
+ connection_epoch: request.connection_epoch,
+ expires_at: request.expires_at,
+ action: "status",
+ });
+ await expect(reading).resolves.toEqual({});
+ },
+ );
+
+ // An older Computer closes the connection on a command it cannot decode.
+ it("refuses an older Computer before sending", async () => {
+ const { gateway, sent } = await connect("0.53.0");
+ await expect(
+ gateway.modelSource({ ...target, action: "status" }),
+ ).rejects.toBeInstanceOf(LocalComputerCapabilityError);
+ expect(sent.some(isModelSourceCommand)).toBe(false);
+ });
+});
diff --git a/apps/teamhub/AGENTS.md b/apps/teamhub/AGENTS.md
index 4a97f4b2..1b4bc750 100644
--- a/apps/teamhub/AGENTS.md
+++ b/apps/teamhub/AGENTS.md
@@ -227,5 +227,13 @@ Go service owning Human HTTP/SSE, Agent callbacks, and active product state.
`LOCAL_MODEL_ACTION_UNCONFIRMED`: it may still act, and the snapshots show
the outcome. The Computer's refusal codes map to `LocalModelsErrorCode` in
`internal/app/handlers_local_models.go`.
+- A Computer's model source lives on the Computer
+ (`internal/app/handlers_model_source.go`); TeamHub never stores a BYOK key.
+ A switch checks for running work, runs `apply` on the Computer, then moves
+ the owner's Agents on it in one transaction
+ (`agentregistry.SwitchComputerRuntime`). Work found before `apply` refuses
+ the switch with `AGENT_HAS_ACTIVE_RUNS` unless the owner sent
+ `force_terminate`; work that starts during `apply` keeps only its Agent
+ behind, answered with the same code after the others moved.
- Do not add write-only audit, event, or provenance tables. A new audit table
needs a named product or compliance reader in the same pull request.
diff --git a/apps/teamhub/internal/agentregistry/computer_model_source.go b/apps/teamhub/internal/agentregistry/computer_model_source.go
new file mode 100644
index 00000000..7c2b95f1
--- /dev/null
+++ b/apps/teamhub/internal/agentregistry/computer_model_source.go
@@ -0,0 +1,166 @@
+package agentregistry
+
+import (
+ "context"
+ "errors"
+
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/store"
+)
+
+// BusyComputerAgent is an Agent on a Computer with running work that a
+// model-source switch would end.
+type BusyComputerAgent struct {
+ AgentID, Name string
+}
+
+// ComputerRuntimeSwitch moves every active Agent the owner placed on one
+// Computer to the Runtime and model the Computer serves after a model-source
+// switch. TerminateWork ends their running work; without it an Agent with
+// running work stays where it is.
+type ComputerRuntimeSwitch struct {
+ TenantID, OwnerActorID, ComputerID string
+ RuntimeType, Model, ReasoningEffort string
+ TerminateWork bool
+}
+
+// ComputerRuntimeSwitchResult counts the Agents moved, lists the Runs that
+// were ended for the switch, and names the Agents left behind because they
+// have running work.
+type ComputerRuntimeSwitchResult struct {
+ UpdatedAgents int
+ TerminatedRuns []agentruntimestate.TerminatedLocalRun
+ BusyAgents []BusyComputerAgent
+}
+
+// BusyComputerAgents lists the owner's Agents on a Computer that hold running
+// work, so a switch can be refused before the Computer changes.
+func (s *Service) BusyComputerAgents(ctx context.Context, tenantID, ownerActorID, computerID string) ([]BusyComputerAgent, error) {
+ placements, err := s.queries.ListAgentRunnerPlacementsOnComputer(ctx, computerID)
+ if err != nil {
+ return nil, err
+ }
+ var busy []BusyComputerAgent
+ for _, placement := range placements {
+ if placement.TenantID != tenantID || placement.CreatedByActorID != ownerActorID {
+ continue
+ }
+ pending, err := s.queries.HasPendingAgentLocalWork(ctx, store.HasPendingAgentLocalWorkParams{TenantID: tenantID, AgentActorID: placement.ActorID})
+ if err != nil {
+ return nil, err
+ }
+ if !pending {
+ continue
+ }
+ agent, err := busyComputerAgent(ctx, s.queries, tenantID, placement.ActorID, placement.AgentManagementID)
+ if err != nil {
+ return nil, err
+ }
+ busy = append(busy, agent)
+ }
+ return busy, nil
+}
+
+// SwitchComputerRuntime applies a model-source switch to the Agents on the
+// Computer in one transaction: each keeps its Computer and workspace grant,
+// and a new Runtime type starts a new Runtime Assignment. An Agent that
+// already runs the target, or still has running work, is left alone; the
+// Computer has already switched, so the others move regardless.
+func (s *Service) SwitchComputerRuntime(ctx context.Context, input ComputerRuntimeSwitch) (ComputerRuntimeSwitchResult, error) {
+ if input.TenantID == "" || input.OwnerActorID == "" || input.ComputerID == "" || input.RuntimeType == "" || input.Model == "" {
+ return ComputerRuntimeSwitchResult{}, errors.New("invalid Computer Runtime switch")
+ }
+ tx, err := s.pool.Begin(ctx)
+ if err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ defer tx.Rollback(ctx)
+ queries := s.queries.WithTx(tx)
+ // Ordered by Agent, so concurrent switches take the Agents' locks in the
+ // same order.
+ placements, err := queries.ListAgentRunnerPlacementsOnComputer(ctx, input.ComputerID)
+ if err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ var (
+ result ComputerRuntimeSwitchResult
+ updated []string
+ )
+ for _, placement := range placements {
+ if placement.TenantID != input.TenantID || placement.CreatedByActorID != input.OwnerActorID {
+ continue
+ }
+ // The locks the Agent update takes, in its order.
+ if err := queries.AcquireAdvisoryTransactionLock(ctx, input.TenantID+"|agent-update|"+placement.ActorID); err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ if err := queries.AcquireAdvisoryTransactionLock(ctx, "agent-skill-bindings|"+placement.ActorID); err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ row, err := queries.GetAgentRegistrationForUpdate(ctx, store.GetAgentRegistrationForUpdateParams{ActorID: placement.ActorID, TenantID: input.TenantID})
+ if err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ if row.Status != "active" || row.ComputerID.String != input.ComputerID {
+ continue
+ }
+ if input.TerminateWork {
+ ended, err := agentruntimestate.TerminateLocalWorkForModelSourceSwitch(ctx, queries, input.TenantID, placement.ActorID)
+ if err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ result.TerminatedRuns = append(result.TerminatedRuns, ended...)
+ }
+ pending, err := queries.HasPendingAgentLocalWork(ctx, store.HasPendingAgentLocalWorkParams{TenantID: input.TenantID, AgentActorID: placement.ActorID})
+ if err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ if pending {
+ agent, err := busyComputerAgent(ctx, queries, input.TenantID, placement.ActorID, row.AgentManagementID.String)
+ if err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ result.BusyAgents = append(result.BusyAgents, agent)
+ continue
+ }
+ if row.LocalRuntimeType.String == input.RuntimeType && row.RuntimeModel == input.Model &&
+ row.RuntimeReasoningEffort.String == input.ReasoningEffort {
+ continue
+ }
+ changed, err := queries.ApplyAgentConfigurationUpdate(ctx, store.ApplyAgentConfigurationUpdateParams{
+ ActorID: placement.ActorID, TenantID: input.TenantID,
+ ExpectedRevision: row.ConfigurationRevision, NextRevision: row.ConfigurationRevision + 1,
+ Description: row.Description, Instructions: row.Instructions,
+ RuntimeModel: input.Model, RuntimeReasoningEffort: textValue(input.ReasoningEffort),
+ ComputerID: input.ComputerID, LocalRuntimeType: input.RuntimeType, WorkspaceGrantID: row.WorkspaceGrantID.String,
+ })
+ if err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ if changed != 1 {
+ return ComputerRuntimeSwitchResult{}, ErrAgentConfigurationConflict
+ }
+ updated = append(updated, row.AgentManagementID.String)
+ }
+ if len(updated) > 0 {
+ if err := createTenantAgentDirectoryDeliveries(ctx, queries, input.TenantID); err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ }
+ if err := tx.Commit(ctx); err != nil {
+ return ComputerRuntimeSwitchResult{}, err
+ }
+ for _, agentID := range updated {
+ s.NotifyAgentRegistrationChanged(ctx, agentID)
+ }
+ result.UpdatedAgents = len(updated)
+ return result, nil
+}
+
+func busyComputerAgent(ctx context.Context, queries *store.Queries, tenantID, actorID, agentID string) (BusyComputerAgent, error) {
+ actor, err := queries.GetActor(ctx, store.GetActorParams{ID: actorID, TenantID: tenantID})
+ if err != nil {
+ return BusyComputerAgent{}, err
+ }
+ return BusyComputerAgent{AgentID: agentID, Name: actor.DisplayName}, nil
+}
diff --git a/apps/teamhub/internal/agentruntimestate/placement_change.go b/apps/teamhub/internal/agentruntimestate/placement_change.go
index f1eb10de..4620d49f 100644
--- a/apps/teamhub/internal/agentruntimestate/placement_change.go
+++ b/apps/teamhub/internal/agentruntimestate/placement_change.go
@@ -8,7 +8,17 @@ import (
"github.com/simplexai-labs/linger/apps/teamhub/internal/store"
)
-var unreachableComputerTerminal = json.RawMessage(`{"type":"failed","error":"local_computer_unavailable","failure":{"code":"computer_unavailable"}}`)
+var (
+ unreachableComputerTerminal = json.RawMessage(`{"type":"failed","error":"local_computer_unavailable","failure":{"code":"computer_unavailable"}}`)
+ modelSourceSwitchTerminal = json.RawMessage(`{"type":"canceled","reason":"model_source_switched"}`)
+)
+
+// TerminatedLocalRun is a running Run a placement change ended. RoomID names
+// the Room of its Meta Context, where Agent Service can stop the live
+// process; it is empty for any other Context.
+type TerminatedLocalRun struct {
+ RunID, AgentManagementID, RoomID string
+}
// TerminateLocalWorkForUnreachableComputer ends the running Runs of an Agent
// that is moving away from a Computer that is not online: they can never
@@ -20,36 +30,60 @@ var unreachableComputerTerminal = json.RawMessage(`{"type":"failed","error":"loc
// registration lock and owns the transaction: Context locks follow the
// registration lock, and each Run's status Room follows its Context.
func TerminateLocalWorkForUnreachableComputer(ctx context.Context, queries *store.Queries, tenantID, agentActorID string) (bool, error) {
+ ended, err := terminateRunningLocalWork(ctx, queries, tenantID, agentActorID, unreachableComputerTerminal)
+ return len(ended) > 0, err
+}
+
+// TerminateLocalWorkForModelSourceSwitch cancels the running Runs of an Agent
+// whose Computer switches to another model source because its owner chose to
+// end them: they run on the old one. Queued Runs and steers fare as in
+// TerminateLocalWorkForUnreachableComputer, and the caller holds the same
+// locks.
+func TerminateLocalWorkForModelSourceSwitch(ctx context.Context, queries *store.Queries, tenantID, agentActorID string) ([]TerminatedLocalRun, error) {
+ return terminateRunningLocalWork(ctx, queries, tenantID, agentActorID, modelSourceSwitchTerminal)
+}
+
+func terminateRunningLocalWork(ctx context.Context, queries *store.Queries, tenantID, agentActorID string, terminal json.RawMessage) ([]TerminatedLocalRun, error) {
if queries == nil || strings.TrimSpace(tenantID) == "" || strings.TrimSpace(agentActorID) == "" {
- return false, ErrInvalid
+ return nil, ErrInvalid
}
contextKeys, err := queries.LockOpenAgentExecutionContextsForAgentRevocation(ctx, store.LockOpenAgentExecutionContextsForAgentRevocationParams{
TenantID: tenantID, AgentActorID: agentActorID, RoomIds: []string{},
})
if err != nil {
- return false, err
+ return nil, err
}
- ended := false
+ var ended []TerminatedLocalRun
for _, contextKey := range contextKeys {
running, err := queries.GetRunningAgentLocalRun(ctx, contextKey)
if isNoRows(err) {
continue
}
if err != nil {
- return false, err
+ return nil, err
}
- terminated, err := TerminateLocalRuns(ctx, queries, []string{running.RunID}, unreachableComputerTerminal)
+ terminated, err := TerminateLocalRuns(ctx, queries, []string{running.RunID}, terminal)
if err != nil {
- return false, err
+ return nil, err
}
- for _, run := range terminated {
- if err := expireRuntimeHumanInteractions(ctx, queries, run.RunID, tenantID, agentActorID); err != nil {
- return false, err
+ if len(terminated) > 0 {
+ owner, err := queries.GetAgentExecutionContext(ctx, contextKey)
+ if err != nil {
+ return nil, err
+ }
+ for _, run := range terminated {
+ if err := expireRuntimeHumanInteractions(ctx, queries, run.RunID, tenantID, agentActorID); err != nil {
+ return nil, err
+ }
+ stopped := TerminatedLocalRun{RunID: run.RunID, AgentManagementID: owner.AgentManagementID}
+ if owner.ContextKind == "meta" && owner.RoomID.Valid {
+ stopped.RoomID = owner.RoomID.String
+ }
+ ended = append(ended, stopped)
}
- ended = true
}
if err := settleSteersOfInterruptedRuns(ctx, queries, contextKey); err != nil {
- return false, err
+ return nil, err
}
}
return ended, nil
diff --git a/apps/teamhub/internal/app/handlers_model_source.go b/apps/teamhub/internal/app/handlers_model_source.go
new file mode 100644
index 00000000..0b0b3b94
--- /dev/null
+++ b/apps/teamhub/internal/app/handlers_model_source.go
@@ -0,0 +1,408 @@
+package app
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentregistry"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/ids"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"
+ "github.com/simplexai-labs/linger/contracts-go/nodeservicesinternal"
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
+)
+
+// modelSourceRunStopLifetime bounds the best-effort requests that stop the
+// live processes of Runs a switch ended.
+const modelSourceRunStopLifetime = 10 * time.Second
+
+// modelSourceRefusalCodes maps the Computer's and Agent Service's refusals a
+// Human can act on to their public code; any other is MODEL_SOURCE_FAILED.
+var modelSourceRefusalCodes = map[string]httpapi.ModelSourceErrorCode{
+ "TOOL_NOT_INSTALLED": httpapi.ModelSourceErrorCodeModelSourceUnavailable,
+ "MODEL_SOURCE_UNAVAILABLE": httpapi.ModelSourceErrorCodeModelSourceUnavailable,
+ "MODEL_SOURCE_UNSUPPORTED": httpapi.ModelSourceErrorCodeModelSourceUnavailable,
+ "RUNTIME_NOT_ENABLED": httpapi.ModelSourceErrorCodeRuntimeNotEnabled,
+ "MODEL_UNKNOWN": httpapi.ModelSourceErrorCodeLocalModelUnknown,
+ "BYOK_INVALID_CONFIG": httpapi.ModelSourceErrorCodeByokInvalidConfig,
+ "BYOK_AUTH_FAILED": httpapi.ModelSourceErrorCodeByokAuthFailed,
+ "BYOK_MODEL_NOT_FOUND": httpapi.ModelSourceErrorCodeByokModelNotFound,
+ "BYOK_UNREACHABLE": httpapi.ModelSourceErrorCodeByokUnreachable,
+ "BYOK_UPSTREAM_REJECTED": httpapi.ModelSourceErrorCodeByokUpstreamRejected,
+ "MODEL_SOURCE_TIMEOUT": httpapi.ModelSourceErrorCodeModelSourceUnconfirmed,
+ "BYOK_CHECK_TIMEOUT": httpapi.ModelSourceErrorCodeModelSourceUnconfirmed,
+}
+
+var modelSourceErrorMessages = map[httpapi.ModelSourceErrorCode]string{
+ httpapi.ModelSourceErrorCodeLocalComputerOffline: "Local Computer is offline",
+ httpapi.ModelSourceErrorCodeModelSourceForbidden: "Only the Computer's owner can change its model source",
+ httpapi.ModelSourceErrorCodeModelSourceUnavailable: "This Computer cannot switch model sources",
+ httpapi.ModelSourceErrorCodeAgentHasActiveRuns: "Agents on this Computer are working on tasks",
+ httpapi.ModelSourceErrorCodeRuntimeNotEnabled: "The selected AI runtime is not enabled on this Computer",
+ httpapi.ModelSourceErrorCodeLocalModelUnknown: "The Computer does not know this model",
+ httpapi.ModelSourceErrorCodeByokInvalidConfig: "The Computer rejected this endpoint configuration",
+ httpapi.ModelSourceErrorCodeByokAuthFailed: "The endpoint rejected the API key",
+ httpapi.ModelSourceErrorCodeByokModelNotFound: "The endpoint does not serve this model",
+ httpapi.ModelSourceErrorCodeByokUnreachable: "The Computer could not reach the endpoint",
+ httpapi.ModelSourceErrorCodeByokUpstreamRejected: "The endpoint rejected the test request",
+ httpapi.ModelSourceErrorCodeModelSourceFailed: "The Computer could not change its model source",
+ httpapi.ModelSourceErrorCodeModelSourceServiceUnavailable: "Model sources are unavailable",
+ httpapi.ModelSourceErrorCodeModelSourceUnconfirmed: "The Computer did not answer in time",
+}
+
+var modelSourceErrorStatuses = map[httpapi.ModelSourceErrorCode]int{
+ httpapi.ModelSourceErrorCodeLocalComputerOffline: http.StatusServiceUnavailable,
+ httpapi.ModelSourceErrorCodeModelSourceForbidden: http.StatusForbidden,
+ httpapi.ModelSourceErrorCodeModelSourceFailed: http.StatusBadGateway,
+ httpapi.ModelSourceErrorCodeModelSourceServiceUnavailable: http.StatusServiceUnavailable,
+ httpapi.ModelSourceErrorCodeModelSourceUnconfirmed: http.StatusGatewayTimeout,
+}
+
+// getLocalComputerModelSource shows any member of the Tenant whether the
+// Computer is online; only its owner sees the model source, because the BYOK
+// endpoint is theirs.
+func (a *App) getLocalComputerModelSource(c *gin.Context) {
+ computer, viewerID, ok := a.modelSourceComputer(c)
+ if !ok {
+ return
+ }
+ view := httpapi.ModelSourceView{
+ ComputerId: computer.ComputerID, ViewerIsOwner: computer.Owner.OwnerActorID == viewerID,
+ Online: localComputerOnline(computer.Status, computer.LastSeenAt, time.Now()),
+ }
+ if !view.ViewerIsOwner || !view.Online {
+ c.Header("Cache-Control", "no-store")
+ c.JSON(http.StatusOK, view)
+ return
+ }
+ management, ok := a.modelSourceManagement(c)
+ if !ok {
+ return
+ }
+ status, err := management.LocalComputerModelSource(c.Request.Context(), modelSourceTarget(computer))
+ var refusal *roomagent.ModelSourceError
+ switch {
+ case errors.Is(err, roomagent.ErrLocalComputerOffline):
+ view.Online = false
+ case errors.As(err, &refusal) && modelSourceRefusalCodes[refusal.Code] == httpapi.ModelSourceErrorCodeModelSourceUnavailable:
+ // A Computer without model sources still shows as online.
+ case err != nil:
+ a.writeModelSourceFailure(c, computer.ComputerID, "status", err)
+ return
+ default:
+ public, err := publicModelSourceStatus(status)
+ if err != nil {
+ a.internalError(c, "project Local Computer model source", err)
+ return
+ }
+ view.Status = &public
+ }
+ c.Header("Cache-Control", "no-store")
+ c.JSON(http.StatusOK, view)
+}
+
+// switchLocalComputerModelSource switches the owner's Computer to another
+// model source, then moves the Agents on it to the Runtime and model it now
+// serves. Running work blocks the switch unless the owner chose to end it;
+// work that starts while the Computer switches keeps its Agent where it is,
+// and the owner is asked about it again.
+func (a *App) switchLocalComputerModelSource(c *gin.Context) {
+ var request httpapi.ModelSourceSwitchRequest
+ if err := decodeJSON(c, &request); err != nil || !validModelSourceSwitch(request) {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "Model source switch is invalid")
+ return
+ }
+ computer, viewerID, ok := a.ownedOnlineModelSourceComputer(c)
+ if !ok {
+ return
+ }
+ management, ok := a.modelSourceManagement(c)
+ if !ok {
+ return
+ }
+ terminate := request.ForceTerminate != nil && *request.ForceTerminate
+ tenantID := computer.Owner.TenantID
+ if !terminate {
+ busy, err := a.agents.BusyComputerAgents(c.Request.Context(), tenantID, viewerID, computer.ComputerID)
+ if err != nil {
+ a.internalError(c, "read busy Agents on a Local Computer", err)
+ return
+ }
+ if len(busy) > 0 {
+ a.writeAgentsBusy(c, busy)
+ return
+ }
+ }
+ command, err := reencodeJSON[nodeservicesinternal.ModelSourceApplyCommand](httpapi.ModelSourceSwitchRequest{
+ Mode: request.Mode, Runtime: request.Runtime, LocalModelId: request.LocalModelId, Byok: request.Byok,
+ })
+ if err != nil {
+ a.internalError(c, "encode model source switch", err)
+ return
+ }
+ status, err := management.ApplyLocalComputerModelSource(c.Request.Context(), modelSourceTarget(computer), command)
+ if err != nil {
+ a.writeModelSourceFailure(c, computer.ComputerID, "apply", err)
+ return
+ }
+ public, err := publicModelSourceStatus(status)
+ if err != nil || status.RuntimeModel == "" {
+ a.logger.Warn("model_source.status_invalid", "computer_id", computer.ComputerID)
+ a.writeModelSourceError(c, httpapi.ModelSourceErrorCodeModelSourceFailed)
+ return
+ }
+ effort := ""
+ if status.ReasoningEffort != nil {
+ effort = string(*status.ReasoningEffort)
+ }
+ result, err := a.agents.SwitchComputerRuntime(c.Request.Context(), agentregistry.ComputerRuntimeSwitch{
+ TenantID: tenantID, OwnerActorID: viewerID, ComputerID: computer.ComputerID,
+ RuntimeType: string(status.Runtime), Model: status.RuntimeModel, ReasoningEffort: effort,
+ TerminateWork: terminate,
+ })
+ if err != nil {
+ a.internalError(c, "switch Agents to a Local Computer's model source", err)
+ return
+ }
+ a.stopTerminatedRuns(c.Request.Context(), result.TerminatedRuns)
+ if len(result.BusyAgents) > 0 {
+ // Work started after the first check. The Computer has switched and
+ // the idle Agents moved; a retry that ends that work moves the rest.
+ a.writeAgentsBusy(c, result.BusyAgents)
+ return
+ }
+ updated, terminated := result.UpdatedAgents, len(result.TerminatedRuns)
+ c.JSON(http.StatusOK, httpapi.ModelSourceView{
+ ComputerId: computer.ComputerID, ViewerIsOwner: true, Online: true, Status: &public,
+ UpdatedAgentCount: &updated, TerminatedRunCount: &terminated,
+ })
+}
+
+// testLocalComputerModelSource probes a BYOK endpoint from the owner's
+// Computer without saving it anywhere.
+func (a *App) testLocalComputerModelSource(c *gin.Context) {
+ var request httpapi.ByokTestRequest
+ if err := decodeJSON(c, &request); err != nil || !request.Runtime.Valid() || !validByokInput(request.Byok) {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "BYOK configuration is invalid")
+ return
+ }
+ computer, _, ok := a.ownedOnlineModelSourceComputer(c)
+ if !ok {
+ return
+ }
+ management, ok := a.modelSourceManagement(c)
+ if !ok {
+ return
+ }
+ input, err := reencodeJSON[nodeservicesinternal.ByokTestRequest](request)
+ if err != nil {
+ a.internalError(c, "encode BYOK test", err)
+ return
+ }
+ result, err := management.TestLocalComputerByok(c.Request.Context(), modelSourceTarget(computer), input)
+ if err != nil {
+ a.writeModelSourceFailure(c, computer.ComputerID, "test", err)
+ return
+ }
+ public, err := reencodeJSON[httpapi.ByokTestResult](result)
+ if err != nil {
+ a.internalError(c, "project BYOK test", err)
+ return
+ }
+ c.JSON(http.StatusOK, public)
+}
+
+// listLocalComputerByokModels lists the models a BYOK endpoint serves, asked
+// from the owner's Computer.
+func (a *App) listLocalComputerByokModels(c *gin.Context) {
+ var endpoint httpapi.ByokEndpointInput
+ if err := decodeJSON(c, &endpoint); err != nil || strings.TrimSpace(endpoint.BaseUrl) == "" ||
+ len(endpoint.BaseUrl) > 2048 || (endpoint.ApiKey != nil && len(*endpoint.ApiKey) > 4096) {
+ a.writeError(c, http.StatusBadRequest, "INVALID_REQUEST", "BYOK endpoint is invalid")
+ return
+ }
+ computer, _, ok := a.ownedOnlineModelSourceComputer(c)
+ if !ok {
+ return
+ }
+ management, ok := a.modelSourceManagement(c)
+ if !ok {
+ return
+ }
+ input, err := reencodeJSON[nodeservicesinternal.ByokEndpointInput](endpoint)
+ if err != nil {
+ a.internalError(c, "encode BYOK endpoint", err)
+ return
+ }
+ list, err := management.ListLocalComputerByokModels(c.Request.Context(), modelSourceTarget(computer), input)
+ if err != nil {
+ a.writeModelSourceFailure(c, computer.ComputerID, "models", err)
+ return
+ }
+ public, err := reencodeJSON[httpapi.ByokModelList](list)
+ if err != nil {
+ a.internalError(c, "project BYOK models", err)
+ return
+ }
+ c.JSON(http.StatusOK, public)
+}
+
+func (a *App) modelSourceComputer(c *gin.Context) (agentruntimestate.LocalComputer, string, bool) {
+ tenantID, computerID := c.Param("tenantId"), c.Param("computerId")
+ viewerID, ok := a.spaceHuman(c, tenantID)
+ if !ok {
+ return agentruntimestate.LocalComputer{}, "", false
+ }
+ if a.agentRuntimeState == nil {
+ a.writeModelSourceError(c, httpapi.ModelSourceErrorCodeModelSourceServiceUnavailable)
+ return agentruntimestate.LocalComputer{}, "", false
+ }
+ computer, err := a.agentRuntimeState.GetLocalComputer(c.Request.Context(), computerID)
+ switch {
+ case errors.Is(err, agentruntimestate.ErrNotFound), errors.Is(err, agentruntimestate.ErrInvalid),
+ err == nil && (computer.Owner.TenantID != tenantID || computer.Status == "removed"):
+ a.writeError(c, http.StatusNotFound, "LOCAL_COMPUTER_NOT_FOUND", "Local Computer was not found")
+ return agentruntimestate.LocalComputer{}, "", false
+ case err != nil:
+ a.internalError(c, "read Local Computer for its model source", err)
+ return agentruntimestate.LocalComputer{}, "", false
+ }
+ return computer, viewerID, true
+}
+
+func (a *App) ownedOnlineModelSourceComputer(c *gin.Context) (agentruntimestate.LocalComputer, string, bool) {
+ computer, viewerID, ok := a.modelSourceComputer(c)
+ switch {
+ case !ok:
+ return agentruntimestate.LocalComputer{}, "", false
+ case computer.Owner.OwnerActorID != viewerID:
+ a.writeModelSourceError(c, httpapi.ModelSourceErrorCodeModelSourceForbidden)
+ return agentruntimestate.LocalComputer{}, "", false
+ case !localComputerOnline(computer.Status, computer.LastSeenAt, time.Now()):
+ a.writeModelSourceError(c, httpapi.ModelSourceErrorCodeLocalComputerOffline)
+ return agentruntimestate.LocalComputer{}, "", false
+ }
+ return computer, viewerID, true
+}
+
+func (a *App) modelSourceManagement(c *gin.Context) (roomagent.ModelSourceManagement, bool) {
+ management, ok := a.localComputers.(roomagent.ModelSourceManagement)
+ if !ok || a.agents == nil {
+ a.writeModelSourceError(c, httpapi.ModelSourceErrorCodeModelSourceServiceUnavailable)
+ return nil, false
+ }
+ return management, true
+}
+
+func modelSourceTarget(computer agentruntimestate.LocalComputer) roomagent.ModelSourceTarget {
+ return roomagent.ModelSourceTarget{
+ TenantID: computer.Owner.TenantID, OwnerActorID: computer.Owner.OwnerActorID, ComputerID: computer.ComputerID,
+ }
+}
+
+// stopTerminatedRuns asks Agent Service to stop the live processes of the
+// Runs a switch ended. TeamHub already ended them; a failure only leaves a
+// process running until its next exchange with TeamHub fences it.
+func (a *App) stopTerminatedRuns(ctx context.Context, runs []agentruntimestate.TerminatedLocalRun) {
+ gateway, ok := a.agentManagement.(roomagent.RunManagement)
+ if !ok || len(runs) == 0 {
+ return
+ }
+ ctx, cancel := context.WithTimeout(context.WithoutCancel(ctx), modelSourceRunStopLifetime)
+ defer cancel()
+ for _, run := range runs {
+ if run.RoomID == "" {
+ continue
+ }
+ if _, err := gateway.CancelRun(ctx, roomagent.RunCancelCommand{
+ RequestID: ids.New("model_source_stop"), RunID: run.RunID, AgentID: run.AgentManagementID, RoomID: run.RoomID,
+ }); err != nil {
+ a.logger.Warn("model_source.run_stop_failed", "run_id", run.RunID, "error", err)
+ }
+ }
+}
+
+func (a *App) writeAgentsBusy(c *gin.Context, agents []agentregistry.BusyComputerAgent) {
+ code := string(httpapi.ModelSourceErrorCodeAgentHasActiveRuns)
+ details := make([]httpapi.ErrorDetail, len(agents))
+ for index, agent := range agents {
+ details[index] = httpapi.ErrorDetail{Code: &code, Field: "agent", Reason: agent.Name}
+ }
+ a.writeErrorWithDetails(c, http.StatusConflict, code, modelSourceErrorMessages[httpapi.ModelSourceErrorCodeAgentHasActiveRuns], details)
+}
+
+func (a *App) writeModelSourceFailure(c *gin.Context, computerID, action string, err error) {
+ var refusal *roomagent.ModelSourceError
+ switch {
+ case errors.Is(err, roomagent.ErrLocalComputerNotFound):
+ a.writeError(c, http.StatusNotFound, "LOCAL_COMPUTER_NOT_FOUND", "Local Computer was not found")
+ case errors.Is(err, roomagent.ErrLocalComputerOffline):
+ a.writeModelSourceError(c, httpapi.ModelSourceErrorCodeLocalComputerOffline)
+ case errors.As(err, &refusal):
+ code, known := modelSourceRefusalCodes[refusal.Code]
+ if !known {
+ a.logger.Warn("model_source.refused", "computer_id", computerID, "action", action, "refusal_code", refusal.Code)
+ code = httpapi.ModelSourceErrorCodeModelSourceFailed
+ }
+ a.writeModelSourceError(c, code)
+ default:
+ a.logger.Error("model_source.failed", "computer_id", computerID, "action", action, "error", err)
+ a.writeModelSourceError(c, httpapi.ModelSourceErrorCodeModelSourceServiceUnavailable)
+ }
+}
+
+func (a *App) writeModelSourceError(c *gin.Context, code httpapi.ModelSourceErrorCode) {
+ status, found := modelSourceErrorStatuses[code]
+ if !found {
+ status = http.StatusConflict
+ }
+ a.writeError(c, status, string(code), modelSourceErrorMessages[code])
+}
+
+func validModelSourceSwitch(request httpapi.ModelSourceSwitchRequest) bool {
+ if request.Runtime != nil && !request.Runtime.Valid() {
+ return false
+ }
+ switch request.Mode {
+ case httpapi.ModelSourceModeByok:
+ return request.Runtime != nil && request.LocalModelId == nil && request.Byok != nil && validByokInput(*request.Byok)
+ case httpapi.ModelSourceModeSubscription:
+ return request.Runtime != nil && *request.Runtime != httpapi.ModelSourceRuntimePi &&
+ request.LocalModelId == nil && request.Byok == nil
+ case httpapi.ModelSourceModeLocal:
+ return (request.Runtime == nil || *request.Runtime == httpapi.ModelSourceRuntimePi) && request.Byok == nil &&
+ (request.LocalModelId == nil || localModelIDPattern.MatchString(*request.LocalModelId))
+ }
+ return false
+}
+
+func validByokInput(input httpapi.ByokInput) bool {
+ return strings.TrimSpace(input.BaseUrl) != "" && len(input.BaseUrl) <= 2048 &&
+ strings.TrimSpace(input.ModelId) != "" && len(input.ModelId) <= 256 &&
+ (input.ApiKey == nil || len(*input.ApiKey) <= 4096) &&
+ (input.ContextWindow == nil || *input.ContextWindow >= 1)
+}
+
+func publicModelSourceStatus(status nodeservicesinternal.ModelSourceStatus) (httpapi.ModelSourceStatus, error) {
+ public, err := reencodeJSON[httpapi.ModelSourceStatus](status)
+ if err == nil && (!public.Mode.Valid() || !public.Runtime.Valid()) {
+ err = errors.New("model source status has an unknown mode or Runtime")
+ }
+ return public, err
+}
+
+// reencodeJSON converts between generated contract types that share a wire
+// shape.
+func reencodeJSON[T any](value any) (T, error) {
+ var converted T
+ encoded, err := json.Marshal(value)
+ if err == nil {
+ err = json.Unmarshal(encoded, &converted)
+ }
+ return converted, err
+}
diff --git a/apps/teamhub/internal/app/handlers_model_source_test.go b/apps/teamhub/internal/app/handlers_model_source_test.go
new file mode 100644
index 00000000..6a3df4e2
--- /dev/null
+++ b/apps/teamhub/internal/app/handlers_model_source_test.go
@@ -0,0 +1,39 @@
+package app
+
+import (
+ "testing"
+
+ httpapi "github.com/simplexai-labs/linger/contracts-go/teamhubpublic"
+)
+
+func TestValidModelSourceSwitchMatchesRuntimeAndInputsToMode(t *testing.T) {
+ claude, pi := httpapi.ModelSourceRuntimeClaude, httpapi.ModelSourceRuntimePi
+ unknown := httpapi.ModelSourceRuntime("gemini")
+ model := "qwen3-4b:Q4_K_M"
+ badModel := "../qwen"
+ byok := &httpapi.ByokInput{BaseUrl: "https://api.example.com", ModelId: "vendor/model"}
+ blankURL := &httpapi.ByokInput{BaseUrl: " ", ModelId: "vendor/model"}
+ for _, test := range []struct {
+ name string
+ request httpapi.ModelSourceSwitchRequest
+ valid bool
+ }{
+ {"byok", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeByok, Runtime: &claude, Byok: byok}, true},
+ {"byok on pi", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeByok, Runtime: &pi, Byok: byok}, true},
+ {"byok without runtime", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeByok, Byok: byok}, false},
+ {"byok without endpoint", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeByok, Runtime: &claude}, false},
+ {"byok blank URL", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeByok, Runtime: &claude, Byok: blankURL}, false},
+ {"subscription", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeSubscription, Runtime: &claude}, true},
+ {"subscription on pi", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeSubscription, Runtime: &pi}, false},
+ {"subscription with endpoint", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeSubscription, Runtime: &claude, Byok: byok}, false},
+ {"local", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeLocal, LocalModelId: &model}, true},
+ {"local on claude", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeLocal, Runtime: &claude}, false},
+ {"local bad model", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeLocal, LocalModelId: &badModel}, false},
+ {"unknown runtime", httpapi.ModelSourceSwitchRequest{Mode: httpapi.ModelSourceModeByok, Runtime: &unknown, Byok: byok}, false},
+ {"unknown mode", httpapi.ModelSourceSwitchRequest{Mode: "cloud", Runtime: &claude}, false},
+ } {
+ if got := validModelSourceSwitch(test.request); got != test.valid {
+ t.Errorf("%s: valid=%v, want %v", test.name, got, test.valid)
+ }
+ }
+}
diff --git a/apps/teamhub/internal/app/routes_public.go b/apps/teamhub/internal/app/routes_public.go
index dfe731eb..bb6e4c61 100644
--- a/apps/teamhub/internal/app/routes_public.go
+++ b/apps/teamhub/internal/app/routes_public.go
@@ -176,6 +176,10 @@ func (a *App) publicRoutes() []contractRoute {
route(http.MethodPut, "/v0/tenants/:tenantId/local-computers/:computerId/browser-connection", nil, session, a.putLocalComputerBrowserConnection),
route(http.MethodGet, "/v0/tenants/:tenantId/local-computers/:computerId/local-models", nil, session, a.getLocalComputerModels),
route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/local-models/:modelId/actions", nil, session, a.actOnLocalComputerModel),
+ route(http.MethodGet, "/v0/tenants/:tenantId/local-computers/:computerId/model-source", nil, session, a.getLocalComputerModelSource),
+ route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/model-source", nil, session, a.switchLocalComputerModelSource),
+ route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/model-source/test", nil, session, a.testLocalComputerModelSource),
+ route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/model-source/models", nil, session, a.listLocalComputerByokModels),
route(http.MethodGet, "/v0/tenants/:tenantId/local-computers/:computerId/permissions", nil, session, a.getLocalComputerPermissions),
route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/permissions", nil, session, a.actOnLocalComputerPermission),
route(http.MethodPost, "/v0/tenants/:tenantId/local-computers/:computerId/skill-scans", nil, session, a.scanLocalSkills),
diff --git a/apps/teamhub/internal/roomagent/http_gateway.go b/apps/teamhub/internal/roomagent/http_gateway.go
index fab9adb1..9ec43695 100644
--- a/apps/teamhub/internal/roomagent/http_gateway.go
+++ b/apps/teamhub/internal/roomagent/http_gateway.go
@@ -21,6 +21,8 @@ type HTTPGateway struct {
client *agentapi.ClientWithResponses
browserClient *agentapi.ClientWithResponses
toolClient *agentapi.ClientWithResponses
+ // modelSourceClient waits out a model-source switch.
+ modelSourceClient *agentapi.ClientWithResponses
}
const agentManagementRequestTimeout = 15 * time.Second
@@ -55,7 +57,13 @@ func NewHTTPGateway(baseURL, token string, client *http.Client) (*HTTPGateway, e
if err != nil {
return nil, fmt.Errorf("create Computer tool contract client: %w", err)
}
- return &HTTPGateway{client: generatedClient, browserClient: browserClient, toolClient: toolClient}, nil
+ modelSourceHTTPClient := *client
+ modelSourceHTTPClient.Timeout = localModelSourceRequestTimeout
+ modelSourceClient, err := NewAgentManagementClient(baseURL, token, &modelSourceHTTPClient)
+ if err != nil {
+ return nil, fmt.Errorf("create model source contract client: %w", err)
+ }
+ return &HTTPGateway{client: generatedClient, browserClient: browserClient, toolClient: toolClient, modelSourceClient: modelSourceClient}, nil
}
// NewAgentManagementClient validates the Agent Service origin and creates a
diff --git a/apps/teamhub/internal/roomagent/model_source.go b/apps/teamhub/internal/roomagent/model_source.go
new file mode 100644
index 00000000..1735468b
--- /dev/null
+++ b/apps/teamhub/internal/roomagent/model_source.go
@@ -0,0 +1,121 @@
+package roomagent
+
+import (
+ "context"
+ "fmt"
+ "net/http"
+ "time"
+
+ "github.com/simplexai-labs/linger/contracts-go/nodeservicesinternal"
+)
+
+// localModelSourceRequestTimeout covers the Gateway's three-minute budget
+// for a switch, which may install a Runtime or start Bifrost first.
+const localModelSourceRequestTimeout = 185 * time.Second
+
+// ModelSourceTarget names the owner's connected Computer a model-source
+// command goes to.
+type ModelSourceTarget struct {
+ TenantID, OwnerActorID, ComputerID string
+}
+
+// ModelSourceError is a refusal with the stable code the Computer or Agent
+// Service reported, such as BYOK_AUTH_FAILED or RUNTIME_NOT_ENABLED.
+type ModelSourceError struct{ Code string }
+
+func (e *ModelSourceError) Error() string { return "model source refused: " + e.Code }
+
+// ModelSourceManagement reads, probes and switches the model source of the
+// owner's connected Computer. A BYOK input carries the API key; it must never
+// be logged or persisted.
+type ModelSourceManagement interface {
+ LocalComputerModelSource(ctx context.Context, target ModelSourceTarget) (nodeservicesinternal.ModelSourceStatus, error)
+ ApplyLocalComputerModelSource(ctx context.Context, target ModelSourceTarget, command nodeservicesinternal.ModelSourceApplyCommand) (nodeservicesinternal.ModelSourceStatus, error)
+ TestLocalComputerByok(ctx context.Context, target ModelSourceTarget, request nodeservicesinternal.ByokTestRequest) (nodeservicesinternal.ByokTestResult, error)
+ ListLocalComputerByokModels(ctx context.Context, target ModelSourceTarget, endpoint nodeservicesinternal.ByokEndpointInput) (nodeservicesinternal.ByokModelList, error)
+}
+
+// LocalComputerModelSource reads the Computer's active model source.
+func (g *HTTPGateway) LocalComputerModelSource(ctx context.Context, target ModelSourceTarget) (nodeservicesinternal.ModelSourceStatus, error) {
+ if !validModelSourceTarget(target) {
+ return nodeservicesinternal.ModelSourceStatus{}, ErrLocalComputerNotFound
+ }
+ response, err := g.modelSourceClient.GetLocalComputerModelSourceWithResponse(ctx, target.TenantID, target.OwnerActorID, target.ComputerID)
+ if err != nil {
+ return nodeservicesinternal.ModelSourceStatus{}, fmt.Errorf("model source status: %w", err)
+ }
+ if response.StatusCode() == http.StatusOK && response.JSON200 != nil {
+ return *response.JSON200, nil
+ }
+ return nodeservicesinternal.ModelSourceStatus{}, modelSourceGatewayError(response.StatusCode(),
+ firstError(response.JSON409, response.JSON502, response.JSON503))
+}
+
+// ApplyLocalComputerModelSource switches the Computer's model source and
+// returns the status the Computer reports after the switch.
+func (g *HTTPGateway) ApplyLocalComputerModelSource(ctx context.Context, target ModelSourceTarget, command nodeservicesinternal.ModelSourceApplyCommand) (nodeservicesinternal.ModelSourceStatus, error) {
+ if !validModelSourceTarget(target) {
+ return nodeservicesinternal.ModelSourceStatus{}, ErrLocalComputerNotFound
+ }
+ response, err := g.modelSourceClient.ApplyLocalComputerModelSourceWithResponse(ctx, target.TenantID, target.OwnerActorID, target.ComputerID, command)
+ if err != nil {
+ // The transport error can wrap the request but never its body.
+ return nodeservicesinternal.ModelSourceStatus{}, fmt.Errorf("model source apply: %w", err)
+ }
+ if response.StatusCode() == http.StatusOK && response.JSON200 != nil {
+ return *response.JSON200, nil
+ }
+ return nodeservicesinternal.ModelSourceStatus{}, modelSourceGatewayError(response.StatusCode(),
+ firstError(response.JSON400, response.JSON409, response.JSON502, response.JSON503))
+}
+
+// TestLocalComputerByok probes a BYOK endpoint from the Computer without
+// saving it.
+func (g *HTTPGateway) TestLocalComputerByok(ctx context.Context, target ModelSourceTarget, request nodeservicesinternal.ByokTestRequest) (nodeservicesinternal.ByokTestResult, error) {
+ if !validModelSourceTarget(target) {
+ return nodeservicesinternal.ByokTestResult{}, ErrLocalComputerNotFound
+ }
+ response, err := g.modelSourceClient.TestLocalComputerByokWithResponse(ctx, target.TenantID, target.OwnerActorID, target.ComputerID, request)
+ if err != nil {
+ return nodeservicesinternal.ByokTestResult{}, fmt.Errorf("BYOK test: %w", err)
+ }
+ if response.StatusCode() == http.StatusOK && response.JSON200 != nil {
+ return *response.JSON200, nil
+ }
+ return nodeservicesinternal.ByokTestResult{}, modelSourceGatewayError(response.StatusCode(),
+ firstError(response.JSON400, response.JSON409, response.JSON502, response.JSON503))
+}
+
+// ListLocalComputerByokModels lists the models a BYOK endpoint serves, asked
+// from the Computer so the key never leaves it.
+func (g *HTTPGateway) ListLocalComputerByokModels(ctx context.Context, target ModelSourceTarget, endpoint nodeservicesinternal.ByokEndpointInput) (nodeservicesinternal.ByokModelList, error) {
+ if !validModelSourceTarget(target) {
+ return nodeservicesinternal.ByokModelList{}, ErrLocalComputerNotFound
+ }
+ response, err := g.modelSourceClient.ListLocalComputerByokModelsWithResponse(ctx, target.TenantID, target.OwnerActorID, target.ComputerID, endpoint)
+ if err != nil {
+ return nodeservicesinternal.ByokModelList{}, fmt.Errorf("BYOK models: %w", err)
+ }
+ if response.StatusCode() == http.StatusOK && response.JSON200 != nil {
+ return *response.JSON200, nil
+ }
+ return nodeservicesinternal.ByokModelList{}, modelSourceGatewayError(response.StatusCode(),
+ firstError(response.JSON400, response.JSON409, response.JSON502, response.JSON503))
+}
+
+func validModelSourceTarget(target ModelSourceTarget) bool {
+ return opaqueIDPattern.MatchString(target.TenantID) && opaqueIDPattern.MatchString(target.OwnerActorID) &&
+ opaqueIDPattern.MatchString(target.ComputerID)
+}
+
+func modelSourceGatewayError(status int, body *nodeservicesinternal.ErrorResponse) error {
+ switch {
+ case status == http.StatusNotFound:
+ return ErrLocalComputerNotFound
+ case body != nil && body.Error.Code == "LOCAL_COMPUTER_OFFLINE":
+ return ErrLocalComputerOffline
+ case body != nil && body.Error.Code != "":
+ return &ModelSourceError{Code: body.Error.Code}
+ }
+ return fmt.Errorf("AgentManagement returned status %d for a model source command", status)
+}
diff --git a/apps/teamhub/internal/roomagent/model_source_test.go b/apps/teamhub/internal/roomagent/model_source_test.go
new file mode 100644
index 00000000..71641362
--- /dev/null
+++ b/apps/teamhub/internal/roomagent/model_source_test.go
@@ -0,0 +1,102 @@
+package roomagent
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/simplexai-labs/linger/contracts-go/nodeservicesinternal"
+)
+
+func TestHTTPGatewayAppliesModelSourceAndMapsRefusals(t *testing.T) {
+ var status int
+ var answer string
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/v1/tenants/tenant_1/owners/actor_owner/local-computers/computer_1/model-source" {
+ t.Fatalf("%s %s", r.Method, r.URL.Path)
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
+ t.Fatal(err)
+ }
+ byok, _ := body["byok"].(map[string]any)
+ if body["mode"] != "byok" || body["runtime"] != "codex" || byok["api_key"] != "sk-test" {
+ t.Fatalf("body=%v", body)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _, _ = w.Write([]byte(answer))
+ }))
+ t.Cleanup(server.Close)
+ gateway, err := NewHTTPGateway(server.URL, "service-secret", server.Client())
+ if err != nil {
+ t.Fatal(err)
+ }
+ target := ModelSourceTarget{TenantID: "tenant_1", OwnerActorID: "actor_owner", ComputerID: "computer_1"}
+ runtime := nodeservicesinternal.ModelSourceRuntime("codex")
+ key := "sk-test"
+ command := nodeservicesinternal.ModelSourceApplyCommand{Mode: "byok", Runtime: &runtime, Byok: &nodeservicesinternal.ByokInput{
+ BaseUrl: "https://api.example.com/v1", ApiKey: &key, ModelId: "gpt-5.5",
+ }}
+
+ status, answer = http.StatusOK, `{"mode":"byok","runtime":"codex","runtime_model":"localmodels-byok","reasoning_effort":"high","byok":{"configured":true,"key_saved":true}}`
+ applied, err := gateway.ApplyLocalComputerModelSource(context.Background(), target, command)
+ if err != nil || applied.RuntimeModel != "localmodels-byok" || applied.ReasoningEffort == nil || *applied.ReasoningEffort != "high" {
+ t.Fatalf("applied=%+v err=%v", applied, err)
+ }
+ for _, test := range []struct {
+ status int
+ body string
+ want error
+ code string
+ }{
+ {status: http.StatusNotFound, body: `{"error":{"code":"LOCAL_COMPUTER_NOT_FOUND","message":"gone","request_id":"r"}}`, want: ErrLocalComputerNotFound},
+ {status: http.StatusServiceUnavailable, body: `{"error":{"code":"LOCAL_COMPUTER_OFFLINE","message":"off","request_id":"r"}}`, want: ErrLocalComputerOffline},
+ {status: http.StatusBadGateway, body: `{"error":{"code":"BYOK_AUTH_FAILED","message":"no","request_id":"r"}}`, code: "BYOK_AUTH_FAILED"},
+ {status: http.StatusConflict, body: `{"error":{"code":"RUNTIME_NOT_ENABLED","message":"no","request_id":"r"}}`, code: "RUNTIME_NOT_ENABLED"},
+ {status: http.StatusInternalServerError, body: `{}`},
+ } {
+ status, answer = test.status, test.body
+ _, err := gateway.ApplyLocalComputerModelSource(context.Background(), target, command)
+ var refusal *ModelSourceError
+ switch {
+ case test.want != nil && !errors.Is(err, test.want),
+ test.code != "" && (!errors.As(err, &refusal) || refusal.Code != test.code),
+ test.want == nil && test.code == "" && (err == nil || errors.As(err, &refusal)):
+ t.Fatalf("status %d: err=%v", test.status, err)
+ }
+ }
+ if _, err := gateway.ApplyLocalComputerModelSource(context.Background(), ModelSourceTarget{TenantID: "tenant 1"}, command); !errors.Is(err, ErrLocalComputerNotFound) {
+ t.Fatalf("invalid target err=%v", err)
+ }
+}
+
+func TestHTTPGatewayListsByokModelsFromTheComputer(t *testing.T) {
+ server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Method != http.MethodPost || r.URL.Path != "/v1/tenants/tenant_1/owners/actor_owner/local-computers/computer_1/model-source/models" {
+ t.Fatalf("%s %s", r.Method, r.URL.Path)
+ }
+ var body map[string]any
+ if err := json.NewDecoder(r.Body).Decode(&body); err != nil || body["api_key"] != "sk-test" || body["base_url"] != "https://api.example.com/v1" {
+ t.Fatalf("body=%v err=%v", body, err)
+ }
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = w.Write([]byte(`{"base_url":"https://api.example.com","models":[{"id":"glm-5","name":"GLM 5","context_window":131072}]}`))
+ }))
+ t.Cleanup(server.Close)
+ gateway, err := NewHTTPGateway(server.URL, "service-secret", server.Client())
+ if err != nil {
+ t.Fatal(err)
+ }
+ key := "sk-test"
+ list, err := gateway.ListLocalComputerByokModels(context.Background(),
+ ModelSourceTarget{TenantID: "tenant_1", OwnerActorID: "actor_owner", ComputerID: "computer_1"},
+ nodeservicesinternal.ByokEndpointInput{BaseUrl: "https://api.example.com/v1", ApiKey: &key})
+ if err != nil || list.BaseUrl != "https://api.example.com" || len(list.Models) != 1 ||
+ list.Models[0].ContextWindow == nil || *list.Models[0].ContextWindow != 131072 {
+ t.Fatalf("list=%+v err=%v", list, err)
+ }
+}
diff --git a/apps/teamhub/tests/integration/local_computer_model_source_test.go b/apps/teamhub/tests/integration/local_computer_model_source_test.go
new file mode 100644
index 00000000..cd51f098
--- /dev/null
+++ b/apps/teamhub/tests/integration/local_computer_model_source_test.go
@@ -0,0 +1,305 @@
+package integration_test
+
+import (
+ "context"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/jackc/pgx/v5/pgxpool"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/agentruntimestate"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/config"
+ "github.com/simplexai-labs/linger/apps/teamhub/internal/roomagent"
+ "github.com/simplexai-labs/linger/contracts-go/nodeservicesinternal"
+)
+
+const modelSourceTestAPIKey = "sk-model-source-never-stored"
+
+type modelSourceComputers struct {
+ recordingLocalComputers
+ mu sync.Mutex
+ applied []nodeservicesinternal.ModelSourceApplyCommand
+ tested []nodeservicesinternal.ByokTestRequest
+ status nodeservicesinternal.ModelSourceStatus
+ // duringApply runs while the Computer switches, before TeamHub moves
+ // the Agents.
+ duringApply func()
+}
+
+func (c *modelSourceComputers) LocalComputerModelSource(_ context.Context, _ roomagent.ModelSourceTarget) (nodeservicesinternal.ModelSourceStatus, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return c.status, nil
+}
+
+func (c *modelSourceComputers) ApplyLocalComputerModelSource(_ context.Context, _ roomagent.ModelSourceTarget, command nodeservicesinternal.ModelSourceApplyCommand) (nodeservicesinternal.ModelSourceStatus, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.applied = append(c.applied, command)
+ if c.duringApply != nil {
+ c.duringApply()
+ }
+ return c.status, nil
+}
+
+func (c *modelSourceComputers) TestLocalComputerByok(_ context.Context, _ roomagent.ModelSourceTarget, request nodeservicesinternal.ByokTestRequest) (nodeservicesinternal.ByokTestResult, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ c.tested = append(c.tested, request)
+ input := request.Byok
+ if input.ApiKey == nil || *input.ApiKey != modelSourceTestAPIKey {
+ return nodeservicesinternal.ByokTestResult{}, &roomagent.ModelSourceError{Code: "BYOK_AUTH_FAILED"}
+ }
+ return nodeservicesinternal.ByokTestResult{Ok: true, Protocol: "anthropic", BaseUrl: input.BaseUrl, ModelId: input.ModelId, ContextWindow: 200000}, nil
+}
+
+func (c *modelSourceComputers) ListLocalComputerByokModels(_ context.Context, _ roomagent.ModelSourceTarget, endpoint nodeservicesinternal.ByokEndpointInput) (nodeservicesinternal.ByokModelList, error) {
+ if endpoint.ApiKey == nil || *endpoint.ApiKey != modelSourceTestAPIKey {
+ return nodeservicesinternal.ByokModelList{}, &roomagent.ModelSourceError{Code: "BYOK_AUTH_FAILED"}
+ }
+ window := 131072
+ return nodeservicesinternal.ByokModelList{BaseUrl: endpoint.BaseUrl, Models: []nodeservicesinternal.ByokModel{{Id: "vendor/model", ContextWindow: &window}}}, nil
+}
+
+func (c *modelSourceComputers) appliedSnapshot() []nodeservicesinternal.ModelSourceApplyCommand {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ return append([]nodeservicesinternal.ModelSourceApplyCommand(nil), c.applied...)
+}
+
+type runStoppingAgentManagement struct {
+ *recordingAgentManagement
+ mu sync.Mutex
+ stopped []roomagent.RunCancelCommand
+}
+
+func (m *runStoppingAgentManagement) CancelRun(_ context.Context, command roomagent.RunCancelCommand) (roomagent.RunCancelResult, error) {
+ m.mu.Lock()
+ defer m.mu.Unlock()
+ m.stopped = append(m.stopped, command)
+ return roomagent.RunCancelResult{RunID: command.RunID, Status: "already_terminal"}, nil
+}
+
+func newModelSourceEnv(t *testing.T, management roomagent.AgentManagement, computers *modelSourceComputers) (*testEnv, *http.Client) {
+ t.Helper()
+ databaseURL := newIntegrationDatabase(t)
+ pool, err := pgxpool.New(context.Background(), databaseURL)
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(pool.Close)
+ seedReadyFixtureComputers(t, pool)
+ artifactRoot := integrationArtifactRoot(t)
+ application, err := newIntegrationApp(context.Background(), config.ForTest(func(c *config.Config) {
+ c.DatabaseURL = databaseURL
+ c.SessionTTL = time.Hour
+ c.CookieName = "teamhub_session"
+ c.TeamHubInternalToken = teamHubInternalToken
+ c.NodeServicesInternalToken = nodeServicesInternalToken
+ c.AgentRunTokenSecret = agentRunTokenSecret
+ c.RoomDocument.RuntimeURL = "http://document-runtime.test"
+ c.ArtifactStorageRoot = artifactRoot
+ }), withAgentManagement(management), withLocalComputers(computers))
+ if err != nil {
+ t.Fatal(err)
+ }
+ t.Cleanup(application.Close)
+ server := httptest.NewServer(application.Handler())
+ registerIntegrationServerCleanup(t, server)
+ env := &testEnv{t: t, databaseURL: databaseURL, pool: pool, server: server, artifactRoot: artifactRoot}
+ return env, env.login("alice", alicePassword)
+}
+
+// TestLocalComputerModelSourceSwitchMovesAgentsAndEndsChosenWork covers what
+// needs PostgreSQL: the owner-only view, the refusal while an Agent works, and
+// the forced switch that ends the work and moves every Agent on the Computer
+// in one transaction, without TeamHub keeping the API key.
+func TestLocalComputerModelSourceSwitchMovesAgentsAndEndsChosenWork(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ management := &runStoppingAgentManagement{recordingAgentManagement: &recordingAgentManagement{}}
+ effort := nodeservicesinternal.AgentReasoningEffort("high")
+ computers := &modelSourceComputers{status: nodeservicesinternal.ModelSourceStatus{
+ Mode: "byok", Runtime: "claude", RuntimeModel: "localmodels-byok", ReasoningEffort: &effort,
+ Byok: nodeservicesinternal.ByokSummary{Configured: true, KeySaved: true},
+ }}
+ env, alice := newModelSourceEnv(t, management, computers)
+ bob := seedPeerHuman(t, env)
+ base := "/v0/tenants/" + acmeTenant + "/local-computers/" + fixtureComputerID + "/model-source"
+
+ agents := map[string]tenantAgentUpdateView{}
+ for _, name := range []string{"Worker", "Idler"} {
+ status, _, body := env.request(alice, http.MethodPost, "/v0/tenants/"+acmeTenant+"/agents", map[string]any{"name": name, "instructions": "Keep work", "runtime": fixtureRuntime("codex-default")}, "model-source-create-"+name)
+ if status != http.StatusCreated {
+ t.Fatalf("create %s: %d %s", name, status, body)
+ }
+ var created tenantAgentUpdateView
+ decode(t, body, &created)
+ agents[name] = created
+ }
+
+ status, _, body := env.request(alice, http.MethodGet, base, nil, "")
+ if status != http.StatusOK || !containsJSONText(body, `"viewer_is_owner":true`) || !containsJSONText(body, `"mode":"byok"`) {
+ t.Fatalf("owner view: %d %s", status, body)
+ }
+ status, _, body = env.request(bob, http.MethodGet, base, nil, "")
+ if status != http.StatusOK || !containsJSONText(body, `"viewer_is_owner":false`) || containsJSONText(body, `"status"`) {
+ t.Fatalf("member view: %d %s", status, body)
+ }
+ byokSwitch := map[string]any{"mode": "byok", "runtime": "claude", "byok": map[string]any{
+ "base_url": "https://api.example.com", "api_key": modelSourceTestAPIKey, "model_id": "vendor/model",
+ }}
+ status, _, body = env.request(bob, http.MethodPost, base, byokSwitch, "")
+ if status != http.StatusForbidden || !containsJSONText(body, "MODEL_SOURCE_FORBIDDEN") {
+ t.Fatalf("member switch: %d %s", status, body)
+ }
+ status, _, body = env.request(alice, http.MethodPost, base, map[string]any{"mode": "subscription", "runtime": "pi"}, "")
+ if status != http.StatusBadRequest {
+ t.Fatalf("subscription on pi: %d %s", status, body)
+ }
+
+ status, _, body = env.request(alice, http.MethodPost, base+"/test", map[string]any{"runtime": "claude", "byok": byokSwitch["byok"]}, "")
+ if status != http.StatusOK || !containsJSONText(body, `"context_window":200000`) || containsJSONText(body, modelSourceTestAPIKey) {
+ t.Fatalf("BYOK test: %d %s", status, body)
+ }
+ status, _, body = env.request(alice, http.MethodPost, base+"/test", byokSwitch["byok"], "")
+ if status != http.StatusBadRequest {
+ t.Fatalf("BYOK test without a Runtime: %d %s", status, body)
+ }
+ status, _, body = env.request(alice, http.MethodPost, base+"/test", map[string]any{"runtime": "claude", "byok": map[string]any{"base_url": "https://api.example.com", "api_key": "wrong", "model_id": "vendor/model"}}, "")
+ if status != http.StatusConflict || !containsJSONText(body, "BYOK_AUTH_FAILED") {
+ t.Fatalf("BYOK test with a wrong key: %d %s", status, body)
+ }
+ status, _, body = env.request(alice, http.MethodPost, base+"/models", map[string]any{"base_url": "https://api.example.com/v1", "api_key": modelSourceTestAPIKey}, "")
+ if status != http.StatusOK || !containsJSONText(body, `"context_window":131072`) || containsJSONText(body, modelSourceTestAPIKey) {
+ t.Fatalf("BYOK models: %d %s", status, body)
+ }
+ status, _, body = env.request(bob, http.MethodPost, base+"/models", map[string]any{"base_url": "https://api.example.com/v1", "api_key": modelSourceTestAPIKey}, "")
+ if status != http.StatusForbidden {
+ t.Fatalf("member BYOK models: %d %s", status, body)
+ }
+
+ const roomID = "room_model_source_worker"
+ worker := agents["Worker"]
+ insertRuntimeRoomMembershipForAgent(t, env.pool, roomID, worker.Actor.ID)
+ ensured, err := agentruntimestate.New(env.pool).EnsureContext(t.Context(), agentruntimestate.EnsureContextInput{
+ Ref: agentruntimestate.ContextRef{Kind: "meta", AgentID: worker.AgentManagementID, RoomID: roomID}, TargetResidency: "active",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ if _, err := env.pool.Exec(t.Context(), `INSERT INTO agent_local_runs(run_id,context_key,status,started_at) VALUES('model-source-run',$1,'running',clock_timestamp())`, ensured.Context.ContextKey); err != nil {
+ t.Fatal(err)
+ }
+
+ // Running work refuses the switch before the Computer changes.
+ status, _, body = env.request(alice, http.MethodPost, base, byokSwitch, "")
+ if status != http.StatusConflict || !containsJSONText(body, "AGENT_HAS_ACTIVE_RUNS") || !containsJSONText(body, `"reason":"Worker"`) ||
+ containsJSONText(body, "Idler") || len(computers.appliedSnapshot()) != 0 {
+ t.Fatalf("busy switch: %d %s applied=%d", status, body, len(computers.appliedSnapshot()))
+ }
+
+ forced := map[string]any{"mode": "byok", "runtime": "claude", "byok": byokSwitch["byok"], "force_terminate": true}
+ status, _, body = env.request(alice, http.MethodPost, base, forced, "")
+ if status != http.StatusOK || !containsJSONText(body, `"terminated_run_count":1`) || containsJSONText(body, modelSourceTestAPIKey) {
+ t.Fatalf("forced switch: %d %s", status, body)
+ }
+ applied := computers.appliedSnapshot()
+ if len(applied) != 1 || applied[0].Byok == nil || applied[0].Byok.ApiKey == nil || *applied[0].Byok.ApiKey != modelSourceTestAPIKey {
+ t.Fatalf("command sent to the Computer: %+v", applied)
+ }
+ var runStatus, runReason string
+ if err := env.pool.QueryRow(t.Context(), `SELECT status,terminal->>'reason' FROM agent_local_runs WHERE run_id='model-source-run'`).Scan(&runStatus, &runReason); err != nil {
+ t.Fatal(err)
+ }
+ if runStatus != "canceled" || runReason != "model_source_switched" {
+ t.Fatalf("ended run: %s/%s", runStatus, runReason)
+ }
+ for name, agent := range agents {
+ if countRows(t, env, `SELECT count(*) FROM agent_registrations WHERE actor_id=$1 AND computer_id=$2 AND local_runtime_type='claude'
+ AND runtime_model='localmodels-byok' AND runtime_reasoning_effort='high' AND configuration_revision=2`, agent.Actor.ID, fixtureComputerID) != 1 {
+ t.Fatalf("%s was not moved to the Computer's new Runtime", name)
+ }
+ }
+ notified := strings.Join(management.notifiedSnapshot(), ",")
+ if !strings.Contains(notified, worker.AgentManagementID) || !strings.Contains(notified, agents["Idler"].AgentManagementID) {
+ t.Fatalf("Agent Service notifications: %s", notified)
+ }
+ management.mu.Lock()
+ stopped := append([]roomagent.RunCancelCommand(nil), management.stopped...)
+ management.mu.Unlock()
+ if len(stopped) != 1 || stopped[0].RunID != "model-source-run" || stopped[0].AgentID != worker.AgentManagementID || stopped[0].RoomID != roomID {
+ t.Fatalf("live process stops: %+v", stopped)
+ }
+ if countRows(t, env, `SELECT count(*) FROM agent_registrations WHERE description LIKE '%'||$1||'%' OR instructions LIKE '%'||$1||'%'`, modelSourceTestAPIKey) != 0 {
+ t.Fatal("TeamHub stored the API key")
+ }
+
+ // A repeated switch to the same target leaves the Agents alone.
+ status, _, body = env.request(alice, http.MethodPost, base, byokSwitch, "")
+ if status != http.StatusOK || !containsJSONText(body, `"updated_agent_count":0`) {
+ t.Fatalf("repeated switch: %d %s", status, body)
+ }
+}
+
+// TestLocalComputerModelSourceWorkStartedDuringSwitchKeepsOnlyItsAgent covers
+// work that starts after the busy check while the Computer switches: the
+// Computer has changed, so the idle Agent moves and only the working one waits
+// for the owner, whose forced retry moves it too.
+func TestLocalComputerModelSourceWorkStartedDuringSwitchKeepsOnlyItsAgent(t *testing.T) {
+ allowParallelIntegrationTest(t)
+ management := &runStoppingAgentManagement{recordingAgentManagement: &recordingAgentManagement{}}
+ computers := &modelSourceComputers{status: nodeservicesinternal.ModelSourceStatus{
+ Mode: "subscription", Runtime: "claude", RuntimeModel: "claude-default",
+ }}
+ env, alice := newModelSourceEnv(t, management, computers)
+ base := "/v0/tenants/" + acmeTenant + "/local-computers/" + fixtureComputerID + "/model-source"
+
+ agents := map[string]tenantAgentUpdateView{}
+ for _, name := range []string{"Worker", "Idler"} {
+ status, _, body := env.request(alice, http.MethodPost, "/v0/tenants/"+acmeTenant+"/agents", map[string]any{"name": name, "instructions": "Keep work", "runtime": fixtureRuntime("codex-default")}, "late-work-create-"+name)
+ if status != http.StatusCreated {
+ t.Fatalf("create %s: %d %s", name, status, body)
+ }
+ var created tenantAgentUpdateView
+ decode(t, body, &created)
+ agents[name] = created
+ }
+ const roomID = "room_model_source_late_worker"
+ worker := agents["Worker"]
+ insertRuntimeRoomMembershipForAgent(t, env.pool, roomID, worker.Actor.ID)
+ ensured, err := agentruntimestate.New(env.pool).EnsureContext(t.Context(), agentruntimestate.EnsureContextInput{
+ Ref: agentruntimestate.ContextRef{Kind: "meta", AgentID: worker.AgentManagementID, RoomID: roomID}, TargetResidency: "active",
+ })
+ if err != nil {
+ t.Fatal(err)
+ }
+ computers.duringApply = func() {
+ computers.duringApply = nil
+ if _, err := env.pool.Exec(context.Background(), `INSERT INTO agent_local_runs(run_id,context_key,status,started_at) VALUES('model-source-late-run',$1,'running',clock_timestamp())`, ensured.Context.ContextKey); err != nil {
+ t.Error(err)
+ }
+ }
+ moved := func(agent tenantAgentUpdateView) bool {
+ return countRows(t, env, `SELECT count(*) FROM agent_registrations WHERE actor_id=$1 AND local_runtime_type='claude' AND runtime_model='claude-default'`, agent.Actor.ID) == 1
+ }
+
+ subscription := map[string]any{"mode": "subscription", "runtime": "claude"}
+ status, _, body := env.request(alice, http.MethodPost, base, subscription, "")
+ if status != http.StatusConflict || !containsJSONText(body, "AGENT_HAS_ACTIVE_RUNS") || !containsJSONText(body, `"reason":"Worker"`) || containsJSONText(body, "Idler") {
+ t.Fatalf("switch with late work: %d %s", status, body)
+ }
+ if !moved(agents["Idler"]) || moved(worker) {
+ t.Fatalf("after late work: Idler moved=%v, Worker moved=%v", moved(agents["Idler"]), moved(worker))
+ }
+
+ status, _, body = env.request(alice, http.MethodPost, base, map[string]any{"mode": "subscription", "runtime": "claude", "force_terminate": true}, "")
+ if status != http.StatusOK || !containsJSONText(body, `"terminated_run_count":1`) || !containsJSONText(body, `"updated_agent_count":1`) {
+ t.Fatalf("forced retry: %d %s", status, body)
+ }
+ if !moved(worker) {
+ t.Fatal("the forced retry did not move Worker")
+ }
+}
diff --git a/apps/web/AGENTS.md b/apps/web/AGENTS.md
index 801191f4..3841b116 100644
--- a/apps/web/AGENTS.md
+++ b/apps/web/AGENTS.md
@@ -23,8 +23,13 @@ build:assets` to check the initial JS budget.
- `src/app`: routes, providers, route error boundaries, and global CSS.
- `src/features/teamhub`: Human API, Session, error, and realtime adapters.
- `src/features/rooms`: Room routes, Chat, Timeline, the right sidebar (Agent Info, Activity, Thread, Document) and membership UI.
-- `src/features/local-models`: Settings › Local models (`settings/local-models?computer=<id>`),
- one Computer's model library as TeamHub last stored it. The Computer decides
+- `src/features/local-models`: Settings › Models (`settings/models?computer=<id>`).
+ Its tabs read and switch the Computer's model source (Local model,
+ Subscription, BYOK) through TeamHub's `model-source` API, which asks the
+ Computer live; the page never holds a saved API key, and a switch refused
+ with `AGENT_HAS_ACTIVE_RUNS` retries with `force_terminate` only after the
+ owner confirms. The Local model tab is one Computer's model library as
+ TeamHub last stored it. The Computer decides
fit, availability, placement, the recommendation and memory; the page only
orders and labels them, picks the Make room default, renders family icons,
capability/parameter badges, download speed/ETA and model-card facts from
diff --git a/apps/web/src/app/router.tsx b/apps/web/src/app/router.tsx
index 8f2daff5..0638bf11 100644
--- a/apps/web/src/app/router.tsx
+++ b/apps/web/src/app/router.tsx
@@ -713,9 +713,9 @@ function createSettingsRoute(): RouteObject {
{
lazy: async () => ({
Component: (await import("@/features/local-models/local-models-page"))
- .LocalModelsPage,
+ .ModelsPage,
}),
- path: "local-models",
+ path: "models",
},
{ loader: openProfile, path: "administration" },
],
diff --git a/apps/web/src/features/local-computer/computers-page.test.tsx b/apps/web/src/features/local-computer/computers-page.test.tsx
index fdb5416c..af367160 100644
--- a/apps/web/src/features/local-computer/computers-page.test.tsx
+++ b/apps/web/src/features/local-computer/computers-page.test.tsx
@@ -50,7 +50,7 @@ describe("ComputersPage", () => {
within(detail).getByRole("link", { name: /Manage local models/ }),
).toHaveAttribute(
"href",
- "/t/tenant-northstar/settings/local-models?computer=computer-offline-lab",
+ "/t/tenant-northstar/settings/models?computer=computer-offline-lab",
);
fireEvent.click(within(detail).getByRole("button", { name: "Advanced" }));
fireEvent.click(within(detail).getByRole("button", { name: "Remove" }));
diff --git a/apps/web/src/features/local-computer/computers-page.tsx b/apps/web/src/features/local-computer/computers-page.tsx
index 78574229..359c7cc5 100644
--- a/apps/web/src/features/local-computer/computers-page.tsx
+++ b/apps/web/src/features/local-computer/computers-page.tsx
@@ -235,7 +235,7 @@ export function ComputersPage() {
)}
computer={selectedComputer}
key={selectedComputer.computer_id}
- localModelsHref={`/t/${tenantId}/settings/local-models?computer=${encodeURIComponent(selectedComputer.computer_id)}`}
+ localModelsHref={`/t/${tenantId}/settings/models?computer=${encodeURIComponent(selectedComputer.computer_id)}`}
onConnect={openSetup}
onOpenAgent={(actorId) => {
if (!openAgent.isPending) openAgent.mutate(actorId);
diff --git a/apps/web/src/features/local-computer/local-computer-gate.test.tsx b/apps/web/src/features/local-computer/local-computer-gate.test.tsx
index 711206a8..a8c02adc 100644
--- a/apps/web/src/features/local-computer/local-computer-gate.test.tsx
+++ b/apps/web/src/features/local-computer/local-computer-gate.test.tsx
@@ -97,12 +97,12 @@ describe("Local Computer gate", () => {
name: "Connect your computer",
});
fireEvent.click(
- await within(gate).findByRole("link", { name: "Local models" }),
+ await within(gate).findByRole("link", { name: "Settings › Models" }),
);
await waitFor(() =>
expect(fixture.router.state.location.pathname).toBe(
- "/t/tenant-northstar/settings/local-models",
+ "/t/tenant-northstar/settings/models",
),
);
expect(fixture.router.state.location.search).toBe(
@@ -124,7 +124,7 @@ describe("Local Computer gate", () => {
}),
);
expect(fixture.router.state.location.pathname).toBe(
- "/t/tenant-northstar/settings/local-models",
+ "/t/tenant-northstar/settings/models",
);
});
diff --git a/apps/web/src/features/local-computer/local-computer-gate.tsx b/apps/web/src/features/local-computer/local-computer-gate.tsx
index 65aff397..2f16e5a8 100644
--- a/apps/web/src/features/local-computer/local-computer-gate.tsx
+++ b/apps/web/src/features/local-computer/local-computer-gate.tsx
@@ -249,9 +249,9 @@ function AppSetup({
Or run a model on {computer.display_name} itself: load one in{" "}
<Link
className="text-foreground underline underline-offset-2"
- to={`/t/${encodeURIComponent(tenantId)}/settings/local-models?computer=${encodeURIComponent(computer.computer_id)}`}
+ to={`/t/${encodeURIComponent(tenantId)}/settings/models?computer=${encodeURIComponent(computer.computer_id)}`}
>
- Local models
+ Settings › Models
</Link>
.
</p>
diff --git a/apps/web/src/features/local-models/local-models-copy.ts b/apps/web/src/features/local-models/local-models-copy.ts
index f72d7c12..bfa5f18e 100644
--- a/apps/web/src/features/local-models/local-models-copy.ts
+++ b/apps/web/src/features/local-models/local-models-copy.ts
@@ -179,3 +179,47 @@ export function architectureCopy(
) {
return architectureLabels[architecture];
}
+
+const modelSourceRefusals: Record<Schemas["ModelSourceErrorCode"], string> = {
+ AGENT_HAS_ACTIVE_RUNS: "Agents on this computer are working on tasks.",
+ BYOK_AUTH_FAILED: "The endpoint rejected the API key.",
+ BYOK_INVALID_CONFIG:
+ "The computer can't use this endpoint. An HTTPS endpoint needs an API key; plain HTTP works only on this computer or your local network.",
+ BYOK_MODEL_NOT_FOUND: "The endpoint doesn't serve this model ID.",
+ BYOK_UNREACHABLE: "The computer couldn't reach the endpoint.",
+ BYOK_UPSTREAM_REJECTED: "The endpoint rejected the test request.",
+ LOCAL_COMPUTER_OFFLINE:
+ "The computer is offline. Reconnect it in Computers, then try again.",
+ LOCAL_MODEL_UNKNOWN: "The computer doesn't have this model anymore.",
+ MODEL_SOURCE_FAILED: "The computer couldn't switch. Try again.",
+ MODEL_SOURCE_FORBIDDEN:
+ "Only the person who connected this computer can change its models.",
+ MODEL_SOURCE_SERVICE_UNAVAILABLE:
+ "Linger couldn't reach the computer right now. Try again.",
+ MODEL_SOURCE_UNAVAILABLE:
+ "This computer can't switch models. Update Linger on it, then try again.",
+ MODEL_SOURCE_UNCONFIRMED:
+ "The computer didn't answer in time. It may still be switching; check again in a minute.",
+ RUNTIME_NOT_ENABLED: "This AI runtime isn't set up on the computer.",
+};
+
+/** Why a model-source switch or endpoint test failed. */
+export function modelSourceErrorCopy(code: string | undefined) {
+ return code && Object.hasOwn(modelSourceRefusals, code)
+ ? modelSourceRefusals[code as keyof typeof modelSourceRefusals]
+ : "Something went wrong. Try again.";
+}
+
+export const modelSourceModeLabels: Record<Schemas["ModelSourceMode"], string> =
+ { byok: "BYOK", local: "Local model", subscription: "Subscription" };
+
+export const modelSourceRuntimeLabels: Record<
+ Schemas["ModelSourceRuntime"],
+ string
+> = { claude: "Claude Code", codex: "Codex", pi: "Pi" };
+
+export const byokProtocolLabels: Record<Schemas["ByokProtocol"], string> = {
+ anthropic: "Anthropic Messages",
+ "openai-chat": "OpenAI Chat Completions",
+ "openai-responses": "OpenAI Responses",
+};
diff --git a/apps/web/src/features/local-models/local-models-page.test.tsx b/apps/web/src/features/local-models/local-models-page.test.tsx
index b1b30e16..dcbd775f 100644
--- a/apps/web/src/features/local-models/local-models-page.test.tsx
+++ b/apps/web/src/features/local-models/local-models-page.test.tsx
@@ -20,7 +20,7 @@ import {
} from "@/test/teamhub-test-runtime";
import { teamHubErrorResponse } from "@/test/teamhub-test-server";
-import { LocalModelsPage } from "./local-models-page";
+import { ModelsPage } from "./local-models-page";
import type { LocalModelsView } from "./local-models-queries";
import {
gb,
@@ -36,6 +36,8 @@ const viewPath =
"/v0/tenants/{tenantId}/local-computers/{computerId}/local-models";
const actionPath =
"/v0/tenants/{tenantId}/local-computers/{computerId}/local-models/{modelId}/actions";
+const modelSourcePath =
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source";
type InventoryComputer = TeamHubLocalComputerPage["items"][number];
@@ -67,6 +69,14 @@ function setup(
),
};
runtime.server
+ // A Computer that cannot switch sources reports none: the library alone.
+ .on("GET", modelSourcePath, ({ params }) =>
+ Response.json({
+ computer_id: params.computerId,
+ online: true,
+ viewer_is_owner: true,
+ }),
+ )
.on("GET", viewPath, ({ params }) => {
const view = fixture.views[params.computerId!];
return view ?? teamHubErrorResponse(404, "LOCAL_COMPUTER_NOT_FOUND");
@@ -112,18 +122,18 @@ function renderPage(fixture: Fixture, search = "") {
<TeamHubRuntimeProvider runtime={fixture.runtime}>
<TeamHubEventSync />
<MemoryRouter
- initialEntries={[`/t/${tenantId}/settings/local-models${search}`]}
+ initialEntries={[`/t/${tenantId}/settings/models${search}`]}
>
<Suspense fallback={<p>Loading page</p>}>
<Routes>
<Route
element={
<>
- <LocalModelsPage />
+ <ModelsPage />
<CurrentSearch />
</>
}
- path="/t/:tenantId/settings/local-models"
+ path="/t/:tenantId/settings/models"
/>
<Route
element={<p>Computers page</p>}
@@ -739,7 +749,7 @@ describe("LocalModelsPage", () => {
await findModels();
expect(screen.getByRole("heading", { level: 1 })).toHaveTextContent(
- "Local models",
+ "Models",
);
expect(
screen.getByText(
@@ -1178,3 +1188,414 @@ describe("LocalModelsPage", () => {
);
});
});
+
+describe("Model source", () => {
+ const switchPath =
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source";
+ const testPath =
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source/test";
+ const modelsPath =
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source/models";
+ const byokStatus = {
+ byok: {
+ base_url: "https://api.example.com/v1",
+ configured: true,
+ key_saved: true,
+ model_id: "vendor/model",
+ protocol: "openai-chat",
+ },
+ mode: "byok",
+ runtime: "codex",
+ runtime_model: "localmodels-byok",
+ };
+
+ function withSource(fixture: Fixture, status: object) {
+ const switches: unknown[] = [];
+ const tests: unknown[] = [];
+ const listings: unknown[] = [];
+ fixture.runtime.server
+ .on("POST", modelsPath, ({ body }) => {
+ listings.push(body);
+ return Response.json({
+ base_url: "https://api.example.com",
+ models: [
+ { context_window: 131_072, id: "vendor/model", name: "Vendor" },
+ { id: "vendor/other" },
+ ],
+ });
+ })
+ .on("GET", switchPath, ({ params }) =>
+ Response.json({
+ computer_id: params.computerId,
+ online: true,
+ status,
+ viewer_is_owner: true,
+ }),
+ )
+ .on("POST", testPath, ({ body }) => {
+ tests.push(body);
+ return Response.json({
+ base_url: "https://api.example.com",
+ context_window: 131_072,
+ model_id: "vendor/model",
+ ok: true,
+ protocol: "openai-chat",
+ });
+ });
+ return { listings, switches, tests };
+ }
+
+ it("opens on the source in use and explains BYOK on hover", async () => {
+ const fixture = setup([labView()]);
+ withSource(fixture, byokStatus);
+ renderPage(fixture);
+
+ const tabs = await screen.findByRole("tablist", { name: "Model source" });
+ expect(
+ within(tabs).getByRole("tab", { name: /BYOK/u, selected: true }),
+ ).toBeInTheDocument();
+ expect(
+ within(tabs).getByRole("img", { name: "In use" }),
+ ).toBeInTheDocument();
+ expect(screen.getByRole("tooltip")).toHaveTextContent("Bring your own key");
+ expect(
+ screen.getByText("Agents on lab-118 use BYOK · vendor/model"),
+ ).toBeInTheDocument();
+ expect(
+ screen.getByText("In use, through OpenAI Chat Completions."),
+ ).toBeInTheDocument();
+ expect(screen.queryByText(/Stored privately/u)).not.toBeInTheDocument();
+ expect(screen.queryByLabelText("API format")).not.toBeInTheDocument();
+ expect(screen.getByLabelText("Base URL")).toHaveValue(
+ "https://api.example.com/v1",
+ );
+ });
+
+ it("asks before ending running tasks and switches only once confirmed", async () => {
+ const fixture = setup([labView()]);
+ const { switches } = withSource(fixture, byokStatus);
+ fixture.runtime.server.on("POST", switchPath, ({ body }) => {
+ switches.push(body);
+ if (!(body as { force_terminate?: boolean }).force_terminate)
+ return Response.json(
+ {
+ error: {
+ code: "AGENT_HAS_ACTIVE_RUNS",
+ details: [
+ {
+ code: "AGENT_HAS_ACTIVE_RUNS",
+ field: "agent",
+ reason: "Research agent",
+ },
+ ],
+ message: "busy",
+ request_id: "test-busy",
+ },
+ },
+ { status: 409 },
+ );
+ return Response.json({
+ computer_id: "computer-lab",
+ online: true,
+ status: { ...byokStatus, mode: "subscription", runtime: "claude" },
+ terminated_run_count: 1,
+ updated_agent_count: 2,
+ viewer_is_owner: true,
+ });
+ });
+ renderPage(fixture);
+
+ fireEvent.click(await screen.findByRole("tab", { name: "Subscription" }));
+ fireEvent.click(
+ screen.getByRole("button", { name: "Switch to Claude Code" }),
+ );
+ const dialog = await screen.findByRole("dialog", {
+ name: "End running tasks?",
+ });
+ expect(dialog).toHaveTextContent("Research agent is working on tasks");
+ fireEvent.click(
+ within(dialog).getByRole("button", { name: "Terminate tasks & Switch" }),
+ );
+
+ expect(
+ await screen.findByText(
+ "Agents now use Subscription · Claude Code. 2 Agents were moved. 1 task was ended.",
+ ),
+ ).toBeInTheDocument();
+ expect(switches).toEqual([
+ { mode: "subscription", runtime: "claude" },
+ { force_terminate: true, mode: "subscription", runtime: "claude" },
+ ]);
+ });
+
+ it("shows what the Computer serves after a switch fails", async () => {
+ const fixture = setup([labView()]);
+ withSource(fixture, byokStatus);
+ let reads = 0;
+ fixture.runtime.server
+ .on("GET", switchPath, ({ params }) => {
+ reads += 1;
+ return Response.json({
+ computer_id: params.computerId,
+ online: true,
+ status:
+ reads === 1
+ ? byokStatus
+ : { ...byokStatus, mode: "subscription", runtime: "claude" },
+ viewer_is_owner: true,
+ });
+ })
+ .on("POST", switchPath, () =>
+ Response.json(
+ {
+ error: {
+ code: "MODEL_SOURCE_UNCONFIRMED",
+ message: "late",
+ request_id: "test-late",
+ },
+ },
+ { status: 504 },
+ ),
+ );
+ renderPage(fixture);
+
+ fireEvent.click(await screen.findByRole("tab", { name: "Subscription" }));
+ fireEvent.click(
+ screen.getByRole("button", { name: "Switch to Claude Code" }),
+ );
+
+ expect(
+ await screen.findByText(
+ "Agents on lab-118 use Subscription · Claude Code",
+ ),
+ ).toBeInTheDocument();
+ expect(reads).toBe(2);
+ });
+
+ it("tests and saves an endpoint, keeping the saved key when left blank", async () => {
+ const fixture = setup([labView()]);
+ const { switches, tests } = withSource(fixture, {
+ ...byokStatus,
+ mode: "local",
+ runtime: "pi",
+ });
+ fixture.runtime.server.on("POST", switchPath, ({ body }) => {
+ switches.push(body);
+ const { byok } = body as { byok: { model_id: string } };
+ return Response.json({
+ computer_id: "computer-lab",
+ online: true,
+ status: {
+ ...byokStatus,
+ byok: { ...byokStatus.byok, model_id: byok.model_id },
+ },
+ viewer_is_owner: true,
+ });
+ });
+ renderPage(fixture);
+
+ fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));
+ expect(
+ await screen.findByRole("combobox", { name: "Model" }),
+ ).toHaveTextContent("vendor/model Vendor · 128K tokens");
+ fireEvent.click(screen.getByRole("button", { name: "Test connection" }));
+ expect(
+ await screen.findByText(
+ "Connected to https://api.example.com through OpenAI Chat Completions. vendor/model has 128K tokens of context.",
+ ),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("combobox", { name: "Model" }));
+ fireEvent.click(
+ await screen.findByRole("option", { name: "vendor/other" }),
+ );
+ fireEvent.change(screen.getByLabelText("API key"), {
+ target: { value: "sk-new" },
+ });
+ fireEvent.click(
+ screen.getByRole("button", { name: "Save & Switch to BYOK" }),
+ );
+
+ await waitFor(() => expect(switches).toHaveLength(1));
+ fireEvent.click(await screen.findByRole("tab", { name: "Subscription" }));
+ fireEvent.click(screen.getByRole("tab", { name: /BYOK/u }));
+ expect(
+ await screen.findByRole("combobox", { name: "Model" }),
+ ).toHaveTextContent("vendor/other");
+ expect(tests).toEqual([
+ {
+ byok: {
+ base_url: "https://api.example.com/v1",
+ model_id: "vendor/model",
+ reuse_saved_key: true,
+ },
+ runtime: "claude",
+ },
+ ]);
+ expect(switches).toEqual([
+ {
+ byok: {
+ api_key: "sk-new",
+ base_url: "https://api.example.com/v1",
+ model_id: "vendor/other",
+ },
+ mode: "byok",
+ runtime: "claude",
+ },
+ ]);
+ });
+
+ it("lists the endpoint's models once its address and key are entered", async () => {
+ const fixture = setup([labView()]);
+ const { listings, tests } = withSource(fixture, {
+ byok: { configured: false, key_saved: false },
+ mode: "subscription",
+ runtime: "claude",
+ runtime_model: "",
+ });
+ renderPage(fixture);
+
+ fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));
+ const baseUrl = screen.getByLabelText("Base URL");
+ fireEvent.change(baseUrl, {
+ target: { value: "https://api.example.com/v1" },
+ });
+ expect(listings).toEqual([]);
+ fireEvent.blur(baseUrl);
+ const model = await screen.findByRole("combobox", { name: "Model" });
+ expect(model).toHaveTextContent("Choose a model");
+ fireEvent.click(model);
+ expect(
+ await screen.findByRole("option", {
+ name: "vendor/model Vendor · 128K tokens",
+ }),
+ ).toBeInTheDocument();
+ fireEvent.click(screen.getByRole("option", { name: "vendor/other" }));
+ expect(screen.getByRole("combobox", { name: "Model" })).toHaveTextContent(
+ "vendor/other",
+ );
+
+ const apiKey = screen.getByLabelText("API key");
+ fireEvent.change(apiKey, { target: { value: "sk-listed" } });
+ fireEvent.blur(apiKey);
+ await waitFor(() => expect(listings).toHaveLength(2));
+ expect(listings).toEqual([
+ { base_url: "https://api.example.com/v1" },
+ { api_key: "sk-listed", base_url: "https://api.example.com/v1" },
+ ]);
+ fireEvent.blur(apiKey);
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Test connection" }),
+ );
+ await waitFor(() => expect(tests).toHaveLength(1));
+ expect(tests[0]).toEqual({
+ byok: {
+ api_key: "sk-listed",
+ base_url: "https://api.example.com/v1",
+ model_id: "vendor/other",
+ },
+ runtime: "claude",
+ });
+ expect(listings).toHaveLength(2);
+ });
+
+ it("lists the models again on request with the key as typed", async () => {
+ const fixture = setup([labView()]);
+ const { listings } = withSource(fixture, byokStatus);
+ renderPage(fixture);
+
+ expect(await screen.findByText("2 models listed.")).toBeInTheDocument();
+ expect(listings).toEqual([
+ { base_url: "https://api.example.com/v1", reuse_saved_key: true },
+ ]);
+ fireEvent.change(screen.getByLabelText("API key"), {
+ target: { value: "sk-typed" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "List models" }));
+
+ await waitFor(() => expect(listings).toHaveLength(2));
+ expect(listings[1]).toEqual({
+ api_key: "sk-typed",
+ base_url: "https://api.example.com/v1",
+ });
+ expect(screen.getByRole("combobox", { name: "Model" })).toHaveTextContent(
+ "vendor/model Vendor · 128K tokens",
+ );
+ });
+
+ it("falls back to typing the model ID when the endpoint lists none", async () => {
+ const fixture = setup([labView()]);
+ withSource(fixture, byokStatus);
+ fixture.runtime.server.on("POST", modelsPath, () =>
+ Response.json(
+ {
+ error: {
+ code: "BYOK_MODEL_NOT_FOUND",
+ message: "not found",
+ request_id: "test-models",
+ },
+ },
+ { status: 409 },
+ ),
+ );
+ renderPage(fixture);
+
+ expect(
+ await screen.findByText(
+ "The endpoint didn't list its models. Type the model ID.",
+ ),
+ ).toBeInTheDocument();
+ expect(screen.getByLabelText("Model")).toHaveValue("vendor/model");
+ });
+
+ it("tests an endpoint on this computer without an API key", async () => {
+ const fixture = setup([labView()]);
+ const { tests } = withSource(fixture, {
+ byok: { configured: false, key_saved: false },
+ mode: "subscription",
+ runtime: "claude",
+ runtime_model: "",
+ });
+ renderPage(fixture);
+
+ fireEvent.click(await screen.findByRole("tab", { name: /BYOK/u }));
+ fireEvent.change(screen.getByLabelText("Base URL"), {
+ target: { value: "http://127.0.0.1:18486/v1" },
+ });
+ fireEvent.change(screen.getByLabelText("Model"), {
+ target: { value: "vendor/model" },
+ });
+ fireEvent.click(screen.getByRole("button", { name: "Test connection" }));
+
+ await waitFor(() => expect(tests).toHaveLength(1));
+ expect(tests[0]).toEqual({
+ byok: { base_url: "http://127.0.0.1:18486/v1", model_id: "vendor/model" },
+ runtime: "claude",
+ });
+ });
+
+ it("switches back to a model already on the computer", async () => {
+ const fixture = setup([labView()]);
+ const { switches } = withSource(fixture, byokStatus);
+ fixture.runtime.server.on("POST", switchPath, ({ body }) => {
+ switches.push(body);
+ return Response.json({
+ computer_id: "computer-lab",
+ online: true,
+ status: { ...byokStatus, mode: "local", runtime: "pi" },
+ viewer_is_owner: true,
+ });
+ });
+ renderPage(fixture);
+
+ fireEvent.click(await screen.findByRole("tab", { name: "Local model" }));
+ fireEvent.click(
+ await screen.findByRole("button", { name: "Switch to Local model" }),
+ );
+
+ await waitFor(() => expect(switches).toHaveLength(1));
+ expect(switches[0]).toMatchObject({ mode: "local" });
+ expect(
+ (switches[0] as { local_model_id?: string }).local_model_id,
+ ).toBeTruthy();
+ });
+});
diff --git a/apps/web/src/features/local-models/local-models-page.tsx b/apps/web/src/features/local-models/local-models-page.tsx
index 745e734b..d117d542 100644
--- a/apps/web/src/features/local-models/local-models-page.tsx
+++ b/apps/web/src/features/local-models/local-models-page.tsx
@@ -19,6 +19,7 @@ import { localComputersQueryOptions } from "@/features/local-computer/local-comp
import { requireRoomRouteParam } from "@/features/rooms/room-route-params";
import { TeamHubError } from "@/features/teamhub/teamhub-error";
import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";
+import type { TeamHubLocalComputerPage } from "@/features/teamhub/teamhub-types";
import { AdvancedDialog } from "./local-model-details";
import { ModelRow } from "./local-model-row";
@@ -41,11 +42,24 @@ import {
downloadStopped,
formatGigabytes,
loadCheck,
+ localSwitchTarget,
memorySummary,
modelEntries,
type ModelEntry,
type ModelStatus,
} from "./local-models-rules";
+import {
+ activeSourceLabel,
+ ByokPanel,
+ ModelSourceTabs,
+ SubscriptionPanel,
+ SwitchToLocalNotice,
+ useModelSourceSwitch,
+} from "./model-source-panel";
+import {
+ type ModelSourceMode,
+ modelSourceQueryOptions,
+} from "./model-source-queries";
type Dialog =
| { kind: "advanced" }
@@ -67,11 +81,15 @@ function computersPath(tenantId: string) {
return `/t/${tenantId}/settings/computers`;
}
+type LocalComputerRuntime = InventoryComputer["runtimes"][number];
+type InventoryComputer = TeamHubLocalComputerPage["items"][number];
+
/**
- * The model library of one Computer, chosen by `?computer=`. Without it the
- * desktop app opens its own Computer and a browser the first one.
+ * Where one Computer's Agents get their model, chosen by `?computer=`, and
+ * its local model library. Without it the desktop app opens its own Computer
+ * and a browser the first one.
*/
-export function LocalModelsPage() {
+export function ModelsPage() {
const { client } = useTeamHubRuntime();
const tenantId = requireRoomRouteParam(useParams().tenantId, "Tenant");
const { data: inventory } = useSuspenseQuery(
@@ -112,6 +130,7 @@ export function LocalModelsPage() {
<ComputerModels
computerId={computer.computer_id}
displayName={computer.display_name}
+ runtimes={computer.runtimes}
computerPicker={
computers.length > 1 ? (
<Select
@@ -135,7 +154,7 @@ export function LocalModelsPage() {
/>
) : (
<>
- <h1 className="text-2xl text-foreground">Local models</h1>
+ <h1 className="text-2xl text-foreground">Models</h1>
<EmptyState title="No computers yet">
Connect a computer in{" "}
<Link
@@ -193,12 +212,14 @@ function ComputerModels({
computerId,
computerPicker,
displayName,
+ runtimes = [],
tenantId,
}: {
computerId: string;
computerPicker: ReactNode;
/** Absent for a Computer outside the viewer's own inventory. */
displayName?: string;
+ runtimes?: readonly LocalComputerRuntime[];
tenantId: string;
}) {
const { client } = useTeamHubRuntime();
@@ -206,12 +227,34 @@ function ComputerModels({
const view = query.data;
const [dialog, setDialog] = useState<Dialog | null>(null);
const summary = view?.available ? memorySummary(view) : undefined;
+ // Only the owner switches sources, and only their own Computers carry a
+ // display name here.
+ const source = useQuery({
+ ...modelSourceQueryOptions(client, tenantId, computerId),
+ enabled: displayName !== undefined,
+ });
+ const status = source.data?.status;
+ const [tab, setTab] = useState<ModelSourceMode | null>(null);
+ const shownTab = tab ?? status?.mode ?? "local";
+ const computerName = displayName ?? "this computer";
+ const { feedback, switcher } = useModelSourceSwitch({
+ computerId,
+ computerName,
+ tenantId,
+ });
+ const switching = switcher.pending !== undefined;
+ const target = view?.available ? localSwitchTarget(view) : undefined;
return (
<>
<header className="flex items-start justify-between gap-4">
<div className="min-w-0">
- <h1 className="text-2xl text-foreground">Local models</h1>
+ <h1 className="text-2xl text-foreground">Models</h1>
+ {status ? (
+ <p className="mt-1.5 text-sm text-muted-foreground">
+ Agents on {computerName} use {activeSourceLabel(status)}
+ </p>
+ ) : null}
{summary?.totalBytes ? (
<p className="mt-1.5 text-sm text-muted-foreground">
{formatGigabytes(summary.usedBytes)} of{" "}
@@ -233,13 +276,57 @@ function ComputerModels({
</div>
</header>
- {view ? (
- <Library
- dialog={dialog}
- setDialog={setDialog}
+ {status ? (
+ <ModelSourceTabs
+ active={status.mode}
+ onChange={setTab}
+ value={shownTab}
+ />
+ ) : null}
+ {switcher.failure ? (
+ <div className="mt-4">
+ <FormFeedback tone="danger">{switcher.failure}</FormFeedback>
+ </div>
+ ) : null}
+ {switching ? (
+ <p className="mt-4 text-sm text-muted-foreground" role="status">
+ Switching {computerName}. This can take a few minutes the first time.
+ </p>
+ ) : null}
+ {feedback}
+ {status && shownTab === "subscription" ? (
+ <SubscriptionPanel
+ disabled={switching}
+ runtimes={runtimes}
+ status={status}
+ switcher={switcher}
+ />
+ ) : status && shownTab === "byok" ? (
+ <ByokPanel
+ computerId={computerId}
+ disabled={switching}
+ key={status.mode}
+ status={status}
+ switcher={switcher}
tenantId={tenantId}
- view={view}
/>
+ ) : view ? (
+ <>
+ {status && status.mode !== "local" ? (
+ <SwitchToLocalNotice
+ disabled={switching || view.computer.status === "offline"}
+ modelId={target?.id}
+ modelName={target?.name}
+ switcher={switcher}
+ />
+ ) : null}
+ <Library
+ dialog={dialog}
+ setDialog={setDialog}
+ tenantId={tenantId}
+ view={view}
+ />
+ </>
) : query.isError ? (
<EmptyState
action={
diff --git a/apps/web/src/features/local-models/local-models-rules.ts b/apps/web/src/features/local-models/local-models-rules.ts
index e1cf2363..de890869 100644
--- a/apps/web/src/features/local-models/local-models-rules.ts
+++ b/apps/web/src/features/local-models/local-models-rules.ts
@@ -327,3 +327,15 @@ export function modelSourceLabel(url: string) {
const parsed = new URL(url);
return `${parsed.host}${parsed.pathname.replace(/\/+$/, "")}`;
}
+
+/**
+ * The model a switch to Local model runs: a loaded one, else one on disk. None
+ * when the Computer has no model downloaded yet.
+ */
+export function localSwitchTarget(view: LocalModelsView) {
+ const models = view.models.map((item) => item.model);
+ return (
+ models.find((model) => model.state === "loaded") ??
+ models.find((model) => model.state === "idle")
+ );
+}
diff --git a/apps/web/src/features/local-models/model-source-panel.tsx b/apps/web/src/features/local-models/model-source-panel.tsx
new file mode 100644
index 00000000..c50c284d
--- /dev/null
+++ b/apps/web/src/features/local-models/model-source-panel.tsx
@@ -0,0 +1,672 @@
+import { RefreshIcon } from "@hugeicons/core-free-icons";
+import {
+ keepPreviousData,
+ useMutation,
+ useQuery,
+ useQueryClient,
+} from "@tanstack/react-query";
+import { type FormEvent, type ReactNode, useId, useState } from "react";
+
+import { Button } from "@/components/ui/button";
+import { Field, fieldControlClassName } from "@/components/ui/field";
+import { FormFeedback } from "@/components/ui/form-feedback";
+import { Icon } from "@/components/ui/icon";
+import { ModalDialog } from "@/components/ui/modal-dialog";
+import { Select, SelectItem } from "@/components/ui/select";
+import { Hint } from "@/features/local-computer/computer-hint";
+import { localComputersQueryKey } from "@/features/local-computer/local-computer-queries";
+import { TeamHubError } from "@/features/teamhub/teamhub-error";
+import { useTeamHubRuntime } from "@/features/teamhub/teamhub-runtime";
+import type { TeamHubLocalComputerPage } from "@/features/teamhub/teamhub-types";
+import { cn } from "@/lib/cn";
+
+import {
+ byokProtocolLabels,
+ modelSourceErrorCopy,
+ modelSourceModeLabels,
+ modelSourceRuntimeLabels,
+} from "./local-models-copy";
+import { tenantLocalModelsQueryKey } from "./local-models-queries";
+import { contextLabel } from "./local-models-rules";
+import {
+ type ByokInput,
+ type ByokModel,
+ type ByokTestRequest,
+ byokModelsQueryOptions,
+ type ModelSourceMode,
+ type ModelSourceRuntime,
+ type ModelSourceStatus,
+ type ModelSourceSwitchRequest,
+ type ModelSourceView,
+ modelSourceQueryKey,
+ switchModelSource,
+ testByokEndpoint,
+} from "./model-source-queries";
+
+type LocalComputerRuntime =
+ TeamHubLocalComputerPage["items"][number]["runtimes"][number];
+
+const modes: readonly ModelSourceMode[] = ["local", "subscription", "byok"];
+const subscriptionRuntimes = ["claude", "codex"] as const;
+const byokRuntimes: readonly ModelSourceRuntime[] = ["claude", "codex", "pi"];
+
+const byokExplanation =
+ "Bring your own key: use your own OpenAI-compatible or Anthropic API endpoint. A gateway on this computer serves it to your Agents.";
+
+/** What the page says the Computer's Agents run on now. */
+export function activeSourceLabel(status: ModelSourceStatus) {
+ const runtime = modelSourceRuntimeLabels[status.runtime];
+ if (status.mode === "byok")
+ return `BYOK · ${status.byok.model_id ?? runtime}`;
+ if (status.mode === "subscription") return `Subscription · ${runtime}`;
+ return "Local model";
+}
+
+interface ModelSourceSwitcher {
+ failure: string | undefined;
+ pending: ModelSourceSwitchRequest | undefined;
+ request: (body: ModelSourceSwitchRequest) => void;
+}
+
+/**
+ * Switching may take minutes while the Computer installs a Runtime or starts
+ * its gateway. When Agents are working, the owner chooses whether to end
+ * their tasks; nothing changes until they do. Work that starts during the
+ * switch is asked about once the Computer has switched.
+ */
+export function useModelSourceSwitch({
+ computerId,
+ computerName,
+ tenantId,
+}: {
+ computerId: string;
+ computerName: string;
+ tenantId: string;
+}) {
+ const { client } = useTeamHubRuntime();
+ const queryClient = useQueryClient();
+ const [busy, setBusy] = useState<{
+ agents: string[];
+ body: ModelSourceSwitchRequest;
+ } | null>(null);
+ const [notice, setNotice] = useState<string | null>(null);
+ const mutation = useMutation({
+ mutationFn: (body: ModelSourceSwitchRequest) =>
+ switchModelSource(client, tenantId, computerId, body),
+ onError: (error, body) => {
+ // A switch can fail after the Computer changed (work started meanwhile,
+ // or no answer in time), so show what it serves now.
+ void queryClient.invalidateQueries({
+ queryKey: modelSourceQueryKey(tenantId, computerId),
+ });
+ if (
+ error instanceof TeamHubError &&
+ error.code === "AGENT_HAS_ACTIVE_RUNS"
+ )
+ setBusy({
+ agents: (error.details ?? []).map((detail) => detail.reason),
+ body,
+ });
+ },
+ onMutate: () => setNotice(null),
+ onSuccess: (view) => {
+ queryClient.setQueryData(modelSourceQueryKey(tenantId, computerId), view);
+ setNotice(switchedNotice(view));
+ void queryClient.invalidateQueries({
+ queryKey: tenantLocalModelsQueryKey(tenantId),
+ });
+ void queryClient.invalidateQueries({
+ queryKey: localComputersQueryKey(tenantId),
+ });
+ },
+ });
+ const failureCode =
+ mutation.error instanceof TeamHubError ? mutation.error.code : undefined;
+ const switcher: ModelSourceSwitcher = {
+ failure:
+ mutation.isError && failureCode !== "AGENT_HAS_ACTIVE_RUNS"
+ ? modelSourceErrorCopy(failureCode)
+ : undefined,
+ pending: mutation.isPending ? mutation.variables : undefined,
+ request: (body) => mutation.mutate(body),
+ };
+ const feedback = (
+ <>
+ {notice ? (
+ <div className="mt-4">
+ <FormFeedback tone="success">{notice}</FormFeedback>
+ </div>
+ ) : null}
+ {busy ? (
+ <TerminateTasksDialog
+ agents={busy.agents}
+ computerName={computerName}
+ onClose={() => setBusy(null)}
+ onConfirm={() => {
+ mutation.mutate({ ...busy.body, force_terminate: true });
+ setBusy(null);
+ }}
+ />
+ ) : null}
+ </>
+ );
+ return { feedback, switcher };
+}
+
+function switchedNotice(view: ModelSourceView) {
+ if (!view.status) return "Switched.";
+ const updated = view.updated_agent_count ?? 0;
+ const ended = view.terminated_run_count ?? 0;
+ const parts = [`Agents now use ${activeSourceLabel(view.status)}.`];
+ if (updated)
+ parts.push(
+ `${updated} ${updated === 1 ? "Agent was" : "Agents were"} moved.`,
+ );
+ if (ended)
+ parts.push(`${ended} ${ended === 1 ? "task was" : "tasks were"} ended.`);
+ return parts.join(" ");
+}
+
+function TerminateTasksDialog({
+ agents,
+ computerName,
+ onClose,
+ onConfirm,
+}: {
+ agents: string[];
+ computerName: string;
+ onClose: () => void;
+ onConfirm: () => void;
+}) {
+ const names = agents.length ? agents.join(", ") : "Some Agents";
+ return (
+ <ModalDialog
+ description={`${names} ${agents.length === 1 ? "is" : "are"} working on tasks on ${computerName}. Switching now ends those tasks; they can't be resumed.`}
+ footer={
+ <>
+ <Button onClick={onClose}>Cancel</Button>
+ <Button onClick={onConfirm} tone="danger">
+ Terminate tasks & Switch
+ </Button>
+ </>
+ }
+ onClose={onClose}
+ size="md"
+ title="End running tasks?"
+ >
+ <p className="px-5 py-4 text-sm text-muted-foreground">
+ To keep them, wait until they finish and switch then.
+ </p>
+ </ModalDialog>
+ );
+}
+
+/** The three model sources as tabs; a dot marks the one in use. */
+export function ModelSourceTabs({
+ active,
+ onChange,
+ value,
+}: {
+ active: ModelSourceMode;
+ onChange: (mode: ModelSourceMode) => void;
+ value: ModelSourceMode;
+}) {
+ return (
+ <div
+ aria-label="Model source"
+ className="mt-6 inline-flex rounded-lg bg-muted p-0.5"
+ role="tablist"
+ >
+ {modes.map((mode) => {
+ const tab = (
+ <button
+ aria-selected={mode === value}
+ className={cn(
+ "inline-flex h-8 items-center gap-1.5 rounded-md px-3 text-sm transition-colors duration-150 focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-ring motion-reduce:transition-none",
+ mode === value
+ ? "bg-background text-foreground shadow-xs"
+ : "text-muted-foreground hover:text-foreground",
+ )}
+ key={mode}
+ onClick={() => onChange(mode)}
+ role="tab"
+ type="button"
+ >
+ {mode === active ? (
+ <span
+ aria-label="In use"
+ className="size-1.5 rounded-full bg-app-success"
+ role="img"
+ />
+ ) : null}
+ {modelSourceModeLabels[mode]}
+ </button>
+ );
+ return mode === "byok" ? (
+ <Hint key={mode} placement="bottom" text={byokExplanation}>
+ {tab}
+ </Hint>
+ ) : (
+ tab
+ );
+ })}
+ </div>
+ );
+}
+
+function Panel({ children, title }: { children: ReactNode; title: string }) {
+ return (
+ <section
+ aria-label={title}
+ className="mt-6 rounded-xl border border-border px-4 py-4"
+ >
+ {children}
+ </section>
+ );
+}
+
+/** Offered above the library while the Agents use another source. */
+export function SwitchToLocalNotice({
+ disabled,
+ modelId,
+ modelName,
+ switcher,
+}: {
+ disabled: boolean;
+ modelId: string | undefined;
+ modelName: string | undefined;
+ switcher: ModelSourceSwitcher;
+}) {
+ return (
+ <div className="mt-6 flex items-center justify-between gap-4 rounded-xl bg-muted px-4 py-3">
+ <p className="text-sm text-muted-foreground">
+ {modelName ? (
+ <>
+ <span className="text-foreground">{modelName}</span> is on this
+ computer and can run your Agents locally.
+ </>
+ ) : (
+ "Download a model below to run your Agents locally."
+ )}
+ </p>
+ <Button
+ disabled={disabled || !modelId}
+ loading={switcher.pending?.mode === "local"}
+ onClick={() =>
+ switcher.request({ local_model_id: modelId, mode: "local" })
+ }
+ size="compact"
+ tone="primary"
+ >
+ Switch to Local model
+ </Button>
+ </div>
+ );
+}
+
+const runtimeStateCopy: Partial<
+ Record<LocalComputerRuntime["status"], string>
+> = {
+ authentication_required: "Signed out",
+ not_installed: "Not installed",
+ ready: "Signed in",
+};
+
+/** Claude Code and Codex on the person's own subscription accounts. */
+export function SubscriptionPanel({
+ disabled,
+ runtimes,
+ status,
+ switcher,
+}: {
+ disabled: boolean;
+ runtimes: readonly LocalComputerRuntime[];
+ status: ModelSourceStatus;
+ switcher: ModelSourceSwitcher;
+}) {
+ return (
+ <Panel title="Subscription">
+ <ul className="grid gap-3">
+ {subscriptionRuntimes.map((runtime) => {
+ const active =
+ status.mode === "subscription" && status.runtime === runtime;
+ // Off subscription, the Computer checks Runtimes against the
+ // gateway, so their sign-in state is only known while active.
+ const state =
+ status.mode === "subscription"
+ ? runtimeStateCopy[
+ runtimes.find((item) => item.type === runtime)?.status ??
+ "not_installed"
+ ]
+ : undefined;
+ return (
+ <li
+ className="flex items-center justify-between gap-4"
+ key={runtime}
+ >
+ <div className="min-w-0">
+ <p className="text-sm text-foreground">
+ {modelSourceRuntimeLabels[runtime]}
+ {active ? (
+ <span className="ml-2 text-xs text-app-success">
+ In use
+ </span>
+ ) : null}
+ </p>
+ <p className="text-xs text-muted-foreground">
+ {state ? `${state} · ` : ""}
+ {runtime === "claude"
+ ? "Anthropic account on this computer"
+ : "ChatGPT account on this computer"}
+ </p>
+ </div>
+ {active ? null : (
+ <Button
+ disabled={disabled}
+ loading={
+ switcher.pending?.mode === "subscription" &&
+ switcher.pending.runtime === runtime
+ }
+ onClick={() =>
+ switcher.request({ mode: "subscription", runtime })
+ }
+ size="compact"
+ >
+ Switch to {modelSourceRuntimeLabels[runtime]}
+ </Button>
+ )}
+ </li>
+ );
+ })}
+ </ul>
+ <p className="mt-4 text-xs text-muted-foreground">
+ Switching to a subscription unloads local models to free memory; their
+ files stay on disk.
+ </p>
+ </Panel>
+ );
+}
+
+/** A listed model: its ID, then its name and context window when known. */
+function ByokModelOption({ model }: { model: ByokModel }) {
+ const details = [
+ model.name,
+ model.context_window ? contextLabel(model.context_window) : undefined,
+ ].filter(Boolean);
+ return (
+ <>
+ {details.length ? `${model.id} ` : model.id}
+ {details.length ? (
+ <span className="ml-1 text-xs text-muted-foreground">
+ {details.join(" · ")}
+ </span>
+ ) : null}
+ </>
+ );
+}
+
+/**
+ * The person's own endpoint. The API key goes to the Computer, which keeps
+ * it private; Linger never shows it again.
+ */
+export function ByokPanel({
+ computerId,
+ disabled,
+ status,
+ switcher,
+ tenantId,
+}: {
+ computerId: string;
+ disabled: boolean;
+ status: ModelSourceStatus;
+ switcher: ModelSourceSwitcher;
+ tenantId: string;
+}) {
+ const { client } = useTeamHubRuntime();
+ const saved = status.byok;
+ const [runtime, setRuntime] = useState<ModelSourceRuntime>(
+ status.mode === "byok" ? status.runtime : "claude",
+ );
+ const [baseUrl, setBaseUrl] = useState(saved.base_url ?? "");
+ const [apiKey, setApiKey] = useState("");
+ // Starts empty until a model is saved, then shows the saved one.
+ const [modelId, setModelId] = useState(saved.model_id ?? "");
+ // Models are listed for the address and key as they stand when a field is
+ // left, not on every keystroke.
+ const [listed, setListed] = useState({
+ baseUrl: saved.base_url ?? "",
+ keyRevision: 0,
+ });
+ const [keyEdited, setKeyEdited] = useState(false);
+ const credentials = apiKey
+ ? { api_key: apiKey }
+ : saved.key_saved
+ ? { reuse_saved_key: true }
+ : {};
+ const input: ByokInput = {
+ base_url: baseUrl.trim(),
+ model_id: modelId.trim(),
+ ...credentials,
+ };
+ const models = useQuery({
+ ...byokModelsQueryOptions(
+ client,
+ tenantId,
+ computerId,
+ { base_url: listed.baseUrl, ...credentials },
+ listed.keyRevision,
+ ),
+ // A refresh keeps the current choices on screen until the new list lands.
+ placeholderData: keepPreviousData,
+ });
+ const listedModels = models.data?.models ?? [];
+ // A saved or typed ID the endpoint does not list stays choosable.
+ const modelOptions =
+ input.model_id === "" ||
+ listedModels.some((model) => model.id === input.model_id)
+ ? listedModels
+ : [{ id: input.model_id }, ...listedModels];
+ const modelControlId = useId();
+ const modelHintId = `${modelControlId}-hint`;
+ const modelHint = models.isFetching
+ ? "Listing the endpoint's models…"
+ : models.isError
+ ? "The endpoint didn't list its models. Type the model ID."
+ : listedModels.length
+ ? `${listedModels.length} ${listedModels.length === 1 ? "model" : "models"} listed.`
+ : undefined;
+ // The Computer decides whether the endpoint needs a key: one on this
+ // computer or the local network may have none.
+ const complete = input.base_url !== "" && input.model_id !== "";
+ const test = useMutation({
+ mutationFn: (body: ByokTestRequest) =>
+ testByokEndpoint(client, tenantId, computerId, body),
+ });
+ const active = status.mode === "byok";
+
+ function save(event: FormEvent) {
+ event.preventDefault();
+ switcher.request({ byok: input, mode: "byok", runtime });
+ }
+
+ function listModels() {
+ setKeyEdited(false);
+ setListed((current) => ({
+ baseUrl: input.base_url,
+ keyRevision: current.keyRevision + 1,
+ }));
+ }
+
+ return (
+ <form
+ aria-label="BYOK"
+ className="mt-6 overflow-hidden rounded-xl border border-border"
+ onSubmit={save}
+ >
+ <div className="grid grid-cols-1 gap-4 px-4 py-4">
+ {active && saved.protocol ? (
+ <p className="text-xs text-muted-foreground">
+ In use, through {byokProtocolLabels[saved.protocol]}.
+ </p>
+ ) : null}
+ <div>
+ <p className="mb-1.5 text-sm font-medium text-foreground">
+ AI runtime
+ </p>
+ <Select
+ aria-label="AI runtime"
+ className="w-full"
+ disabled={disabled}
+ onValueChange={(value) => {
+ setRuntime(value as ModelSourceRuntime);
+ // The runtime decides which API format is tried first.
+ test.reset();
+ }}
+ value={runtime}
+ >
+ {byokRuntimes.map((item) => (
+ <SelectItem key={item} value={item}>
+ {modelSourceRuntimeLabels[item]}
+ </SelectItem>
+ ))}
+ </Select>
+ </div>
+ <Field
+ autoComplete="off"
+ disabled={disabled}
+ label="Base URL"
+ onBlur={() =>
+ setListed((current) =>
+ current.baseUrl === input.base_url
+ ? current
+ : { ...current, baseUrl: input.base_url },
+ )
+ }
+ onChange={(event) => setBaseUrl(event.target.value)}
+ placeholder="https://api.example.com/v1"
+ spellCheck={false}
+ value={baseUrl}
+ />
+ <Field
+ autoComplete="new-password"
+ disabled={disabled}
+ hint={
+ saved.key_saved
+ ? "A key is saved on this computer. Leave blank to keep it."
+ : "Optional for an endpoint on this computer or your local network."
+ }
+ label="API key"
+ onBlur={() => {
+ if (!keyEdited) return;
+ setKeyEdited(false);
+ setListed((current) => ({
+ ...current,
+ keyRevision: current.keyRevision + 1,
+ }));
+ }}
+ onChange={(event) => {
+ setApiKey(event.target.value);
+ setKeyEdited(true);
+ }}
+ type="password"
+ value={apiKey}
+ />
+ <div>
+ <label
+ className="mb-1.5 block text-sm font-medium text-foreground"
+ htmlFor={modelControlId}
+ >
+ Model
+ </label>
+ <div className="flex gap-2">
+ <div className="min-w-0 flex-1">
+ {listedModels.length ? (
+ <Select
+ aria-describedby={modelHint ? modelHintId : undefined}
+ aria-label="Model"
+ className="w-full"
+ disabled={disabled}
+ id={modelControlId}
+ onValueChange={(value) => {
+ setModelId(value);
+ test.reset();
+ }}
+ placeholder="Choose a model"
+ value={input.model_id}
+ >
+ {modelOptions.map((model) => (
+ <SelectItem key={model.id} value={model.id}>
+ <ByokModelOption model={model} />
+ </SelectItem>
+ ))}
+ </Select>
+ ) : (
+ <input
+ aria-describedby={modelHint ? modelHintId : undefined}
+ autoComplete="off"
+ className={fieldControlClassName}
+ disabled={disabled}
+ id={modelControlId}
+ onChange={(event) => setModelId(event.target.value)}
+ placeholder="provider/model-name"
+ spellCheck={false}
+ value={modelId}
+ />
+ )}
+ </div>
+ <Button
+ disabled={disabled || input.base_url === ""}
+ loading={models.isFetching}
+ onClick={listModels}
+ size="large"
+ >
+ {models.isFetching ? null : <Icon icon={RefreshIcon} size={16} />}
+ List models
+ </Button>
+ </div>
+ {modelHint ? (
+ <p
+ className="mt-1.5 text-xs text-muted-foreground"
+ id={modelHintId}
+ >
+ {modelHint}
+ </p>
+ ) : null}
+ </div>
+ {test.isSuccess ? (
+ <FormFeedback tone="success">
+ Connected to {test.data.base_url} through{" "}
+ {byokProtocolLabels[test.data.protocol]}. {test.data.model_id} has{" "}
+ {contextLabel(test.data.context_window)} of context.
+ </FormFeedback>
+ ) : null}
+ {test.isError ? (
+ <FormFeedback tone="danger">
+ {modelSourceErrorCopy(
+ test.error instanceof TeamHubError ? test.error.code : undefined,
+ )}
+ </FormFeedback>
+ ) : null}
+ </div>
+ <footer className="flex flex-wrap items-center justify-end gap-2 border-t border-border bg-muted/40 px-4 py-3">
+ <Button
+ disabled={disabled || !complete}
+ loading={test.isPending}
+ onClick={() => test.mutate({ byok: input, runtime })}
+ size="large"
+ >
+ Test connection
+ </Button>
+ <Button
+ disabled={disabled || !complete}
+ loading={switcher.pending?.mode === "byok"}
+ size="large"
+ tone="primary"
+ type="submit"
+ >
+ {active ? "Save" : "Save & Switch to BYOK"}
+ </Button>
+ </footer>
+ </form>
+ );
+}
diff --git a/apps/web/src/features/local-models/model-source-queries.ts b/apps/web/src/features/local-models/model-source-queries.ts
new file mode 100644
index 00000000..95953bc9
--- /dev/null
+++ b/apps/web/src/features/local-models/model-source-queries.ts
@@ -0,0 +1,120 @@
+import type { components } from "@linger/wire-contracts/teamhub-public/types";
+import { queryOptions } from "@tanstack/react-query";
+
+import { teamHubData } from "@/features/teamhub/teamhub-api";
+import type { TeamHubClient } from "@/features/teamhub/teamhub-client";
+
+type Schemas = components["schemas"];
+export type ModelSourceView = Schemas["ModelSourceView"];
+export type ModelSourceStatus = Schemas["ModelSourceStatus"];
+export type ModelSourceMode = Schemas["ModelSourceMode"];
+export type ModelSourceRuntime = Schemas["ModelSourceRuntime"];
+export type ModelSourceSwitchRequest = Schemas["ModelSourceSwitchRequest"];
+export type ByokInput = Schemas["ByokInput"];
+export type ByokTestRequest = Schemas["ByokTestRequest"];
+export type ByokEndpointInput = Schemas["ByokEndpointInput"];
+export type ByokModel = Schemas["ByokModel"];
+
+const modelSourcePath =
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source";
+const modelSourceTestPath =
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source/test";
+const modelSourceModelsPath =
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source/models";
+
+export function modelSourceQueryKey(tenantId: string, computerId: string) {
+ return ["teamhub", tenantId, "model-source", computerId] as const;
+}
+
+/**
+ * Where one Computer's Agents get their model. Reading it asks the Computer,
+ * so it is not refetched on local-models hints, only after a switch.
+ */
+export function modelSourceQueryOptions(
+ client: TeamHubClient,
+ tenantId: string,
+ computerId: string,
+) {
+ return queryOptions({
+ queryFn: ({ signal }) =>
+ teamHubData(
+ client.api.GET(modelSourcePath, {
+ params: { path: { computerId, tenantId } },
+ signal,
+ }),
+ ),
+ queryKey: modelSourceQueryKey(tenantId, computerId),
+ retry: false,
+ staleTime: 60_000,
+ });
+}
+
+/** Switches the Computer, then moves its Agents; may take minutes. */
+export function switchModelSource(
+ client: TeamHubClient,
+ tenantId: string,
+ computerId: string,
+ body: ModelSourceSwitchRequest,
+) {
+ return teamHubData(
+ client.api.POST(modelSourcePath, {
+ body,
+ params: { path: { computerId, tenantId } },
+ }),
+ );
+}
+
+/**
+ * Probes a BYOK endpoint from the Computer without saving it, finding the
+ * wire format it answers for the Runtime.
+ */
+export function testByokEndpoint(
+ client: TeamHubClient,
+ tenantId: string,
+ computerId: string,
+ body: ByokTestRequest,
+) {
+ return teamHubData(
+ client.api.POST(modelSourceTestPath, {
+ body,
+ params: { path: { computerId, tenantId } },
+ }),
+ );
+}
+
+/**
+ * The models a BYOK endpoint lists, asked from the Computer. `keyRevision`
+ * stands in for the API key, which stays out of the query key; it changes
+ * whenever the owner enters a different key.
+ */
+export function byokModelsQueryOptions(
+ client: TeamHubClient,
+ tenantId: string,
+ computerId: string,
+ endpoint: ByokEndpointInput,
+ keyRevision: number,
+) {
+ return queryOptions({
+ enabled: endpoint.base_url !== "",
+ gcTime: 0,
+ queryFn: ({ signal }) =>
+ teamHubData(
+ client.api.POST(modelSourceModelsPath, {
+ body: endpoint,
+ params: { path: { computerId, tenantId } },
+ signal,
+ }),
+ ),
+ queryKey: [
+ "teamhub",
+ tenantId,
+ "byok-models",
+ computerId,
+ endpoint.base_url,
+ keyRevision,
+ ] as const,
+ refetchOnWindowFocus: false,
+ retry: false,
+ staleTime: Number.POSITIVE_INFINITY,
+ });
+}
diff --git a/apps/web/src/features/rooms/room-shell.tsx b/apps/web/src/features/rooms/room-shell.tsx
index 8ff451fc..50851491 100644
--- a/apps/web/src/features/rooms/room-shell.tsx
+++ b/apps/web/src/features/rooms/room-shell.tsx
@@ -109,7 +109,7 @@ function RoomShellReady({
// pushing every row down.
const navigationPending = roomsQuery.isPending || anotherMeQuery.isPending;
// Settings stays open under the gate: a Computer whose only app is Pi gets
- // its first model from Settings › Local models.
+ // its first model from Settings › Models.
const onSettings = useMatch("/t/:tenantId/settings/*") !== null;
const gated =
anotherMeQuery.isSuccess && !anotherMe?.agent_actor_id && !onSettings;
diff --git a/apps/web/src/features/settings/settings-page.tsx b/apps/web/src/features/settings/settings-page.tsx
index 227dce57..093df87f 100644
--- a/apps/web/src/features/settings/settings-page.tsx
+++ b/apps/web/src/features/settings/settings-page.tsx
@@ -43,8 +43,8 @@ export function SettingsLayout() {
/>
<SettingsLink
icon={<Icon icon={AiChipIcon} size={14} />}
- label="Local models"
- to="local-models"
+ label="Models"
+ to="models"
/>
</nav>
</aside>
diff --git a/apps/web/src/features/settings/settings-pages.test.tsx b/apps/web/src/features/settings/settings-pages.test.tsx
index 92e5a7fb..8c170814 100644
--- a/apps/web/src/features/settings/settings-pages.test.tsx
+++ b/apps/web/src/features/settings/settings-pages.test.tsx
@@ -168,7 +168,7 @@ describe("Settings surfaces", () => {
within(settingsNav)
.getAllByRole("link")
.map((link) => link.textContent?.replace(/\s+/g, " ").trim()),
- ).toEqual(["Profile", "Security", "Computers", "Local models"]);
+ ).toEqual(["Profile", "Security", "Computers", "Models"]);
expect(
screen.queryByRole("button", { name: "Log out" }),
).not.toBeInTheDocument();
diff --git a/contracts/README.md b/contracts/README.md
index 96dc419f..ce8f9b36 100644
--- a/contracts/README.md
+++ b/contracts/README.md
@@ -112,3 +112,34 @@ Progress and outcomes travel back only as snapshots:
with runtime `pi` whose runtime model is the model's `pi_model`. localmodels
reports `pi_model` for every model on the Computer, loaded or not, so an
idle model still lists the Agents that will run on it.
+
+## Model source flow
+
+Which source a Computer's Agents use (local model, subscription or BYOK) is
+the `localmodels` tool's `<state>/model-source.json`. Schemas live in
+`openapi/components/model-source.yaml` and the `CapabilityModelSource*`
+definitions of `runner-gateway/envelope.schema.json`.
+
+Web → TeamHub → Agent Service → Computer → `localmodels source`:
+
+1. Web calls `getLocalComputerModelSource`, `switchLocalComputerModelSource`,
+ `testLocalComputerModelSource` or `listLocalComputerByokModels` under
+ `/v0/tenants/{tenantId}/local-computers/{computerId}/model-source`. Only the
+ Computer owner sees the source or acts on it.
+2. TeamHub calls Node Services `getLocalComputerModelSource`,
+ `applyLocalComputerModelSource`, `testLocalComputerByok` or
+ `listLocalComputerByokModels` under
+ `/v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/model-source`.
+3. Agent Service sends `execute` with kind `model_source` (`status`, `test`,
+ `models` or `apply`), only to Computer 0.54.0 or later; an older one answers
+ `MODEL_SOURCE_UNSUPPORTED` without the command. The Daemon runs
+ `localmodels source status|check|models|apply` and answers `executed`. A BYOK
+ API key travels in the request and the envelope only, reaches `localmodels`
+ on stdin, and is kept on the Computer in an owner-only file.
+
+A switch runs `apply` on the Computer first, then moves the owner's Agents on it
+to the Runtime and model it now serves, in one TeamHub transaction. An Agent
+with running work stays where it is unless the owner chose to end that work:
+work found before `apply` refuses the switch with `AGENT_HAS_ACTIVE_RUNS`, and
+work that started during it leaves only that Agent behind, answered with the
+same code after the others moved.
diff --git a/contracts/generated/go/nodeservicesinternal/openapi.gen.go b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
index a0215c1f..243886b5 100644
--- a/contracts/generated/go/nodeservicesinternal/openapi.gen.go
+++ b/contracts/generated/go/nodeservicesinternal/openapi.gen.go
@@ -188,6 +188,39 @@ func (e AgentDebugRuntimeHistorySource) Valid() bool {
}
}
+// Defines values for AgentReasoningEffort.
+const (
+ AgentReasoningEffortHigh AgentReasoningEffort = "high"
+ AgentReasoningEffortLow AgentReasoningEffort = "low"
+ AgentReasoningEffortMax AgentReasoningEffort = "max"
+ AgentReasoningEffortMedium AgentReasoningEffort = "medium"
+ AgentReasoningEffortNone AgentReasoningEffort = "none"
+ AgentReasoningEffortUltra AgentReasoningEffort = "ultra"
+ AgentReasoningEffortXhigh AgentReasoningEffort = "xhigh"
+)
+
+// Valid indicates whether the value is a known member of the AgentReasoningEffort enum.
+func (e AgentReasoningEffort) Valid() bool {
+ switch e {
+ case AgentReasoningEffortHigh:
+ return true
+ case AgentReasoningEffortLow:
+ return true
+ case AgentReasoningEffortMax:
+ return true
+ case AgentReasoningEffortMedium:
+ return true
+ case AgentReasoningEffortNone:
+ return true
+ case AgentReasoningEffortUltra:
+ return true
+ case AgentReasoningEffortXhigh:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for BrowserConnectionStatusBrowser.
const (
BrowserConnectionBrowserChrome BrowserConnectionStatusBrowser = "chrome"
@@ -275,6 +308,27 @@ func (e BrowserConnectionStatusState) Valid() bool {
}
}
+// Defines values for ByokProtocol.
+const (
+ ByokProtocolAnthropic ByokProtocol = "anthropic"
+ ByokProtocolOpenaiChat ByokProtocol = "openai-chat"
+ ByokProtocolOpenaiResponses ByokProtocol = "openai-responses"
+)
+
+// Valid indicates whether the value is a known member of the ByokProtocol enum.
+func (e ByokProtocol) Valid() bool {
+ switch e {
+ case ByokProtocolAnthropic:
+ return true
+ case ByokProtocolOpenaiChat:
+ return true
+ case ByokProtocolOpenaiResponses:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for CancelAgentRunResultStatus.
const (
AlreadyTerminal CancelAgentRunResultStatus = "already_terminal"
@@ -979,19 +1033,19 @@ func (e MemoryRebuildStatusPhase) Valid() bool {
// Defines values for ModelCallEffort.
const (
- High ModelCallEffort = "high"
- Low ModelCallEffort = "low"
- Medium ModelCallEffort = "medium"
+ ModelCallEffortHigh ModelCallEffort = "high"
+ ModelCallEffortLow ModelCallEffort = "low"
+ ModelCallEffortMedium ModelCallEffort = "medium"
)
// Valid indicates whether the value is a known member of the ModelCallEffort enum.
func (e ModelCallEffort) Valid() bool {
switch e {
- case High:
+ case ModelCallEffortHigh:
return true
- case Low:
+ case ModelCallEffortLow:
return true
- case Medium:
+ case ModelCallEffortMedium:
return true
default:
return false
@@ -1034,6 +1088,48 @@ func (e ModelCallKind) Valid() bool {
}
}
+// Defines values for ModelSourceMode.
+const (
+ ModelSourceModeByok ModelSourceMode = "byok"
+ ModelSourceModeLocal ModelSourceMode = "local"
+ ModelSourceModeSubscription ModelSourceMode = "subscription"
+)
+
+// Valid indicates whether the value is a known member of the ModelSourceMode enum.
+func (e ModelSourceMode) Valid() bool {
+ switch e {
+ case ModelSourceModeByok:
+ return true
+ case ModelSourceModeLocal:
+ return true
+ case ModelSourceModeSubscription:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for ModelSourceRuntime.
+const (
+ ModelSourceRuntimeClaude ModelSourceRuntime = "claude"
+ ModelSourceRuntimeCodex ModelSourceRuntime = "codex"
+ ModelSourceRuntimePi ModelSourceRuntime = "pi"
+)
+
+// Valid indicates whether the value is a known member of the ModelSourceRuntime enum.
+func (e ModelSourceRuntime) Valid() bool {
+ switch e {
+ case ModelSourceRuntimeClaude:
+ return true
+ case ModelSourceRuntimeCodex:
+ return true
+ case ModelSourceRuntimePi:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for PersonalKnowledgeQueryRequestScope.
const (
PersonalKnowledgeQueryRequestScopeOriginals PersonalKnowledgeQueryRequestScope = "originals"
@@ -1300,6 +1396,9 @@ type AgentDebugRuntimeHistorySource string
// AgentId defines model for AgentId.
type AgentId = string
+// AgentReasoningEffort defines model for AgentReasoningEffort.
+type AgentReasoningEffort string
+
// AgentRuntimeContextKey defines model for AgentRuntimeContextKey.
type AgentRuntimeContextKey = string
@@ -1412,6 +1511,74 @@ type BrowserConnectionStatusState string
// BrowserProfile A Chrome profile directory name inside the user's Chrome data directory.
type BrowserProfile = string
+// ByokEndpointInput A BYOK endpoint address and key, enough to list its models. The API key is never persisted in TeamHub or Agent Service.
+type ByokEndpointInput struct {
+ ApiKey *string `json:"api_key,omitempty"`
+ BaseUrl string `json:"base_url"`
+ ReuseSavedKey *bool `json:"reuse_saved_key,omitempty"`
+}
+
+// ByokInput Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file.
+type ByokInput struct {
+ ApiKey *string `json:"api_key,omitempty"`
+ BaseUrl string `json:"base_url"`
+ ContextWindow *int `json:"context_window,omitempty"`
+ ModelId string `json:"model_id"`
+ ReuseSavedKey *bool `json:"reuse_saved_key,omitempty"`
+}
+
+// ByokModel A model a BYOK endpoint lists.
+type ByokModel struct {
+ ContextWindow *int `json:"context_window,omitempty"`
+ Id string `json:"id"`
+
+ // Name The endpoint's display name, when it differs from id.
+ Name *string `json:"name,omitempty"`
+}
+
+// ByokModelList The models a BYOK endpoint lists, sorted by id.
+type ByokModelList struct {
+ // BaseUrl The address that listed them.
+ BaseUrl string `json:"base_url"`
+ Models []ByokModel `json:"models"`
+}
+
+// ByokProtocol Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+type ByokProtocol string
+
+// ByokSummary Redacted BYOK configuration metadata reported by the Computer.
+type ByokSummary struct {
+ BaseUrl *string `json:"base_url,omitempty"`
+ Configured bool `json:"configured"`
+ ContextWindow *int `json:"context_window,omitempty"`
+ KeySaved bool `json:"key_saved"`
+ ModelId *string `json:"model_id,omitempty"`
+
+ // Protocol Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+ Protocol *ByokProtocol `json:"protocol,omitempty"`
+}
+
+// ByokTestRequest A BYOK endpoint to verify from the Computer for the Runtime that would serve it, which decides the order wire formats are tried.
+type ByokTestRequest struct {
+ // Byok Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file.
+ Byok ByokInput `json:"byok"`
+
+ // Runtime Agent runtime harness driving turns on the Computer.
+ Runtime ModelSourceRuntime `json:"runtime"`
+}
+
+// ByokTestResult Outcome of probing an upstream BYOK endpoint from the Local Computer.
+type ByokTestResult struct {
+ // BaseUrl The address that answered, which can add or drop the /anthropic of a gateway that serves OpenAI under /v1 and Anthropic under /anthropic.
+ BaseUrl string `json:"base_url"`
+ ContextWindow int `json:"context_window"`
+ ModelId string `json:"model_id"`
+ Ok bool `json:"ok"`
+
+ // Protocol Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+ Protocol ByokProtocol `json:"protocol"`
+}
+
// CancelAgentRunRequest defines model for CancelAgentRunRequest.
type CancelAgentRunRequest struct {
ContextRef *AgentRuntimeContextRef `json:"context_ref,omitempty"`
@@ -2102,6 +2269,44 @@ type ModelCallResult struct {
Text *string `json:"text,omitempty"`
}
+// ModelSourceApplyCommand Internal command sent from TeamHub to Agent Service to switch a Computer's model source.
+type ModelSourceApplyCommand struct {
+ // Byok Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file.
+ Byok *ByokInput `json:"byok,omitempty"`
+
+ // LocalModelId Stable localmodels library id: catalog id and variant, such as qwen3-4b:Q4_K_M.
+ LocalModelId *LocalModelId `json:"local_model_id,omitempty"`
+
+ // Mode Active model source mode on a Local Computer.
+ Mode ModelSourceMode `json:"mode"`
+
+ // Runtime Agent runtime harness driving turns on the Computer.
+ Runtime *ModelSourceRuntime `json:"runtime,omitempty"`
+}
+
+// ModelSourceMode Active model source mode on a Local Computer.
+type ModelSourceMode string
+
+// ModelSourceRuntime Agent runtime harness driving turns on the Computer.
+type ModelSourceRuntime string
+
+// ModelSourceStatus Active model source and redacted BYOK metadata on one Local Computer.
+type ModelSourceStatus struct {
+ // Byok Redacted BYOK configuration metadata reported by the Computer.
+ Byok ByokSummary `json:"byok"`
+ GatewayUrl *string `json:"gateway_url,omitempty"`
+
+ // Mode Active model source mode on a Local Computer.
+ Mode ModelSourceMode `json:"mode"`
+ ReasoningEffort *AgentReasoningEffort `json:"reasoning_effort,omitempty"`
+
+ // Runtime Agent runtime harness driving turns on the Computer.
+ Runtime ModelSourceRuntime `json:"runtime"`
+
+ // RuntimeModel After a switch, the model the Computer's Agents run: the target model when the active Runtime offers it, else that Runtime's default.
+ RuntimeModel string `json:"runtime_model"`
+}
+
// PersistedSequence defines model for PersistedSequence.
type PersistedSequence = int64
@@ -2759,6 +2964,15 @@ type ConfigureLocalComputerBrowserConnectionJSONRequestBody = BrowserConnectionC
// ActOnLocalComputerModelsJSONRequestBody defines body for ActOnLocalComputerModels for application/json ContentType.
type ActOnLocalComputerModelsJSONRequestBody = LocalModelActionCommand
+// ApplyLocalComputerModelSourceJSONRequestBody defines body for ApplyLocalComputerModelSource for application/json ContentType.
+type ApplyLocalComputerModelSourceJSONRequestBody = ModelSourceApplyCommand
+
+// ListLocalComputerByokModelsJSONRequestBody defines body for ListLocalComputerByokModels for application/json ContentType.
+type ListLocalComputerByokModelsJSONRequestBody = ByokEndpointInput
+
+// TestLocalComputerByokJSONRequestBody defines body for TestLocalComputerByok for application/json ContentType.
+type TestLocalComputerByokJSONRequestBody = ByokTestRequest
+
// ActOnLocalComputerPermissionJSONRequestBody defines body for ActOnLocalComputerPermission for application/json ContentType.
type ActOnLocalComputerPermissionJSONRequestBody = ComputerPermissionAction
@@ -3772,6 +3986,24 @@ type ClientInterface interface {
ActOnLocalComputerModels(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ActOnLocalComputerModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
+ // GetLocalComputerModelSource request
+ GetLocalComputerModelSource(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, reqEditors ...RequestEditorFn) (*http.Response, error)
+
+ // ApplyLocalComputerModelSourceWithBody request with any body
+ ApplyLocalComputerModelSourceWithBody(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)
+
+ ApplyLocalComputerModelSource(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ApplyLocalComputerModelSourceJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
+
+ // ListLocalComputerByokModelsWithBody request with any body
+ ListLocalComputerByokModelsWithBody(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)
+
+ ListLocalComputerByokModels(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ListLocalComputerByokModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
+
+ // TestLocalComputerByokWithBody request with any body
+ TestLocalComputerByokWithBody(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error)
+
+ TestLocalComputerByok(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body TestLocalComputerByokJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error)
+
// GetLocalComputerPermissions request
GetLocalComputerPermissions(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, reqEditors ...RequestEditorFn) (*http.Response, error)
@@ -4401,6 +4633,90 @@ func (c *Client) ActOnLocalComputerModels(ctx context.Context, tenantId TenantId
return c.Client.Do(req)
}
+func (c *Client) GetLocalComputerModelSource(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, reqEditors ...RequestEditorFn) (*http.Response, error) {
+ req, err := NewGetLocalComputerModelSourceRequest(c.Server, tenantId, ownerActorId, computerId)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if err := c.applyEditors(ctx, req, reqEditors); err != nil {
+ return nil, err
+ }
+ return c.Client.Do(req)
+}
+
+func (c *Client) ApplyLocalComputerModelSourceWithBody(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) {
+ req, err := NewApplyLocalComputerModelSourceRequestWithBody(c.Server, tenantId, ownerActorId, computerId, contentType, body)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if err := c.applyEditors(ctx, req, reqEditors); err != nil {
+ return nil, err
+ }
+ return c.Client.Do(req)
+}
+
+func (c *Client) ApplyLocalComputerModelSource(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ApplyLocalComputerModelSourceJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) {
+ req, err := NewApplyLocalComputerModelSourceRequest(c.Server, tenantId, ownerActorId, computerId, body)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if err := c.applyEditors(ctx, req, reqEditors); err != nil {
+ return nil, err
+ }
+ return c.Client.Do(req)
+}
+
+func (c *Client) ListLocalComputerByokModelsWithBody(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) {
+ req, err := NewListLocalComputerByokModelsRequestWithBody(c.Server, tenantId, ownerActorId, computerId, contentType, body)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if err := c.applyEditors(ctx, req, reqEditors); err != nil {
+ return nil, err
+ }
+ return c.Client.Do(req)
+}
+
+func (c *Client) ListLocalComputerByokModels(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ListLocalComputerByokModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) {
+ req, err := NewListLocalComputerByokModelsRequest(c.Server, tenantId, ownerActorId, computerId, body)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if err := c.applyEditors(ctx, req, reqEditors); err != nil {
+ return nil, err
+ }
+ return c.Client.Do(req)
+}
+
+func (c *Client) TestLocalComputerByokWithBody(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*http.Response, error) {
+ req, err := NewTestLocalComputerByokRequestWithBody(c.Server, tenantId, ownerActorId, computerId, contentType, body)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if err := c.applyEditors(ctx, req, reqEditors); err != nil {
+ return nil, err
+ }
+ return c.Client.Do(req)
+}
+
+func (c *Client) TestLocalComputerByok(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body TestLocalComputerByokJSONRequestBody, reqEditors ...RequestEditorFn) (*http.Response, error) {
+ req, err := NewTestLocalComputerByokRequest(c.Server, tenantId, ownerActorId, computerId, body)
+ if err != nil {
+ return nil, err
+ }
+ req = req.WithContext(ctx)
+ if err := c.applyEditors(ctx, req, reqEditors); err != nil {
+ return nil, err
+ }
+ return c.Client.Do(req)
+}
+
func (c *Client) GetLocalComputerPermissions(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, reqEditors ...RequestEditorFn) (*http.Response, error) {
req, err := NewGetLocalComputerPermissionsRequest(c.Server, tenantId, ownerActorId, computerId)
if err != nil {
@@ -5889,8 +6205,8 @@ func NewActOnLocalComputerModelsRequestWithBody(server string, tenantId TenantId
return req, nil
}
-// NewGetLocalComputerPermissionsRequest generates requests for GetLocalComputerPermissions
-func NewGetLocalComputerPermissionsRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId) (*http.Request, error) {
+// NewGetLocalComputerModelSourceRequest generates requests for GetLocalComputerModelSource
+func NewGetLocalComputerModelSourceRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId) (*http.Request, error) {
var err error
var pathParam0 string
@@ -5919,7 +6235,7 @@ func NewGetLocalComputerPermissionsRequest(server string, tenantId TenantId, own
return nil, err
}
- operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/permissions", pathParam0, pathParam1, pathParam2)
+ operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/model-source", pathParam0, pathParam1, pathParam2)
if operationPath[0] == '/' {
operationPath = "." + operationPath
}
@@ -5937,19 +6253,19 @@ func NewGetLocalComputerPermissionsRequest(server string, tenantId TenantId, own
return req, nil
}
-// NewActOnLocalComputerPermissionRequest calls the generic ActOnLocalComputerPermission builder with application/json body
-func NewActOnLocalComputerPermissionRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ActOnLocalComputerPermissionJSONRequestBody) (*http.Request, error) {
+// NewApplyLocalComputerModelSourceRequest calls the generic ApplyLocalComputerModelSource builder with application/json body
+func NewApplyLocalComputerModelSourceRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ApplyLocalComputerModelSourceJSONRequestBody) (*http.Request, error) {
var bodyReader io.Reader
buf, err := json.Marshal(body)
if err != nil {
return nil, err
}
bodyReader = bytes.NewReader(buf)
- return NewActOnLocalComputerPermissionRequestWithBody(server, tenantId, ownerActorId, computerId, "application/json", bodyReader)
+ return NewApplyLocalComputerModelSourceRequestWithBody(server, tenantId, ownerActorId, computerId, "application/json", bodyReader)
}
-// NewActOnLocalComputerPermissionRequestWithBody generates requests for ActOnLocalComputerPermission with any type of body
-func NewActOnLocalComputerPermissionRequestWithBody(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader) (*http.Request, error) {
+// NewApplyLocalComputerModelSourceRequestWithBody generates requests for ApplyLocalComputerModelSource with any type of body
+func NewApplyLocalComputerModelSourceRequestWithBody(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader) (*http.Request, error) {
var err error
var pathParam0 string
@@ -5978,7 +6294,7 @@ func NewActOnLocalComputerPermissionRequestWithBody(server string, tenantId Tena
return nil, err
}
- operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/permissions", pathParam0, pathParam1, pathParam2)
+ operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/model-source", pathParam0, pathParam1, pathParam2)
if operationPath[0] == '/' {
operationPath = "." + operationPath
}
@@ -5998,19 +6314,19 @@ func NewActOnLocalComputerPermissionRequestWithBody(server string, tenantId Tena
return req, nil
}
-// NewScanLocalComputerSkillsRequest calls the generic ScanLocalComputerSkills builder with application/json body
-func NewScanLocalComputerSkillsRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ScanLocalComputerSkillsJSONRequestBody) (*http.Request, error) {
+// NewListLocalComputerByokModelsRequest calls the generic ListLocalComputerByokModels builder with application/json body
+func NewListLocalComputerByokModelsRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ListLocalComputerByokModelsJSONRequestBody) (*http.Request, error) {
var bodyReader io.Reader
buf, err := json.Marshal(body)
if err != nil {
return nil, err
}
bodyReader = bytes.NewReader(buf)
- return NewScanLocalComputerSkillsRequestWithBody(server, tenantId, ownerActorId, computerId, "application/json", bodyReader)
+ return NewListLocalComputerByokModelsRequestWithBody(server, tenantId, ownerActorId, computerId, "application/json", bodyReader)
}
-// NewScanLocalComputerSkillsRequestWithBody generates requests for ScanLocalComputerSkills with any type of body
-func NewScanLocalComputerSkillsRequestWithBody(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader) (*http.Request, error) {
+// NewListLocalComputerByokModelsRequestWithBody generates requests for ListLocalComputerByokModels with any type of body
+func NewListLocalComputerByokModelsRequestWithBody(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader) (*http.Request, error) {
var err error
var pathParam0 string
@@ -6039,7 +6355,7 @@ func NewScanLocalComputerSkillsRequestWithBody(server string, tenantId TenantId,
return nil, err
}
- operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/skill-scans", pathParam0, pathParam1, pathParam2)
+ operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/model-source/models", pathParam0, pathParam1, pathParam2)
if operationPath[0] == '/' {
operationPath = "." + operationPath
}
@@ -6059,16 +6375,48 @@ func NewScanLocalComputerSkillsRequestWithBody(server string, tenantId TenantId,
return req, nil
}
-// NewReconcileVoiceWorkersRequest generates requests for ReconcileVoiceWorkers
-func NewReconcileVoiceWorkersRequest(server string) (*http.Request, error) {
+// NewTestLocalComputerByokRequest calls the generic TestLocalComputerByok builder with application/json body
+func NewTestLocalComputerByokRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body TestLocalComputerByokJSONRequestBody) (*http.Request, error) {
+ var bodyReader io.Reader
+ buf, err := json.Marshal(body)
+ if err != nil {
+ return nil, err
+ }
+ bodyReader = bytes.NewReader(buf)
+ return NewTestLocalComputerByokRequestWithBody(server, tenantId, ownerActorId, computerId, "application/json", bodyReader)
+}
+
+// NewTestLocalComputerByokRequestWithBody generates requests for TestLocalComputerByok with any type of body
+func NewTestLocalComputerByokRequestWithBody(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader) (*http.Request, error) {
var err error
+ var pathParam0 string
+
+ pathParam0, err = runtime.StyleParamWithOptions("simple", false, "tenantId", tenantId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ var pathParam1 string
+
+ pathParam1, err = runtime.StyleParamWithOptions("simple", false, "ownerActorId", ownerActorId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ var pathParam2 string
+
+ pathParam2, err = runtime.StyleParamWithOptions("simple", false, "computerId", computerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
serverURL, err := url.Parse(server)
if err != nil {
return nil, err
}
- operationPath := fmt.Sprintf("/v1/voice/workers:reconcile")
+ operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/model-source/test", pathParam0, pathParam1, pathParam2)
if operationPath[0] == '/' {
operationPath = "." + operationPath
}
@@ -6078,46 +6426,245 @@ func NewReconcileVoiceWorkersRequest(server string) (*http.Request, error) {
return nil, err
}
- req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil)
+ req, err := http.NewRequest(http.MethodPost, queryURL.String(), body)
if err != nil {
return nil, err
}
+ req.Header.Add("Content-Type", contentType)
+
return req, nil
}
-func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error {
- for _, r := range c.RequestEditors {
- if err := r(ctx, req); err != nil {
- return err
- }
+// NewGetLocalComputerPermissionsRequest generates requests for GetLocalComputerPermissions
+func NewGetLocalComputerPermissionsRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId) (*http.Request, error) {
+ var err error
+
+ var pathParam0 string
+
+ pathParam0, err = runtime.StyleParamWithOptions("simple", false, "tenantId", tenantId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
}
- for _, r := range additionalEditors {
- if err := r(ctx, req); err != nil {
- return err
- }
+
+ var pathParam1 string
+
+ pathParam1, err = runtime.StyleParamWithOptions("simple", false, "ownerActorId", ownerActorId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
}
- return nil
-}
-// ClientWithResponses builds on ClientInterface to offer response payloads
-type ClientWithResponses struct {
- ClientInterface
-}
+ var pathParam2 string
-// NewClientWithResponses creates a new ClientWithResponses, which wraps
-// Client with return type handling
-func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) {
- client, err := NewClient(server, opts...)
+ pathParam2, err = runtime.StyleParamWithOptions("simple", false, "computerId", computerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
if err != nil {
return nil, err
}
- return &ClientWithResponses{client}, nil
-}
-// WithBaseURL overrides the baseURL.
-func WithBaseURL(baseURL string) ClientOption {
- return func(c *Client) error {
+ serverURL, err := url.Parse(server)
+ if err != nil {
+ return nil, err
+ }
+
+ operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/permissions", pathParam0, pathParam1, pathParam2)
+ if operationPath[0] == '/' {
+ operationPath = "." + operationPath
+ }
+
+ queryURL, err := serverURL.Parse(operationPath)
+ if err != nil {
+ return nil, err
+ }
+
+ req, err := http.NewRequest(http.MethodGet, queryURL.String(), nil)
+ if err != nil {
+ return nil, err
+ }
+
+ return req, nil
+}
+
+// NewActOnLocalComputerPermissionRequest calls the generic ActOnLocalComputerPermission builder with application/json body
+func NewActOnLocalComputerPermissionRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ActOnLocalComputerPermissionJSONRequestBody) (*http.Request, error) {
+ var bodyReader io.Reader
+ buf, err := json.Marshal(body)
+ if err != nil {
+ return nil, err
+ }
+ bodyReader = bytes.NewReader(buf)
+ return NewActOnLocalComputerPermissionRequestWithBody(server, tenantId, ownerActorId, computerId, "application/json", bodyReader)
+}
+
+// NewActOnLocalComputerPermissionRequestWithBody generates requests for ActOnLocalComputerPermission with any type of body
+func NewActOnLocalComputerPermissionRequestWithBody(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader) (*http.Request, error) {
+ var err error
+
+ var pathParam0 string
+
+ pathParam0, err = runtime.StyleParamWithOptions("simple", false, "tenantId", tenantId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ var pathParam1 string
+
+ pathParam1, err = runtime.StyleParamWithOptions("simple", false, "ownerActorId", ownerActorId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ var pathParam2 string
+
+ pathParam2, err = runtime.StyleParamWithOptions("simple", false, "computerId", computerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ serverURL, err := url.Parse(server)
+ if err != nil {
+ return nil, err
+ }
+
+ operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/permissions", pathParam0, pathParam1, pathParam2)
+ if operationPath[0] == '/' {
+ operationPath = "." + operationPath
+ }
+
+ queryURL, err := serverURL.Parse(operationPath)
+ if err != nil {
+ return nil, err
+ }
+
+ req, err := http.NewRequest(http.MethodPost, queryURL.String(), body)
+ if err != nil {
+ return nil, err
+ }
+
+ req.Header.Add("Content-Type", contentType)
+
+ return req, nil
+}
+
+// NewScanLocalComputerSkillsRequest calls the generic ScanLocalComputerSkills builder with application/json body
+func NewScanLocalComputerSkillsRequest(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ScanLocalComputerSkillsJSONRequestBody) (*http.Request, error) {
+ var bodyReader io.Reader
+ buf, err := json.Marshal(body)
+ if err != nil {
+ return nil, err
+ }
+ bodyReader = bytes.NewReader(buf)
+ return NewScanLocalComputerSkillsRequestWithBody(server, tenantId, ownerActorId, computerId, "application/json", bodyReader)
+}
+
+// NewScanLocalComputerSkillsRequestWithBody generates requests for ScanLocalComputerSkills with any type of body
+func NewScanLocalComputerSkillsRequestWithBody(server string, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader) (*http.Request, error) {
+ var err error
+
+ var pathParam0 string
+
+ pathParam0, err = runtime.StyleParamWithOptions("simple", false, "tenantId", tenantId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ var pathParam1 string
+
+ pathParam1, err = runtime.StyleParamWithOptions("simple", false, "ownerActorId", ownerActorId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ var pathParam2 string
+
+ pathParam2, err = runtime.StyleParamWithOptions("simple", false, "computerId", computerId, runtime.StyleParamOptions{ParamLocation: runtime.ParamLocationPath, Type: "string", Format: ""})
+ if err != nil {
+ return nil, err
+ }
+
+ serverURL, err := url.Parse(server)
+ if err != nil {
+ return nil, err
+ }
+
+ operationPath := fmt.Sprintf("/v1/tenants/%s/owners/%s/local-computers/%s/skill-scans", pathParam0, pathParam1, pathParam2)
+ if operationPath[0] == '/' {
+ operationPath = "." + operationPath
+ }
+
+ queryURL, err := serverURL.Parse(operationPath)
+ if err != nil {
+ return nil, err
+ }
+
+ req, err := http.NewRequest(http.MethodPost, queryURL.String(), body)
+ if err != nil {
+ return nil, err
+ }
+
+ req.Header.Add("Content-Type", contentType)
+
+ return req, nil
+}
+
+// NewReconcileVoiceWorkersRequest generates requests for ReconcileVoiceWorkers
+func NewReconcileVoiceWorkersRequest(server string) (*http.Request, error) {
+ var err error
+
+ serverURL, err := url.Parse(server)
+ if err != nil {
+ return nil, err
+ }
+
+ operationPath := fmt.Sprintf("/v1/voice/workers:reconcile")
+ if operationPath[0] == '/' {
+ operationPath = "." + operationPath
+ }
+
+ queryURL, err := serverURL.Parse(operationPath)
+ if err != nil {
+ return nil, err
+ }
+
+ req, err := http.NewRequest(http.MethodPost, queryURL.String(), nil)
+ if err != nil {
+ return nil, err
+ }
+
+ return req, nil
+}
+
+func (c *Client) applyEditors(ctx context.Context, req *http.Request, additionalEditors []RequestEditorFn) error {
+ for _, r := range c.RequestEditors {
+ if err := r(ctx, req); err != nil {
+ return err
+ }
+ }
+ for _, r := range additionalEditors {
+ if err := r(ctx, req); err != nil {
+ return err
+ }
+ }
+ return nil
+}
+
+// ClientWithResponses builds on ClientInterface to offer response payloads
+type ClientWithResponses struct {
+ ClientInterface
+}
+
+// NewClientWithResponses creates a new ClientWithResponses, which wraps
+// Client with return type handling
+func NewClientWithResponses(server string, opts ...ClientOption) (*ClientWithResponses, error) {
+ client, err := NewClient(server, opts...)
+ if err != nil {
+ return nil, err
+ }
+ return &ClientWithResponses{client}, nil
+}
+
+// WithBaseURL overrides the baseURL.
+func WithBaseURL(baseURL string) ClientOption {
+ return func(c *Client) error {
newBaseURL, err := url.Parse(baseURL)
if err != nil {
return err
@@ -6262,6 +6809,24 @@ type ClientWithResponsesInterface interface {
ActOnLocalComputerModelsWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ActOnLocalComputerModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*ActOnLocalComputerModelsResponse, error)
+ // GetLocalComputerModelSourceWithResponse request
+ GetLocalComputerModelSourceWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, reqEditors ...RequestEditorFn) (*GetLocalComputerModelSourceResponse, error)
+
+ // ApplyLocalComputerModelSourceWithBodyWithResponse request with any body
+ ApplyLocalComputerModelSourceWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ApplyLocalComputerModelSourceResponse, error)
+
+ ApplyLocalComputerModelSourceWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ApplyLocalComputerModelSourceJSONRequestBody, reqEditors ...RequestEditorFn) (*ApplyLocalComputerModelSourceResponse, error)
+
+ // ListLocalComputerByokModelsWithBodyWithResponse request with any body
+ ListLocalComputerByokModelsWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ListLocalComputerByokModelsResponse, error)
+
+ ListLocalComputerByokModelsWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ListLocalComputerByokModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*ListLocalComputerByokModelsResponse, error)
+
+ // TestLocalComputerByokWithBodyWithResponse request with any body
+ TestLocalComputerByokWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TestLocalComputerByokResponse, error)
+
+ TestLocalComputerByokWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body TestLocalComputerByokJSONRequestBody, reqEditors ...RequestEditorFn) (*TestLocalComputerByokResponse, error)
+
// GetLocalComputerPermissionsWithResponse request
GetLocalComputerPermissionsWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, reqEditors ...RequestEditorFn) (*GetLocalComputerPermissionsResponse, error)
@@ -7314,6 +7879,149 @@ func (r ActOnLocalComputerModelsResponse) ContentType() string {
return ""
}
+type GetLocalComputerModelSourceResponse struct {
+ Body []byte
+ HTTPResponse *http.Response
+ JSON200 *ModelSourceStatus
+ JSON401 *Unauthenticated
+ JSON404 *NotFound
+ JSON409 *Conflict
+ JSON502 *BadGateway
+ JSON503 *ServiceUnavailable
+}
+
+// Status returns HTTPResponse.Status
+func (r GetLocalComputerModelSourceResponse) Status() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Status
+ }
+ return http.StatusText(0)
+}
+
+// StatusCode returns HTTPResponse.StatusCode
+func (r GetLocalComputerModelSourceResponse) StatusCode() int {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.StatusCode
+ }
+ return 0
+}
+
+// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers
+func (r GetLocalComputerModelSourceResponse) ContentType() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Header.Get("Content-Type")
+ }
+ return ""
+}
+
+type ApplyLocalComputerModelSourceResponse struct {
+ Body []byte
+ HTTPResponse *http.Response
+ JSON200 *ModelSourceStatus
+ JSON400 *BadRequest
+ JSON401 *Unauthenticated
+ JSON404 *NotFound
+ JSON409 *Conflict
+ JSON502 *BadGateway
+ JSON503 *ServiceUnavailable
+}
+
+// Status returns HTTPResponse.Status
+func (r ApplyLocalComputerModelSourceResponse) Status() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Status
+ }
+ return http.StatusText(0)
+}
+
+// StatusCode returns HTTPResponse.StatusCode
+func (r ApplyLocalComputerModelSourceResponse) StatusCode() int {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.StatusCode
+ }
+ return 0
+}
+
+// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers
+func (r ApplyLocalComputerModelSourceResponse) ContentType() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Header.Get("Content-Type")
+ }
+ return ""
+}
+
+type ListLocalComputerByokModelsResponse struct {
+ Body []byte
+ HTTPResponse *http.Response
+ JSON200 *ByokModelList
+ JSON400 *BadRequest
+ JSON401 *Unauthenticated
+ JSON404 *NotFound
+ JSON409 *Conflict
+ JSON502 *BadGateway
+ JSON503 *ServiceUnavailable
+}
+
+// Status returns HTTPResponse.Status
+func (r ListLocalComputerByokModelsResponse) Status() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Status
+ }
+ return http.StatusText(0)
+}
+
+// StatusCode returns HTTPResponse.StatusCode
+func (r ListLocalComputerByokModelsResponse) StatusCode() int {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.StatusCode
+ }
+ return 0
+}
+
+// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers
+func (r ListLocalComputerByokModelsResponse) ContentType() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Header.Get("Content-Type")
+ }
+ return ""
+}
+
+type TestLocalComputerByokResponse struct {
+ Body []byte
+ HTTPResponse *http.Response
+ JSON200 *ByokTestResult
+ JSON400 *BadRequest
+ JSON401 *Unauthenticated
+ JSON404 *NotFound
+ JSON409 *Conflict
+ JSON502 *BadGateway
+ JSON503 *ServiceUnavailable
+}
+
+// Status returns HTTPResponse.Status
+func (r TestLocalComputerByokResponse) Status() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Status
+ }
+ return http.StatusText(0)
+}
+
+// StatusCode returns HTTPResponse.StatusCode
+func (r TestLocalComputerByokResponse) StatusCode() int {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.StatusCode
+ }
+ return 0
+}
+
+// ContentType is a convenience method to retrieve the Content-Type value from the HTTP response headers
+func (r TestLocalComputerByokResponse) ContentType() string {
+ if r.HTTPResponse != nil {
+ return r.HTTPResponse.Header.Get("Content-Type")
+ }
+ return ""
+}
+
type GetLocalComputerPermissionsResponse struct {
Body []byte
HTTPResponse *http.Response
@@ -7873,21 +8581,81 @@ func (c *ClientWithResponses) ConfigureLocalComputerBrowserConnectionWithRespons
return ParseConfigureLocalComputerBrowserConnectionResponse(rsp)
}
-// ActOnLocalComputerModelsWithBodyWithResponse request with arbitrary body returning *ActOnLocalComputerModelsResponse
-func (c *ClientWithResponses) ActOnLocalComputerModelsWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ActOnLocalComputerModelsResponse, error) {
- rsp, err := c.ActOnLocalComputerModelsWithBody(ctx, tenantId, ownerActorId, computerId, contentType, body, reqEditors...)
+// ActOnLocalComputerModelsWithBodyWithResponse request with arbitrary body returning *ActOnLocalComputerModelsResponse
+func (c *ClientWithResponses) ActOnLocalComputerModelsWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ActOnLocalComputerModelsResponse, error) {
+ rsp, err := c.ActOnLocalComputerModelsWithBody(ctx, tenantId, ownerActorId, computerId, contentType, body, reqEditors...)
+ if err != nil {
+ return nil, err
+ }
+ return ParseActOnLocalComputerModelsResponse(rsp)
+}
+
+func (c *ClientWithResponses) ActOnLocalComputerModelsWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ActOnLocalComputerModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*ActOnLocalComputerModelsResponse, error) {
+ rsp, err := c.ActOnLocalComputerModels(ctx, tenantId, ownerActorId, computerId, body, reqEditors...)
+ if err != nil {
+ return nil, err
+ }
+ return ParseActOnLocalComputerModelsResponse(rsp)
+}
+
+// GetLocalComputerModelSourceWithResponse request returning *GetLocalComputerModelSourceResponse
+func (c *ClientWithResponses) GetLocalComputerModelSourceWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, reqEditors ...RequestEditorFn) (*GetLocalComputerModelSourceResponse, error) {
+ rsp, err := c.GetLocalComputerModelSource(ctx, tenantId, ownerActorId, computerId, reqEditors...)
+ if err != nil {
+ return nil, err
+ }
+ return ParseGetLocalComputerModelSourceResponse(rsp)
+}
+
+// ApplyLocalComputerModelSourceWithBodyWithResponse request with arbitrary body returning *ApplyLocalComputerModelSourceResponse
+func (c *ClientWithResponses) ApplyLocalComputerModelSourceWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ApplyLocalComputerModelSourceResponse, error) {
+ rsp, err := c.ApplyLocalComputerModelSourceWithBody(ctx, tenantId, ownerActorId, computerId, contentType, body, reqEditors...)
+ if err != nil {
+ return nil, err
+ }
+ return ParseApplyLocalComputerModelSourceResponse(rsp)
+}
+
+func (c *ClientWithResponses) ApplyLocalComputerModelSourceWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ApplyLocalComputerModelSourceJSONRequestBody, reqEditors ...RequestEditorFn) (*ApplyLocalComputerModelSourceResponse, error) {
+ rsp, err := c.ApplyLocalComputerModelSource(ctx, tenantId, ownerActorId, computerId, body, reqEditors...)
+ if err != nil {
+ return nil, err
+ }
+ return ParseApplyLocalComputerModelSourceResponse(rsp)
+}
+
+// ListLocalComputerByokModelsWithBodyWithResponse request with arbitrary body returning *ListLocalComputerByokModelsResponse
+func (c *ClientWithResponses) ListLocalComputerByokModelsWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*ListLocalComputerByokModelsResponse, error) {
+ rsp, err := c.ListLocalComputerByokModelsWithBody(ctx, tenantId, ownerActorId, computerId, contentType, body, reqEditors...)
+ if err != nil {
+ return nil, err
+ }
+ return ParseListLocalComputerByokModelsResponse(rsp)
+}
+
+func (c *ClientWithResponses) ListLocalComputerByokModelsWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ListLocalComputerByokModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*ListLocalComputerByokModelsResponse, error) {
+ rsp, err := c.ListLocalComputerByokModels(ctx, tenantId, ownerActorId, computerId, body, reqEditors...)
+ if err != nil {
+ return nil, err
+ }
+ return ParseListLocalComputerByokModelsResponse(rsp)
+}
+
+// TestLocalComputerByokWithBodyWithResponse request with arbitrary body returning *TestLocalComputerByokResponse
+func (c *ClientWithResponses) TestLocalComputerByokWithBodyWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, contentType string, body io.Reader, reqEditors ...RequestEditorFn) (*TestLocalComputerByokResponse, error) {
+ rsp, err := c.TestLocalComputerByokWithBody(ctx, tenantId, ownerActorId, computerId, contentType, body, reqEditors...)
if err != nil {
return nil, err
}
- return ParseActOnLocalComputerModelsResponse(rsp)
+ return ParseTestLocalComputerByokResponse(rsp)
}
-func (c *ClientWithResponses) ActOnLocalComputerModelsWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body ActOnLocalComputerModelsJSONRequestBody, reqEditors ...RequestEditorFn) (*ActOnLocalComputerModelsResponse, error) {
- rsp, err := c.ActOnLocalComputerModels(ctx, tenantId, ownerActorId, computerId, body, reqEditors...)
+func (c *ClientWithResponses) TestLocalComputerByokWithResponse(ctx context.Context, tenantId TenantId, ownerActorId OwnerActorId, computerId ComputerId, body TestLocalComputerByokJSONRequestBody, reqEditors ...RequestEditorFn) (*TestLocalComputerByokResponse, error) {
+ rsp, err := c.TestLocalComputerByok(ctx, tenantId, ownerActorId, computerId, body, reqEditors...)
if err != nil {
return nil, err
}
- return ParseActOnLocalComputerModelsResponse(rsp)
+ return ParseTestLocalComputerByokResponse(rsp)
}
// GetLocalComputerPermissionsWithResponse request returning *GetLocalComputerPermissionsResponse
@@ -9444,6 +10212,271 @@ func ParseActOnLocalComputerModelsResponse(rsp *http.Response) (*ActOnLocalCompu
return response, nil
}
+// ParseGetLocalComputerModelSourceResponse parses an HTTP response from a GetLocalComputerModelSourceWithResponse call
+func ParseGetLocalComputerModelSourceResponse(rsp *http.Response) (*GetLocalComputerModelSourceResponse, error) {
+ bodyBytes, err := io.ReadAll(rsp.Body)
+ defer func() { _ = rsp.Body.Close() }()
+ if err != nil {
+ return nil, err
+ }
+
+ response := &GetLocalComputerModelSourceResponse{
+ Body: bodyBytes,
+ HTTPResponse: rsp,
+ }
+
+ switch {
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
+ var dest ModelSourceStatus
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON200 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401:
+ var dest Unauthenticated
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON401 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404:
+ var dest NotFound
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON404 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409:
+ var dest Conflict
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON409 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 502:
+ var dest BadGateway
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON502 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503:
+ var dest ServiceUnavailable
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON503 = &dest
+
+ }
+
+ return response, nil
+}
+
+// ParseApplyLocalComputerModelSourceResponse parses an HTTP response from a ApplyLocalComputerModelSourceWithResponse call
+func ParseApplyLocalComputerModelSourceResponse(rsp *http.Response) (*ApplyLocalComputerModelSourceResponse, error) {
+ bodyBytes, err := io.ReadAll(rsp.Body)
+ defer func() { _ = rsp.Body.Close() }()
+ if err != nil {
+ return nil, err
+ }
+
+ response := &ApplyLocalComputerModelSourceResponse{
+ Body: bodyBytes,
+ HTTPResponse: rsp,
+ }
+
+ switch {
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
+ var dest ModelSourceStatus
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON200 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400:
+ var dest BadRequest
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON400 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401:
+ var dest Unauthenticated
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON401 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404:
+ var dest NotFound
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON404 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409:
+ var dest Conflict
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON409 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 502:
+ var dest BadGateway
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON502 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503:
+ var dest ServiceUnavailable
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON503 = &dest
+
+ }
+
+ return response, nil
+}
+
+// ParseListLocalComputerByokModelsResponse parses an HTTP response from a ListLocalComputerByokModelsWithResponse call
+func ParseListLocalComputerByokModelsResponse(rsp *http.Response) (*ListLocalComputerByokModelsResponse, error) {
+ bodyBytes, err := io.ReadAll(rsp.Body)
+ defer func() { _ = rsp.Body.Close() }()
+ if err != nil {
+ return nil, err
+ }
+
+ response := &ListLocalComputerByokModelsResponse{
+ Body: bodyBytes,
+ HTTPResponse: rsp,
+ }
+
+ switch {
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
+ var dest ByokModelList
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON200 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400:
+ var dest BadRequest
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON400 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401:
+ var dest Unauthenticated
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON401 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404:
+ var dest NotFound
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON404 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409:
+ var dest Conflict
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON409 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 502:
+ var dest BadGateway
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON502 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503:
+ var dest ServiceUnavailable
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON503 = &dest
+
+ }
+
+ return response, nil
+}
+
+// ParseTestLocalComputerByokResponse parses an HTTP response from a TestLocalComputerByokWithResponse call
+func ParseTestLocalComputerByokResponse(rsp *http.Response) (*TestLocalComputerByokResponse, error) {
+ bodyBytes, err := io.ReadAll(rsp.Body)
+ defer func() { _ = rsp.Body.Close() }()
+ if err != nil {
+ return nil, err
+ }
+
+ response := &TestLocalComputerByokResponse{
+ Body: bodyBytes,
+ HTTPResponse: rsp,
+ }
+
+ switch {
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 200:
+ var dest ByokTestResult
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON200 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 400:
+ var dest BadRequest
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON400 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 401:
+ var dest Unauthenticated
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON401 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 404:
+ var dest NotFound
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON404 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 409:
+ var dest Conflict
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON409 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 502:
+ var dest BadGateway
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON502 = &dest
+
+ case strings.Contains(rsp.Header.Get("Content-Type"), "json") && rsp.StatusCode == 503:
+ var dest ServiceUnavailable
+ if err := json.Unmarshal(bodyBytes, &dest); err != nil {
+ return nil, err
+ }
+ response.JSON503 = &dest
+
+ }
+
+ return response, nil
+}
+
// ParseGetLocalComputerPermissionsResponse parses an HTTP response from a GetLocalComputerPermissionsWithResponse call
func ParseGetLocalComputerPermissionsResponse(rsp *http.Response) (*GetLocalComputerPermissionsResponse, error) {
bodyBytes, err := io.ReadAll(rsp.Body)
diff --git a/contracts/generated/go/runnergateway/wire.gen.go b/contracts/generated/go/runnergateway/wire.gen.go
index cce88750..ab8144c3 100644
--- a/contracts/generated/go/runnergateway/wire.gen.go
+++ b/contracts/generated/go/runnergateway/wire.gen.go
@@ -56,6 +56,7 @@ const (
KindBrowserConnect = "browser_connect"
KindComputerPermission = "computer_permission"
KindLocalModels = "local_models"
+ KindModelSource = "model_source"
TargetOperation = "operation"
TargetProvider = "provider"
KindSessionCompact = "session_compact"
@@ -94,6 +95,7 @@ var AgentToDaemonMessages = []Message{
{Name: "CapabilityBrowserConnect", Type: "execute", Match: map[string]string{"kind": "browser_connect"}},
{Name: "CapabilityComputerPermission", Type: "execute", Match: map[string]string{"kind": "computer_permission"}},
{Name: "CapabilityLocalModelsExecute", Type: "execute", Match: map[string]string{"kind": "local_models"}},
+ {Name: "CapabilityModelSource", Type: "execute", Match: map[string]string{"kind": "model_source"}},
{Name: "OperationPrepare", Type: "prepare", Match: map[string]string{"target": "operation"}},
{Name: "ProviderPrepare", Type: "prepare", Match: map[string]string{"target": "provider"}},
{Name: "SessionCompact", Type: "execute", Match: map[string]string{"kind": "session_compact"}},
@@ -127,6 +129,8 @@ var DaemonToAgentMessages = []Message{
{Name: "CapabilityComputerPermissionFailed", Type: "executed", Match: map[string]string{"kind": "computer_permission", "outcome": "failed"}},
{Name: "CapabilityLocalModelsAccepted", Type: "executed", Match: map[string]string{"kind": "local_models", "outcome": "accepted"}},
{Name: "CapabilityLocalModelsRefused", Type: "executed", Match: map[string]string{"kind": "local_models", "outcome": "refused"}},
+ {Name: "CapabilityModelSourceSucceeded", Type: "executed", Match: map[string]string{"kind": "model_source", "outcome": "succeeded"}},
+ {Name: "CapabilityModelSourceFailed", Type: "executed", Match: map[string]string{"kind": "model_source", "outcome": "failed"}},
{Name: "OperationPrepared", Type: "prepared", Match: map[string]string{"target": "operation"}},
{Name: "ProviderPrepared", Type: "prepared", Match: map[string]string{"target": "provider"}},
{Name: "SessionCompacted", Type: "executed", Match: map[string]string{"kind": "session_compact"}},
@@ -862,6 +866,179 @@ func (CapabilityBrowserFailed) RequiredFields() []string {
return []string{"protocol_version", "command_id", "runner_id", "tenant_id", "owner_actor_id", "connection_epoch", "expires_at", "type", "action", "error", "kind", "outcome"}
}
+// ByokConfigInput mirrors the ByokConfigInput schema shape.
+type ByokConfigInput struct {
+ BaseURL string `json:"base_url"`
+ APIKey string `json:"api_key,omitempty"`
+ ModelID string `json:"model_id,omitempty"`
+ ContextWindow *uint64 `json:"context_window,omitempty"`
+ ReuseSavedKey *bool `json:"reuse_saved_key,omitempty"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a ByokConfigInput.
+func (ByokConfigInput) FixedFields() map[string]string { return nil }
+
+// RequiredFields lists the keys a ByokConfigInput must carry.
+func (ByokConfigInput) RequiredFields() []string { return []string{"base_url"} }
+
+// ByokSummary mirrors the ByokSummary schema shape.
+type ByokSummary struct {
+ Configured bool `json:"configured"`
+ Protocol string `json:"protocol,omitempty"`
+ BaseURL string `json:"base_url,omitempty"`
+ ModelID string `json:"model_id,omitempty"`
+ ContextWindow *uint64 `json:"context_window,omitempty"`
+ KeySaved bool `json:"key_saved"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a ByokSummary.
+func (ByokSummary) FixedFields() map[string]string { return nil }
+
+// RequiredFields lists the keys a ByokSummary must carry.
+func (ByokSummary) RequiredFields() []string { return []string{"configured", "key_saved"} }
+
+// ModelSourceStatus mirrors the ModelSourceStatus schema shape.
+type ModelSourceStatus struct {
+ Mode string `json:"mode"`
+ Runtime string `json:"runtime"`
+ RuntimeModel string `json:"runtime_model"`
+ ReasoningEffort string `json:"reasoning_effort,omitempty"`
+ GatewayURL string `json:"gateway_url,omitempty"`
+ Byok ByokSummary `json:"byok"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a ModelSourceStatus.
+func (ModelSourceStatus) FixedFields() map[string]string { return nil }
+
+// RequiredFields lists the keys a ModelSourceStatus must carry.
+func (ModelSourceStatus) RequiredFields() []string {
+ return []string{"mode", "runtime", "runtime_model", "byok"}
+}
+
+// ByokModelListModelsItem mirrors the ByokModelListModelsItem schema shape.
+type ByokModelListModelsItem struct {
+ ID string `json:"id"`
+ Name string `json:"name,omitempty"`
+ ContextWindow *uint64 `json:"context_window,omitempty"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a ByokModelListModelsItem.
+func (ByokModelListModelsItem) FixedFields() map[string]string { return nil }
+
+// RequiredFields lists the keys a ByokModelListModelsItem must carry.
+func (ByokModelListModelsItem) RequiredFields() []string { return []string{"id"} }
+
+// ByokModelList mirrors the ByokModelList schema shape.
+type ByokModelList struct {
+ BaseURL string `json:"base_url"`
+ Models []ByokModelListModelsItem `json:"models"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a ByokModelList.
+func (ByokModelList) FixedFields() map[string]string { return nil }
+
+// RequiredFields lists the keys a ByokModelList must carry.
+func (ByokModelList) RequiredFields() []string { return []string{"base_url", "models"} }
+
+// ByokTestResult mirrors the ByokTestResult schema shape.
+type ByokTestResult struct {
+ Ok bool `json:"ok"`
+ Protocol string `json:"protocol"`
+ BaseURL string `json:"base_url"`
+ ModelID string `json:"model_id"`
+ ContextWindow uint64 `json:"context_window"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a ByokTestResult.
+func (ByokTestResult) FixedFields() map[string]string { return nil }
+
+// RequiredFields lists the keys a ByokTestResult must carry.
+func (ByokTestResult) RequiredFields() []string {
+ return []string{"ok", "protocol", "base_url", "model_id", "context_window"}
+}
+
+// CapabilityModelSource mirrors the CapabilityModelSource schema shape.
+type CapabilityModelSource struct {
+ ProtocolVersion string `json:"protocol_version"`
+ CommandID string `json:"command_id"`
+ RunnerID string `json:"runner_id"`
+ TenantID string `json:"tenant_id"`
+ OwnerActorID string `json:"owner_actor_id"`
+ ConnectionEpoch uint64 `json:"connection_epoch"`
+ ExpiresAt string `json:"expires_at"`
+ Type string `json:"type"`
+ Kind string `json:"kind"`
+ Action string `json:"action"`
+ Mode string `json:"mode,omitempty"`
+ Runtime string `json:"runtime,omitempty"`
+ LocalModelID string `json:"local_model_id,omitempty"`
+ Byok *ByokConfigInput `json:"byok,omitempty"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a CapabilityModelSource.
+func (CapabilityModelSource) FixedFields() map[string]string {
+ return map[string]string{"protocol_version": "2", "type": "execute", "kind": "model_source"}
+}
+
+// RequiredFields lists the keys a CapabilityModelSource must carry.
+func (CapabilityModelSource) RequiredFields() []string {
+ return []string{"protocol_version", "command_id", "runner_id", "tenant_id", "owner_actor_id", "connection_epoch", "expires_at", "type", "kind", "action"}
+}
+
+// CapabilityModelSourceSucceeded mirrors the CapabilityModelSourceSucceeded schema shape.
+type CapabilityModelSourceSucceeded struct {
+ ProtocolVersion string `json:"protocol_version"`
+ CommandID string `json:"command_id"`
+ RunnerID string `json:"runner_id"`
+ TenantID string `json:"tenant_id"`
+ OwnerActorID string `json:"owner_actor_id"`
+ ConnectionEpoch uint64 `json:"connection_epoch"`
+ ExpiresAt string `json:"expires_at"`
+ Type string `json:"type"`
+ Kind string `json:"kind"`
+ Action string `json:"action"`
+ Outcome string `json:"outcome"`
+ Status *ModelSourceStatus `json:"status,omitempty"`
+ TestResult *ByokTestResult `json:"test_result,omitempty"`
+ ModelList *ByokModelList `json:"model_list,omitempty"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a CapabilityModelSourceSucceeded.
+func (CapabilityModelSourceSucceeded) FixedFields() map[string]string {
+ return map[string]string{"protocol_version": "2", "type": "executed", "kind": "model_source", "outcome": "succeeded"}
+}
+
+// RequiredFields lists the keys a CapabilityModelSourceSucceeded must carry.
+func (CapabilityModelSourceSucceeded) RequiredFields() []string {
+ return []string{"protocol_version", "command_id", "runner_id", "tenant_id", "owner_actor_id", "connection_epoch", "expires_at", "type", "kind", "action", "outcome"}
+}
+
+// CapabilityModelSourceFailed mirrors the CapabilityModelSourceFailed schema shape.
+type CapabilityModelSourceFailed struct {
+ ProtocolVersion string `json:"protocol_version"`
+ CommandID string `json:"command_id"`
+ RunnerID string `json:"runner_id"`
+ TenantID string `json:"tenant_id"`
+ OwnerActorID string `json:"owner_actor_id"`
+ ConnectionEpoch uint64 `json:"connection_epoch"`
+ ExpiresAt string `json:"expires_at"`
+ Type string `json:"type"`
+ Kind string `json:"kind"`
+ Action string `json:"action"`
+ Error AgentRunnerError `json:"error"`
+ Outcome string `json:"outcome"`
+}
+
+// FixedFields lists the keys whose value the schema fixes for a CapabilityModelSourceFailed.
+func (CapabilityModelSourceFailed) FixedFields() map[string]string {
+ return map[string]string{"protocol_version": "2", "type": "executed", "kind": "model_source", "outcome": "failed"}
+}
+
+// RequiredFields lists the keys a CapabilityModelSourceFailed must carry.
+func (CapabilityModelSourceFailed) RequiredFields() []string {
+ return []string{"protocol_version", "command_id", "runner_id", "tenant_id", "owner_actor_id", "connection_epoch", "expires_at", "type", "kind", "action", "error", "outcome"}
+}
+
// ComputerPermissionStatusSubjectsItemPermissionsItem mirrors the ComputerPermissionStatusSubjectsItemPermissionsItem schema shape.
type ComputerPermissionStatusSubjectsItemPermissionsItem struct {
ID string `json:"id"`
diff --git a/contracts/generated/go/teamhubpublic/openapi.gen.go b/contracts/generated/go/teamhubpublic/openapi.gen.go
index 9433ed27..4d1b333b 100644
--- a/contracts/generated/go/teamhubpublic/openapi.gen.go
+++ b/contracts/generated/go/teamhubpublic/openapi.gen.go
@@ -602,6 +602,27 @@ func (e BrowserConnectionStatusState) Valid() bool {
}
}
+// Defines values for ByokProtocol.
+const (
+ ByokProtocolAnthropic ByokProtocol = "anthropic"
+ ByokProtocolOpenaiChat ByokProtocol = "openai-chat"
+ ByokProtocolOpenaiResponses ByokProtocol = "openai-responses"
+)
+
+// Valid indicates whether the value is a known member of the ByokProtocol enum.
+func (e ByokProtocol) Valid() bool {
+ switch e {
+ case ByokProtocolAnthropic:
+ return true
+ case ByokProtocolOpenaiChat:
+ return true
+ case ByokProtocolOpenaiResponses:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for CaptureSessionChangedPayloadStatus.
const (
CaptureSessionChangedPayloadStatusFinalized CaptureSessionChangedPayloadStatus = "finalized"
@@ -2771,6 +2792,102 @@ func (e MessageKind) Valid() bool {
}
}
+// Defines values for ModelSourceErrorCode.
+const (
+ ModelSourceErrorCodeAgentHasActiveRuns ModelSourceErrorCode = "AGENT_HAS_ACTIVE_RUNS"
+ ModelSourceErrorCodeByokAuthFailed ModelSourceErrorCode = "BYOK_AUTH_FAILED"
+ ModelSourceErrorCodeByokInvalidConfig ModelSourceErrorCode = "BYOK_INVALID_CONFIG"
+ ModelSourceErrorCodeByokModelNotFound ModelSourceErrorCode = "BYOK_MODEL_NOT_FOUND"
+ ModelSourceErrorCodeByokUnreachable ModelSourceErrorCode = "BYOK_UNREACHABLE"
+ ModelSourceErrorCodeByokUpstreamRejected ModelSourceErrorCode = "BYOK_UPSTREAM_REJECTED"
+ ModelSourceErrorCodeLocalComputerOffline ModelSourceErrorCode = "LOCAL_COMPUTER_OFFLINE"
+ ModelSourceErrorCodeLocalModelUnknown ModelSourceErrorCode = "LOCAL_MODEL_UNKNOWN"
+ ModelSourceErrorCodeModelSourceFailed ModelSourceErrorCode = "MODEL_SOURCE_FAILED"
+ ModelSourceErrorCodeModelSourceForbidden ModelSourceErrorCode = "MODEL_SOURCE_FORBIDDEN"
+ ModelSourceErrorCodeModelSourceServiceUnavailable ModelSourceErrorCode = "MODEL_SOURCE_SERVICE_UNAVAILABLE"
+ ModelSourceErrorCodeModelSourceUnavailable ModelSourceErrorCode = "MODEL_SOURCE_UNAVAILABLE"
+ ModelSourceErrorCodeModelSourceUnconfirmed ModelSourceErrorCode = "MODEL_SOURCE_UNCONFIRMED"
+ ModelSourceErrorCodeRuntimeNotEnabled ModelSourceErrorCode = "RUNTIME_NOT_ENABLED"
+)
+
+// Valid indicates whether the value is a known member of the ModelSourceErrorCode enum.
+func (e ModelSourceErrorCode) Valid() bool {
+ switch e {
+ case ModelSourceErrorCodeAgentHasActiveRuns:
+ return true
+ case ModelSourceErrorCodeByokAuthFailed:
+ return true
+ case ModelSourceErrorCodeByokInvalidConfig:
+ return true
+ case ModelSourceErrorCodeByokModelNotFound:
+ return true
+ case ModelSourceErrorCodeByokUnreachable:
+ return true
+ case ModelSourceErrorCodeByokUpstreamRejected:
+ return true
+ case ModelSourceErrorCodeLocalComputerOffline:
+ return true
+ case ModelSourceErrorCodeLocalModelUnknown:
+ return true
+ case ModelSourceErrorCodeModelSourceFailed:
+ return true
+ case ModelSourceErrorCodeModelSourceForbidden:
+ return true
+ case ModelSourceErrorCodeModelSourceServiceUnavailable:
+ return true
+ case ModelSourceErrorCodeModelSourceUnavailable:
+ return true
+ case ModelSourceErrorCodeModelSourceUnconfirmed:
+ return true
+ case ModelSourceErrorCodeRuntimeNotEnabled:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for ModelSourceMode.
+const (
+ ModelSourceModeByok ModelSourceMode = "byok"
+ ModelSourceModeLocal ModelSourceMode = "local"
+ ModelSourceModeSubscription ModelSourceMode = "subscription"
+)
+
+// Valid indicates whether the value is a known member of the ModelSourceMode enum.
+func (e ModelSourceMode) Valid() bool {
+ switch e {
+ case ModelSourceModeByok:
+ return true
+ case ModelSourceModeLocal:
+ return true
+ case ModelSourceModeSubscription:
+ return true
+ default:
+ return false
+ }
+}
+
+// Defines values for ModelSourceRuntime.
+const (
+ ModelSourceRuntimeClaude ModelSourceRuntime = "claude"
+ ModelSourceRuntimeCodex ModelSourceRuntime = "codex"
+ ModelSourceRuntimePi ModelSourceRuntime = "pi"
+)
+
+// Valid indicates whether the value is a known member of the ModelSourceRuntime enum.
+func (e ModelSourceRuntime) Valid() bool {
+ switch e {
+ case ModelSourceRuntimeClaude:
+ return true
+ case ModelSourceRuntimeCodex:
+ return true
+ case ModelSourceRuntimePi:
+ return true
+ default:
+ return false
+ }
+}
+
// Defines values for NotionResourceKind.
const (
NotionResourceKindNotionDatabase NotionResourceKind = "notion_database"
@@ -4638,6 +4755,74 @@ type BrowserConnectionStatusState string
// BrowserProfile A Chrome profile directory name inside the user's Chrome data directory.
type BrowserProfile = string
+// ByokEndpointInput A BYOK endpoint address and key, enough to list its models. The API key is never persisted in TeamHub or Agent Service.
+type ByokEndpointInput struct {
+ ApiKey *string `json:"api_key,omitempty"`
+ BaseUrl string `json:"base_url"`
+ ReuseSavedKey *bool `json:"reuse_saved_key,omitempty"`
+}
+
+// ByokInput Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file.
+type ByokInput struct {
+ ApiKey *string `json:"api_key,omitempty"`
+ BaseUrl string `json:"base_url"`
+ ContextWindow *int `json:"context_window,omitempty"`
+ ModelId string `json:"model_id"`
+ ReuseSavedKey *bool `json:"reuse_saved_key,omitempty"`
+}
+
+// ByokModel A model a BYOK endpoint lists.
+type ByokModel struct {
+ ContextWindow *int `json:"context_window,omitempty"`
+ Id string `json:"id"`
+
+ // Name The endpoint's display name, when it differs from id.
+ Name *string `json:"name,omitempty"`
+}
+
+// ByokModelList The models a BYOK endpoint lists, sorted by id.
+type ByokModelList struct {
+ // BaseUrl The address that listed them.
+ BaseUrl string `json:"base_url"`
+ Models []ByokModel `json:"models"`
+}
+
+// ByokProtocol Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+type ByokProtocol string
+
+// ByokSummary Redacted BYOK configuration metadata reported by the Computer.
+type ByokSummary struct {
+ BaseUrl *string `json:"base_url,omitempty"`
+ Configured bool `json:"configured"`
+ ContextWindow *int `json:"context_window,omitempty"`
+ KeySaved bool `json:"key_saved"`
+ ModelId *string `json:"model_id,omitempty"`
+
+ // Protocol Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+ Protocol *ByokProtocol `json:"protocol,omitempty"`
+}
+
+// ByokTestRequest A BYOK endpoint to verify from the Computer for the Runtime that would serve it, which decides the order wire formats are tried.
+type ByokTestRequest struct {
+ // Byok Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file.
+ Byok ByokInput `json:"byok"`
+
+ // Runtime Agent runtime harness driving turns on the Computer.
+ Runtime ModelSourceRuntime `json:"runtime"`
+}
+
+// ByokTestResult Outcome of probing an upstream BYOK endpoint from the Local Computer.
+type ByokTestResult struct {
+ // BaseUrl The address that answered, which can add or drop the /anthropic of a gateway that serves OpenAI under /v1 and Anthropic under /anthropic.
+ BaseUrl string `json:"base_url"`
+ ContextWindow int `json:"context_window"`
+ ModelId string `json:"model_id"`
+ Ok bool `json:"ok"`
+
+ // Protocol Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+ Protocol ByokProtocol `json:"protocol"`
+}
+
// CaptureSessionChangedPayload defines model for CaptureSessionChangedPayload.
type CaptureSessionChangedPayload struct {
Kind interface{} `json:"kind"`
@@ -7022,6 +7207,80 @@ type MessageThreadSummaryUpdatedPayload struct {
Thread MessageThreadSummary `json:"thread"`
}
+// ModelSourceError The common error body with error.code narrowed to ModelSourceErrorCode.
+type ModelSourceError struct {
+ // Code error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).
+ Code ModelSourceErrorCode `json:"code"`
+ Details *[]ErrorDetail `json:"details,omitempty"`
+
+ // Message Human-readable summary safe to display; clients branch on code, not message.
+ Message string `json:"message"`
+ RequestId string `json:"request_id"`
+}
+
+// ModelSourceErrorCode error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).
+type ModelSourceErrorCode string
+
+// ModelSourceErrorResponse defines model for ModelSourceErrorResponse.
+type ModelSourceErrorResponse struct {
+ // Error The common error body with error.code narrowed to ModelSourceErrorCode.
+ Error ModelSourceError `json:"error"`
+}
+
+// ModelSourceMode Active model source mode on a Local Computer.
+type ModelSourceMode string
+
+// ModelSourceRuntime Agent runtime harness driving turns on the Computer.
+type ModelSourceRuntime string
+
+// ModelSourceStatus Active model source and redacted BYOK metadata on one Local Computer.
+type ModelSourceStatus struct {
+ // Byok Redacted BYOK configuration metadata reported by the Computer.
+ Byok ByokSummary `json:"byok"`
+ GatewayUrl *string `json:"gateway_url,omitempty"`
+
+ // Mode Active model source mode on a Local Computer.
+ Mode ModelSourceMode `json:"mode"`
+ ReasoningEffort *AgentReasoningEffort `json:"reasoning_effort,omitempty"`
+
+ // Runtime Agent runtime harness driving turns on the Computer.
+ Runtime ModelSourceRuntime `json:"runtime"`
+
+ // RuntimeModel After a switch, the model the Computer's Agents run: the target model when the active Runtime offers it, else that Runtime's default.
+ RuntimeModel string `json:"runtime_model"`
+}
+
+// ModelSourceSwitchRequest Owner request to switch a Computer between local models, native subscriptions, and BYOK on Bifrost. When active Runs exist on the Computer's affected Agents and force_terminate is false, TeamHub refuses with 409 AGENT_HAS_ACTIVE_RUNS; retrying with force_terminate true terminates those Runs and applies the switch.
+type ModelSourceSwitchRequest struct {
+ // Byok Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file.
+ Byok *ByokInput `json:"byok,omitempty"`
+
+ // ForceTerminate True ends running work on the Computer's Agents; absent means false.
+ ForceTerminate *bool `json:"force_terminate,omitempty"`
+
+ // LocalModelId Stable localmodels library id: catalog id and variant, such as qwen3-4b:Q4_K_M.
+ LocalModelId *LocalModelId `json:"local_model_id,omitempty"`
+
+ // Mode Active model source mode on a Local Computer.
+ Mode ModelSourceMode `json:"mode"`
+
+ // Runtime Agent runtime harness driving turns on the Computer.
+ Runtime *ModelSourceRuntime `json:"runtime,omitempty"`
+}
+
+// ModelSourceView Current model source state of one Local Computer as viewed from Settings.
+type ModelSourceView struct {
+ // ComputerId Opaque, case-sensitive identifier. Clients must not infer type or time from it.
+ ComputerId Id `json:"computer_id"`
+ Online bool `json:"online"`
+
+ // Status Active model source and redacted BYOK metadata on one Local Computer.
+ Status *ModelSourceStatus `json:"status,omitempty"`
+ TerminatedRunCount *int `json:"terminated_run_count,omitempty"`
+ UpdatedAgentCount *int `json:"updated_agent_count,omitempty"`
+ ViewerIsOwner bool `json:"viewer_is_owner"`
+}
+
// MyDocumentTree defines model for MyDocumentTree.
type MyDocumentTree struct {
Items []DocumentPlacementNode `json:"items"`
@@ -9253,6 +9512,9 @@ type InternalError = ErrorResponse
// LocalModelsRefused defines model for LocalModelsRefused.
type LocalModelsRefused = LocalModelsErrorResponse
+// ModelSourceRefused defines model for ModelSourceRefused.
+type ModelSourceRefused = ModelSourceErrorResponse
+
// NotFound defines model for NotFound.
type NotFound = ErrorResponse
@@ -9877,6 +10139,15 @@ type PutLocalComputerBrowserConnectionJSONRequestBody = BrowserConnectionConfigu
// ActOnLocalComputerModelJSONRequestBody defines body for ActOnLocalComputerModel for application/json ContentType.
type ActOnLocalComputerModelJSONRequestBody = LocalModelActionRequest
+// SwitchLocalComputerModelSourceJSONRequestBody defines body for SwitchLocalComputerModelSource for application/json ContentType.
+type SwitchLocalComputerModelSourceJSONRequestBody = ModelSourceSwitchRequest
+
+// ListLocalComputerByokModelsJSONRequestBody defines body for ListLocalComputerByokModels for application/json ContentType.
+type ListLocalComputerByokModelsJSONRequestBody = ByokEndpointInput
+
+// TestLocalComputerModelSourceJSONRequestBody defines body for TestLocalComputerModelSource for application/json ContentType.
+type TestLocalComputerModelSourceJSONRequestBody = ByokTestRequest
+
// ActOnLocalComputerPermissionJSONRequestBody defines body for ActOnLocalComputerPermission for application/json ContentType.
type ActOnLocalComputerPermissionJSONRequestBody = ComputerPermissionAction
diff --git a/contracts/generated/typescript/src/generated/linger-installer/types.ts b/contracts/generated/typescript/src/generated/linger-installer/types.ts
index 706eb89a..8691a93a 100644
--- a/contracts/generated/typescript/src/generated/linger-installer/types.ts
+++ b/contracts/generated/typescript/src/generated/linger-installer/types.ts
@@ -283,6 +283,23 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/api/byok/check": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Validate BYOK upstream endpoint via localmodels */
+ post: operations["checkInstallerByok"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/api/runtime-login": {
parameters: {
query?: never;
@@ -398,6 +415,22 @@ export interface components {
ModelCheckReport: {
checks: components["schemas"]["CheckResult"][];
};
+ ByokConfiguration: {
+ baseUrl: string;
+ apiKey?: string;
+ modelId: string;
+ contextWindow?: number;
+ /** @enum {string} */
+ runtime?: "claude" | "codex" | "pi";
+ };
+ ByokCheckReport: {
+ ok: boolean;
+ /** @enum {string} */
+ protocol: "openai-chat" | "openai-responses" | "anthropic";
+ baseUrl: string;
+ modelId: string;
+ contextWindow: number;
+ };
/** @description Continue the private saved job input, replacing only model approval or explicit review. Omit both for an ordinary retry without spent authority. */
LocalModelsAuthority: {
localModelsApproval?: string;
@@ -429,6 +462,7 @@ export interface components {
*/
preparation?: "codex" | "claude" | "pi";
runtimeModel?: components["schemas"]["ModelConfiguration"];
+ byok?: components["schemas"]["ByokConfiguration"];
/** @default default */
instance: string;
port?: number;
@@ -1528,6 +1562,48 @@ export interface operations {
};
};
};
+ checkInstallerByok: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path?: never;
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["ByokConfiguration"];
+ };
+ };
+ responses: {
+ /** @description BYOK check result */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ByokCheckReport"];
+ };
+ };
+ /** @description Invalid request */
+ 400: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["InstallerError"];
+ };
+ };
+ /** @description Local installer session required */
+ 401: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["InstallerError"];
+ };
+ };
+ };
+ };
inspectInstallerRuntimeLogin: {
parameters: {
query: {
diff --git a/contracts/generated/typescript/src/generated/node-services-internal/types.ts b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
index fb56291b..15046f4d 100644
--- a/contracts/generated/typescript/src/generated/node-services-internal/types.ts
+++ b/contracts/generated/typescript/src/generated/node-services-internal/types.ts
@@ -127,6 +127,70 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/model-source": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ ownerActorId: components["parameters"]["OwnerActorId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ /** Read the active model source and redacted BYOK configuration of an owned Local Computer */
+ get: operations["getLocalComputerModelSource"];
+ put?: never;
+ /** Switch the active model source on an owned Local Computer */
+ post: operations["applyLocalComputerModelSource"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/model-source/models": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ ownerActorId: components["parameters"]["OwnerActorId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** List the models a BYOK endpoint serves, from an owned Local Computer without saving credentials */
+ post: operations["listLocalComputerByokModels"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/model-source/test": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ ownerActorId: components["parameters"]["OwnerActorId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Verify a BYOK upstream endpoint from an owned Local Computer without saving credentials */
+ post: operations["testLocalComputerByok"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/browser-connection": {
parameters: {
query?: never;
@@ -1496,6 +1560,97 @@ export interface components {
/** @description Present only when refused. */
refusal?: components["schemas"]["LocalModelActionRefusal"];
};
+ /**
+ * @description Active model source mode on a Local Computer.
+ * @enum {string}
+ */
+ ModelSourceMode: "local" | "subscription" | "byok";
+ /**
+ * @description Agent runtime harness driving turns on the Computer.
+ * @enum {string}
+ */
+ ModelSourceRuntime: "claude" | "codex" | "pi";
+ /** @enum {string} */
+ AgentReasoningEffort:
+ | "none"
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max"
+ | "ultra";
+ /**
+ * @description Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+ * @enum {string}
+ */
+ ByokProtocol: "openai-chat" | "openai-responses" | "anthropic";
+ /** @description Redacted BYOK configuration metadata reported by the Computer. */
+ ByokSummary: {
+ configured: boolean;
+ protocol?: components["schemas"]["ByokProtocol"];
+ base_url?: string;
+ model_id?: string;
+ context_window?: number;
+ key_saved: boolean;
+ };
+ /** @description Active model source and redacted BYOK metadata on one Local Computer. */
+ ModelSourceStatus: {
+ mode: components["schemas"]["ModelSourceMode"];
+ runtime: components["schemas"]["ModelSourceRuntime"];
+ /** @description After a switch, the model the Computer's Agents run: the target model when the active Runtime offers it, else that Runtime's default. */
+ runtime_model: string;
+ reasoning_effort?: components["schemas"]["AgentReasoningEffort"];
+ gateway_url?: string;
+ byok: components["schemas"]["ByokSummary"];
+ };
+ /** @description Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file. */
+ ByokInput: {
+ base_url: string;
+ api_key?: string;
+ model_id: string;
+ context_window?: number;
+ reuse_saved_key?: boolean;
+ };
+ /** @description Internal command sent from TeamHub to Agent Service to switch a Computer's model source. */
+ ModelSourceApplyCommand: {
+ mode: components["schemas"]["ModelSourceMode"];
+ runtime?: components["schemas"]["ModelSourceRuntime"];
+ local_model_id?: components["schemas"]["LocalModelId"];
+ byok?: components["schemas"]["ByokInput"];
+ };
+ /** @description A BYOK endpoint address and key, enough to list its models. The API key is never persisted in TeamHub or Agent Service. */
+ ByokEndpointInput: {
+ base_url: string;
+ api_key?: string;
+ reuse_saved_key?: boolean;
+ };
+ /** @description A model a BYOK endpoint lists. */
+ ByokModel: {
+ id: string;
+ /** @description The endpoint's display name, when it differs from id. */
+ name?: string;
+ context_window?: number;
+ };
+ /** @description The models a BYOK endpoint lists, sorted by id. */
+ ByokModelList: {
+ /** @description The address that listed them. */
+ base_url: string;
+ models: components["schemas"]["ByokModel"][];
+ };
+ /** @description A BYOK endpoint to verify from the Computer for the Runtime that would serve it, which decides the order wire formats are tried. */
+ ByokTestRequest: {
+ runtime: components["schemas"]["ModelSourceRuntime"];
+ byok: components["schemas"]["ByokInput"];
+ };
+ /** @description Outcome of probing an upstream BYOK endpoint from the Local Computer. */
+ ByokTestResult: {
+ ok: boolean;
+ protocol: components["schemas"]["ByokProtocol"];
+ /** @description The address that answered, which can add or drop the /anthropic of a gateway that serves OpenAI under /v1 and Anthropic under /anthropic. */
+ base_url: string;
+ model_id: string;
+ context_window: number;
+ };
/** @description A Chrome profile directory name inside the user's Chrome data directory. */
BrowserProfile: string;
/** @description The browser that browser tools of this owner's Agents drive on one Local Computer. It never contains the Playwright Extension token. */
@@ -2235,6 +2390,137 @@ export interface operations {
503: components["responses"]["ServiceUnavailable"];
};
};
+ getLocalComputerModelSource: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ ownerActorId: components["parameters"]["OwnerActorId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Current model source status without secret API keys. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ModelSourceStatus"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["Conflict"];
+ 502: components["responses"]["BadGateway"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
+ applyLocalComputerModelSource: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ ownerActorId: components["parameters"]["OwnerActorId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["ModelSourceApplyCommand"];
+ };
+ };
+ responses: {
+ /** @description Updated model source status without secret API keys. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ModelSourceStatus"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["Conflict"];
+ 502: components["responses"]["BadGateway"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
+ listLocalComputerByokModels: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ ownerActorId: components["parameters"]["OwnerActorId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["ByokEndpointInput"];
+ };
+ };
+ responses: {
+ /** @description The endpoint's models. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ByokModelList"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["Conflict"];
+ 502: components["responses"]["BadGateway"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
+ testLocalComputerByok: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ ownerActorId: components["parameters"]["OwnerActorId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["ByokTestRequest"];
+ };
+ };
+ responses: {
+ /** @description BYOK verification result. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ByokTestResult"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["Conflict"];
+ 502: components["responses"]["BadGateway"];
+ 503: components["responses"]["ServiceUnavailable"];
+ };
+ };
getLocalComputerBrowserConnection: {
parameters: {
query?: never;
diff --git a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
index d3d2b8cc..9415f080 100644
--- a/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
+++ b/contracts/generated/typescript/src/generated/runner-gateway/schema.ts
@@ -48,6 +48,9 @@ export const runnerGatewayEnvelopeSchema = {
{
$ref: "#/$defs/CapabilityLocalModelsExecute",
},
+ {
+ $ref: "#/$defs/CapabilityModelSource",
+ },
{
$ref: "#/$defs/OperationPrepare",
},
@@ -139,6 +142,12 @@ export const runnerGatewayEnvelopeSchema = {
{
$ref: "#/$defs/CapabilityLocalModelsRefused",
},
+ {
+ $ref: "#/$defs/CapabilityModelSourceSucceeded",
+ },
+ {
+ $ref: "#/$defs/CapabilityModelSourceFailed",
+ },
{
$ref: "#/$defs/OperationPrepared",
},
@@ -1690,6 +1699,264 @@ export const runnerGatewayEnvelopeSchema = {
},
],
},
+ ByokConfigInput: {
+ description:
+ "A BYOK endpoint; model_id is required except to list the endpoint's models.",
+ type: "object",
+ additionalProperties: false,
+ required: ["base_url"],
+ properties: {
+ base_url: {
+ type: "string",
+ minLength: 1,
+ maxLength: 2048,
+ },
+ api_key: {
+ type: "string",
+ maxLength: 4096,
+ },
+ model_id: {
+ type: "string",
+ minLength: 1,
+ maxLength: 256,
+ },
+ context_window: {
+ type: "integer",
+ minimum: 1,
+ maximum: 2147483647,
+ },
+ reuse_saved_key: {
+ type: "boolean",
+ },
+ },
+ },
+ ByokSummary: {
+ type: "object",
+ additionalProperties: false,
+ required: ["configured", "key_saved"],
+ properties: {
+ configured: {
+ type: "boolean",
+ },
+ protocol: {
+ enum: ["openai-chat", "openai-responses", "anthropic"],
+ },
+ base_url: {
+ type: "string",
+ maxLength: 2048,
+ },
+ model_id: {
+ type: "string",
+ maxLength: 256,
+ },
+ context_window: {
+ type: "integer",
+ minimum: 1,
+ maximum: 2147483647,
+ },
+ key_saved: {
+ type: "boolean",
+ },
+ },
+ },
+ ModelSourceStatus: {
+ type: "object",
+ additionalProperties: false,
+ required: ["mode", "runtime", "runtime_model", "byok"],
+ properties: {
+ mode: {
+ enum: ["local", "subscription", "byok"],
+ },
+ runtime: {
+ enum: ["claude", "codex", "pi"],
+ },
+ runtime_model: {
+ description:
+ "After apply, the model the Computer's Agents run: the target model when the active Runtime offers it, else that Runtime's default.",
+ type: "string",
+ maxLength: 256,
+ },
+ reasoning_effort: {
+ description:
+ "After apply, the reasoning effort runtime_model needs; absent when it offers none.",
+ enum: ["none", "low", "medium", "high", "xhigh", "max", "ultra"],
+ },
+ gateway_url: {
+ type: "string",
+ maxLength: 2048,
+ },
+ byok: {
+ $ref: "#/$defs/ByokSummary",
+ },
+ },
+ },
+ ByokModelList: {
+ type: "object",
+ additionalProperties: false,
+ required: ["base_url", "models"],
+ properties: {
+ base_url: {
+ type: "string",
+ minLength: 1,
+ maxLength: 2048,
+ },
+ models: {
+ type: "array",
+ maxItems: 1000,
+ items: {
+ type: "object",
+ additionalProperties: false,
+ required: ["id"],
+ properties: {
+ id: {
+ type: "string",
+ minLength: 1,
+ maxLength: 256,
+ },
+ name: {
+ type: "string",
+ maxLength: 256,
+ },
+ context_window: {
+ type: "integer",
+ minimum: 1,
+ maximum: 2147483647,
+ },
+ },
+ },
+ },
+ },
+ },
+ ByokTestResult: {
+ type: "object",
+ additionalProperties: false,
+ required: ["ok", "protocol", "base_url", "model_id", "context_window"],
+ properties: {
+ ok: {
+ type: "boolean",
+ },
+ protocol: {
+ enum: ["openai-chat", "openai-responses", "anthropic"],
+ },
+ base_url: {
+ type: "string",
+ minLength: 1,
+ maxLength: 2048,
+ },
+ model_id: {
+ type: "string",
+ minLength: 1,
+ maxLength: 256,
+ },
+ context_window: {
+ type: "integer",
+ minimum: 1,
+ maximum: 2147483647,
+ },
+ },
+ },
+ CapabilityModelSource: {
+ type: "object",
+ unevaluatedProperties: false,
+ allOf: [
+ {
+ $ref: "#/$defs/LocalSkillCommandIdentity",
+ },
+ {
+ type: "object",
+ required: ["type", "kind", "action"],
+ properties: {
+ type: {
+ const: "execute",
+ },
+ kind: {
+ const: "model_source",
+ },
+ action: {
+ enum: ["status", "test", "models", "apply"],
+ },
+ mode: {
+ enum: ["local", "subscription", "byok"],
+ },
+ runtime: {
+ enum: ["claude", "codex", "pi"],
+ },
+ local_model_id: {
+ $ref: "#/$defs/LocalModelId",
+ },
+ byok: {
+ $ref: "#/$defs/ByokConfigInput",
+ },
+ },
+ },
+ ],
+ },
+ CapabilityModelSourceSucceeded: {
+ type: "object",
+ unevaluatedProperties: false,
+ allOf: [
+ {
+ $ref: "#/$defs/LocalSkillCommandIdentity",
+ },
+ {
+ type: "object",
+ required: ["type", "kind", "action", "outcome"],
+ properties: {
+ type: {
+ const: "executed",
+ },
+ kind: {
+ const: "model_source",
+ },
+ action: {
+ enum: ["status", "test", "models", "apply"],
+ },
+ outcome: {
+ const: "succeeded",
+ },
+ status: {
+ $ref: "#/$defs/ModelSourceStatus",
+ },
+ test_result: {
+ $ref: "#/$defs/ByokTestResult",
+ },
+ model_list: {
+ $ref: "#/$defs/ByokModelList",
+ },
+ },
+ },
+ ],
+ },
+ CapabilityModelSourceFailed: {
+ type: "object",
+ unevaluatedProperties: false,
+ allOf: [
+ {
+ $ref: "#/$defs/LocalSkillCommandIdentity",
+ },
+ {
+ type: "object",
+ required: ["type", "kind", "action", "error", "outcome"],
+ properties: {
+ type: {
+ const: "executed",
+ },
+ kind: {
+ const: "model_source",
+ },
+ action: {
+ enum: ["status", "test", "models", "apply"],
+ },
+ error: {
+ $ref: "#/$defs/AgentRunnerError",
+ },
+ outcome: {
+ const: "failed",
+ },
+ },
+ },
+ ],
+ },
ComputerPermissionStatus: {
description:
"The macOS privacy permissions of this Computer. Other platforms report no subjects.",
diff --git a/contracts/generated/typescript/src/generated/runner-gateway/types.ts b/contracts/generated/typescript/src/generated/runner-gateway/types.ts
index f8c2fb49..13220df0 100644
--- a/contracts/generated/typescript/src/generated/runner-gateway/types.ts
+++ b/contracts/generated/typescript/src/generated/runner-gateway/types.ts
@@ -15,6 +15,7 @@ export type AgentToDaemonEnvelope =
| CapabilityBrowserConnect
| CapabilityComputerPermission
| CapabilityLocalModelsExecute
+ | CapabilityModelSource
| OperationPrepare
| ProviderPrepare
| SessionCompact
@@ -114,6 +115,15 @@ export type CapabilityLocalModelsExecute = LocalSkillCommandIdentity & {
* Stable localmodels library id: catalog id and variant, such as qwen3-4b:Q4_K_M.
*/
export type LocalModelId = string;
+export type CapabilityModelSource = LocalSkillCommandIdentity & {
+ type: "execute";
+ kind: "model_source";
+ action: "status" | "test" | "models" | "apply";
+ mode?: "local" | "subscription" | "byok";
+ runtime?: "claude" | "codex" | "pi";
+ local_model_id?: LocalModelId;
+ byok?: ByokConfigInput;
+};
export type OperationPrepare = OperationIdentity & {
type: "prepare";
command_id: Id;
@@ -207,6 +217,8 @@ export type DaemonToAgentEnvelope =
| CapabilityComputerPermissionFailed
| CapabilityLocalModelsAccepted
| CapabilityLocalModelsRefused
+ | CapabilityModelSourceSucceeded
+ | CapabilityModelSourceFailed
| OperationPrepared
| ProviderPrepared
| SessionCompacted
@@ -478,6 +490,22 @@ export type LocalModelActionRefusalCode =
| "CANCELLED"
| "TOOL_NOT_INSTALLED"
| "TOOL_FAILED";
+export type CapabilityModelSourceSucceeded = LocalSkillCommandIdentity & {
+ type: "executed";
+ kind: "model_source";
+ action: "status" | "test" | "models" | "apply";
+ outcome: "succeeded";
+ status?: ModelSourceStatus;
+ test_result?: ByokTestResult;
+ model_list?: ByokModelList;
+};
+export type CapabilityModelSourceFailed = LocalSkillCommandIdentity & {
+ type: "executed";
+ kind: "model_source";
+ action: "status" | "test" | "models" | "apply";
+ error: AgentRunnerError;
+ outcome: "failed";
+};
export type OperationPrepared = OperationIdentity & {
type: "prepared";
command_id: Id;
@@ -899,6 +927,16 @@ export interface LocalSkillCommandIdentity {
connection_epoch: PositiveInteger;
expires_at: Timestamp;
}
+/**
+ * A BYOK endpoint; model_id is required except to list the endpoint's models.
+ */
+export interface ByokConfigInput {
+ base_url: string;
+ api_key?: string;
+ model_id?: string;
+ context_window?: number;
+ reuse_saved_key?: boolean;
+}
export interface OperationScope {
protocol_version: ProtocolVersion;
host_access: "trusted";
@@ -1835,6 +1873,53 @@ export interface LocalModelActionRefusal {
*/
free_bytes?: number;
}
+export interface ModelSourceStatus {
+ mode: "local" | "subscription" | "byok";
+ runtime: "claude" | "codex" | "pi";
+ /**
+ * After apply, the model the Computer's Agents run: the target model when the active Runtime offers it, else that Runtime's default.
+ */
+ runtime_model: string;
+ /**
+ * After apply, the reasoning effort runtime_model needs; absent when it offers none.
+ */
+ reasoning_effort?:
+ | "none"
+ | "low"
+ | "medium"
+ | "high"
+ | "xhigh"
+ | "max"
+ | "ultra";
+ gateway_url?: string;
+ byok: ByokSummary;
+}
+export interface ByokSummary {
+ configured: boolean;
+ protocol?: "openai-chat" | "openai-responses" | "anthropic";
+ base_url?: string;
+ model_id?: string;
+ context_window?: number;
+ key_saved: boolean;
+}
+export interface ByokTestResult {
+ ok: boolean;
+ protocol: "openai-chat" | "openai-responses" | "anthropic";
+ base_url: string;
+ model_id: string;
+ context_window: number;
+}
+export interface ByokModelList {
+ base_url: string;
+ /**
+ * @maxItems 1000
+ */
+ models: {
+ id: string;
+ name?: string;
+ context_window?: number;
+ }[];
+}
export interface NativeResumeMeasurement {
duration_ms: NonNegativeInteger;
result: "success" | "error" | "canceled";
diff --git a/contracts/generated/typescript/src/generated/teamhub-public/types.ts b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
index 4ca8e5d4..0cdaf996 100644
--- a/contracts/generated/typescript/src/generated/teamhub-public/types.ts
+++ b/contracts/generated/typescript/src/generated/teamhub-public/types.ts
@@ -494,6 +494,67 @@ export interface paths {
patch?: never;
trace?: never;
};
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ /** Read the active model source and redacted BYOK configuration of one Local Computer. */
+ get: operations["getLocalComputerModelSource"];
+ put?: never;
+ /** Switch a Local Computer between local models, subscriptions, and BYOK on Bifrost. */
+ post: operations["switchLocalComputerModelSource"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source/models": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** List the models a BYOK endpoint serves, asked from an owned Local Computer without saving anything. */
+ post: operations["listLocalComputerByokModels"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
+ "/v0/tenants/{tenantId}/local-computers/{computerId}/model-source/test": {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ get?: never;
+ put?: never;
+ /** Verify a BYOK upstream endpoint from an owned Local Computer without saving credentials. */
+ post: operations["testLocalComputerModelSource"];
+ delete?: never;
+ options?: never;
+ head?: never;
+ patch?: never;
+ trace?: never;
+ };
"/v0/tenants/{tenantId}/local-computers/{computerId}/permissions": {
parameters: {
query?: never;
@@ -4774,6 +4835,129 @@ export interface components {
LocalModelsErrorResponse: {
error: components["schemas"]["LocalModelsError"];
};
+ /**
+ * @description Active model source mode on a Local Computer.
+ * @enum {string}
+ */
+ ModelSourceMode: "local" | "subscription" | "byok";
+ /**
+ * @description Agent runtime harness driving turns on the Computer.
+ * @enum {string}
+ */
+ ModelSourceRuntime: "claude" | "codex" | "pi";
+ /**
+ * @description Wire format the Computer found a BYOK upstream endpoint answers, trying the active Runtime's own format first.
+ * @enum {string}
+ */
+ ByokProtocol: "openai-chat" | "openai-responses" | "anthropic";
+ /** @description Redacted BYOK configuration metadata reported by the Computer. */
+ ByokSummary: {
+ configured: boolean;
+ protocol?: components["schemas"]["ByokProtocol"];
+ base_url?: string;
+ model_id?: string;
+ context_window?: number;
+ key_saved: boolean;
+ };
+ /** @description Active model source and redacted BYOK metadata on one Local Computer. */
+ ModelSourceStatus: {
+ mode: components["schemas"]["ModelSourceMode"];
+ runtime: components["schemas"]["ModelSourceRuntime"];
+ /** @description After a switch, the model the Computer's Agents run: the target model when the active Runtime offers it, else that Runtime's default. */
+ runtime_model: string;
+ reasoning_effort?: components["schemas"]["AgentReasoningEffort"];
+ gateway_url?: string;
+ byok: components["schemas"]["ByokSummary"];
+ };
+ /** @description Current model source state of one Local Computer as viewed from Settings. */
+ ModelSourceView: {
+ computer_id: components["schemas"]["Id"];
+ viewer_is_owner: boolean;
+ online: boolean;
+ status?: components["schemas"]["ModelSourceStatus"];
+ updated_agent_count?: number;
+ terminated_run_count?: number;
+ };
+ /**
+ * @description error.code of a refused model-source request (403, 409, 502, 503, 504); 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS: Agents on the Computer have running work and force_terminate was false; details carries one entry per such Agent, with field "agent" and the Agent's display name as reason. RUNTIME_NOT_ENABLED, LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the Computer had not answered by the deadline; it may still switch (504).
+ * @enum {string}
+ */
+ ModelSourceErrorCode:
+ | "LOCAL_COMPUTER_OFFLINE"
+ | "MODEL_SOURCE_FORBIDDEN"
+ | "MODEL_SOURCE_UNAVAILABLE"
+ | "AGENT_HAS_ACTIVE_RUNS"
+ | "RUNTIME_NOT_ENABLED"
+ | "LOCAL_MODEL_UNKNOWN"
+ | "BYOK_INVALID_CONFIG"
+ | "BYOK_AUTH_FAILED"
+ | "BYOK_MODEL_NOT_FOUND"
+ | "BYOK_UNREACHABLE"
+ | "BYOK_UPSTREAM_REJECTED"
+ | "MODEL_SOURCE_FAILED"
+ | "MODEL_SOURCE_SERVICE_UNAVAILABLE"
+ | "MODEL_SOURCE_UNCONFIRMED";
+ /** @description The common error body with error.code narrowed to ModelSourceErrorCode. */
+ ModelSourceError: {
+ code: components["schemas"]["ModelSourceErrorCode"];
+ /** @description Human-readable summary safe to display; clients branch on code, not message. */
+ message: string;
+ request_id: string;
+ details?: components["schemas"]["ErrorDetail"][];
+ };
+ ModelSourceErrorResponse: {
+ error: components["schemas"]["ModelSourceError"];
+ };
+ /** @description Upstream endpoint configuration supplied by the Computer owner. The API key is never persisted in TeamHub or Agent Service; only the Local Computer stores it in a private 0600 file. */
+ ByokInput: {
+ base_url: string;
+ api_key?: string;
+ model_id: string;
+ context_window?: number;
+ reuse_saved_key?: boolean;
+ };
+ /** @description Owner request to switch a Computer between local models, native subscriptions, and BYOK on Bifrost. When active Runs exist on the Computer's affected Agents and force_terminate is false, TeamHub refuses with 409 AGENT_HAS_ACTIVE_RUNS; retrying with force_terminate true terminates those Runs and applies the switch. */
+ ModelSourceSwitchRequest: {
+ mode: components["schemas"]["ModelSourceMode"];
+ runtime?: components["schemas"]["ModelSourceRuntime"];
+ local_model_id?: components["schemas"]["LocalModelId"];
+ byok?: components["schemas"]["ByokInput"];
+ /** @description True ends running work on the Computer's Agents; absent means false. */
+ force_terminate?: boolean;
+ };
+ /** @description A BYOK endpoint address and key, enough to list its models. The API key is never persisted in TeamHub or Agent Service. */
+ ByokEndpointInput: {
+ base_url: string;
+ api_key?: string;
+ reuse_saved_key?: boolean;
+ };
+ /** @description A model a BYOK endpoint lists. */
+ ByokModel: {
+ id: string;
+ /** @description The endpoint's display name, when it differs from id. */
+ name?: string;
+ context_window?: number;
+ };
+ /** @description The models a BYOK endpoint lists, sorted by id. */
+ ByokModelList: {
+ /** @description The address that listed them. */
+ base_url: string;
+ models: components["schemas"]["ByokModel"][];
+ };
+ /** @description A BYOK endpoint to verify from the Computer for the Runtime that would serve it, which decides the order wire formats are tried. */
+ ByokTestRequest: {
+ runtime: components["schemas"]["ModelSourceRuntime"];
+ byok: components["schemas"]["ByokInput"];
+ };
+ /** @description Outcome of probing an upstream BYOK endpoint from the Local Computer. */
+ ByokTestResult: {
+ ok: boolean;
+ protocol: components["schemas"]["ByokProtocol"];
+ /** @description The address that answered, which can add or drop the /anthropic of a gateway that serves OpenAI under /v1 and Anthropic under /anthropic. */
+ base_url: string;
+ model_id: string;
+ context_window: number;
+ };
/**
* @description The app macOS grants the permission to. linger is the Linger desktop app, which owns shell commands such as screencapture; computer_use is CuaDriver, which owns the computer-use tools.
* @enum {string}
@@ -8101,6 +8285,15 @@ export interface components {
"application/json": components["schemas"]["LocalModelsErrorResponse"];
};
};
+ /** @description The Computer or TeamHub refused the model-source request; error.code is one of ModelSourceErrorCode. */
+ ModelSourceRefused: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ModelSourceErrorResponse"];
+ };
+ };
/** @description The resource existed but was explicitly removed and cannot be reused. */
Gone: {
headers: {
@@ -8951,6 +9144,138 @@ export interface operations {
504: components["responses"]["LocalModelsRefused"];
};
};
+ getLocalComputerModelSource: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody?: never;
+ responses: {
+ /** @description Current model source view. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ModelSourceView"];
+ };
+ };
+ 401: components["responses"]["Unauthenticated"];
+ 404: components["responses"]["NotFound"];
+ 502: components["responses"]["ModelSourceRefused"];
+ 503: components["responses"]["ModelSourceRefused"];
+ };
+ };
+ switchLocalComputerModelSource: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["ModelSourceSwitchRequest"];
+ };
+ };
+ responses: {
+ /** @description Switched model source view. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ModelSourceView"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["ModelSourceRefused"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["ModelSourceRefused"];
+ 502: components["responses"]["ModelSourceRefused"];
+ 503: components["responses"]["ModelSourceRefused"];
+ 504: components["responses"]["ModelSourceRefused"];
+ };
+ };
+ listLocalComputerByokModels: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["ByokEndpointInput"];
+ };
+ };
+ responses: {
+ /** @description The endpoint's models. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ByokModelList"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["ModelSourceRefused"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["ModelSourceRefused"];
+ 502: components["responses"]["ModelSourceRefused"];
+ 503: components["responses"]["ModelSourceRefused"];
+ 504: components["responses"]["ModelSourceRefused"];
+ };
+ };
+ testLocalComputerModelSource: {
+ parameters: {
+ query?: never;
+ header?: never;
+ path: {
+ tenantId: components["parameters"]["TenantId"];
+ computerId: components["parameters"]["ComputerId"];
+ };
+ cookie?: never;
+ };
+ requestBody: {
+ content: {
+ "application/json": components["schemas"]["ByokTestRequest"];
+ };
+ };
+ responses: {
+ /** @description BYOK verification result. */
+ 200: {
+ headers: {
+ [name: string]: unknown;
+ };
+ content: {
+ "application/json": components["schemas"]["ByokTestResult"];
+ };
+ };
+ 400: components["responses"]["BadRequest"];
+ 401: components["responses"]["Unauthenticated"];
+ 403: components["responses"]["ModelSourceRefused"];
+ 404: components["responses"]["NotFound"];
+ 409: components["responses"]["ModelSourceRefused"];
+ 502: components["responses"]["ModelSourceRefused"];
+ 503: components["responses"]["ModelSourceRefused"];
+ 504: components["responses"]["ModelSourceRefused"];
+ };
+ };
getLocalComputerPermissions: {
parameters: {
query?: never;
diff --git a/contracts/openapi/components/model-source.yaml b/contracts/openapi/components/model-source.yaml
new file mode 100644
index 00000000..7d0799be
--- /dev/null
+++ b/contracts/openapi/components/model-source.yaml
@@ -0,0 +1,331 @@
+components:
+ responses:
+ ModelSourceRefused:
+ description: >-
+ The Computer or TeamHub refused the model-source request; error.code is
+ one of ModelSourceErrorCode.
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ModelSourceErrorResponse"
+ schemas:
+ ByokProtocol:
+ description: >-
+ Wire format the Computer found a BYOK upstream endpoint answers, trying
+ the active Runtime's own format first.
+ type: string
+ enum: [openai-chat, openai-responses, anthropic]
+ x-enum-varnames:
+ [
+ ByokProtocolOpenaiChat,
+ ByokProtocolOpenaiResponses,
+ ByokProtocolAnthropic,
+ ]
+ ModelSourceMode:
+ description: Active model source mode on a Local Computer.
+ type: string
+ enum: [local, subscription, byok]
+ x-enum-varnames:
+ [ModelSourceModeLocal, ModelSourceModeSubscription, ModelSourceModeByok]
+ ModelSourceRuntime:
+ description: Agent runtime harness driving turns on the Computer.
+ type: string
+ enum: [claude, codex, pi]
+ x-enum-varnames:
+ [
+ ModelSourceRuntimeClaude,
+ ModelSourceRuntimeCodex,
+ ModelSourceRuntimePi,
+ ]
+ ByokInput:
+ description: >-
+ Upstream endpoint configuration supplied by the Computer owner. The API
+ key is never persisted in TeamHub or Agent Service; only the Local
+ Computer stores it in a private 0600 file.
+ type: object
+ additionalProperties: false
+ required: [base_url, model_id]
+ properties:
+ base_url:
+ type: string
+ minLength: 1
+ maxLength: 2048
+ api_key:
+ type: string
+ writeOnly: true
+ maxLength: 4096
+ model_id:
+ type: string
+ minLength: 1
+ maxLength: 256
+ context_window:
+ type: integer
+ minimum: 1
+ maximum: 2147483647
+ reuse_saved_key:
+ type: boolean
+ ByokEndpointInput:
+ description: >-
+ A BYOK endpoint address and key, enough to list its models. The API
+ key is never persisted in TeamHub or Agent Service.
+ type: object
+ additionalProperties: false
+ required: [base_url]
+ properties:
+ base_url:
+ type: string
+ minLength: 1
+ maxLength: 2048
+ api_key:
+ type: string
+ writeOnly: true
+ maxLength: 4096
+ reuse_saved_key:
+ type: boolean
+ ByokModel:
+ description: A model a BYOK endpoint lists.
+ type: object
+ additionalProperties: false
+ required: [id]
+ properties:
+ id:
+ type: string
+ minLength: 1
+ maxLength: 256
+ name:
+ description: The endpoint's display name, when it differs from id.
+ type: string
+ maxLength: 256
+ context_window:
+ type: integer
+ minimum: 1
+ maximum: 2147483647
+ ByokModelList:
+ description: The models a BYOK endpoint lists, sorted by id.
+ type: object
+ additionalProperties: false
+ required: [base_url, models]
+ properties:
+ base_url:
+ description: The address that listed them.
+ type: string
+ minLength: 1
+ maxLength: 2048
+ models:
+ type: array
+ maxItems: 1000
+ items:
+ $ref: "#/components/schemas/ByokModel"
+ ByokTestRequest:
+ description: >-
+ A BYOK endpoint to verify from the Computer for the Runtime that would
+ serve it, which decides the order wire formats are tried.
+ type: object
+ additionalProperties: false
+ required: [runtime, byok]
+ properties:
+ runtime:
+ $ref: "#/components/schemas/ModelSourceRuntime"
+ byok:
+ $ref: "#/components/schemas/ByokInput"
+ ByokSummary:
+ description: Redacted BYOK configuration metadata reported by the Computer.
+ type: object
+ additionalProperties: false
+ required: [configured, key_saved]
+ properties:
+ configured:
+ type: boolean
+ protocol:
+ $ref: "#/components/schemas/ByokProtocol"
+ base_url:
+ type: string
+ maxLength: 2048
+ model_id:
+ type: string
+ maxLength: 256
+ context_window:
+ type: integer
+ minimum: 1
+ maximum: 2147483647
+ key_saved:
+ type: boolean
+ ModelSourceStatus:
+ description: Active model source and redacted BYOK metadata on one Local Computer.
+ type: object
+ additionalProperties: false
+ required: [mode, runtime, runtime_model, byok]
+ properties:
+ mode:
+ $ref: "#/components/schemas/ModelSourceMode"
+ runtime:
+ $ref: "#/components/schemas/ModelSourceRuntime"
+ runtime_model:
+ description: >-
+ After a switch, the model the Computer's Agents run: the target
+ model when the active Runtime offers it, else that Runtime's
+ default.
+ type: string
+ maxLength: 256
+ reasoning_effort:
+ $ref: "./domain.yaml#/components/schemas/AgentReasoningEffort"
+ gateway_url:
+ type: string
+ maxLength: 2048
+ byok:
+ $ref: "#/components/schemas/ByokSummary"
+ ByokTestResult:
+ description: Outcome of probing an upstream BYOK endpoint from the Local Computer.
+ type: object
+ additionalProperties: false
+ required: [ok, protocol, base_url, model_id, context_window]
+ properties:
+ ok:
+ type: boolean
+ protocol:
+ $ref: "#/components/schemas/ByokProtocol"
+ base_url:
+ description: >-
+ The address that answered, which can add or drop the /anthropic of
+ a gateway that serves OpenAI under /v1 and Anthropic under
+ /anthropic.
+ type: string
+ minLength: 1
+ maxLength: 2048
+ model_id:
+ type: string
+ minLength: 1
+ maxLength: 256
+ context_window:
+ type: integer
+ minimum: 1
+ maximum: 2147483647
+ ModelSourceApplyCommand:
+ description: Internal command sent from TeamHub to Agent Service to switch a Computer's model source.
+ type: object
+ additionalProperties: false
+ required: [mode]
+ properties:
+ mode:
+ $ref: "#/components/schemas/ModelSourceMode"
+ runtime:
+ $ref: "#/components/schemas/ModelSourceRuntime"
+ local_model_id:
+ $ref: "./local-models.yaml#/components/schemas/LocalModelId"
+ byok:
+ $ref: "#/components/schemas/ByokInput"
+ ModelSourceSwitchRequest:
+ description: >-
+ Owner request to switch a Computer between local models, native
+ subscriptions, and BYOK on Bifrost. When active Runs exist on the
+ Computer's affected Agents and force_terminate is false, TeamHub
+ refuses with 409 AGENT_HAS_ACTIVE_RUNS; retrying with force_terminate
+ true terminates those Runs and applies the switch.
+ type: object
+ additionalProperties: false
+ required: [mode]
+ properties:
+ mode:
+ $ref: "#/components/schemas/ModelSourceMode"
+ runtime:
+ $ref: "#/components/schemas/ModelSourceRuntime"
+ local_model_id:
+ $ref: "./local-models.yaml#/components/schemas/LocalModelId"
+ byok:
+ $ref: "#/components/schemas/ByokInput"
+ force_terminate:
+ description: True ends running work on the Computer's Agents; absent means false.
+ type: boolean
+ ModelSourceView:
+ description: Current model source state of one Local Computer as viewed from Settings.
+ type: object
+ additionalProperties: false
+ required: [computer_id, viewer_is_owner, online]
+ properties:
+ computer_id:
+ $ref: "./common.yaml#/components/schemas/Id"
+ viewer_is_owner:
+ type: boolean
+ online:
+ type: boolean
+ status:
+ $ref: "#/components/schemas/ModelSourceStatus"
+ updated_agent_count:
+ type: integer
+ minimum: 0
+ terminated_run_count:
+ type: integer
+ minimum: 0
+ ModelSourceErrorCode:
+ description: >-
+ error.code of a refused model-source request (403, 409, 502, 503, 504);
+ 400, 401, and 404 use the common codes. LOCAL_COMPUTER_OFFLINE: the
+ Computer is not connected. MODEL_SOURCE_FORBIDDEN: the viewer is not
+ the Computer owner. MODEL_SOURCE_UNAVAILABLE: the Computer has no
+ localmodels tool or cannot switch model sources. AGENT_HAS_ACTIVE_RUNS:
+ Agents on the Computer have running work and force_terminate was
+ false; details carries one entry per such Agent, with field "agent"
+ and the Agent's display name as reason. RUNTIME_NOT_ENABLED,
+ LOCAL_MODEL_UNKNOWN, and the BYOK_ codes are the Computer's refusals
+ (409). MODEL_SOURCE_FAILED: the Computer failed with an error that has
+ no code of its own here (502). MODEL_SOURCE_SERVICE_UNAVAILABLE: Agent
+ Service could not be reached (503). MODEL_SOURCE_UNCONFIRMED: the
+ Computer had not answered by the deadline; it may still switch (504).
+ type: string
+ enum:
+ - LOCAL_COMPUTER_OFFLINE
+ - MODEL_SOURCE_FORBIDDEN
+ - MODEL_SOURCE_UNAVAILABLE
+ - AGENT_HAS_ACTIVE_RUNS
+ - RUNTIME_NOT_ENABLED
+ - LOCAL_MODEL_UNKNOWN
+ - BYOK_INVALID_CONFIG
+ - BYOK_AUTH_FAILED
+ - BYOK_MODEL_NOT_FOUND
+ - BYOK_UNREACHABLE
+ - BYOK_UPSTREAM_REJECTED
+ - MODEL_SOURCE_FAILED
+ - MODEL_SOURCE_SERVICE_UNAVAILABLE
+ - MODEL_SOURCE_UNCONFIRMED
+ x-enum-varnames:
+ - ModelSourceErrorCodeLocalComputerOffline
+ - ModelSourceErrorCodeModelSourceForbidden
+ - ModelSourceErrorCodeModelSourceUnavailable
+ - ModelSourceErrorCodeAgentHasActiveRuns
+ - ModelSourceErrorCodeRuntimeNotEnabled
+ - ModelSourceErrorCodeLocalModelUnknown
+ - ModelSourceErrorCodeByokInvalidConfig
+ - ModelSourceErrorCodeByokAuthFailed
+ - ModelSourceErrorCodeByokModelNotFound
+ - ModelSourceErrorCodeByokUnreachable
+ - ModelSourceErrorCodeByokUpstreamRejected
+ - ModelSourceErrorCodeModelSourceFailed
+ - ModelSourceErrorCodeModelSourceServiceUnavailable
+ - ModelSourceErrorCodeModelSourceUnconfirmed
+ ModelSourceError:
+ description: The common error body with error.code narrowed to ModelSourceErrorCode.
+ type: object
+ additionalProperties: false
+ required: [code, message, request_id]
+ properties:
+ code:
+ $ref: "#/components/schemas/ModelSourceErrorCode"
+ message:
+ type: string
+ minLength: 1
+ description: Human-readable summary safe to display; clients branch on code, not message.
+ request_id:
+ type: string
+ minLength: 1
+ maxLength: 128
+ details:
+ type: array
+ items:
+ $ref: "./common.yaml#/components/schemas/ErrorDetail"
+ ModelSourceErrorResponse:
+ type: object
+ additionalProperties: false
+ required: [error]
+ properties:
+ error:
+ $ref: "#/components/schemas/ModelSourceError"
diff --git a/contracts/openapi/linger-installer/openapi.yaml b/contracts/openapi/linger-installer/openapi.yaml
index aad31af5..f8bd9137 100644
--- a/contracts/openapi/linger-installer/openapi.yaml
+++ b/contracts/openapi/linger-installer/openapi.yaml
@@ -389,6 +389,25 @@ paths:
$ref: "#/components/schemas/ModelCheckReport"
"400": *a2
"401": *a3
+ /api/byok/check:
+ post:
+ operationId: checkInstallerByok
+ summary: Validate BYOK upstream endpoint via localmodels
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ByokConfiguration"
+ responses:
+ "200":
+ description: BYOK check result
+ content:
+ application/json:
+ schema:
+ $ref: "#/components/schemas/ByokCheckReport"
+ "400": *a2
+ "401": *a3
/api/runtime-login:
get:
operationId: inspectInstallerRuntimeLogin
@@ -636,6 +655,52 @@ components:
type: array
items:
$ref: "#/components/schemas/CheckResult"
+ ByokConfiguration:
+ type: object
+ additionalProperties: false
+ required:
+ - baseUrl
+ - modelId
+ properties:
+ baseUrl:
+ type: string
+ minLength: 1
+ maxLength: 2048
+ apiKey:
+ type: string
+ maxLength: 4096
+ modelId:
+ type: string
+ minLength: 1
+ maxLength: 256
+ contextWindow:
+ type: integer
+ minimum: 1
+ maximum: 2147483647
+ runtime:
+ type: string
+ enum: [claude, codex, pi]
+ ByokCheckReport:
+ type: object
+ additionalProperties: false
+ required:
+ - ok
+ - protocol
+ - baseUrl
+ - modelId
+ - contextWindow
+ properties:
+ ok:
+ type: boolean
+ protocol:
+ type: string
+ enum: [openai-chat, openai-responses, anthropic]
+ baseUrl: *a1
+ modelId: *a1
+ contextWindow:
+ type: integer
+ minimum: 1
+ maximum: 2147483647
LocalModelsAuthority:
type: object
additionalProperties: false
@@ -715,6 +780,8 @@ components:
description: Prepare a dependency without starting product services.
runtimeModel:
$ref: "#/components/schemas/ModelConfiguration"
+ byok:
+ $ref: "#/components/schemas/ByokConfiguration"
instance:
type: string
pattern: ^[a-z][a-z0-9-]{0,39}$
diff --git a/contracts/openapi/node-services-internal/openapi.yaml b/contracts/openapi/node-services-internal/openapi.yaml
index 0693498d..935277fc 100644
--- a/contracts/openapi/node-services-internal/openapi.yaml
+++ b/contracts/openapi/node-services-internal/openapi.yaml
@@ -244,6 +244,133 @@ paths:
$ref: ../components/common.yaml#/components/responses/ServiceUnavailable
security:
- agentManagementBearer: []
+ /v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/model-source:
+ parameters:
+ - $ref: "#/components/parameters/TenantId"
+ - $ref: "#/components/parameters/OwnerActorId"
+ - $ref: "#/components/parameters/ComputerId"
+ get:
+ summary: Read the active model source and redacted BYOK configuration of an owned Local Computer
+ operationId: getLocalComputerModelSource
+ responses:
+ "200":
+ description: Current model source status without secret API keys.
+ content:
+ application/json:
+ schema:
+ $ref: ../components/model-source.yaml#/components/schemas/ModelSourceStatus
+ "401":
+ $ref: ../components/common.yaml#/components/responses/Unauthenticated
+ "404":
+ $ref: ../components/common.yaml#/components/responses/NotFound
+ "409":
+ $ref: ../components/common.yaml#/components/responses/Conflict
+ "502":
+ $ref: ../components/common.yaml#/components/responses/BadGateway
+ "503":
+ $ref: ../components/common.yaml#/components/responses/ServiceUnavailable
+ security:
+ - agentManagementBearer: []
+ post:
+ summary: Switch the active model source on an owned Local Computer
+ operationId: applyLocalComputerModelSource
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: ../components/model-source.yaml#/components/schemas/ModelSourceApplyCommand
+ responses:
+ "200":
+ description: Updated model source status without secret API keys.
+ content:
+ application/json:
+ schema:
+ $ref: ../components/model-source.yaml#/components/schemas/ModelSourceStatus
+ "400":
+ $ref: ../components/common.yaml#/components/responses/BadRequest
+ "401":
+ $ref: ../components/common.yaml#/components/responses/Unauthenticated
+ "404":
+ $ref: ../components/common.yaml#/components/responses/NotFound
+ "409":
+ $ref: ../components/common.yaml#/components/responses/Conflict
+ "502":
+ $ref: ../components/common.yaml#/components/responses/BadGateway
+ "503":
+ $ref: ../components/common.yaml#/components/responses/ServiceUnavailable
+ security:
+ - agentManagementBearer: []
+ /v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/model-source/models:
+ parameters:
+ - $ref: "#/components/parameters/TenantId"
+ - $ref: "#/components/parameters/OwnerActorId"
+ - $ref: "#/components/parameters/ComputerId"
+ post:
+ summary: List the models a BYOK endpoint serves, from an owned Local Computer without saving credentials
+ operationId: listLocalComputerByokModels
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: ../components/model-source.yaml#/components/schemas/ByokEndpointInput
+ responses:
+ "200":
+ description: The endpoint's models.
+ content:
+ application/json:
+ schema:
+ $ref: ../components/model-source.yaml#/components/schemas/ByokModelList
+ "400":
+ $ref: ../components/common.yaml#/components/responses/BadRequest
+ "401":
+ $ref: ../components/common.yaml#/components/responses/Unauthenticated
+ "404":
+ $ref: ../components/common.yaml#/components/responses/NotFound
+ "409":
+ $ref: ../components/common.yaml#/components/responses/Conflict
+ "502":
+ $ref: ../components/common.yaml#/components/responses/BadGateway
+ "503":
+ $ref: ../components/common.yaml#/components/responses/ServiceUnavailable
+ security:
+ - agentManagementBearer: []
+ /v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/model-source/test:
+ parameters:
+ - $ref: "#/components/parameters/TenantId"
+ - $ref: "#/components/parameters/OwnerActorId"
+ - $ref: "#/components/parameters/ComputerId"
+ post:
+ summary: Verify a BYOK upstream endpoint from an owned Local Computer without saving credentials
+ operationId: testLocalComputerByok
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: ../components/model-source.yaml#/components/schemas/ByokTestRequest
+ responses:
+ "200":
+ description: BYOK verification result.
+ content:
+ application/json:
+ schema:
+ $ref: ../components/model-source.yaml#/components/schemas/ByokTestResult
+ "400":
+ $ref: ../components/common.yaml#/components/responses/BadRequest
+ "401":
+ $ref: ../components/common.yaml#/components/responses/Unauthenticated
+ "404":
+ $ref: ../components/common.yaml#/components/responses/NotFound
+ "409":
+ $ref: ../components/common.yaml#/components/responses/Conflict
+ "502":
+ $ref: ../components/common.yaml#/components/responses/BadGateway
+ "503":
+ $ref: ../components/common.yaml#/components/responses/ServiceUnavailable
+ security:
+ - agentManagementBearer: []
/v1/tenants/{tenantId}/owners/{ownerActorId}/local-computers/{computerId}/browser-connection:
parameters:
- $ref: "#/components/parameters/TenantId"
diff --git a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
index 26252f77..030e882b 100644
--- a/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
+++ b/contracts/openapi/teamhub-public/teamhub-api.openapi.yaml
@@ -810,6 +810,136 @@ paths:
$ref: '../components/local-models.yaml#/components/responses/LocalModelsRefused'
'504':
$ref: '../components/local-models.yaml#/components/responses/LocalModelsRefused'
+ /v0/tenants/{tenantId}/local-computers/{computerId}/model-source:
+ parameters:
+ - $ref: '#/components/parameters/TenantId'
+ - $ref: '#/components/parameters/ComputerId'
+ get:
+ tags: [Local Computers]
+ operationId: getLocalComputerModelSource
+ summary: Read the active model source and redacted BYOK configuration of one Local Computer.
+ responses:
+ '200':
+ description: Current model source view.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/model-source.yaml#/components/schemas/ModelSourceView'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
+ '502':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '503':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ post:
+ tags: [Local Computers]
+ operationId: switchLocalComputerModelSource
+ summary: Switch a Local Computer between local models, subscriptions, and BYOK on Bifrost.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../components/model-source.yaml#/components/schemas/ModelSourceSwitchRequest'
+ responses:
+ '200':
+ description: Switched model source view.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/model-source.yaml#/components/schemas/ModelSourceView'
+ '400':
+ $ref: '../components/common.yaml#/components/responses/BadRequest'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '403':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
+ '409':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '502':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '503':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '504':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ /v0/tenants/{tenantId}/local-computers/{computerId}/model-source/models:
+ parameters:
+ - $ref: '#/components/parameters/TenantId'
+ - $ref: '#/components/parameters/ComputerId'
+ post:
+ tags: [Local Computers]
+ operationId: listLocalComputerByokModels
+ summary: List the models a BYOK endpoint serves, asked from an owned Local Computer without saving anything.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../components/model-source.yaml#/components/schemas/ByokEndpointInput'
+ responses:
+ '200':
+ description: The endpoint's models.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/model-source.yaml#/components/schemas/ByokModelList'
+ '400':
+ $ref: '../components/common.yaml#/components/responses/BadRequest'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '403':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
+ '409':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '502':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '503':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '504':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ /v0/tenants/{tenantId}/local-computers/{computerId}/model-source/test:
+ parameters:
+ - $ref: '#/components/parameters/TenantId'
+ - $ref: '#/components/parameters/ComputerId'
+ post:
+ tags: [Local Computers]
+ operationId: testLocalComputerModelSource
+ summary: Verify a BYOK upstream endpoint from an owned Local Computer without saving credentials.
+ requestBody:
+ required: true
+ content:
+ application/json:
+ schema:
+ $ref: '../components/model-source.yaml#/components/schemas/ByokTestRequest'
+ responses:
+ '200':
+ description: BYOK verification result.
+ content:
+ application/json:
+ schema:
+ $ref: '../components/model-source.yaml#/components/schemas/ByokTestResult'
+ '400':
+ $ref: '../components/common.yaml#/components/responses/BadRequest'
+ '401':
+ $ref: '../components/common.yaml#/components/responses/Unauthenticated'
+ '403':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '404':
+ $ref: '../components/common.yaml#/components/responses/NotFound'
+ '409':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '502':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '503':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
+ '504':
+ $ref: '../components/model-source.yaml#/components/responses/ModelSourceRefused'
/v0/tenants/{tenantId}/local-computers/{computerId}/permissions:
parameters:
- $ref: '#/components/parameters/TenantId'
diff --git a/contracts/runner-gateway/asyncapi.yaml b/contracts/runner-gateway/asyncapi.yaml
index 49787ebd..6b76609b 100644
--- a/contracts/runner-gateway/asyncapi.yaml
+++ b/contracts/runner-gateway/asyncapi.yaml
@@ -21,7 +21,7 @@ info:
prepared (target operation or provider), cancel (target operation or
model_invoke), execute and executed (kind session_compact, model_invoke,
computer_tool, skills_scan, browser_connect, computer_permission,
- local_models, debug_history or
+ local_models, model_source, debug_history or
cli_credential), agent_runner.state (state ready, removed or failed) and
operation.input_result (outcome accepted, rejected or closed); the
Operation family carries operation.start, operation.input, operation.ack,
diff --git a/contracts/runner-gateway/envelope.schema.json b/contracts/runner-gateway/envelope.schema.json
index 59dfdbac..f67314e2 100644
--- a/contracts/runner-gateway/envelope.schema.json
+++ b/contracts/runner-gateway/envelope.schema.json
@@ -47,6 +47,9 @@
{
"$ref": "#/$defs/CapabilityLocalModelsExecute"
},
+ {
+ "$ref": "#/$defs/CapabilityModelSource"
+ },
{
"$ref": "#/$defs/OperationPrepare"
},
@@ -138,6 +141,12 @@
{
"$ref": "#/$defs/CapabilityLocalModelsRefused"
},
+ {
+ "$ref": "#/$defs/CapabilityModelSourceSucceeded"
+ },
+ {
+ "$ref": "#/$defs/CapabilityModelSourceFailed"
+ },
{
"$ref": "#/$defs/OperationPrepared"
},
@@ -1680,6 +1689,261 @@
}
]
},
+ "ByokConfigInput": {
+ "description": "A BYOK endpoint; model_id is required except to list the endpoint's models.",
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["base_url"],
+ "properties": {
+ "base_url": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2048
+ },
+ "api_key": {
+ "type": "string",
+ "maxLength": 4096
+ },
+ "model_id": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256
+ },
+ "context_window": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 2147483647
+ },
+ "reuse_saved_key": {
+ "type": "boolean"
+ }
+ }
+ },
+ "ByokSummary": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["configured", "key_saved"],
+ "properties": {
+ "configured": {
+ "type": "boolean"
+ },
+ "protocol": {
+ "enum": ["openai-chat", "openai-responses", "anthropic"]
+ },
+ "base_url": {
+ "type": "string",
+ "maxLength": 2048
+ },
+ "model_id": {
+ "type": "string",
+ "maxLength": 256
+ },
+ "context_window": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 2147483647
+ },
+ "key_saved": {
+ "type": "boolean"
+ }
+ }
+ },
+ "ModelSourceStatus": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["mode", "runtime", "runtime_model", "byok"],
+ "properties": {
+ "mode": {
+ "enum": ["local", "subscription", "byok"]
+ },
+ "runtime": {
+ "enum": ["claude", "codex", "pi"]
+ },
+ "runtime_model": {
+ "description": "After apply, the model the Computer's Agents run: the target model when the active Runtime offers it, else that Runtime's default.",
+ "type": "string",
+ "maxLength": 256
+ },
+ "reasoning_effort": {
+ "description": "After apply, the reasoning effort runtime_model needs; absent when it offers none.",
+ "enum": ["none", "low", "medium", "high", "xhigh", "max", "ultra"]
+ },
+ "gateway_url": {
+ "type": "string",
+ "maxLength": 2048
+ },
+ "byok": {
+ "$ref": "#/$defs/ByokSummary"
+ }
+ }
+ },
+ "ByokModelList": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["base_url", "models"],
+ "properties": {
+ "base_url": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2048
+ },
+ "models": {
+ "type": "array",
+ "maxItems": 1000,
+ "items": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["id"],
+ "properties": {
+ "id": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256
+ },
+ "name": {
+ "type": "string",
+ "maxLength": 256
+ },
+ "context_window": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 2147483647
+ }
+ }
+ }
+ }
+ }
+ },
+ "ByokTestResult": {
+ "type": "object",
+ "additionalProperties": false,
+ "required": ["ok", "protocol", "base_url", "model_id", "context_window"],
+ "properties": {
+ "ok": {
+ "type": "boolean"
+ },
+ "protocol": {
+ "enum": ["openai-chat", "openai-responses", "anthropic"]
+ },
+ "base_url": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 2048
+ },
+ "model_id": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 256
+ },
+ "context_window": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 2147483647
+ }
+ }
+ },
+ "CapabilityModelSource": {
+ "type": "object",
+ "unevaluatedProperties": false,
+ "allOf": [
+ {
+ "$ref": "#/$defs/LocalSkillCommandIdentity"
+ },
+ {
+ "type": "object",
+ "required": ["type", "kind", "action"],
+ "properties": {
+ "type": {
+ "const": "execute"
+ },
+ "kind": {
+ "const": "model_source"
+ },
+ "action": {
+ "enum": ["status", "test", "models", "apply"]
+ },
+ "mode": {
+ "enum": ["local", "subscription", "byok"]
+ },
+ "runtime": {
+ "enum": ["claude", "codex", "pi"]
+ },
+ "local_model_id": {
+ "$ref": "#/$defs/LocalModelId"
+ },
+ "byok": {
+ "$ref": "#/$defs/ByokConfigInput"
+ }
+ }
+ }
+ ]
+ },
+ "CapabilityModelSourceSucceeded": {
+ "type": "object",
+ "unevaluatedProperties": false,
+ "allOf": [
+ {
+ "$ref": "#/$defs/LocalSkillCommandIdentity"
+ },
+ {
+ "type": "object",
+ "required": ["type", "kind", "action", "outcome"],
+ "properties": {
+ "type": {
+ "const": "executed"
+ },
+ "kind": {
+ "const": "model_source"
+ },
+ "action": {
+ "enum": ["status", "test", "models", "apply"]
+ },
+ "outcome": {
+ "const": "succeeded"
+ },
+ "status": {
+ "$ref": "#/$defs/ModelSourceStatus"
+ },
+ "test_result": {
+ "$ref": "#/$defs/ByokTestResult"
+ },
+ "model_list": {
+ "$ref": "#/$defs/ByokModelList"
+ }
+ }
+ }
+ ]
+ },
+ "CapabilityModelSourceFailed": {
+ "type": "object",
+ "unevaluatedProperties": false,
+ "allOf": [
+ {
+ "$ref": "#/$defs/LocalSkillCommandIdentity"
+ },
+ {
+ "type": "object",
+ "required": ["type", "kind", "action", "error", "outcome"],
+ "properties": {
+ "type": {
+ "const": "executed"
+ },
+ "kind": {
+ "const": "model_source"
+ },
+ "action": {
+ "enum": ["status", "test", "models", "apply"]
+ },
+ "error": {
+ "$ref": "#/$defs/AgentRunnerError"
+ },
+ "outcome": {
+ "const": "failed"
+ }
+ }
+ }
+ ]
+ },
"ComputerPermissionStatus": {
"description": "The macOS privacy permissions of this Computer. Other platforms report no subjects.",
"type": "object",
diff --git a/docs/local-inference.md b/docs/local-inference.md
index c2828173..e20e2166 100644
--- a/docs/local-inference.md
+++ b/docs/local-inference.md
@@ -13,6 +13,28 @@ install sets up a language model, and it stays quick even on a fanless laptop.
How agents, approvals and background work share a model is in
[Model scheduling](model-scheduling.md).
+## Model source
+
+Each computer serves all of its agents from one source at a time. Setup asks
+for it, and **Settings › Models** switches it later.
+
+| Source | Runtime | Where the model runs |
+| ------------ | ------------------------ | ------------------------------------------------------------------------------------------ |
+| Local model | Pi | A model loaded on this computer, through the local gateway |
+| Subscription | Claude Code or Codex | The plan the runtime is signed in to, with its own settings |
+| BYOK | Claude Code, Codex or Pi | Your own OpenAI-compatible or Anthropic endpoint, key and model, through the local gateway |
+
+For BYOK you enter only the URL and key, then pick a model from the ones the
+endpoint lists, with their names and context windows; you type the model ID
+when the endpoint lists none. The computer finds which API format the endpoint
+answers, trying the runtime's own format first so the gateway passes its
+requests through unchanged. A gateway that serves OpenAI under `/v1` and
+Anthropic under `/anthropic` on one host works from either address. The key stays on the computer in
+an owner-only file; the server never stores or shows it. A switch moves every agent on the computer to the new runtime and
+model, and leaving Local model unloads the local models to free memory. When an
+agent is still working, the switch asks first and ends that work only if you
+confirm.
+
## Planning
The planner chooses hardware and model settings together: layer by layer, the
diff --git a/docs/self-hosting.md b/docs/self-hosting.md
index 2507a589..d4f05be4 100644
--- a/docs/self-hosting.md
+++ b/docs/self-hosting.md
@@ -22,9 +22,9 @@ printf '%s\n' 'choose-a-password' | docker compose exec -T teamhub \
Open <http://localhost:3000> and sign in. The app then shows the commands that
connect your computer, and it opens once Claude Code, Codex or Pi is installed
-and signed in there. With Pi and no model yet, open Settings › Local models
-from that screen and load one; Settings stays reachable while the rest of the
-app waits.
+and signed in there. With Pi and no model yet, open Settings › Models from
+that screen and load one; Settings stays reachable while the rest of the app
+waits.
To serve other computers on your network, set these in `.env`, run
`docker compose stop node-services`, then run
diff --git a/packages/local-installation/AGENTS.md b/packages/local-installation/AGENTS.md
index 28f695b0..03e51376 100644
--- a/packages/local-installation/AGENTS.md
+++ b/packages/local-installation/AGENTS.md
@@ -106,6 +106,12 @@ existing Computer is rebound once on its next connect. A distribution without
the tool writes none. External Computers (the Desktop's) get the same paths as
the `LINGER_LOCALMODELS_*` keys of the installer's instance runtime.
+Setup sets the Computer's model source through `localmodels source apply`
+(`byok-source.ts`): BYOK after the Runtime is ready, a local model after the
+stack is, and a subscription after its Runtime installs, signed in or not.
+The installer reads `model-source.json` (`readByokEnvironment`) but never
+writes it.
+
Each native service runs under a detached supervisor
(`native-process-worker.mjs`) whose record holds its PID, birth and an
unguessable lease. POSIX finds the service's processes by process group and
diff --git a/packages/local-installation/src/byok-source.test.ts b/packages/local-installation/src/byok-source.test.ts
new file mode 100644
index 00000000..d008c49a
--- /dev/null
+++ b/packages/local-installation/src/byok-source.test.ts
@@ -0,0 +1,216 @@
+import fs from "node:fs/promises";
+import os from "node:os";
+import path from "node:path";
+import { afterEach, describe, expect, it, vi } from "vitest";
+import {
+ checkByokEndpoint,
+ isAllowedByokUrl,
+ prepareByokRuntime,
+ applyNativeSource,
+ readByokEnvironment,
+ validateByokConfiguration,
+} from "./byok-source.js";
+import { atomicPrivate, privateDirectory } from "./instance.js";
+
+const tempDirs: string[] = [];
+
+async function makeHome(): Promise<string> {
+ const dir = await fs.mkdtemp(path.join(os.tmpdir(), "linger-byok-test-"));
+ tempDirs.push(dir);
+ return dir;
+}
+
+afterEach(async () => {
+ await Promise.all(
+ tempDirs
+ .splice(0)
+ .map((dir) => fs.rm(dir, { recursive: true, force: true })),
+ );
+});
+
+describe("isAllowedByokUrl", () => {
+ it("allows HTTPS and private LAN/loopback HTTP endpoints", () => {
+ expect(isAllowedByokUrl("https://api.openai.com/v1/")).toBe(true);
+ expect(isAllowedByokUrl("http://127.0.0.1:8000/v1")).toBe(true);
+ expect(isAllowedByokUrl("http://192.168.10.117:8080/v1")).toBe(true);
+ expect(isAllowedByokUrl("http://100.88.1.5:11434/v1")).toBe(true);
+ expect(
+ validateByokConfiguration({
+ baseUrl: "https://api.openai.com/v1/",
+ modelId: "gpt-5.4",
+ }).baseUrl,
+ ).toBe("https://api.openai.com/v1");
+ });
+
+ it("blocks link-local metadata, public HTTP, and URL credentials", () => {
+ expect(isAllowedByokUrl("http://169.254.169.254/latest/meta-data")).toBe(
+ false,
+ );
+ expect(isAllowedByokUrl("https://metadata.google.internal/v1")).toBe(false);
+ expect(isAllowedByokUrl("http://api.example.com/v1")).toBe(false);
+ expect(isAllowedByokUrl("https://[email protected]/v1")).toBe(false);
+ });
+});
+
+describe("BYOK localmodels integration", () => {
+ it("passes BYOK secrets over stdin and never in argv", async () => {
+ const home = await makeHome();
+ const calls: { args: string[]; input?: string }[] = [];
+ const fakeLocalmodels = vi.fn(
+ async (
+ _home: string,
+ args: string[],
+ options: { input?: string } = {},
+ ) => {
+ calls.push({ args, input: options.input });
+ return {
+ code: 0,
+ stdout: JSON.stringify({
+ ok: true,
+ protocol: "openai-responses",
+ base_url: "https://api.example.com/v1",
+ model_id: "gpt-5.4",
+ context_window: 200_000,
+ }),
+ stderr: "",
+ };
+ },
+ );
+ const report = await checkByokEndpoint(
+ home,
+ {
+ baseUrl: "https://api.example.com/v1",
+ apiKey: "sk-private-secret",
+ modelId: "gpt-5.4",
+ runtime: "codex",
+ },
+ new AbortController().signal,
+ { localmodels: fakeLocalmodels },
+ );
+ expect(report).toEqual({
+ ok: true,
+ protocol: "openai-responses",
+ baseUrl: "https://api.example.com/v1",
+ modelId: "gpt-5.4",
+ contextWindow: 200_000,
+ });
+ expect(calls).toHaveLength(1);
+ expect(calls[0]!.args.join(" ")).not.toContain("sk-private-secret");
+ expect(calls[0]!.args).toContain("--config-stdin");
+ expect(calls[0]!.args.join(" ")).toContain("--runtime codex");
+ expect(JSON.parse(calls[0]!.input!)).toMatchObject({
+ apiKey: "sk-private-secret",
+ modelId: "gpt-5.4",
+ });
+ });
+
+ it("mounts BYOK on Bifrost even when native runtime lacks vendor OAuth", async () => {
+ const home = await makeHome();
+ const outcome = await prepareByokRuntime(
+ {
+ baseUrl: "https://api.anthropic.com",
+ apiKey: "sk-ant-test",
+ modelId: "claude-sonnet-4-6",
+ runtime: "claude",
+ },
+ {
+ home,
+ signal: new AbortController().signal,
+ onEvent: () => {},
+ },
+ {
+ prepareNative: async () => ({
+ code: 1,
+ state: "waiting_user",
+ message: "Login required",
+ details: { code: "RUNTIME_AUTH_REQUIRED" },
+ }),
+ localmodels: async () => ({
+ code: 0,
+ stdout: JSON.stringify({ ok: true }),
+ stderr: "",
+ }),
+ },
+ );
+ expect(outcome.code).toBe(0);
+ expect(outcome.state).toBe("ready");
+ });
+
+ it("sets a subscription source through localmodels, never writing it itself", async () => {
+ const home = await makeHome();
+ const calls: string[][] = [];
+ const outcome = await applyNativeSource(
+ home,
+ "subscription",
+ "codex",
+ new AbortController().signal,
+ {
+ localmodels: async (_home, args) => {
+ calls.push(args);
+ return { code: 0, stdout: "{}", stderr: "" };
+ },
+ },
+ );
+ expect(outcome).toBeUndefined();
+ expect(calls).toHaveLength(1);
+ expect(calls[0]!.slice(0, 6)).toEqual([
+ "source",
+ "apply",
+ "--mode",
+ "subscription",
+ "--runtime",
+ "codex",
+ ]);
+ expect(calls[0]).not.toContain("--config-stdin");
+ expect(await readByokEnvironment(home)).toBeUndefined();
+ });
+
+ it("reports what localmodels refused when setting a source", async () => {
+ const outcome = await applyNativeSource(
+ await makeHome(),
+ "local",
+ "pi",
+ new AbortController().signal,
+ {
+ localmodels: async () => ({
+ code: 2,
+ stdout: JSON.stringify({
+ code: "MODEL_UNKNOWN",
+ message: "No model is loaded.",
+ }),
+ stderr: "",
+ }),
+ },
+ );
+ expect(outcome).toEqual({
+ code: 1,
+ state: "failed",
+ message: "No model is loaded.",
+ details: { code: "MODEL_UNKNOWN" },
+ });
+ });
+
+ it("reads the runtime environment overrides localmodels recorded", async () => {
+ const home = await makeHome();
+ const state = path.join(home, "runtime", "localmodels", "state");
+ await privateDirectory(state);
+ await atomicPrivate(
+ path.join(state, "model-source.json"),
+ JSON.stringify({
+ schema: "localmodels.model-source/v1",
+ mode: "byok",
+ runtime: "pi",
+ runtime_model: "localmodels-byok",
+ model_label: "vendor/model",
+ gateway_url: "http://127.0.0.1:18480",
+ environment: { PI_CODING_AGENT_DIR: "/abs/pi", OTHER: "/ignored" },
+ }),
+ );
+ expect(await readByokEnvironment(home)).toEqual({
+ mode: "byok",
+ runtime: "pi",
+ runtimeModel: "localmodels-byok",
+ environment: { PI_CODING_AGENT_DIR: "/abs/pi" },
+ });
+ });
+});
diff --git a/packages/local-installation/src/byok-source.ts b/packages/local-installation/src/byok-source.ts
new file mode 100644
index 00000000..3cc5e480
--- /dev/null
+++ b/packages/local-installation/src/byok-source.ts
@@ -0,0 +1,412 @@
+import path from "node:path";
+import { readPrivate } from "./instance.js";
+import {
+ localmodelsBaseDirectory,
+ localmodelsStateDirectory,
+ runLocalmodels,
+} from "./localmodels-tool.js";
+import { prepareRuntime, type NativeRuntime } from "./managed-runtimes.js";
+import type { InstallOutcome, InstallerEvent } from "./events.js";
+
+export type ByokProtocol = "openai-chat" | "openai-responses" | "anthropic";
+
+export interface ByokConfiguration {
+ baseUrl: string;
+ apiKey?: string;
+ modelId: string;
+ contextWindow?: number;
+ runtime?: NativeRuntime;
+}
+
+export interface ByokCheckOutcome {
+ ok: true;
+ protocol: ByokProtocol;
+ baseUrl: string;
+ modelId: string;
+ contextWindow: number;
+}
+
+interface StoredModelSource {
+ schema: "localmodels.model-source/v1";
+ mode: "local" | "subscription" | "byok";
+ runtime: NativeRuntime;
+ runtime_model: string;
+ model_label: string | null;
+ gateway_url: string | null;
+ environment: Record<string, string>;
+}
+
+const PRIVATE_HOST_IPV4 =
+ /^(?:127\.\d{1,3}\.\d{1,3}\.\d{1,3}|10\.\d{1,3}\.\d{1,3}\.\d{1,3}|192\.168\.\d{1,3}\.\d{1,3}|172\.(?:1[6-9]|2\d|3[01])\.\d{1,3}\.\d{1,3}|100\.(?:6[4-9]|[7-9]\d|1[01]\d|12[0-7])\.\d{1,3}\.\d{1,3})$/;
+
+export function isAllowedByokUrl(raw: string): boolean {
+ try {
+ const url = new URL(raw.trim());
+ if (
+ (url.protocol !== "https:" && url.protocol !== "http:") ||
+ !url.hostname ||
+ url.username ||
+ url.password ||
+ url.search ||
+ url.hash
+ )
+ return false;
+ const host = url.hostname.toLowerCase().replace(/^\[\s*|\s*\]$/g, "");
+ if (
+ host === "0.0.0.0" ||
+ host === "::" ||
+ host === "metadata.google.internal" ||
+ host.startsWith("169.254.") ||
+ host.startsWith("fe80:")
+ )
+ return false;
+ if (url.protocol === "https:") return true;
+ return (
+ host === "localhost" ||
+ host === "::1" ||
+ host.endsWith(".local") ||
+ !host.includes(".") ||
+ PRIVATE_HOST_IPV4.test(host)
+ );
+ } catch {
+ return false;
+ }
+}
+
+export function validateByokConfiguration(value: unknown): ByokConfiguration {
+ if (!value || typeof value !== "object" || Array.isArray(value))
+ throw new Error("Invalid BYOK configuration.");
+ const record = value as Record<string, unknown>;
+ for (const key of Object.keys(record))
+ if (
+ !["baseUrl", "apiKey", "modelId", "contextWindow", "runtime"].includes(
+ key,
+ )
+ )
+ throw new Error("Invalid BYOK configuration.");
+ if (
+ typeof record.baseUrl !== "string" ||
+ record.baseUrl.length > 2048 ||
+ !isAllowedByokUrl(record.baseUrl)
+ )
+ throw new Error(
+ "Endpoint URL must use HTTPS, or HTTP on localhost / a private network.",
+ );
+ if (
+ typeof record.modelId !== "string" ||
+ !/^[-a-zA-Z0-9_./:@]{1,256}$/.test(record.modelId.trim())
+ )
+ throw new Error("Model ID is invalid.");
+ const apiKey = record.apiKey;
+ if (
+ apiKey !== undefined &&
+ (typeof apiKey !== "string" ||
+ apiKey.length > 4096 ||
+ [...apiKey].some((c) => c.charCodeAt(0) <= 32 || c.charCodeAt(0) === 127))
+ )
+ throw new Error("API key format is invalid.");
+ const contextWindow = record.contextWindow;
+ if (
+ contextWindow !== undefined &&
+ (!Number.isSafeInteger(contextWindow) ||
+ Number(contextWindow) < 1 ||
+ Number(contextWindow) > 2_147_483_647)
+ )
+ throw new Error("Context window must be a positive integer.");
+ const runtime = record.runtime;
+ if (
+ runtime !== undefined &&
+ runtime !== "claude" &&
+ runtime !== "codex" &&
+ runtime !== "pi"
+ )
+ throw new Error("Invalid BYOK runtime selection.");
+ return {
+ baseUrl: record.baseUrl.trim().replace(/\/+$/, ""),
+ ...(apiKey !== undefined ? { apiKey } : {}),
+ modelId: record.modelId.trim(),
+ ...(contextWindow !== undefined
+ ? { contextWindow: Number(contextWindow) }
+ : {}),
+ ...(runtime !== undefined ? { runtime } : {}),
+ };
+}
+
+// The API key travels on stdin, never in argv.
+function byokStdin(config: ByokConfiguration): string {
+ return JSON.stringify({
+ baseUrl: config.baseUrl,
+ ...(config.apiKey !== undefined ? { apiKey: config.apiKey } : {}),
+ modelId: config.modelId,
+ ...(config.contextWindow !== undefined
+ ? { contextWindow: config.contextWindow }
+ : {}),
+ });
+}
+
+function isByokProtocol(value: unknown): value is ByokProtocol {
+ return (
+ value === "openai-chat" ||
+ value === "openai-responses" ||
+ value === "anthropic"
+ );
+}
+
+/**
+ * Verifies the endpoint from this computer and finds the wire format it
+ * answers, trying the runtime's own format first.
+ */
+export async function checkByokEndpoint(
+ home: string,
+ config: ByokConfiguration,
+ signal: AbortSignal,
+ dependencies: { localmodels?: typeof runLocalmodels } = {},
+): Promise<ByokCheckOutcome> {
+ const validated = validateByokConfiguration(config);
+ signal.throwIfAborted();
+ const result = await (dependencies.localmodels ?? runLocalmodels)(
+ home,
+ [
+ "source",
+ "check",
+ "--config-stdin",
+ "--runtime",
+ validated.runtime ?? "claude",
+ "--json",
+ ],
+ { signal, timeoutMs: 45_000, input: byokStdin(validated) },
+ );
+ let parsed: Record<string, unknown> | undefined;
+ try {
+ parsed = JSON.parse(result.stdout) as Record<string, unknown>;
+ } catch {
+ parsed = undefined;
+ }
+ if (
+ result.code !== 0 ||
+ parsed?.ok !== true ||
+ !isByokProtocol(parsed.protocol)
+ ) {
+ const message =
+ typeof parsed?.message === "string" && parsed.message
+ ? parsed.message
+ : "Could not verify the BYOK endpoint. Check the URL, API key, model ID and network.";
+ const code =
+ typeof parsed?.code === "string" ? parsed.code : "BYOK_CHECK_FAILED";
+ throw Object.assign(new Error(message), { code });
+ }
+ return {
+ ok: true,
+ protocol: parsed.protocol,
+ baseUrl:
+ typeof parsed.base_url === "string" ? parsed.base_url : validated.baseUrl,
+ modelId:
+ typeof parsed.model_id === "string" ? parsed.model_id : validated.modelId,
+ contextWindow:
+ typeof parsed.context_window === "number" && parsed.context_window > 0
+ ? parsed.context_window
+ : (validated.contextWindow ?? 131_072),
+ };
+}
+
+// The installer switches the source through localmodels, as the Computer
+// does from Settings, so model-source.json has one writer.
+function applySource(
+ home: string,
+ mode: "local" | "subscription" | "byok",
+ runtime: NativeRuntime,
+ options: { signal: AbortSignal; timeoutMs: number; input?: string },
+ localmodels: typeof runLocalmodels,
+) {
+ return localmodels(
+ home,
+ [
+ "source",
+ "apply",
+ "--mode",
+ mode,
+ "--runtime",
+ runtime,
+ "--base-dir",
+ localmodelsBaseDirectory(home),
+ "--harness-root",
+ path.join(path.resolve(home), "runtime", "harness"),
+ "--node",
+ process.execPath,
+ ...(options.input === undefined ? [] : ["--config-stdin"]),
+ "--json",
+ ],
+ {
+ signal: options.signal,
+ timeoutMs: options.timeoutMs,
+ ...(options.input === undefined ? {} : { input: options.input }),
+ },
+ );
+}
+
+function sourceApplyFailure(
+ stdout: string,
+ message: string,
+ code: string,
+): InstallOutcome {
+ let detail = message;
+ let detailCode = code;
+ try {
+ const errDoc = JSON.parse(stdout) as { message?: unknown; code?: unknown };
+ if (typeof errDoc.message === "string" && errDoc.message)
+ detail = errDoc.message;
+ if (typeof errDoc.code === "string" && errDoc.code)
+ detailCode = errDoc.code;
+ } catch {
+ /* Non-JSON tool output stays private. */
+ }
+ return {
+ code: 1,
+ state: "failed",
+ message: detail,
+ details: { code: detailCode },
+ };
+}
+
+export async function prepareByokRuntime(
+ config: ByokConfiguration,
+ options: {
+ home: string;
+ signal: AbortSignal;
+ onEvent: (event: InstallerEvent) => void;
+ env?: NodeJS.ProcessEnv;
+ },
+ dependencies: {
+ localmodels?: typeof runLocalmodels;
+ prepareNative?: typeof prepareRuntime;
+ } = {},
+): Promise<InstallOutcome> {
+ const validated = validateByokConfiguration(config);
+ const runtime = validated.runtime ?? "claude";
+ const nativeOutcome = await (dependencies.prepareNative ?? prepareRuntime)(
+ runtime,
+ {
+ home: options.home,
+ signal: options.signal,
+ onEvent: options.onEvent,
+ env: options.env,
+ },
+ dependencies.localmodels ? { localmodels: dependencies.localmodels } : {},
+ );
+ if (
+ nativeOutcome.code !== 0 &&
+ (nativeOutcome.details as { code?: string } | undefined)?.code !==
+ "RUNTIME_AUTH_REQUIRED"
+ )
+ return nativeOutcome;
+
+ options.onEvent({
+ kind: "stage",
+ stage: "runtime",
+ state: "running",
+ message: "Mounting BYOK endpoint on local Bifrost gateway…",
+ });
+ const result = await applySource(
+ options.home,
+ "byok",
+ runtime,
+ {
+ signal: options.signal,
+ timeoutMs: 180_000,
+ input: byokStdin(validated),
+ },
+ dependencies.localmodels ?? runLocalmodels,
+ );
+ if (result.code !== 0)
+ return sourceApplyFailure(
+ result.stdout,
+ "BYOK gateway configuration failed. Check the endpoint settings and retry.",
+ "BYOK_GATEWAY_FAILED",
+ );
+ options.onEvent({
+ kind: "stage",
+ stage: "runtime",
+ state: "succeeded",
+ message: "BYOK gateway and runtime profiles are ready.",
+ });
+ return {
+ code: 0,
+ state: "ready",
+ message: "BYOK gateway and runtime profiles are ready.",
+ };
+}
+
+/**
+ * Makes a local-model or subscription setup the Computer's model source, which
+ * also ends a BYOK source left from an earlier setup. Returns a failed outcome
+ * when localmodels refuses.
+ */
+export async function applyNativeSource(
+ home: string,
+ mode: "local" | "subscription",
+ runtime: NativeRuntime,
+ signal: AbortSignal,
+ dependencies: { localmodels?: typeof runLocalmodels } = {},
+): Promise<InstallOutcome | undefined> {
+ const result = await applySource(
+ home,
+ mode,
+ runtime,
+ { signal, timeoutMs: 180_000 },
+ dependencies.localmodels ?? runLocalmodels,
+ );
+ return result.code === 0
+ ? undefined
+ : sourceApplyFailure(
+ result.stdout,
+ "Could not set the model source. Retry setup.",
+ "MODEL_SOURCE_FAILED",
+ );
+}
+
+export async function readByokEnvironment(home: string): Promise<
+ | {
+ mode: "local" | "subscription" | "byok";
+ runtime: NativeRuntime;
+ runtimeModel: string;
+ environment: Record<string, string>;
+ }
+ | undefined
+> {
+ try {
+ const raw = await readPrivate(
+ path.join(localmodelsStateDirectory(home), "model-source.json"),
+ );
+ if (!raw) return undefined;
+ const parsed = JSON.parse(raw) as Partial<StoredModelSource>;
+ if (
+ parsed.schema !== "localmodels.model-source/v1" ||
+ !parsed.mode ||
+ !["local", "subscription", "byok"].includes(parsed.mode) ||
+ !parsed.runtime ||
+ !["claude", "codex", "pi"].includes(parsed.runtime)
+ )
+ return undefined;
+ const environment: Record<string, string> = {};
+ if (parsed.environment && typeof parsed.environment === "object") {
+ for (const key of [
+ "CODEX_HOME",
+ "CLAUDE_CONFIG_DIR",
+ "PI_CODING_AGENT_DIR",
+ ]) {
+ const val = parsed.environment[key];
+ if (typeof val === "string" && path.isAbsolute(val))
+ environment[key] = val;
+ }
+ }
+ return {
+ mode: parsed.mode,
+ runtime: parsed.runtime,
+ runtimeModel:
+ typeof parsed.runtime_model === "string" ? parsed.runtime_model : "",
+ environment,
+ };
+ } catch {
+ return undefined;
+ }
+}
diff --git a/packages/local-installation/src/computer.ts b/packages/local-installation/src/computer.ts
index e9a8ff7f..9179837a 100644
--- a/packages/local-installation/src/computer.ts
+++ b/packages/local-installation/src/computer.ts
@@ -6,6 +6,7 @@ import { atomicPrivate, readPrivate, type Instance } from "./instance.js";
import { runProcess } from "./process.js";
import path from "node:path";
import { localModelsEnvironment } from "./local-models.js";
+import { readByokEnvironment } from "./byok-source.js";
import {
localModelsConfig,
localModelsLoginArguments,
@@ -96,13 +97,13 @@ async function environment(instance: Instance): Promise<NodeJS.ProcessEnv> {
]);
for (const key of Object.keys(inherited))
if (explicit.has(key.toUpperCase())) delete inherited[key];
+ const home = path.resolve(instance.root, "../..");
+ const byok = await readByokEnvironment(home);
return {
...inherited,
- ...(await managedRuntimeEnvironment(
- path.resolve(instance.root, "../.."),
- instance.root,
- )),
+ ...(await managedRuntimeEnvironment(home, instance.root)),
...(await localModelsEnvironment(instance)),
+ ...(byok?.mode === "byok" ? byok.environment : {}),
PATH: await runtimePath(instance),
LINGER_COMPUTER_INSECURE_DEVELOPMENT_ORIGIN: instance.origin,
};
@@ -225,12 +226,15 @@ export async function inspectComputer(
return inspectInstanceComputer(instance, options);
}
async function managedRuntimeState(instance: Instance) {
+ const home = path.resolve(instance.root, "../..");
const descriptors = await inspectSelectedRuntimeDescriptors(
- path.resolve(instance.root, "../.."),
+ home,
instance.root,
);
const managed = runtimeEnvironmentFromDescriptors(descriptors);
Object.assign(managed, await localModelsEnvironment(instance));
+ const byok = await readByokEnvironment(home);
+ if (byok?.mode === "byok") Object.assign(managed, byok.environment);
managed.PATH = await runtimePath(instance);
// Part of the fingerprint, so an install from before the Computer knew
// its localmodels tool is rebound once on its next connect.
diff --git a/packages/local-installation/src/model-gateway.ts b/packages/local-installation/src/model-gateway.ts
index 4e2995dc..a0edc65c 100644
--- a/packages/local-installation/src/model-gateway.ts
+++ b/packages/local-installation/src/model-gateway.ts
@@ -91,15 +91,27 @@ export async function prepareModelGateway(
},
dependencies: Dependencies = {},
): Promise<void> {
- if (setupSelection(choice).modelSource !== "local")
+ const source = setupSelection(choice).modelSource;
+ if (source !== "local" && source !== "byok")
return retireModelGateway(instance, options, dependencies);
- // The SDK controller fronts the approved stack's existing Magpie catalog.
+ // The SDK controller fronts the approved stack or BYOK Bifrost catalog.
const raw = await readPrivate(
path.join(instance.root, "model-services.json"),
);
- if (!raw)
+ if (!raw) {
+ if (source === "byok") return;
throw new Error("The local stack application gateway is not prepared.");
- const binding = validateLocal(instance, JSON.parse(raw));
+ }
+ const parsed = JSON.parse(raw) as unknown;
+ if (
+ source === "byok" &&
+ parsed &&
+ typeof parsed === "object" &&
+ "state" in parsed &&
+ (parsed as { state?: unknown }).state === "unavailable"
+ )
+ return;
+ const binding = validateLocal(instance, parsed);
await validateLocalKey(instance, binding);
await atomicPrivate(descriptorFile(instance), JSON.stringify(binding));
}
diff --git a/packages/local-installation/src/native-source-flow.test.ts b/packages/local-installation/src/native-source-flow.test.ts
index c0ed0ef2..8f530f1e 100644
--- a/packages/local-installation/src/native-source-flow.test.ts
+++ b/packages/local-installation/src/native-source-flow.test.ts
@@ -75,6 +75,12 @@ vi.mock("./native-livekit.js", async (original) => ({
readLiveKitSettings: vi.fn(),
startNativeLiveKit: vi.fn(),
}));
+// Setting the model source runs the localmodels tool, which these tests never
+// install.
+vi.mock("./byok-source.js", async (original) => ({
+ ...(await original<typeof import("./byok-source.js")>()),
+ applyNativeSource: vi.fn(async () => undefined),
+}));
vi.mock("./managed-runtimes.js", () => ({
runtimeVersionFailure: vi.fn(() => undefined),
prepareRuntime: vi.fn(),
diff --git a/packages/local-installation/src/native-source.ts b/packages/local-installation/src/native-source.ts
index 29a4c872..885f727a 100644
--- a/packages/local-installation/src/native-source.ts
+++ b/packages/local-installation/src/native-source.ts
@@ -43,6 +43,7 @@ import {
managedRuntimeEnvironment,
} from "./managed-codex.js";
import { prepareRuntime, runtimeVersionFailure } from "./managed-runtimes.js";
+import { applyNativeSource, prepareByokRuntime } from "./byok-source.js";
import {
readSetupChoice,
writeGpuSharing,
@@ -424,8 +425,14 @@ async function runNativeSource(
try {
options.signal.throwIfAborted();
validateLocalCredentials(options);
+ if (options.byok?.apiKey) secrets.push(options.byok.apiKey);
if (options.setupChoice) validateSetupChoice(options.setupChoice);
- const choice = options.setupChoice ?? (await readSetupChoice(options));
+ const choice = options.byok
+ ? (options.byok.runtime ??
+ (options.setupChoice && options.setupChoice !== "local-models"
+ ? options.setupChoice
+ : "claude"))
+ : (options.setupChoice ?? (await readSetupChoice(options)));
if (!choice)
return {
code: 4,
@@ -471,21 +478,53 @@ async function runNativeSource(
let runtimeError: unknown;
const runtime = (async () => {
try {
- runtimeOutcome =
- choice === "local-models"
- ? await prepareLocalModels(current, {
- shareGpu: options.shareGpu,
- signal,
- onEvent: emit,
- localModelsApproval: options.localModelsApproval,
- localModelsReplan: options.localModelsReplan,
- })
- : await prepareRuntime(choice, {
+ if (options.byok) {
+ const byokRuntime =
+ choice === "local-models"
+ ? (options.byok.runtime ?? "claude")
+ : choice;
+ runtimeOutcome = await prepareByokRuntime(
+ { ...options.byok, runtime: byokRuntime },
+ {
+ home,
+ signal,
+ onEvent: emit,
+ env: await managedRuntimeEnvironment(home, current.root),
+ },
+ );
+ } else if (choice === "local-models") {
+ runtimeOutcome = await prepareLocalModels(current, {
+ shareGpu: options.shareGpu,
+ signal,
+ onEvent: emit,
+ localModelsApproval: options.localModelsApproval,
+ localModelsReplan: options.localModelsReplan,
+ });
+ if (runtimeOutcome?.code === 0)
+ runtimeOutcome =
+ (await applyNativeSource(home, "local", "pi", signal)) ??
+ runtimeOutcome;
+ } else {
+ runtimeOutcome = await prepareRuntime(choice, {
+ home,
+ signal,
+ onEvent: emit,
+ env: await managedRuntimeEnvironment(home, current.root),
+ });
+ if (
+ choice !== "pi" &&
+ (runtimeOutcome.code === 0 ||
+ (runtimeOutcome.details as { code?: string } | undefined)
+ ?.code === "RUNTIME_AUTH_REQUIRED")
+ )
+ runtimeOutcome =
+ (await applyNativeSource(
home,
+ "subscription",
+ choice,
signal,
- onEvent: emit,
- env: await managedRuntimeEnvironment(home, current.root),
- });
+ )) ?? runtimeOutcome;
+ }
if (
runtimeOutcome &&
runtimeOutcome.code !== 0 &&
@@ -808,11 +847,17 @@ async function runNativeSource(
});
// Binds the local stack's gateway for local models; with a runtime's own
// sign-in, retires one an earlier release started.
- await prepareModelGateway(current, choice, {
- home,
- signal,
- onEvent: emit,
- });
+ await prepareModelGateway(
+ current,
+ options.byok && choice !== "local-models"
+ ? { runtime: choice, modelSource: "byok" }
+ : choice,
+ {
+ home,
+ signal,
+ onEvent: emit,
+ },
+ );
step("services", "Starting native collaboration services…");
const ends = await logEnds(current);
const liveKit = voice && (await readLiveKitSettings(current.root));
diff --git a/packages/local-installation/src/setup-plan.ts b/packages/local-installation/src/setup-plan.ts
index c9aff3cf..0849d576 100644
--- a/packages/local-installation/src/setup-plan.ts
+++ b/packages/local-installation/src/setup-plan.ts
@@ -13,7 +13,7 @@ export type RuntimeChoice = Exclude<SetupChoice, "local-models">;
* names one combination per runtime; "local-models" is the local source served
* by Pi, the only runtime the local stack binds today.
*/
-export type ModelSource = "local" | "runtime";
+export type ModelSource = "local" | "runtime" | "byok";
export interface SetupSelection {
runtime: RuntimeChoice;
modelSource: ModelSource;
diff --git a/packages/local-installation/src/source-checkout.ts b/packages/local-installation/src/source-checkout.ts
index 4a53b916..0bf68db6 100644
--- a/packages/local-installation/src/source-checkout.ts
+++ b/packages/local-installation/src/source-checkout.ts
@@ -24,12 +24,14 @@ import {
} from "./native-process.js";
import { freePort, portFree } from "./ports.js";
import type { SetupChoice } from "./setup-plan.js";
+import type { ByokConfiguration } from "./byok-source.js";
import type { InstallerEvent } from "./events.js";
// A Native installation of one Linger source checkout: the desktop client's
// unpacked source package, or a developer's clone.
export interface SourceInstallOptions {
setupChoice?: SetupChoice;
+ byok?: ByokConfiguration;
shareGpu?: boolean;
localModelsApproval?: string;
localModelsReplan?: boolean;