Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
Show all changes
38 commits
Select commit Hold shift + click to select a range
dc9a0c5
Fail over to the local daemon when the configured server is unreachable
lawrencecchen Jul 28, 2026
f271cf4
Add sr setup, doctor and cleanup, and move lifecycle under sr server
lawrencecchen Jul 28, 2026
9f7e236
Auto-start the local daemon when launching an agent
lawrencecchen Jul 28, 2026
f99083f
Add team-vault credential leases with local egress
lawrencecchen Jul 29, 2026
73498c1
Merge remote-tracking branch 'origin/main' into feat/client-failover
lawrencecchen Jul 29, 2026
61a0481
Test credential storage mode overrides legacy servers
lawrencecchen Jul 29, 2026
10fa100
Make credential storage mode authoritative
lawrencecchen Jul 29, 2026
b66d411
Test lifecycle waits for daemon readiness
lawrencecchen Jul 29, 2026
2a09316
Wait for daemon health after lifecycle starts
lawrencecchen Jul 29, 2026
8895763
Isolate doctor tests from live team config
lawrencecchen Jul 29, 2026
fc1bbf6
Test credential custody review regressions
lawrencecchen Jul 29, 2026
5d5c726
Harden central credential custody and local egress
lawrencecchen Jul 29, 2026
99b1e63
Test daemon custody and lease lifecycle regressions
lawrencecchen Jul 29, 2026
1dbb4c6
Harden local credential proxy custody
lawrencecchen Jul 29, 2026
6f7f586
Test credential failover review regressions
lawrencecchen Jul 29, 2026
0392925
Harden credential failover and provider custody
lawrencecchen Jul 29, 2026
7ac1cee
Allow explicit proxy health recovery probes
lawrencecchen Jul 29, 2026
d90bde9
Test device authorization client binding
lawrencecchen Jul 29, 2026
3bfec39
Bind Subrouter login to its device authorization
lawrencecchen Jul 29, 2026
298a336
Test systemd path escaping
lawrencecchen Jul 29, 2026
dfa19a2
Escape systemd user service paths
lawrencecchen Jul 29, 2026
1c714fc
Add regression coverage for cloud credential boundaries
lawrencecchen Jul 29, 2026
8ab2695
Harden local proxy and cloud credential recovery
lawrencecchen Jul 29, 2026
953c310
Test stale credential lease outcomes
lawrencecchen Jul 29, 2026
7da74c6
Ignore stale credential lease outcomes
lawrencecchen Jul 29, 2026
0be9500
Keep Go module metadata tidy
lawrencecchen Jul 29, 2026
8f3b799
Test central adoption and monotonic cooldowns
lawrencecchen Jul 29, 2026
7ecab5c
Adopt uploaded refresh chains and preserve cooldowns
lawrencecchen Jul 29, 2026
7916574
Test team-vault failure isolation and cleanup
lawrencecchen Jul 29, 2026
7c9892e
Harden team leases and scoped failover
lawrencecchen Jul 29, 2026
b888dae
Test quota-scoped forbidden lease rotation
lawrencecchen Jul 29, 2026
1bb42c5
Rotate model-scoped forbidden leases
lawrencecchen Jul 29, 2026
cd8c320
Test provider-specific forbidden lease handling
lawrencecchen Jul 29, 2026
e21eec6
Classify forbidden leases by provider context
lawrencecchen Jul 29, 2026
446c833
Test Claude API-key forbidden scope
lawrencecchen Jul 29, 2026
ba3da7f
Scope Claude forbidden leases by auth mode
lawrencecchen Jul 29, 2026
03b24b0
Test provider-specific lease retry deadlines
lawrencecchen Jul 29, 2026
2856789
Use provider-specific lease retry deadlines
lawrencecchen Jul 29, 2026
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 18 additions & 1 deletion cmd/subrouter/codex.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package main
import (
"context"
"fmt"
"io"
"os"
"os/exec"
"strconv"
Expand All @@ -15,7 +16,7 @@ import (
const defaultCodexBaseURL = "http://127.0.0.1:31415/v1"

func codex(args []string) error {
baseURL, err := codexBaseURL(defaultSRServerStore(accounts.DefaultCodexStore()))
baseURL, err := codexBaseURLWithFallback(defaultSRServerStore(accounts.DefaultCodexStore()), os.Stderr)
if err != nil {
return err
}
Expand Down Expand Up @@ -67,6 +68,22 @@ func defaultCodexBaseURLFor(store srServerStore) (string, error) {
return codexBaseURLForServer(server), nil
}

// codexBaseURLWithFallback resolves the base URL for launching codex, then
// substitutes the local daemon when the configured server is unreachable. An
// explicit SUBROUTER_CODEX_BASE_URL or SUBROUTER_CODEX_SERVER is treated as a
// deliberate pin and is never overridden.
func codexBaseURLWithFallback(store srServerStore, warn io.Writer) (string, error) {
baseURL, err := codexBaseURL(store)
if err != nil {
return "", err
}
if strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_BASE_URL")) != "" ||
strings.TrimSpace(os.Getenv("SUBROUTER_CODEX_SERVER")) != "" {
return baseURL, nil
}
return withLocalFallback(context.Background(), fallbackHTTPClient(), baseURL, warn), nil
}

func codexBaseURLForNamedServer(store srServerStore, name string) (string, error) {
if name == "local" || name == "localhost" {
return defaultCodexBaseURL, nil
Expand Down
178 changes: 178 additions & 0 deletions cmd/subrouter/lifecycle.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,178 @@
package main

import (
"context"
"fmt"
"io"
"os"
"path/filepath"
"runtime"
"strings"

"github.com/manaflow-ai/subrouter/internal/accounts"
)

// serviceController starts, stops and inspects the installed local daemon. The
// two implementations wrap launchd and systemd rather than managing processes
// directly, so `sr up` and a reboot converge on the same supervised state.
type serviceController interface {
start() error
stop() error
restart() error
// installed reports whether a unit or agent exists to act on.
installed() bool
// describe names the managed unit for user-facing messages.
describe() string
}

// launchdController manages the per-user LaunchAgent written by install-daemon.
type launchdController struct {
label string
home string
runner commandRunner
}

func (c launchdController) plist() string { return launchAgentPath(c.home, c.label) }

func (c launchdController) installed() bool {
_, err := os.Stat(c.plist())
return err == nil
}

func (c launchdController) describe() string { return c.label }

func (c launchdController) domain() string {
return fmt.Sprintf("gui/%d", os.Getuid())
}

func (c launchdController) start() error {
if err := c.runner.Run("launchctl", "bootstrap", c.domain(), c.plist()); err != nil {
// Already bootstrapped is not a failure; kickstart still brings it up.
return c.runner.Run("launchctl", "kickstart", "-k", c.domain()+"/"+c.label)
}
return nil
}

func (c launchdController) stop() error {
return c.runner.Run("launchctl", "bootout", c.domain(), c.plist())
}

func (c launchdController) restart() error {
return restartLaunchAgent(c.plist(), c.label, c.runner)
}

// systemdController manages the system service written by install-systemd.
type systemdController struct {
service string
runner commandRunner
}

func (c systemdController) installed() bool {
_, err := os.Stat(systemdUnitPath(systemdConfig{ServiceName: c.service}))
return err == nil
}

func (c systemdController) describe() string { return c.service + ".service" }

func (c systemdController) start() error {
return c.runner.Run("systemctl", "start", c.service)
}

func (c systemdController) stop() error {
return c.runner.Run("systemctl", "stop", c.service)
}

func (c systemdController) restart() error {
return c.runner.Run("systemctl", "restart", c.service)
}

// newServiceController picks the supervisor for the running OS.
func newServiceController() (serviceController, error) {
switch runtime.GOOS {
case "darwin":
home, err := os.UserHomeDir()
if err != nil {
return nil, err
}
return launchdController{label: defaultDaemonLabel, home: home, runner: commandRunner{}}, nil
case "linux":
return systemdController{service: defaultSystemdServiceName, runner: commandRunner{}}, nil
default:
return nil, fmt.Errorf("managing the local daemon is not supported on %s", runtime.GOOS)
}
}

// runServerLifecycle implements `sr up`, `sr down` and `sr restart`.
func runServerLifecycle(action string, out io.Writer) error {
controller, err := newServiceController()
if err != nil {
return err
}
if !controller.installed() {
return fmt.Errorf("no local Subrouter daemon installed; run '%s install-daemon' first", filepath.Base(os.Args[0]))
}
switch action {
case "up", "start":
if err := controller.start(); err != nil {
return fmt.Errorf("start %s: %w", controller.describe(), err)
}
fmt.Fprintf(out, "started %s\n", controller.describe())
case "down", "stop":
if err := controller.stop(); err != nil {
return fmt.Errorf("stop %s: %w", controller.describe(), err)
}
fmt.Fprintf(out, "stopped %s\n", controller.describe())
case "restart":
if err := controller.restart(); err != nil {
return fmt.Errorf("restart %s: %w", controller.describe(), err)
}
fmt.Fprintf(out, "restarted %s\n", controller.describe())
default:
return fmt.Errorf("unknown server action %q", action)
}
return nil
}

// runServerHealth implements `sr up --check` style reporting: it prints whether
// the configured server and the local daemon each answer their health probe, so
// an operator can tell a routing problem from a dead host without curl.
func runServerHealth(ctx context.Context, out io.Writer) error {
client := fallbackHTTPClient()
local := localBaseURL()
fmt.Fprintf(out, "%-40s %s\n", local, healthLabel(serverHealthy(ctx, client, local)))

configured, err := defaultCodexBaseURLForHealth()
if err != nil {
return err
}
if configured != "" && !sameEndpoint(configured, local) {
fmt.Fprintf(out, "%-40s %s\n", configured, healthLabel(serverHealthy(ctx, client, configured)))
}
return nil
}

func healthLabel(ok bool) string {
if ok {
return "healthy"
}
return "UNREACHABLE"
}

// defaultCodexBaseURLForHealth resolves the configured server without applying
// fallback, so the health report shows what is configured rather than what a
// probe would substitute.
func defaultCodexBaseURLForHealth() (string, error) {
store := defaultSRServerStore(accounts.DefaultCodexStore())
file, err := store.load()
if err != nil {
return "", err
}
if strings.TrimSpace(file.Default) == "" {
return "", nil
}
server, ok := file.find(file.Default)
if !ok {
return "", nil
}
return codexBaseURLForServer(server), nil
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}
133 changes: 133 additions & 0 deletions cmd/subrouter/serverfallback.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,133 @@
package main

import (
"context"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strings"
"time"
)

// localFallbackBaseURL is where the per-machine daemon listens. It is the same
// address install-daemon and install-systemd bind.
const localFallbackBaseURL = "http://127.0.0.1:31415/v1"

// fallbackProbeTimeout bounds each health probe. A host that has exhausted its
// kernel socket buffers drops SYNs instead of refusing them, so an unbounded
// dial hangs the agent launch indefinitely rather than failing over.
const fallbackProbeTimeout = 1500 * time.Millisecond

// healthURLFor derives the health endpoint from a Subrouter base URL. Base URLs
// carry an optional /v1 suffix for OpenAI-compatible clients, while the health
// route is served at the origin.
func healthURLFor(baseURL string) (string, error) {
trimmed := strings.TrimSpace(baseURL)
if trimmed == "" {
return "", fmt.Errorf("empty base URL")
}
parsed, err := url.Parse(trimmed)
if err != nil {
return "", err
}
if parsed.Scheme == "" || parsed.Host == "" {
return "", fmt.Errorf("base URL %q is not absolute", baseURL)
}
parsed.Path = "/_subrouter/health"
parsed.RawQuery = ""
parsed.Fragment = ""
return parsed.String(), nil
}

// sameEndpoint reports whether two base URLs address the same origin, so a
// server that is already local is never "failed over" onto itself.
func sameEndpoint(a, b string) bool {
parsedA, errA := url.Parse(strings.TrimSpace(a))
parsedB, errB := url.Parse(strings.TrimSpace(b))
if errA != nil || errB != nil {
return false
}
return strings.EqualFold(parsedA.Host, parsedB.Host)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
}

// serverHealthy reports whether a Subrouter server answers its health probe.
func serverHealthy(ctx context.Context, client *http.Client, baseURL string) bool {
healthURL, err := healthURLFor(baseURL)
if err != nil {
return false
}
probeCtx, cancel := context.WithTimeout(ctx, fallbackProbeTimeout)
defer cancel()
req, err := http.NewRequestWithContext(probeCtx, http.MethodGet, healthURL, nil)
if err != nil {
return false
}
resp, err := client.Do(req)
if err != nil {
return false
}
defer resp.Body.Close()
_, _ = io.Copy(io.Discard, io.LimitReader(resp.Body, 1<<10))
return resp.StatusCode == http.StatusOK
}

// fallbackDisabled lets an operator pin the configured server even when it is
// down, for cases where routing through local accounts is worse than failing.
func fallbackDisabled() bool {
switch strings.ToLower(strings.TrimSpace(os.Getenv("SUBROUTER_DISABLE_FALLBACK"))) {
case "", "0", "false", "no":
return false
default:
return true
}
}

// localBaseURL resolves where the per-machine daemon listens, allowing an
// override for non-default installs and for tests.
func localBaseURL() string {
if override := strings.TrimSpace(os.Getenv("SUBROUTER_LOCAL_BASE_URL")); override != "" {
return override
}
return localFallbackBaseURL
}

// withLocalFallback returns baseURL when the configured server answers its
// health probe. When it does not and the local daemon does, it returns the local
// base URL so agents keep working through this machine's own accounts instead of
// hanging against a wedged host.
func withLocalFallback(ctx context.Context, client *http.Client, baseURL string, warn io.Writer) string {
return withLocalFallbackTo(ctx, client, baseURL, localBaseURL(), warn)
}

// withLocalFallbackTo is withLocalFallback with an explicit local address.
func withLocalFallbackTo(ctx context.Context, client *http.Client, baseURL, local string, warn io.Writer) string {
if fallbackDisabled() {
return baseURL
}
if sameEndpoint(baseURL, local) {
return baseURL
}
if serverHealthy(ctx, client, baseURL) {
return baseURL
}
if !serverHealthy(ctx, client, local) {
return baseURL
}
if warn != nil {
fmt.Fprintf(warn, "subrouter: %s is unreachable; falling back to the local daemon at %s\n", baseURL, local)
}
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
return local
}

// fallbackHTTPClient is the probe client. It deliberately does not follow
// redirects and keeps no idle connections, so a probe never wedges a later call.
func fallbackHTTPClient() *http.Client {
return &http.Client{
Timeout: fallbackProbeTimeout,
CheckRedirect: func(*http.Request, []*http.Request) error {
return http.ErrUseLastResponse
},
}
}
Loading