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
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
feat: cap concurrent CoS agents per local inference endpoint (#4834)
[._.]/ Adam Eivy11a8ffe797bc
diff --git a/server/services/cos.js b/server/services/cos.jsindex e78f79a230..21a52b7342 100644--- a/server/services/cos.js+++ b/server/services/cos.js@@ -146,7 +146,8 @@ import {// predicates are shared with the scheduler unit tests so they exercise the real// guards instead of a local replica. The async tiers stay here as// `spawnDequeuePriorityN(ctx)` helpers.-import { createDequeueCapacity, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';+import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';+import { buildLocalEndpointSlotContext } from './cosLocalEndpointSlots.js';/*** Get current CoS status@@ -842,6 +843,20 @@ async function tryImmediateSpawn(task) {return;}+ // Per-local-endpoint cap (#4834). This path bypasses the evaluation interval+ // entirely, so without the same gate a user-submitted task would dispatch+ // straight past the local-GPU slot limit dequeueNextTask enforces.+ const localSlots = await buildLocalEndpointSlotContext();+ const taskEndpoint = localSlots.resolveLocalEndpoint(task);+ if (taskEndpoint) {+ const endpointCounts = countRunningAgentsByLocalEndpoint(state.agents, localSlots.endpointForAgent);+ const running = endpointCounts[taskEndpoint] || 0;+ if (running >= localSlots.limit) {+ emitLog('debug', `⏳ Queued task ${task.id} - local endpoint ${taskEndpoint} at capacity (${running}/${localSlots.limit})`);+ return;+ }+ }+emitLog('info', `⚡ Immediate spawn: ${task.id} (${task.priority || 'MEDIUM'})`, {taskId: task.id,availableSlots@@ -1228,7 +1243,24 @@ async function dequeueNextTask({ ignoreTaskId = null } = {}) {const paused = await isPaused();const state = await loadState();- const capacity = createDequeueCapacity(state, { agentsByProject: countRunningAgentsByProject(state.agents) });+ // Per-local-endpoint agent slots (#4834). A CoS agent runs a vendor CLI that+ // talks to the local model server directly, so promptRunner's in-flight gate+ // never sees it; without this, two agents can be dispatched at one GPU and+ // take an accelerator OOM. Resolved once per cycle and threaded into the+ // capacity tracker, which enforces it alongside the global/per-project caps.+ const localSlots = await buildLocalEndpointSlotContext();+ const capacity = createDequeueCapacity(state, {+ agentsByProject: countRunningAgentsByProject(state.agents),+ localEndpointCounts: countRunningAgentsByLocalEndpoint(state.agents, localSlots.endpointForAgent),+ localEndpointLimit: localSlots.limit,+ resolveLocalEndpoint: localSlots.resolveLocalEndpoint,+ onLocalEndpointHold: (task, endpoint, running) => {+ emitLog('debug', `⏳ Queued task ${task.id} - local endpoint ${endpoint} at capacity (${running}/${localSlots.limit})`, {+ taskId: task.id,+ endpoint+ });+ }+ });const availableSlots = capacity.availableSlots;if (availableSlots <= 0) return;diff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex a675d8e55d..43cf36409b 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -36,7 +36,8 @@ import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { firstLine, isPerpetualRefillCandidate, perpetualRefillPlan } from './cos.js';import { canQueueImprovementTasks } from './cosState.js';-import { createDequeueCapacity, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';+import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';+import { createLocalEndpointSlotContext, localEndpointOfProvider } from './cosLocalEndpointSlots.js';import { PENDING_MERGE_SWEEP_INTERVAL_MS, MAX_PENDING_MERGE_TICKS } from './prWatcher.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -458,6 +459,255 @@ describe('dequeueNextTask — capacity guards', () => {});});+// ─── dequeueNextTask: per-local-endpoint agent cap (issue #4834) ───────────+//+// A CoS agent runs a vendor CLI that opens its own connection to the local+// model server, so promptRunner's in-flight gate never sees it. These drive the+// REAL `createLocalEndpointSlotContext` resolvers through the REAL capacity+// tracker — the same pair `dequeueNextTask` wires together — so a regression in+// either half fails here.++const LOCAL_ENDPOINT = 'http://localhost:1234/v1';+const OTHER_LOCAL_ENDPOINT = 'http://127.0.0.1:11434';++// A TUI provider pointed at a local server is exactly the case #4834 exists+// for: PortOS launches the CLI, the CLI talks to the GPU directly.+const LOCAL_TUI_PROVIDER = { id: 'lmstudio-tui', type: 'tui', endpoint: LOCAL_ENDPOINT };+const OTHER_LOCAL_PROVIDER = { id: 'ollama-local', type: 'api', endpoint: OTHER_LOCAL_ENDPOINT };+// No recorded endpoint — PortOS cannot know where it points, so it stays ungated.+const BARE_CLI_PROVIDER = { id: 'claude-cli', type: 'cli', endpoint: null };+const CLOUD_PROVIDER = { id: 'anthropic', type: 'api', endpoint: 'https://api.anthropic.com/v1' };++const ALL_PROVIDERS = [LOCAL_TUI_PROVIDER, OTHER_LOCAL_PROVIDER, BARE_CLI_PROVIDER, CLOUD_PROVIDER];++/** A running agent stamped with the providerId agentLifecycle persists. */+function makeRunningAgentOnProvider(providerId, app = '_self') {+ return { status: 'running', metadata: { taskApp: app, app, providerId } };+}++/** A pending task pinned to a provider via `metadata.provider`. */+const taskOnProvider = (id, providerId) => ({+ id,+ priority: 'HIGH',+ status: 'pending',+ metadata: providerId === undefined ? {} : { provider: providerId },+});++/**+ * Build the capacity tracker the way `dequeueNextTask` does: real slot context+ * over the fixture provider list, real running-agent endpoint tally, real hold+ * callback (captured so tests can assert the queued-no-slot log fired).+ */+function makeLocalSlotCapacity(state, { activeProvider = CLOUD_PROVIDER, limit = 1, agentsByProject = {} } = {}) {+ const slots = createLocalEndpointSlotContext({ providers: ALL_PROVIDERS, activeProvider, limit });+ const holds = [];+ const capacity = createDequeueCapacity(state, {+ agentsByProject,+ localEndpointCounts: countRunningAgentsByLocalEndpoint(state.agents, slots.endpointForAgent),+ localEndpointLimit: slots.limit,+ resolveLocalEndpoint: slots.resolveLocalEndpoint,+ onLocalEndpointHold: (task, endpoint, running) => holds.push({ taskId: task.id, endpoint, running }),+ });+ return { capacity, holds, slots };+}++const userBuckets = (tasks) => ({ onDemand: [], user: tasks, autoSystem: [], mission: [], idle: [] });++describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {+ it('serializes two queued tasks that resolve to the SAME local endpoint', () => {+ // Global cap 5, nothing running: both tasks clear the global and+ // per-project guards. Only the local-endpoint slot separates them.+ const state = makeState({ maxConcurrentAgents: 5 });+ const { capacity, holds } = makeLocalSlotCapacity(state);++ const spawned = priorityDequeue(userBuckets([+ taskOnProvider('task-local-1', 'lmstudio-tui'),+ taskOnProvider('task-local-2', 'lmstudio-tui'),+ ]), capacity);++ expect(spawned.map(t => t.id)).toEqual(['task-local-1']);+ expect(holds).toEqual([{ taskId: 'task-local-2', endpoint: LOCAL_ENDPOINT, running: 1 }]);+ expect(capacity.spawnLocalEndpointCounts[LOCAL_ENDPOINT]).toBe(1);+ });++ it('dispatches the held task once the endpoint frees up (next cycle)', () => {+ // Same fixture, but the first agent has finished — nothing is running, so+ // the previously-held task now takes the slot. This is the "dispatches when+ // the first finishes" half of the acceptance criteria.+ const state = makeState({ maxConcurrentAgents: 5 });+ const { capacity, holds } = makeLocalSlotCapacity(state);++ const spawned = priorityDequeue(userBuckets([taskOnProvider('task-local-2', 'lmstudio-tui')]), capacity);++ expect(spawned.map(t => t.id)).toEqual(['task-local-2']);+ expect(holds).toEqual([]);+ });++ it('counts an ALREADY-RUNNING agent against its local endpoint', () => {+ // One agent is live on the local TUI provider. A queued task for the same+ // endpoint must be held even though the global cap has room.+ const state = makeState({+ maxConcurrentAgents: 5,+ runningAgents: [makeRunningAgentOnProvider('lmstudio-tui')],+ });+ const { capacity, holds } = makeLocalSlotCapacity(state);++ const spawned = priorityDequeue(userBuckets([taskOnProvider('task-local-1', 'lmstudio-tui')]), capacity);++ expect(spawned).toEqual([]);+ expect(holds).toEqual([{ taskId: 'task-local-1', endpoint: LOCAL_ENDPOINT, running: 1 }]);+ });++ it('leaves cloud and endpoint-less providers unaffected', () => {+ // A cloud API provider and a CLI provider with NO recorded endpoint both+ // resolve to null. Neither is gated, so all three spawn concurrently even+ // though a local agent is already saturating its endpoint.+ const state = makeState({+ maxConcurrentAgents: 5,+ runningAgents: [makeRunningAgentOnProvider('lmstudio-tui')],+ });+ const { capacity, holds } = makeLocalSlotCapacity(state);++ const spawned = priorityDequeue(userBuckets([+ taskOnProvider('task-cloud', 'anthropic'),+ taskOnProvider('task-bare-cli', 'claude-cli'),+ taskOnProvider('task-cloud-2', 'anthropic'),+ ]), capacity);++ expect(spawned.map(t => t.id)).toEqual(['task-cloud', 'task-bare-cli', 'task-cloud-2']);+ expect(holds).toEqual([]);+ });++ it('runs two DISTINCT local endpoints in parallel', () => {+ // Keyed by endpoint, not by "is local" — two separate local servers each+ // get their own slot.+ const state = makeState({ maxConcurrentAgents: 5 });+ const { capacity } = makeLocalSlotCapacity(state);++ const spawned = priorityDequeue(userBuckets([+ taskOnProvider('task-lmstudio', 'lmstudio-tui'),+ taskOnProvider('task-ollama', 'ollama-local'),+ ]), capacity);++ expect(spawned.map(t => t.id)).toEqual(['task-lmstudio', 'task-ollama']);+ });++ it('honors a lifted limit (LOCAL_LLM_MAX_CONCURRENCY > 1)', () => {+ const state = makeState({ maxConcurrentAgents: 5 });+ const { capacity, holds } = makeLocalSlotCapacity(state, { limit: 2 });++ const spawned = priorityDequeue(userBuckets([+ taskOnProvider('task-local-1', 'lmstudio-tui'),+ taskOnProvider('task-local-2', 'lmstudio-tui'),+ taskOnProvider('task-local-3', 'lmstudio-tui'),+ ]), capacity);++ expect(spawned.map(t => t.id)).toEqual(['task-local-1', 'task-local-2']);+ expect(holds.map(h => h.taskId)).toEqual(['task-local-3']);+ });++ it('gates UNPINNED tasks by the ACTIVE provider endpoint', () => {+ // A task with no `metadata.provider` runs on the active provider — when+ // that is local, the cap applies to it too.+ const state = makeState({ maxConcurrentAgents: 5 });+ const { capacity } = makeLocalSlotCapacity(state, { activeProvider: LOCAL_TUI_PROVIDER });++ const spawned = priorityDequeue(userBuckets([+ taskOnProvider('task-unpinned-1'),+ taskOnProvider('task-unpinned-2'),+ ]), capacity);++ expect(spawned.map(t => t.id)).toEqual(['task-unpinned-1']);+ });++ it('falls back to the active provider for an UNKNOWN pinned id (mirrors spawn)', () => {+ // resolveAgentProviderAndModel logs and uses the active provider when the+ // pinned id is missing; the gate must predict the same landing spot.+ const state = makeState({ maxConcurrentAgents: 5 });+ const { capacity, holds } = makeLocalSlotCapacity(state, { activeProvider: LOCAL_TUI_PROVIDER });++ const spawned = priorityDequeue(userBuckets([+ taskOnProvider('task-local-1', 'lmstudio-tui'),+ taskOnProvider('task-ghost', 'deleted-provider'),+ ]), capacity);++ expect(spawned.map(t => t.id)).toEqual(['task-local-1']);+ expect(holds).toEqual([{ taskId: 'task-ghost', endpoint: LOCAL_ENDPOINT, running: 1 }]);+ });++ it('leaves the cap disabled when no limit is supplied', () => {+ // createDequeueCapacity's defaults must not gate anything — every existing+ // caller (and every test above this block) constructs it without the+ // local-endpoint options.+ const state = makeState({ maxConcurrentAgents: 5 });+ const capacity = createDequeueCapacity(state, {});+ expect(capacity.localEndpointLimit).toBe(Infinity);+ expect(priorityDequeue(userBuckets([+ taskOnProvider('task-a', 'lmstudio-tui'),+ taskOnProvider('task-b', 'lmstudio-tui'),+ ]), capacity)).toHaveLength(2);+ });++ it('floors a 0/NaN limit at 1 rather than wedging the queue forever', () => {+ const state = makeState({ maxConcurrentAgents: 5 });+ const slots = createLocalEndpointSlotContext({ providers: ALL_PROVIDERS, activeProvider: CLOUD_PROVIDER, limit: 0 });+ const capacity = createDequeueCapacity(state, {+ localEndpointLimit: slots.limit,+ resolveLocalEndpoint: slots.resolveLocalEndpoint,+ });+ expect(capacity.localEndpointLimit).toBe(1);+ expect(priorityDequeue(userBuckets([+ taskOnProvider('task-a', 'lmstudio-tui'),+ taskOnProvider('task-b', 'lmstudio-tui'),+ ]), capacity).map(t => t.id)).toEqual(['task-a']);+ });+});++describe('countRunningAgentsByLocalEndpoint (#4834)', () => {+ const slots = createLocalEndpointSlotContext({ providers: ALL_PROVIDERS, activeProvider: CLOUD_PROVIDER });++ it('tallies only RUNNING agents, only on local endpoints', () => {+ const agents = {+ a: makeRunningAgentOnProvider('lmstudio-tui'),+ b: makeRunningAgentOnProvider('lmstudio-tui'),+ c: makeRunningAgentOnProvider('ollama-local'),+ d: makeRunningAgentOnProvider('anthropic'), // cloud → not counted+ e: makeRunningAgentOnProvider('claude-cli'), // no endpoint → not counted+ f: { status: 'completed', metadata: { providerId: 'lmstudio-tui' } },+ };+ expect(countRunningAgentsByLocalEndpoint(agents, slots.endpointForAgent)).toEqual({+ [LOCAL_ENDPOINT]: 2,+ [OTHER_LOCAL_ENDPOINT]: 1,+ });+ });++ it('ignores agents with no provider stamp (pre-upgrade records)', () => {+ const agents = { a: { status: 'running', metadata: {} }, b: { status: 'running' } };+ expect(countRunningAgentsByLocalEndpoint(agents, slots.endpointForAgent)).toEqual({});+ });+});++describe('localEndpointOfProvider (#4834)', () => {+ it('resolves a local endpoint regardless of provider type', () => {+ expect(localEndpointOfProvider({ type: 'tui', endpoint: 'http://localhost:1234/v1' })).toBe('http://localhost:1234/v1');+ expect(localEndpointOfProvider({ type: 'api', endpoint: 'http://127.0.0.1:11434' })).toBe('http://127.0.0.1:11434');+ });++ it('returns null for a remote endpoint, a missing endpoint, or no provider', () => {+ expect(localEndpointOfProvider({ type: 'api', endpoint: 'https://api.anthropic.com/v1' })).toBeNull();+ expect(localEndpointOfProvider({ type: 'cli', endpoint: null })).toBeNull();+ expect(localEndpointOfProvider({ type: 'tui' })).toBeNull();+ expect(localEndpointOfProvider(null)).toBeNull();+ });++ it('never guesses from a model id — only the recorded endpoint counts', () => {+ // The issue is explicit: a TUI provider whose endpoint isn't recorded stays+ // ungated even when its model id names a local runtime.+ expect(localEndpointOfProvider({ type: 'tui', defaultModel: 'mtplx/local-qwen-27b', endpoint: null })).toBeNull();+ });+});++// ─── Source-level regression guards ────────────────────────────────────────//// These pin two structural invariants of the production code that the@@ -773,6 +1023,26 @@ describe('cos.js source — priority + capacity invariants', () => {expect(evalFn).toMatch(pattern);});+ it('dequeueNextTask threads the local-endpoint cap into its capacity tracker (#4834)', () => {+ // The gate only works if the scheduler actually supplies the resolver and+ // the running-agent tally — a refactor that drops either option silently+ // reverts to unlimited local dispatch, which is what caused the accelerator+ // OOM in the first place. Read from the real function body so a stray+ // reference elsewhere in cos.js can't satisfy this.+ const dequeueFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function dequeueNextTask'));+ expect(dequeueFn).toMatch(/countRunningAgentsByLocalEndpoint\(/);+ expect(dequeueFn).toMatch(/resolveLocalEndpoint:/);+ expect(dequeueFn).toMatch(/localEndpointLimit:/);+ });++ it('tryImmediateSpawn enforces the same local-endpoint cap (#4834)', () => {+ // This path bypasses the evaluation interval, so without its own check a+ // user-submitted task would dispatch straight past the local-GPU limit.+ const immediateFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function tryImmediateSpawn'));+ expect(immediateFn).toMatch(/resolveLocalEndpoint\(task\)/);+ expect(immediateFn).toMatch(/countRunningAgentsByLocalEndpoint\(/);+ });+it('idle generator is fenced by spawned===0 / tasksToSpawn.length===0', () => {// Pin the strict-idle gate. If a refactor drops either fence, idle could// spawn alongside autoSystem/mission and double-load the agent pool.diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.jsindex d5eff31fb1..8b1f864c54 100644--- a/server/services/cosDequeue.js+++ b/server/services/cosDequeue.js@@ -34,31 +34,67 @@* against both the global slots and the budget. A task with no `metadata.app`* buckets into the `_self` project key (PortOS-on-itself work) so app-less tasks* can't bypass the per-project cap.+ *+ * The THIRD cap is per local inference endpoint (issue #4834): a single GPU+ * can't hold N model contexts at once, so agents whose provider resolves to the+ * same local endpoint dispatch `localEndpointLimit` at a time and the rest stay+ * queued. Callers supply the already-resolved pieces — `localEndpointCounts`+ * (endpoint → running agents) and `resolveLocalEndpoint(task)` (which endpoint a+ * candidate would land on, built by cosLocalEndpointSlots.js) — so this module+ * stays pure and dependency-free. A task resolving to `null` (cloud provider, or+ * a TUI provider with no recorded endpoint) is ungated. `onLocalEndpointHold`+ * fires on a denial so the scheduler can log queued-no-slot without this module+ * importing the event bus.*/-export function createDequeueCapacity(state, { agentsByProject = {} } = {}) {+export function createDequeueCapacity(state, {+ agentsByProject = {},+ localEndpointCounts = {},+ localEndpointLimit = Infinity,+ resolveLocalEndpoint = () => null,+ onLocalEndpointHold = null,+} = {}) {const runningAgents = Object.values(state.agents).filter(a => a.status === 'running').length;const availableSlots = state.config.maxConcurrentAgents - runningAgents;const perProjectLimit = state.config.maxConcurrentAgentsPerProject || state.config.maxConcurrentAgents;+ // A caller passing 0/NaN would wedge every local-endpoint task forever; floor+ // at 1 so the cap degrades to "serialize", never to "never dispatch".+ const localSlotLimit = localEndpointLimit === Infinity+ ? Infinity+ : Math.max(1, Number(localEndpointLimit) || 1);const spawnProjectCounts = { ...agentsByProject };+ const spawnLocalEndpointCounts = { ...localEndpointCounts };let spawned = 0;const canSpawn = (task, ceiling = availableSlots) => {if (spawned >= ceiling) return false;const project = task.metadata?.app || '_self';- return (spawnProjectCounts[project] || 0) < perProjectLimit;+ if ((spawnProjectCounts[project] || 0) >= perProjectLimit) return false;+ const endpoint = resolveLocalEndpoint(task);+ if (endpoint) {+ const running = spawnLocalEndpointCounts[endpoint] || 0;+ if (running >= localSlotLimit) {+ onLocalEndpointHold?.(task, endpoint, running);+ return false;+ }+ }+ return true;};const trackSpawn = (task) => {const project = task.metadata?.app || '_self';spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;+ const endpoint = resolveLocalEndpoint(task);+ if (endpoint) spawnLocalEndpointCounts[endpoint] = (spawnLocalEndpointCounts[endpoint] || 0) + 1;spawned++;};return {availableSlots,perProjectLimit,+ localEndpointLimit: localSlotLimit,spawnProjectCounts,+ spawnLocalEndpointCounts,canSpawn,trackSpawn,// Live read of the running spawn count — a getter so callers always see the@@ -67,6 +103,24 @@ export function createDequeueCapacity(state, { agentsByProject = {} } = {}) {};}+/**+ * Count running agents grouped by the local inference endpoint they occupy+ * (issue #4834). `endpointForAgent` maps a running agent to its local endpoint+ * or null — supplied by cosLocalEndpointSlots.js so this stays pure. Agents on+ * cloud providers (and TUI providers with no recorded endpoint) resolve to null+ * and are not counted, mirroring the ungated path in `createDequeueCapacity`.+ */+export function countRunningAgentsByLocalEndpoint(agents, endpointForAgent) {+ const counts = {};+ for (const agent of Object.values(agents || {})) {+ if (agent.status !== 'running') continue;+ const endpoint = endpointForAgent(agent);+ if (!endpoint) continue;+ counts[endpoint] = (counts[endpoint] || 0) + 1;+ }+ return counts;+}+/*** Priority 3 (mission) tier eligibility. Mission tasks are speculative* autonomous spawns: they only run when there's autonomous headroom left thisdiff --git a/server/services/cosLocalEndpointSlots.js b/server/services/cosLocalEndpointSlots.jsnew file mode 100644index 0000000000..a644d7d296--- /dev/null+++ b/server/services/cosLocalEndpointSlots.js@@ -0,0 +1,93 @@+/**+ * CoS local-inference agent slots (issue #4834)+ *+ * `promptRunner`'s `withLocalConcurrencyGate` caps concurrent IN-FLIGHT calls+ * per local endpoint, but it only sees requests PortOS itself makes. A CoS TUI+ * agent runs a vendor CLI that opens its own connection to the local model+ * server — PortOS never observes that traffic, so `dequeueNextTask` could+ * dispatch two or three agents at one GPU and push it into an accelerator OOM.+ *+ * This module supplies the *avoidance* half: the per-cycle lookups the spawn+ * scheduler needs to count running agents per local endpoint and to predict+ * which endpoint a queued task would land on. The gate itself is enforced by+ * the pure capacity tracker in cosDequeue.js.+ *+ * Deliberately separate accounting from promptRunner's in-process gate: one+ * throttles requests PortOS makes, the other throttles agents PortOS launches.+ * A shared counter across process boundaries isn't worth the coupling.+ */++import { isLocalEndpoint, LOCAL_LLM_MAX_CONCURRENCY } from '../lib/promptRunner.js';+import { listProviders, getActiveProvider } from './providers.js';++// One knob governs both paths — no new config key. A local box beefy enough to+// hold N model contexts lifts LOCAL_LLM_MAX_CONCURRENCY and gets N agent slots+// along with N in-flight API calls.+export const LOCAL_ENDPOINT_AGENT_LIMIT = LOCAL_LLM_MAX_CONCURRENCY;++/**+ * The local endpoint a provider runs against, or null when it has none.+ *+ * Reads ONLY the endpoint recorded on the provider — never a model-id prefix.+ * A CLI/TUI provider with no recorded endpoint resolves to null and stays+ * ungated, which is the intended behavior: PortOS cannot know where an+ * unconfigured vendor CLI points.+ *+ * Not gated on `provider.type === 'api'` (unlike promptRunner's request gate):+ * a TUI provider pointed at a local LM Studio IS the case this exists for.+ */+export function localEndpointOfProvider(provider) {+ const endpoint = provider?.endpoint;+ return isLocalEndpoint(endpoint) ? endpoint.trim() : null;+}++/**+ * Build the per-cycle local-endpoint lookups from an ALREADY-FETCHED provider+ * snapshot. Pure and synchronous — the capacity tracker consults it per+ * candidate task, and tests drive it with fixtures instead of a live toolkit.+ *+ * - `endpointForAgent(agent)` — the endpoint a RUNNING agent is occupying,+ * from the `providerId` agentLifecycle stamps onto its metadata.+ * - `resolveLocalEndpoint(task)` — the endpoint a QUEUED task would land on.+ * Mirrors `resolveAgentProviderAndModel`: a `metadata.provider` pin wins,+ * and an unknown pin falls back to the active provider exactly as spawn+ * does. A runtime fallback swap can still move a run to another provider —+ * this is avoidance, not a guarantee, and promptRunner's gate plus the OOM+ * nudge/fail-over remain the recovery half.+ */+export function createLocalEndpointSlotContext({ providers = [], activeProvider = null, limit = LOCAL_ENDPOINT_AGENT_LIMIT } = {}) {+ const byId = new Map();+ for (const provider of providers) {+ if (provider?.id) byId.set(provider.id, provider);+ }+ if (activeProvider?.id && !byId.has(activeProvider.id)) byId.set(activeProvider.id, activeProvider);++ const endpointById = (id) => localEndpointOfProvider(byId.get(id));+ const activeEndpoint = localEndpointOfProvider(activeProvider);++ return {+ limit,+ endpointForAgent: (agent) => {+ const providerId = agent?.metadata?.providerId || agent?.providerId;+ return providerId ? endpointById(providerId) : null;+ },+ resolveLocalEndpoint: (task) => {+ const pinnedId = task?.metadata?.provider;+ if (pinnedId) return byId.has(pinnedId) ? endpointById(pinnedId) : activeEndpoint;+ return activeEndpoint;+ },+ };+}++/**+ * Fetch the provider snapshot and build the lookups above.+ *+ * Never throws: `listProviders` already swallows a failed read into `[]`, and+ * an uninitialized toolkit yields a null active provider — which resolves every+ * task to null (ungated) rather than stalling the queue.+ */+export async function buildLocalEndpointSlotContext() {+ const providers = await listProviders();+ const activeProvider = await getActiveProvider().catch(() => null);+ return createLocalEndpointSlotContext({ providers, activeProvider });+}