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

refactor: reuse localProviderRuntime for endpoint slot keys, drop the duplicate cap (#4834)

[._.]/ Adam Eivy1369f81e0b50
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.js
index 88587bf427..ed3d9f3713 100644
--- a/server/services/agentLifecycle.js
+++ b/server/services/agentLifecycle.js
@@ -75,6 +75,7 @@ import { v4 as uuidv4 } from '../lib/uuid.js';
// Imported for use here only; the pass-through re-exports that used to sit
// below them were retired with the `subAgentSpawner.js` barrel (#3450).
import { resolveAgentProviderAndModel } from './agentProviderResolution.js';
+import { providerBaseUrl } from './cosLocalEndpointSlots.js';
import { prepareAgentWorkspace } from './agentWorkspacePrep.js';
// `releaseRetryHold` is imported STATICALLY here (the TUI/direct-CLI spawners
// reach for it via `await import()` only because they sit BELOW this module and
@@ -506,10 +507,12 @@ async function runAgentSpawn(task) {
// mid-run. Pre-#4834 agent records have no value here, so the counter
// falls back to resolving the id against the live provider list.
//
- // `ANTHROPIC_BASE_URL` is the second source because an Ollama-backed CLI
- // provider (shipped: claude-ollama, claude-ollama-tui) records its daemon
- // there and leaves `endpoint` unset.
- providerEndpoint: provider.endpoint || provider.envVars?.ANTHROPIC_BASE_URL || null,
+ // Resolved through the SAME helper the counter reads with, so writer and
+ // reader can't drift — a CLI provider records its daemon in envVars or an
+ // OpenCode config, not in `endpoint`. Stamped as the RAW url, never the
+ // slot key: a slot key is null for a cloud provider, and stamping null
+ // would re-open the mid-run-edit hole this exists to close.
+ providerEndpoint: providerBaseUrl(provider),
leanMode,
// Whether THIS run's prompt told the agent to push, open, review, and merge
// its own PR. Persisted rather than re-derived at cleanup time: the two
diff --git a/server/services/cos.js b/server/services/cos.js
index f77d5b98f2..5bff0b58e9 100644
--- a/server/services/cos.js
+++ b/server/services/cos.js
@@ -853,19 +853,12 @@ 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;
- }
- }
+ // No local-endpoint check here (#4834). The task is already persisted by
+ // `addTask`, so emitting and letting the chokepoint hold it produces exactly
+ // the state an early return would — still `pending`, marker released, job
+ // reservation freed — and the chokepoint also counts in-flight reservations,
+ // which a snapshot here cannot. A copy would be a weaker duplicate that can
+ // pass a task the chokepoint then holds, for a fourth provider-list fetch.
emitLog('info', `⚡ Immediate spawn: ${task.id} (${task.priority || 'MEDIUM'})`, {
taskId: task.id,
@@ -966,12 +959,10 @@ async function spawnDequeuePriority0OnDemand(ctx) {
}
applyOnDemandConsent(task);
- // `gateLocalEndpoint: false` — a denial HERE would discard the user's "Run":
- // the request is already cleared and the app-review marker bound, and this
- // branch is the only thing that persists the task. Let it through and let the
- // chokepoint hold it (#4834) — that path leaves the task pending and releases
- // both side effects.
- if (task && capacity.canSpawn(task, undefined, { gateLocalEndpoint: false })) {
+ // Committed tier — the request is already cleared and the marker bound, and
+ // this branch is the only thing that persists the task, so a denial would
+ // discard the user's "Run". See canSpawnCommitted (#4834).
+ if (task && capacity.canSpawnCommitted(task)) {
// Mark this as a MANUAL (on-demand) run so a completed perpetual drain
// continues in the same user-initiated lane instead of the auto-run-gated
// queue path (see perpetualRefillPlan). Stamped before addTask so the
@@ -1183,13 +1174,14 @@ async function spawnDequeuePriority3Missions(ctx) {
taskType: 'internal',
approvalRequired: !missionTask.autoApprove
};
- // `gateLocalEndpoint: false` — same reason as Priority 0 (#4834). Mission
- // tasks are never written to COS-TASKS.md, and `generateMissionTasks` has
- // ALREADY flipped the sub-task to `in_progress` and saved the mission by the
- // time we get here. A denial would drop the only copy of a sub-task that
- // `generateMissionTask` will never re-pick (it selects `pending` only).
- // Emitting lets the chokepoint hold it instead.
- if (!capacity.canSpawn(cosTask, ctx.autonomousSpawnCeiling, { gateLocalEndpoint: false })) continue;
+ // Committed tier — `generateMissionTasks` has already flipped the sub-task to
+ // `in_progress` and saved the mission, and mission tasks are never written to
+ // COS-TASKS.md, so a denial drops the only copy of a sub-task that
+ // `generateMissionTask` will never re-pick (it selects `pending` only). See
+ // canSpawnCommitted (#4834). Note the emit does NOT recover the sub-task
+ // either — `holdTask` releases `metadata.app`/`jobId`, and a mission task
+ // carries neither — it just avoids making the loss worse here. Filed as #4858.
+ if (!capacity.canSpawnCommitted(cosTask, ctx.autonomousSpawnCeiling)) continue;
cosEvents.emit('task:ready', cosTask);
capacity.trackSpawn(cosTask);
emitLog('info', `Generated mission task: ${missionTask.id}`, {
@@ -1217,12 +1209,11 @@ async function spawnDequeuePriority4IdleReview(ctx) {
const pendingSystemTasks = freshCosTasks.autoApproved?.length || 0;
if (pendingSystemTasks === 0) {
const idleTask = await generateIdleReviewTask(state, { ignoreTaskId });
- // `gateLocalEndpoint: false` — same reason as Priority 0 (#4834).
- // `generateIdleReviewTask` has already bound the app-review marker and
- // advanced the 30-minute review cooldown by the time we get here, and only
- // `holdTask` releases that marker — which requires the emit. A denial would
- // leave the app reading "in review" indefinitely (issue #978's failure mode).
- if (idleTask && capacity.canSpawn(idleTask, ctx.autonomousSpawnCeiling, { gateLocalEndpoint: false })) {
+ // Committed tier — `generateIdleReviewTask` has already bound the app-review
+ // marker and advanced the 30-minute cooldown, and only `holdTask` releases
+ // that marker, which requires the emit. A denial would leave the app reading
+ // "in review" indefinitely (#978's mode). See canSpawnCommitted (#4834).
+ if (idleTask && capacity.canSpawnCommitted(idleTask, ctx.autonomousSpawnCeiling)) {
cosEvents.emit('task:ready', idleTask);
capacity.trackSpawn(idleTask);
}
@@ -1269,18 +1260,37 @@ async function dequeueNextTask({ ignoreTaskId = null } = {}) {
const paused = await isPaused();
const state = await loadState();
+
+ // Bail before the provider fetch below. This function fires from ~8 event
+ // sources plus a setImmediate on every completion, and a saturated pool — the
+ // state that makes those fire in bursts — would otherwise pay two awaits and
+ // a full agent scan per trigger for a tracker discarded immediately.
+ if (state.config.maxConcurrentAgents - Object.values(state.agents).filter(a => a.status === 'running').length <= 0) return;
+
// 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.
+ //
+ // Predictive only — it just avoids emitting a task the chokepoint would hold,
+ // so unlike `acquireLocalEndpointSpawnSlot` it does NOT count in-flight
+ // reservations. Erring toward admitting is correct here: the authoritative
+ // gate still refuses, and a hold is cheap.
const localSlots = await buildLocalEndpointSlotContext();
+ // One debug line per saturated endpoint per cycle, not one per queued task —
+ // the user/system tiers `continue` past a denial, so a 40-task queue behind
+ // one busy GPU would otherwise emit 40 identical log events, each broadcast
+ // to every CoS-subscribed socket client.
+ const loggedFullEndpoints = new Set();
const capacity = createDequeueCapacity(state, {
agentsByProject: countRunningAgentsByProject(state.agents),
localEndpointCounts: countRunningAgentsByLocalEndpoint(state.agents, localSlots.endpointForAgent),
localEndpointLimit: localSlots.limit,
resolveLocalEndpoint: localSlots.resolveLocalEndpoint,
onLocalEndpointHold: (task, endpoint, running) => {
+ if (loggedFullEndpoints.has(endpoint)) return;
+ loggedFullEndpoints.add(endpoint);
emitLog('debug', `⏳ Queued task ${task.id} - local endpoint ${endpoint} at capacity (${running}/${localSlots.limit})`, {
taskId: task.id,
endpoint
diff --git a/server/services/cos.test.js b/server/services/cos.test.js
index 133143e11c..0b52965aa8 100644
--- a/server/services/cos.test.js
+++ b/server/services/cos.test.js
@@ -109,10 +109,10 @@ function priorityDequeue(buckets, capacity, { paused = false } = {}) {
// cleared on-demand request, an `in_progress` mission sub-task, a bound
// app-review marker) instead of deferring it, so they emit and let the
// spawner chokepoint hold.
- const opts = { gateLocalEndpoint: !['onDemand', 'mission', 'idle'].includes(bucketName) };
+ const committed = ['onDemand', 'mission', 'idle'].includes(bucketName);
for (const task of buckets[bucketName] || []) {
if (capacity.spawned >= capacity.availableSlots) return;
- if (!capacity.canSpawn(task, undefined, opts)) continue;
+ if (!(committed ? capacity.canSpawnCommitted(task) : capacity.canSpawn(task))) continue;
capacity.trackSpawn(task);
admitted.push({ ...task, _bucket: bucketName });
}
@@ -595,9 +595,10 @@ describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {
expect(spawned.map(t => t.id)).toEqual(['mission-task']);
});
- it('keeps gating the deferrable tiers (1 and 2) at the same endpoint', () => {
- // The opt-out is scoped to the tiers whose denial is destructive. A
- // persisted user- or system-queue task stays queued, which is a real defer.
+ it.each(['user', 'autoSystem'])('keeps gating the deferrable %s tier at the same endpoint', (bucket) => {
+ // The opt-out is scoped to the tiers whose denial is destructive. A task
+ // from a persisted queue stays queued, which is a real defer — the next
+ // cycle re-picks it once the endpoint frees up.
const state = makeState({
maxConcurrentAgents: 5,
runningAgents: [makeRunningAgentOnProvider('lmstudio-tui')],
@@ -605,41 +606,13 @@ describe('dequeueNextTask — per-local-endpoint agent cap (#4834)', () => {
const { capacity } = makeLocalSlotCapacity(state);
const spawned = priorityDequeue({
- onDemand: [],
- user: [],
- autoSystem: [taskOnProvider('system-task', 'lmstudio-tui')],
- mission: [],
- idle: [],
+ onDemand: [], user: [], autoSystem: [], mission: [], idle: [],
+ [bucket]: [taskOnProvider('deferrable-task', 'lmstudio-tui')],
}, capacity);
expect(spawned).toEqual([]);
});
- it('still gates the SAME task from a deferrable tier', () => {
- // The opt-out is scoped to Priority 0. A user-tier task at the same endpoint
- // stays queued, because skipping it there is a genuine defer.
- const state = makeState({
- maxConcurrentAgents: 5,
- runningAgents: [makeRunningAgentOnProvider('lmstudio-tui')],
- });
- const { capacity } = makeLocalSlotCapacity(state);
-
- expect(priorityDequeue(userBuckets([taskOnProvider('task-run-now', 'lmstudio-tui')]), capacity)).toEqual([]);
- });
-
- 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.
@@ -949,11 +922,20 @@ describe('endpointForAgent — stamped endpoint wins over the id lookup (#4834)'
it('falls back to the id lookup for a pre-#4834 record with no stamp', () => {
expect(slots.endpointForAgent({ status: 'running', metadata: { providerId: 'lmstudio-tui' } })).toBe(LOCAL_ENDPOINT);
+ expect(slots.endpointForAgent({ status: 'running', metadata: { providerId: 'lmstudio-tui', providerEndpoint: null } })).toBe(LOCAL_ENDPOINT);
});
- it('ignores a stamped REMOTE endpoint rather than gating on it', () => {
- const agent = { status: 'running', metadata: { providerId: 'anthropic', providerEndpoint: 'https://api.anthropic.com/v1' } };
- expect(slots.endpointForAgent(agent)).toBeNull();
+ it('does NOT re-resolve when the stamp is REMOTE', () => {
+ // The agent is talking to the cloud. If its provider record is re-pointed at
+ // a local server mid-run, falling through to the id lookup would count this
+ // cloud agent against that GPU — saturating an endpoint with zero agents on
+ // it and holding every task behind it at the default limit of 1.
+ const cloudAgent = {
+ status: 'running',
+ metadata: { providerId: 'lmstudio-tui', providerEndpoint: 'https://api.anthropic.com/v1' },
+ };
+ expect(slots.endpointForAgent(cloudAgent)).toBeNull();
+ expect(countRunningAgentsByLocalEndpoint({ a: cloudAgent }, slots.endpointForAgent)).toEqual({});
});
});
@@ -1100,32 +1082,6 @@ describe('localEndpointOfProvider — Ollama-backed CLI/TUI providers (#4834)',
envVars: { ANTHROPIC_BASE_URL: 'http://192.0.2.10:11434' },
})).toBeNull();
});
-
- it('leaves a non-Ollama CLI provider with no endpoint ungated', () => {
- expect(localEndpointOfProvider({ id: 'claude-cli', type: 'cli', endpoint: null })).toBeNull();
- });
-});
-
-describe('endpointForAgent — a present stamp is authoritative both ways (#4834)', () => {
- const slots = createLocalEndpointSlotContext({ providers: ALL_PROVIDERS, activeProvider: CLOUD_PROVIDER });
-
- it('does NOT re-resolve when the stamp is REMOTE', () => {
- // The agent is talking to the cloud. If its provider record is re-pointed at
- // a local server mid-run, falling through to the id lookup would count this
- // cloud agent against that GPU — saturating an endpoint with zero agents on
- // it and holding every task behind it at the default limit of 1.
- const cloudAgent = {
- status: 'running',
- metadata: { providerId: 'lmstudio-tui', providerEndpoint: 'https://api.orcarouter.ai/v1' },
- };
- expect(slots.endpointForAgent(cloudAgent)).toBeNull();
- expect(countRunningAgentsByLocalEndpoint({ a: cloudAgent }, slots.endpointForAgent)).toEqual({});
- });
-
- it('still falls back to the id lookup when the stamp is ABSENT', () => {
- expect(slots.endpointForAgent({ status: 'running', metadata: { providerId: 'lmstudio-tui' } })).toBe(LOCAL_ENDPOINT);
- expect(slots.endpointForAgent({ status: 'running', metadata: { providerId: 'lmstudio-tui', providerEndpoint: null } })).toBe(LOCAL_ENDPOINT);
- });
});
// ─── Source-level regression guards ────────────────────────────────────────
@@ -1455,12 +1411,15 @@ describe('cos.js source — priority + capacity invariants', () => {
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.
+ it('tryImmediateSpawn does NOT re-implement the local-endpoint cap (#4834)', () => {
+ // Its task is already persisted by `addTask`, so emitting and letting the
+ // chokepoint hold produces exactly what an early return would. A local copy
+ // would be a weaker duplicate — it can only see a running-agent snapshot,
+ // not the in-flight reservations the authoritative gate also counts — so it
+ // could pass a task the chokepoint then holds, for an extra provider fetch.
const immediateFn = extractFnBody(COS_SRC, COS_SRC.indexOf('async function tryImmediateSpawn'));
- expect(immediateFn).toMatch(/resolveLocalEndpoint\(task\)/);
- expect(immediateFn).toMatch(/countRunningAgentsByLocalEndpoint\(/);
+ expect(immediateFn).not.toMatch(/resolveLocalEndpoint\(/);
+ expect(immediateFn).not.toMatch(/countRunningAgentsByLocalEndpoint\(/);
});
it('subAgentSpawner holds at the chokepoint every task:ready emitter funnels through (#4834)', () => {
@@ -1484,9 +1443,9 @@ describe('cos.js source — priority + capacity invariants', () => {
// Counting a running agent by provider id alone breaks when the provider is
// edited or deleted while the agent still holds the GPU.
const LIFECYCLE_SRC = readFileSync(join(__dirname, 'agentLifecycle.js'), 'utf-8');
- // Second source: an Ollama-backed CLI provider records its daemon in
- // ANTHROPIC_BASE_URL and leaves `endpoint` unset.
- expect(LIFECYCLE_SRC).toMatch(/providerEndpoint:\s*provider\.endpoint\s*\|\|\s*provider\.envVars\?\.ANTHROPIC_BASE_URL\s*\|\|\s*null/);
+ // Stamped through the SAME resolver the counter reads with, so writer and
+ // reader cannot drift on where a CLI provider records its daemon.
+ expect(LIFECYCLE_SRC).toMatch(/providerEndpoint:\s*providerBaseUrl\(provider\)/);
});
it('forceSpawnTask refuses synchronously when the local endpoint is full (#4834)', () => {
@@ -1503,23 +1462,25 @@ describe('cos.js source — priority + capacity invariants', () => {
.toBeLessThan(forceFn.indexOf("cosEvents.emit('task:ready'"));
});
- it('forceSpawnTask excludes the task\'s own zombie agent from the tally (#4834)', () => {
- // The route deliberately supersedes a stale `running` holder — counting it
- // would make that recovery unreachable at a limit of 1.
+ it('forceSpawnTask passes its task id so its own zombie agent is excluded (#4834)', () => {
+ // The route deliberately supersedes a stale `running` holder — counting that
+ // agent would make the recovery unreachable at a limit of 1. The exclusion
+ // itself is driven directly in the `readEndpointCapacity` block above; what
+ // that can't see is whether this caller opts into it.
const forceFn = extractFnBody(COS_SRC, COS_SRC.indexOf('export async function forceSpawnTask'));
- expect(forceFn).toMatch(/localEndpointCapacityError\(resolution\.provider,\s*state\.agents,\s*taskId\)/);
+ expect(forceFn).toMatch(/localEndpointCapacityError\([^)]*taskId\)/);
});
- it('the gate ignores an UNAVAILABLE provider so a held task cannot starve (#4834)', () => {
- // A saturated local provider that is down is not where the task lands —
- // spawn swaps it for a fallback. Holding on it would wait on a GPU the task
- // never touches, with nothing to clear the hold.
+ it('the LIVE gate wires in the real availability + fallback resolvers (#4834)', () => {
+ // The branch logic itself is driven directly above (`resolveLocalEndpoint —
+ // follows the fallback swap`) through injected doubles. What no unit test
+ // can reach is whether the PRODUCTION context injects the real ones — if it
+ // ever passed its own approximation, the prediction would silently drift
+ // from where spawn actually sends the task.
const SLOTS_SRC = readFileSync(join(__dirname, 'cosLocalEndpointSlots.js'), 'utf-8');
- const ctxFn = extractFnBody(SLOTS_SRC, SLOTS_SRC.indexOf('export function createLocalEndpointSlotContext'));
- expect(ctxFn).toMatch(/isAvailable\(primary\.id\)\s*\?\s*primary\s*:\s*resolveFallback\(/);
- expect(SLOTS_SRC, 'the live context must use the real provider-status predicate')
+ expect(SLOTS_SRC, 'must use the real provider-status predicate')
.toMatch(/isAvailable:\s*isProviderAvailable/);
- expect(SLOTS_SRC, 'and the REAL fallback resolver, so the prediction cannot drift from spawn')
+ expect(SLOTS_SRC, 'and the real fallback resolver spawn uses')
.toMatch(/getFallbackProvider\(/);
});
@@ -1533,11 +1494,11 @@ describe('cos.js source — priority + capacity invariants', () => {
// genuine defer — they keep the cap.
for (const tier of ['spawnDequeuePriority0OnDemand', 'spawnDequeuePriority3Missions', 'spawnDequeuePriority4IdleReview']) {
const body = extractFnBody(COS_SRC, COS_SRC.indexOf(`async function ${tier}`));
- expect(body, `${tier} must opt out of the local-endpoint cap`).toMatch(/gateLocalEndpoint:\s*false/);
+ expect(body, `${tier} must admit via canSpawnCommitted`).toMatch(/canSpawnCommitted\(/);
}
for (const tier of ['spawnDequeuePriority1UserTasks', 'spawnDequeuePriority2AutoApproved']) {
const body = extractFnBody(COS_SRC, COS_SRC.indexOf(`async function ${tier}`));
- expect(body, `${tier} must not opt out of the local-endpoint cap`).not.toMatch(/gateLocalEndpoint:\s*false/);
+ expect(body, `${tier} defers rather than discards — it must keep the cap`).not.toMatch(/canSpawnCommitted\(/);
}
});
diff --git a/server/services/cosDequeue.js b/server/services/cosDequeue.js
index d11c90a429..2c66aeeac9 100644
--- a/server/services/cosDequeue.js
+++ b/server/services/cosDequeue.js
@@ -46,7 +46,7 @@
* fires on a denial so the scheduler can log queued-no-slot without this module
* importing the event bus.
*
- * `gateLocalEndpoint: false` opts a tier out of that third cap. Three tiers do,
+ * `canSpawnCommitted` opts a tier out of that third cap. Three tiers use it,
* because a denial there is DESTRUCTIVE rather than a defer — each has already
* committed side effects by the time `canSpawn` runs, and none of them persists
* the task, so `false` discards the only copy:
@@ -75,15 +75,14 @@ export function createDequeueCapacity(state, {
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);
+ // `Infinity` (the no-cap default) passes through unchanged.
+ const localSlotLimit = Math.max(1, Number(localEndpointLimit) || 1);
const spawnProjectCounts = { ...agentsByProject };
const spawnLocalEndpointCounts = { ...localEndpointCounts };
let spawned = 0;
- const canSpawn = (task, ceiling = availableSlots, { gateLocalEndpoint = true } = {}) => {
+ const admit = (task, ceiling, gateLocalEndpoint) => {
if (spawned >= ceiling) return false;
const project = task.metadata?.app || '_self';
if ((spawnProjectCounts[project] || 0) >= perProjectLimit) return false;
@@ -98,6 +97,12 @@ export function createDequeueCapacity(state, {
return true;
};
+ const canSpawn = (task, ceiling = availableSlots) => admit(task, ceiling, true);
+ // For a COMMITTED tier — one that has already taken side effects and does not
+ // persist the task, so a denial would discard it rather than defer it. Skips
+ // only the local-endpoint cap; see the header for which tiers qualify and why.
+ const canSpawnCommitted = (task, ceiling = availableSlots) => admit(task, ceiling, false);
+
const trackSpawn = (task) => {
const project = task.metadata?.app || '_self';
spawnProjectCounts[project] = (spawnProjectCounts[project] || 0) + 1;
@@ -113,6 +118,7 @@ export function createDequeueCapacity(state, {
spawnProjectCounts,
spawnLocalEndpointCounts,
canSpawn,
+ canSpawnCommitted,
trackSpawn,
// Live read of the running spawn count — a getter so callers always see the
// current total after trackSpawn mutations rather than a stale snapshot.
diff --git a/server/services/cosLocalEndpointSlots.js b/server/services/cosLocalEndpointSlots.js
index 12a50e5198..48949c1e9c 100644
--- a/server/services/cosLocalEndpointSlots.js
+++ b/server/services/cosLocalEndpointSlots.js
@@ -22,68 +22,56 @@
* A shared counter across process boundaries isn't worth the coupling.
*/
-import { isLocalEndpoint, LOCAL_LLM_MAX_CONCURRENCY } from '../lib/promptRunner.js';
-import { listProviders, getActiveProvider, isOllamaBackedProvider } from './providers.js';
+import { LOCAL_LLM_MAX_CONCURRENCY } from '../lib/promptRunner.js';
+import { localRuntimeForProvider, localEndpointPort, normalizeOpenAiBaseUrl } from '../lib/localProviderRuntime.js';
+import { listProviders, getActiveProvider } from './providers.js';
import { isProviderAvailable, getFallbackProvider } from './providerStatus.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;
-
-// An Ollama-backed CLI/TUI provider carries the daemon in `envVars`, not in
-// `endpoint` — the shipped `claude-ollama` / `claude-ollama-tui` set
-// `ANTHROPIC_BASE_URL`, and `opencode-ollama` / `opencode-ollama-tui` carry only
-// the `ollamaBacked` marker (their base lives inside an OPENCODE_CONFIG_CONTENT
-// blob, which `ollamaBaseFromProvider` in the toolkit does not parse either —
-// the marker alone means the default daemon).
-const DEFAULT_OLLAMA_BASE = 'http://localhost:11434';
-
/**
- * The local endpoint a provider runs against, or null when it has none.
- *
- * Reads ONLY what the provider RECORD says — the endpoint, else the Ollama base
- * its `envVars` name, else the default daemon when (and only when) the record
- * carries an explicit `ollamaBacked` marker. Never a model-id prefix. Everything
- * else stays ungated: PortOS cannot know where an unconfigured vendor CLI points.
+ * The raw base URL a provider's inference actually goes to, local or not.
*
- * The Ollama arm matters because four SHIPPED CLI/TUI providers run against the
- * local daemon with no `endpoint` at all — precisely the "the vendor CLI opens
- * its own connection and PortOS never sees it" case #4834 exists for. Skipping
- * them would leave the cap inconsistent across providers of the same shape.
+ * `localRuntimeForProvider` already owns this question — it reads the base the
+ * provider ITSELF configures (an OpenCode `baseURL`, `ANTHROPIC_BASE_URL`, or
+ * `endpoint`), then the `OLLAMA_URL`/`OLLAMA_HOST`/`LM_STUDIO_URL` overrides the
+ * backend managers read, then the runtime's canonical default. That matters
+ * here: a user who relocates their daemon with `OLLAMA_HOST` would otherwise get
+ * two independent slot keys for one daemon — the exact double-booking this cap
+ * exists to prevent.
*
- * 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.
+ * It answers `null` for a provider that maps to no KNOWN local runtime, so fall
+ * back to the recorded endpoint: an arbitrary local server (the shipped
+ * `opencode-vllm-tui` on `127.0.0.1:18020`, or a user's own TUI provider) still
+ * occupies a GPU. Whether either is on THIS box is decided by
+ * `localEndpointPort` below, never by the provider's name or model id.
+ */
+export function providerBaseUrl(provider) {
+ return localRuntimeForProvider(provider)?.endpoint || provider?.endpoint || null;
+}
+
+/**
+ * The slot key a provider's inference occupies, or null when it isn't on this
+ * machine. Host+port identifies the model server; the scheme, the path (`/v1`)
+ * and the host SPELLING do not — the shipped catalog seeds `lmstudio` at
+ * `localhost:1234` and everything else at `127.0.0.1`, so keying on the raw
+ * string would give one LM Studio process two independent caps.
*
- * The return value is a NORMALIZED SLOT KEY (`localhost:<port>`), not the raw
- * string — see `LOCAL_SLOT_KEY_RE`. It is only ever used as a Map key and in the
- * queued-no-slot log line.
+ * `localEndpointPort` supplies that normalization (every loopback spelling
+ * collapses, the port defaults by scheme) AND rejects a LAN/Tailscale peer that
+ * merely shares a port. 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) {
- if (!provider) return null;
- // A recorded base is authoritative, including when it is REMOTE: an Ollama
- // daemon on another host must resolve to null, not to the local default.
- const recorded = provider.endpoint || provider.envVars?.ANTHROPIC_BASE_URL;
- if (recorded) return localSlotKey(recorded);
- return isOllamaBackedProvider(provider) ? localSlotKey(DEFAULT_OLLAMA_BASE) : null;
+ return localSlotKey(providerBaseUrl(provider));
}
-// Host+port identifies the model server; the scheme, path (`/v1`) and host
-// SPELLING do not. The shipped catalog already mixes spellings — `lmstudio` is
-// seeded at `http://localhost:1234/v1` while everything else uses `127.0.0.1` —
-// so keying on the raw string would give one LM Studio process two independent
-// caps and let two agents onto the same GPU, the exact OOM #4834 prevents.
-// Every loopback host collapses onto one key; the port keeps distinct local
-// servers apart.
-const LOCAL_SLOT_KEY_RE = /^(?:https?:\/\/)?(?:localhost|127\.0\.0\.1|0\.0\.0\.0|\[?::1\]?)(?::(\d+))?(?:[/?#]|$)/i;
-
-/** The slot key for `endpoint`, or null when it is remote/absent/unparseable. */
-function localSlotKey(endpoint) {
- if (!isLocalEndpoint(endpoint)) return null;
- const match = endpoint.trim().match(LOCAL_SLOT_KEY_RE);
- if (!match) return null;
- return match[1] ? `localhost:${match[1]}` : 'localhost';
-}
+// Normalize first so a schemeless value still parses — `localEndpointPort` goes
+// through `new URL`, which reads `localhost:1234` as a SCHEME and yields null.
+// Providers configured through the UI can carry a bare `host:port`.
+const localSlotKey = (endpoint) => {
+ const port = localEndpointPort(normalizeOpenAiBaseUrl(endpoint));
+ return port ? `localhost:${port}` : null;
+};
/**
* Build the per-cycle local-endpoint lookups from an ALREADY-FETCHED provider
@@ -112,7 +100,10 @@ function localSlotKey(endpoint) {
export function createLocalEndpointSlotContext({
providers = [],
activeProvider = null,
- limit = LOCAL_ENDPOINT_AGENT_LIMIT,
+ // One knob governs both paths — no new config key. A 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.
+ limit = LOCAL_LLM_MAX_CONCURRENCY,
isAvailable = () => true,
resolveFallback = () => null,
} = {}) {
@@ -173,7 +164,33 @@ export function createLocalEndpointSlotContext({
* an uninitialized toolkit yields a null active provider — which resolves every
* task to null (ungated) rather than stalling the queue.
*/
+// One dispatch consults this 2-3 times — the dequeue cycle, then the chokepoint
+// per emitted task (and "Run now" checks before emitting too). Each build costs
+// two provider reads plus a Map and an object over the whole catalog, so cache
+// the SNAPSHOT for a beat. Deliberately the same TTL the toolkit's own provider
+// cache uses: this adds no staleness the callers didn't already have.
+//
+// Only the provider LIST is cached. `isAvailable` and `resolveFallback` are read
+// live inside the returned closures, so a provider going unavailable still
+// changes the answer immediately — which is what the gate turns on.
+const SNAPSHOT_TTL_MS = 1000;
+let snapshot = null;
+let snapshotAt = 0;
+
+/** Test hook — drop the cached provider snapshot. */
+export function __resetLocalEndpointSlotCache() {
+ snapshot = null;
+ snapshotAt = 0;
+}
+
export async function buildLocalEndpointSlotContext() {
+ if (snapshot && Date.now() - snapshotAt < SNAPSHOT_TTL_MS) return snapshot;
+ snapshot = await buildSlotContextUncached();
+ snapshotAt = Date.now();
+ return snapshot;
+}
+
+async function buildSlotContextUncached() {
const providers = await listProviders();
const activeProvider = await getActiveProvider().catch(() => null);
return createLocalEndpointSlotContext({
@@ -215,9 +232,9 @@ let reservationSeq = 0;
const NOOP_RELEASE = () => {};
/**
- * Reserve an in-flight spawn slot on `endpoint` for `taskId`. Returns the
- * release function, which is idempotent so a double-release (a throw plus the
- * `finally`) can't free a slot that is still occupied.
+ * Reserve an in-flight spawn slot on `endpoint` for `taskId`. Release is
+ * idempotent because the spawner calls it from a `finally` that a throw can
+ * reach twice — a second decrement would free a slot still occupied.
*/
export function reserveLocalEndpointSpawn(endpoint, taskId = null) {
if (!endpoint) return NOOP_RELEASE;
@@ -239,12 +256,7 @@ export function reserveLocalEndpointSpawn(endpoint, taskId = null) {
};
}
-/**
- * Spawns dispatched at `endpoint` that have not yet reached `running`.
- *
- * `excludeTaskIds` drops reservations whose agent HAS already registered — the
- * running tally counts those, and double-counting them under-admits.
- */
+/** Spawns dispatched at `endpoint` that have not yet reached `running`. */
export function pendingLocalEndpointSpawns(endpoint, { excludeTaskIds = null } = {}) {
const held = endpoint ? pendingSpawnsByEndpoint.get(endpoint) : null;
if (!held) return 0;
diff --git a/server/services/cosTaskGenerator.test.js b/server/services/cosTaskGenerator.test.js
index 466d87bbe3..54e84d3460 100644
--- a/server/services/cosTaskGenerator.test.js
+++ b/server/services/cosTaskGenerator.test.js
@@ -266,9 +266,9 @@ describe('both on-demand engines apply consent before addTask', () => {
it('dequeueNextTask engine consents before canSpawn / addTask', () => {
const engine = engineBody(COS_SRC, 'async function spawnDequeuePriority0OnDemand');
expect(engine.indexOf('applyOnDemandConsent(task)')).toBeGreaterThan(-1);
- // Prefix match, not the full call: Priority 0 passes the local-endpoint
- // opt-out (#4834), so the arg list is no longer bare `(task)`.
- expect(engine.indexOf('applyOnDemandConsent(task)')).toBeLessThan(engine.indexOf('capacity.canSpawn(task'));
+ // Match either admit method: Priority 0 is a COMMITTED tier, so it calls
+ // `canSpawnCommitted` rather than `canSpawn` (#4834).
+ expect(engine.indexOf('applyOnDemandConsent(task)')).toBeLessThan(engine.search(/capacity\.canSpawn(Committed)?\(task/));
});
it('idle-review steal path consents when it drains an on-demand request', () => {
diff --git a/server/services/subAgentSpawner.dispatchHolds.test.js b/server/services/subAgentSpawner.dispatchHolds.test.js
index fd2d6ce738..5fb658e16c 100644
--- a/server/services/subAgentSpawner.dispatchHolds.test.js
+++ b/server/services/subAgentSpawner.dispatchHolds.test.js
@@ -18,6 +18,7 @@
* vendor CLI that talks to the local model server directly, so promptRunner's
* in-flight gate never sees it; two agents at one GPU takes an accelerator
* OOM. The slot is reserved across the spawn window and released after.
+ *
* The holds live in that listener, not inside `runAgentSpawn`, because a hold
* below the spawn body's entry returns past `releaseAppReviewMarker` and strands
* the synthetic "in review" marker for the whole outage (issue #989). The side