Skip to content

Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS

fix: one loopback predicate for local-endpoint checks (#12968)

[._.]/ Adam Eivy2d6c3fb2f6e1
diff --git a/client/src/utils/providerEndpoints.js b/client/src/utils/providerEndpoints.js
index 3c8633de61..0ce33f0589 100644
--- a/client/src/utils/providerEndpoints.js
+++ b/client/src/utils/providerEndpoints.js
@@ -56,15 +56,9 @@ export const localBackendForProvider = (provider) => {
return null;
};
-// The whole loopback block (`127.0.0.0/8`), not just `127.0.0.1` — a daemon on a
-// loopback alias (`127.0.0.2`) is as local as one on `.1`, and the server's
-// `isLocalInstanceHost` already accepts the full block. While they disagreed, a
-// provider on `http://127.0.0.2:11434` was badged NEEDS SETUP for an API key a
-// loopback endpoint never needs.
-const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.\d{1,3}\.\d{1,3}\.\d{1,3}|0\.0\.0\.0|\[?::1\]?|\[?::\]?)(:|\/|$)/i;
-
-export const isLocalEndpoint = (endpoint) =>
- typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());
+// One shared predicate (full `127.0.0.0/8`, `::`, `0.0.0.0`) so client and server
+// cannot disagree on a loopback alias like `http://127.0.0.2:11434`.
+export const isLocalEndpoint = isLoopbackEndpoint;
// THE private-network classification (RFC1918 LAN ranges, link-local, the
// Tailscale CGNAT range, `.local`/`.ts.net`/`.internal` names, single-label
@@ -72,7 +66,7 @@ export const isLocalEndpoint = (endpoint) =>
// so the two documented edge cases (`http://127.1`, a bracketless IPv6
// literal) can't disagree between client and server again. (Imported, not
// re-exported directly, because isFleetProvider below reads it too.)
-import { isPrivateNetworkEndpoint } from '../../../server/lib/localEndpoint.js';
+import { isLoopbackEndpoint, isPrivateNetworkEndpoint } from '../../../server/lib/localEndpoint.js';
export { isPrivateNetworkEndpoint };
/**
diff --git a/server/lib/README.md b/server/lib/README.md
index f44bd4336f..382cb8166e 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -347,6 +347,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `agentCompletionMode.js` | The ONE completion-contract decision behind every agent prompt: `resolveCompletionMode(flags)` returns a single `COMPLETION_MODES` key (`tool-free`, `sentinel-payload`, `action-output`, `discard-worktree`, `claim-flow`, `read-only`, `review-loop-follow-up`, `release-flow`, `tui-slashdo-free`, `tui`, `portos-merges`, `worktree-no-push`, `commit-and-push`) from an ordered rule list, plus `portosMergesBranchOnExit`. Replaces the five independent flag ladders in `agentPromptBuilder.js` that each re-derived it in a different order — two had drifted far enough to render a prompt telling a tool-free or read-only task both to commit and that it had no git at all (#6616). Call sites branch on the key and render per mode; they never re-test the flags. |
| `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |
| `localLlmConcurrency.js` | `LOCAL_LLM_MAX_CONCURRENCY` — the per-endpoint local-LLM concurrency cap (env read at load); a leaf so `cosLocalEndpointSlots.js` avoids importing `promptRunner.js`, which re-exports it. |
+| `localEndpoint.js` | Dependency-light local-instance URL predicates (`isLocalInstanceHost`, `isLocalInstanceEndpoint`, scheme-optional `isLoopbackEndpoint` — the one "is this a local daemon" answer, `localEndpointPort`) shared by provider safety policy and local-runtime classification without importing backend configuration or daemon managers. |
| `credentialBootstrap.js` | resolveBootstrapEnv(provider, { safetyProfile }) runs an optional `envCommand` argv for ordinary provider runs or a no-tool review, parses KEY=value output without evaluation, and caches credentials in memory for one minute — the alternative for a bootstrap that PRINTS credentials rather than exec'ing the harness; a record that only names the wrap form is credentialed by the wrap and gets `{}`. Generic support for a CLI/TUI provider whose auth is provisioned by an external CLI at spawn time (e.g. a short-lived token for a proxy) rather than a static `apiKey` PortOS stores — a `provider.credentialBootstrap: { setupCommand?, command, args?, harnessId?, argsSeparator? }` record. `hasCredentialBootstrap(provider)` and `applyCredentialBootstrap(provider, command, args)` (pure) return the command+args PortOS should actually spawn: `<command> <args...> <harnessId ?? command> [<argsSeparator>] <args...>` — the bootstrap CLI in front of the harness invocation, naming the harness as `harnessId` when the bootstrap CLI uses its own identifier rather than the binary name, and inserting `argsSeparator` (e.g. `--`) before the harness's own args when the bootstrap CLI needs its flags kept apart from the wrapped program's. `resolveCliSpawn(provider, command, args, childEnv)` composes that with Windows shim resolution (`bufferedSpawn.js`) for the three headless spawn sites that repeated the same sequence (`runner.js`, `cliProviderRun.js`, `visionCli.js`) — the argv analog of why `cliChildEnv.js`'s `buildCliChildEnv` exists. Every call site keeps resolving `provider.command`/`args` unchanged for vendor detection, prompt-delivery convention, and the TUI's own ready-text heuristics, and only asks this module for the pair handed to the literal `spawn`/`pty.spawn` call — plus anything that observes the launching shell or PATH (missing-binary detection, readiness probes), which must read the SPAWNED pair. The `sandboxed-actions` posture is never wrapped — it executes contributor-supplied code inside a sandbox spelled entirely in the recipe's argv, so nothing may sit in front of the harness and rewrite it; the `no-tool` postures (the tool-free reviewer among them) ARE wrapped, because spawned bare they carry no credential at all (#7720). The split lives in the helper, keyed on `safetyProfile`. The pure argv composition lives in `aiToolkit/internal/credentialBootstrap.js` (`composeBootstrapSpawn` / `hasCredentialBootstrap`, dependency-free), re-exported through here so the vendored toolkit's own catalog probes compose the same shape without importing out. Every provider spawn site goes through here — a bare-harness spawn runs with no credential and falls through to ambient vendor auth. Both also return `wrapped`, because a wrapped spawn's direct child is the SUPERVISING wrapper rather than the harness: `needsProcessGroup(wrapped)` says whether to spawn `detached` and kill with `{ processGroup: true }` (POSIX only — Windows' `taskkill /T` is already tree-wide), and `processGroupKillable(child, processGroup)` adapts a child for the aiToolkit runner's external-run registry, whose vendored `killProcessTree` has no group option. Without them a stop/timeout/cancel signals the wrapper alone and leaves the harness running. `trackDetachedGroup(child, processGroup)` / `signalDetachedGroups(signal, logFailure)` are the other side of that trade: detaching also moves a child OUT of the server's own process group, so the shutdown handler sweeps this registry to keep a signal aimed at that group (Ctrl-C at `npm start`) from orphaning one. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. Optional `safetyProfile` runs only maintained no-tool vendor recipes and composes the same restricted environment, refusing extra argv and unsupported providers. |
diff --git a/server/lib/localEndpoint.js b/server/lib/localEndpoint.js
index 0bcb9b32f4..d867bdd678 100644
--- a/server/lib/localEndpoint.js
+++ b/server/lib/localEndpoint.js
@@ -89,6 +89,16 @@ const endpointHost = (endpoint) => {
return new URL(candidate).hostname.toLowerCase().replace(/^\[|\]$/g, '');
};
+/**
+ * True when a scheme-optional endpoint string (`localhost:11434`, `http://127.0.0.2/v1`)
+ * names this machine. The single "does this provider talk to a local daemon"
+ * answer; do not re-implement it as a regex.
+ */
+export const isLoopbackEndpoint = (endpoint) => {
+ const host = endpointHost(endpoint);
+ return host !== null && isLocalInstanceHost(host);
+};
+
/**
* Is this endpoint inside the private network — loopback, a LAN/tailnet
* address, a `.local`/`.ts.net`/`.internal` name, or a bare single-label host?
diff --git a/server/lib/localEndpoint.test.js b/server/lib/localEndpoint.test.js
new file mode 100644
index 0000000000..a05e68e6e3
--- /dev/null
+++ b/server/lib/localEndpoint.test.js
@@ -0,0 +1,21 @@
+import { describe, it, expect } from 'vitest';
+import { isLoopbackEndpoint } from './localEndpoint.js';
+
+describe('isLoopbackEndpoint', () => {
+ it.each([
+ ['localhost', true],
+ ['localhost:11434', true],
+ ['http://127.0.0.1', true],
+ ['http://127.0.0.2:11434', true],
+ ['http://[::1]', true],
+ ['http://[::]:8080', true],
+ ['http://0.0.0.0', true],
+ ['http://192.0.2.10:11434', false],
+ ['https://api.example.com/v1', false],
+ ['http://localhost.example.com', false],
+ ['', false],
+ [undefined, false],
+ ])('%s -> %s', (endpoint, expected) => {
+ expect(isLoopbackEndpoint(endpoint)).toBe(expected);
+ });
+});
diff --git a/server/lib/modelPricing.js b/server/lib/modelPricing.js
index 81948e3631..94e8d6afe8 100644
--- a/server/lib/modelPricing.js
+++ b/server/lib/modelPricing.js
@@ -29,6 +29,8 @@
* answered so the UI can flag approximate rows.
*/
+import { isLoopbackEndpoint } from './localEndpoint.js';
+
export const PRICING_AS_OF = '2026-09-01';
// Newer model launch rates are tracked separately so the baseline date above
@@ -301,11 +303,8 @@ export function resolveModelRates(providerId, model) {
return { ...withCacheRates(FALLBACK_RATES), matched: 'fallback' };
}
-// Mirrors promptRunner.js's LOCAL_ENDPOINT_RE (scheme optional, unbracketed
-// ::1 accepted) so the concurrency gate and the cost report agree on what
-// "local" means. Duplicated rather than imported because modelPricing must
-// stay a leaf module — promptRunner pulls in the whole runner/provider graph.
-const LOCALHOST_ENDPOINT = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;
+// The concurrency gate and the cost report share isLoopbackEndpoint's answer
+// for what "local" means; localEndpoint.js is dependency-free so this stays a leaf.
const FREE_ID = /ollama|lmstudio|lm-studio/i;
// A record derived from a service instance (#7563) carries the plan the user
@@ -400,7 +399,7 @@ export function isFreeProvider(providerOrId) {
if (p.ollamaBacked === true || p.lmstudioBacked === true || p.mtplxBacked === true || p.llamaBacked === true || p.vllmBacked === true || p.sglangBacked === true) return true;
if (FREE_ID.test(p.id || '') || FREE_ID.test(p.command || '')) return true;
if (ZEN_PROVIDER_ID.test(p.id || '')) return true;
- if (typeof p.endpoint === 'string' && (LOCALHOST_ENDPOINT.test(p.endpoint.trim()) || ZEN_ENDPOINT.test(p.endpoint.trim()))) return true;
+ if (typeof p.endpoint === 'string' && (isLoopbackEndpoint(p.endpoint) || ZEN_ENDPOINT.test(p.endpoint.trim()))) return true;
return false;
}
diff --git a/server/lib/modelPricing.test.js b/server/lib/modelPricing.test.js
index 41d2f90726..34f30df5fd 100644
--- a/server/lib/modelPricing.test.js
+++ b/server/lib/modelPricing.test.js
@@ -225,6 +225,11 @@ describe('isFreeProvider', () => {
expect(isFreeProvider({ id: 'opencode-mtplx', mtplxBacked: true, command: 'opencode' })).toBe(true);
});
+ it('classifies loopback-alias endpoints (127.0.0.2, [::]) as free', () => {
+ expect(isFreeProvider({ id: 'my-local', type: 'api', endpoint: 'http://127.0.0.2:11434/v1' })).toBe(true);
+ expect(isFreeProvider({ id: 'my-local', type: 'api', endpoint: 'http://[::]:8080' })).toBe(true);
+ });
+
it('classifies localhost API endpoints as free', () => {
expect(isFreeProvider({ id: 'my-local', type: 'api', endpoint: 'http://localhost:1234/v1' })).toBe(true);
expect(isFreeProvider({ id: 'my-local', type: 'api', endpoint: 'http://127.0.0.1:11434/v1' })).toBe(true);
diff --git a/server/services/portosModelBenchmarks.js b/server/services/portosModelBenchmarks.js
index 6ce8b90254..46be1275b4 100644
--- a/server/services/portosModelBenchmarks.js
+++ b/server/services/portosModelBenchmarks.js
@@ -2,6 +2,7 @@
import { randomUUID } from 'crypto';
import { estimateTokens } from '../lib/contextBudget.js';
import { estimateCostUsd, isFreeProvider, pricingAsOfForModel, resolveModelRates } from '../lib/modelPricing.js';
+import { isLoopbackEndpoint } from '../lib/localEndpoint.js';
import { familyForProvider } from '../lib/providerFamilies.js';
import { commandBasename } from '../lib/providerModels.js';
import { isCodexTextTransportEnabled } from '../lib/codexTurn.js';
@@ -49,7 +50,7 @@ export const isLocalProvider = provider => Boolean(provider && (
provider.servicePlan === 'local'
|| provider.ollamaBacked || provider.lmstudioBacked || provider.mtplxBacked
|| provider.llamaBacked || provider.vllmBacked || provider.sglangBacked
- || /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i.test(provider.endpoint || '')
+ || isLoopbackEndpoint(provider.endpoint)
|| /^(?:ollama|lm[-_]?studio|mtplx|llama|vllm|sglang)(?:[-_.]|$)/i.test(provider.id || '')
|| /^(?:ollama|lm[-_]?studio|mtplx|llama|vllm|sglang)(?:[-_.]|$)/i.test(commandBasename(provider.command))
));
diff --git a/server/services/promptRunner.js b/server/services/promptRunner.js
index 1016fb780e..47ed3b8622 100644
--- a/server/services/promptRunner.js
+++ b/server/services/promptRunner.js
@@ -1,3 +1,4 @@
+import { isLoopbackEndpoint } from '../lib/localEndpoint.js';
import { maintenance } from '../lib/maintenanceAdmission.js';
/**
* Shared LLM runner wrapper.
@@ -144,9 +145,7 @@ export function buildRequestCapabilities({ prompt, screenshots, outputReserveTok
// lands on a local backend after a remote/CLI primary fails. Gating only the
// outer stageRunner call missed the fallback path — a failure storm could still
// fire N concurrent calls at one local endpoint.
-const LOCAL_ENDPOINT_RE = /^(https?:\/\/)?(localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(:|\/|$)/i;
-export const isLocalEndpoint = (endpoint) =>
- typeof endpoint === 'string' && LOCAL_ENDPOINT_RE.test(endpoint.trim());
+export const isLocalEndpoint = isLoopbackEndpoint;
export { LOCAL_LLM_MAX_CONCURRENCY };
const localEndpointGates = new Map(); // endpoint -> { active: number, queue: (()=>void)[] }
diff --git a/server/services/stageRunner.test.js b/server/services/stageRunner.test.js
index e580ca73ae..5ee5ee8cf3 100644
--- a/server/services/stageRunner.test.js
+++ b/server/services/stageRunner.test.js
@@ -948,6 +948,13 @@ describe('withLocalConcurrencyGate', () => {
expect(LOCAL_LLM_MAX_CONCURRENCY).toBe(1); // default — serialized
});
+ it('serializes a loopback-alias endpoint (127.0.0.2) like 127.0.0.1', async () => {
+ const provider = { type: 'api', endpoint: 'http://127.0.0.2:11434' };
+ const { state, fn } = makeTracker();
+ await Promise.all(Array.from({ length: 4 }, () => withLocalConcurrencyGate(provider, fn)));
+ expect(state.peak).toBeLessThanOrEqual(LOCAL_LLM_MAX_CONCURRENCY);
+ });
+
it('does NOT gate a remote api endpoint (runs concurrently)', async () => {
const provider = { type: 'api', endpoint: 'https://api.openai.com' };
const { state, fn } = makeTracker();