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
fix: enforce the local-endpoint agent cap at the spawner chokepoint (#4834)
[._.]/ Adam Eivy81b37532687e
diff --git a/server/services/agentLifecycle.js b/server/services/agentLifecycle.jsindex ac9e724387..c41a90973d 100644--- a/server/services/agentLifecycle.js+++ b/server/services/agentLifecycle.js@@ -499,6 +499,13 @@ async function runAgentSpawn(task) {// answer that — a path-configured `claude` under a custom id is slashdo-// capable, and a lean `--bare` session is not.providerCommand: provider.command || null,+ // The endpoint this agent's inference actually lands on, stamped for the+ // same reason as the command above: the per-local-endpoint spawn cap+ // (#4834) must know which GPU a RUNNING agent is occupying, and an id+ // alone can't answer that once the provider record is edited or deleted+ // mid-run. Pre-#4834 agent records have no value here, so the counter+ // falls back to resolving the id against the live provider list.+ providerEndpoint: provider.endpoint || null,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 twodiff --git a/server/services/cos.test.js b/server/services/cos.test.jsindex 43cf36409b..e7c01904ce 100644--- a/server/services/cos.test.js+++ b/server/services/cos.test.js@@ -30,14 +30,20 @@* `availableSlots <= 0` short-circuit flips a clear red flag.*/-import { describe, it, expect } from 'vitest';+import { describe, it, expect, beforeEach } from 'vitest';import { readFileSync } from 'fs';import { fileURLToPath } from 'url';import { dirname, join } from 'path';import { firstLine, isPerpetualRefillCandidate, perpetualRefillPlan } from './cos.js';import { canQueueImprovementTasks } from './cosState.js';import { createDequeueCapacity, countRunningAgentsByLocalEndpoint, isMissionTierEligible, isIdleTierEligible } from './cosDequeue.js';-import { createLocalEndpointSlotContext, localEndpointOfProvider } from './cosLocalEndpointSlots.js';+import {+ createLocalEndpointSlotContext,+ localEndpointOfProvider,+ reserveLocalEndpointSpawn,+ pendingLocalEndpointSpawns,+ __resetLocalEndpointSpawnReservations,+} from './cosLocalEndpointSlots.js';import { PENDING_MERGE_SWEEP_INTERVAL_MS, MAX_PENDING_MERGE_TICKS } from './prWatcher.js';const __dirname = dirname(fileURLToPath(import.meta.url));@@ -708,6 +714,77 @@ describe('localEndpointOfProvider (#4834)', () => {});+describe('local-endpoint spawn reservations (#4834)', () => {+ beforeEach(() => __resetLocalEndpointSpawnReservations());++ it('counts a reserved-but-not-yet-running spawn against the endpoint', () => {+ // The window between `task:ready` and the agent record reaching `running`+ // is several awaits wide. Without the reservation, a second dispatch inside+ // it reads a snapshot showing zero running agents and over-dispatches.+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(0);+ const release = reserveLocalEndpointSpawn(LOCAL_ENDPOINT);+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(1);+ release();+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(0);+ });++ it('is idempotent — a double release cannot free a slot twice', () => {+ // The spawner releases in a `finally`, so a throw plus the finally can call+ // it twice. A naive decrement would go negative and hand out a phantom slot.+ const first = reserveLocalEndpointSpawn(LOCAL_ENDPOINT);+ const second = reserveLocalEndpointSpawn(LOCAL_ENDPOINT);+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(2);+ first();+ first();+ first();+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(1);+ second();+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(0);+ });++ it('reserving a null endpoint is a no-op', () => {+ const release = reserveLocalEndpointSpawn(null);+ expect(pendingLocalEndpointSpawns(null)).toBe(0);+ expect(() => release()).not.toThrow();+ });++ it('keeps reservations per endpoint', () => {+ reserveLocalEndpointSpawn(LOCAL_ENDPOINT);+ reserveLocalEndpointSpawn(OTHER_LOCAL_ENDPOINT);+ expect(pendingLocalEndpointSpawns(LOCAL_ENDPOINT)).toBe(1);+ expect(pendingLocalEndpointSpawns(OTHER_LOCAL_ENDPOINT)).toBe(1);+ });+});++describe('endpointForAgent — stamped endpoint wins over the id lookup (#4834)', () => {+ const slots = createLocalEndpointSlotContext({ providers: ALL_PROVIDERS, activeProvider: CLOUD_PROVIDER });++ it('counts an agent whose provider record was deleted mid-run', () => {+ // Only `providerId` was persisted pre-#4834, so a deleted provider made a+ // still-running agent invisible to the cap — freeing a slot the GPU was+ // still holding. The stamped endpoint survives the deletion.+ const orphaned = { status: 'running', metadata: { providerId: 'deleted-provider', providerEndpoint: LOCAL_ENDPOINT } };+ expect(slots.endpointForAgent(orphaned)).toBe(LOCAL_ENDPOINT);+ expect(countRunningAgentsByLocalEndpoint({ a: orphaned }, slots.endpointForAgent)).toEqual({ [LOCAL_ENDPOINT]: 1 });+ });++ it('prefers the stamp when the provider record was re-pointed mid-run', () => {+ // The agent is still talking to the endpoint it started on, not the one the+ // provider now names.+ const agent = { status: 'running', metadata: { providerId: 'ollama-local', providerEndpoint: LOCAL_ENDPOINT } };+ expect(slots.endpointForAgent(agent)).toBe(LOCAL_ENDPOINT);+ });++ 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);+ });++ 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();+ });+});+// ─── Source-level regression guards ────────────────────────────────────────//// These pin two structural invariants of the production code that the@@ -1043,6 +1120,30 @@ describe('cos.js source — priority + capacity invariants', () => {expect(immediateFn).toMatch(/countRunningAgentsByLocalEndpoint\(/);});+ it('subAgentSpawner holds at the chokepoint every task:ready emitter funnels through (#4834)', () => {+ // dequeueNextTask is only ONE of the emitters — evaluateTasks,+ // forceSpawnTask, the job scheduler and the Creative Director bridge all+ // reach the spawner directly. If the gate ever moves back to the scheduler+ // alone, those paths silently over-dispatch at the local GPU again.+ const SPAWNER_SRC = readFileSync(join(__dirname, 'subAgentSpawner.js'), 'utf-8');+ expect(SPAWNER_SRC, 'spawner must acquire a local-endpoint slot before spawning')+ .toMatch(/acquireLocalEndpointSpawnSlot\(/);+ // The reservation is only correct if it is released once the spawn settles;+ // a missing `finally` leaks the slot and wedges the endpoint forever.+ const listener = SPAWNER_SRC.slice(SPAWNER_SRC.indexOf("cosEvents.on('task:ready'"));+ expect(listener, 'the acquired slot must be released in a finally')+ .toMatch(/finally\s*\{\s*\n\s*localSlot\.release\(\);/);+ expect(listener, 'a task at capacity must be HELD (left pending), not failed')+ .toMatch(/holdTask\(task,\s*localSlot\.reason\)/);+ });++ it('agentLifecycle stamps the resolved endpoint onto the agent record (#4834)', () => {+ // 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');+ expect(LIFECYCLE_SRC).toMatch(/providerEndpoint:\s*provider\.endpoint\s*\|\|\s*null/);+ });+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/cosLocalEndpointSlots.js b/server/services/cosLocalEndpointSlots.jsindex a644d7d296..70cb743fdf 100644--- a/server/services/cosLocalEndpointSlots.js+++ b/server/services/cosLocalEndpointSlots.js@@ -7,10 +7,15 @@* 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.+ * This module supplies the *avoidance* half, enforced at two altitudes:+ *+ * - `acquireLocalEndpointSpawnSlot` is the AUTHORITATIVE cap, called from+ * subAgentSpawner's `task:ready` listener — the one chokepoint every+ * emitter funnels through. It reserves the slot across the spawn window so+ * two dispatches can't both read a pre-registration snapshot and pass.+ * - `createLocalEndpointSlotContext` feeds the pure capacity tracker in+ * cosDequeue.js, so `dequeueNextTask` simply never emits a task that would+ * be held — cheaper, and it logs queued-no-slot against the right task.** Deliberately separate accounting from promptRunner's in-process gate: one* throttles requests PortOS makes, the other throttles agents PortOS launches.@@ -19,6 +24,7 @@import { isLocalEndpoint, LOCAL_LLM_MAX_CONCURRENCY } from '../lib/promptRunner.js';import { listProviders, getActiveProvider } from './providers.js';+import { countRunningAgentsByLocalEndpoint } from './cosDequeue.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@@ -68,6 +74,12 @@ export function createLocalEndpointSlotContext({ providers = [], activeProviderreturn {limit,endpointForAgent: (agent) => {+ // The endpoint stamped at spawn wins: it is what this agent's inference+ // ACTUALLY landed on, and it survives the provider record being edited or+ // deleted while the agent is still holding the GPU. Falling back to the id+ // lookup keeps pre-#4834 agent records counted.+ const stamped = localEndpointOfProvider({ endpoint: agent?.metadata?.providerEndpoint });+ if (stamped) return stamped;const providerId = agent?.metadata?.providerId || agent?.providerId;return providerId ? endpointById(providerId) : null;},@@ -91,3 +103,77 @@ export async function buildLocalEndpointSlotContext() {const activeProvider = await getActiveProvider().catch(() => null);return createLocalEndpointSlotContext({ providers, activeProvider });}++// ── In-flight spawn reservations ───────────────────────────────────────────+// A dispatched task is invisible to `countRunningAgentsByLocalEndpoint` until+// its agent record reaches `running` — a window several awaits wide (provider+// resolution, prompt build, worktree setup, PTY spawn). Two `task:ready`+// dispatches landing inside that window would both read the same snapshot and+// both pass the cap, which is the exact over-dispatch #4834 exists to stop.+//+// So the chokepoint reserves the slot up front and releases it once the spawn+// settles — by which point the agent record carries the load. This is a simple+// in-process re-entrancy guard over one server's own dispatch loop, not a+// defense against competing actors (see the Security Model in CLAUDE.md).+// Mirrors `spawningJobIds` in cosJobScheduler.js, which bridges the same gap.+const pendingSpawnsByEndpoint = new Map();++const NOOP_RELEASE = () => {};++/**+ * Reserve an in-flight spawn slot on `endpoint`. Returns the release function,+ * which is idempotent so a double-release (a throw plus the `finally`) can't+ * drive the count negative and hand out a slot that is still occupied.+ */+export function reserveLocalEndpointSpawn(endpoint) {+ if (!endpoint) return NOOP_RELEASE;+ pendingSpawnsByEndpoint.set(endpoint, (pendingSpawnsByEndpoint.get(endpoint) || 0) + 1);+ let released = false;+ return () => {+ if (released) return;+ released = true;+ const remaining = (pendingSpawnsByEndpoint.get(endpoint) || 1) - 1;+ if (remaining > 0) pendingSpawnsByEndpoint.set(endpoint, remaining);+ else pendingSpawnsByEndpoint.delete(endpoint);+ };+}++/** Spawns dispatched at `endpoint` that have not yet reached `running`. */+export function pendingLocalEndpointSpawns(endpoint) {+ return endpoint ? (pendingSpawnsByEndpoint.get(endpoint) || 0) : 0;+}++/** Test hook — drop every outstanding reservation. */+export function __resetLocalEndpointSpawnReservations() {+ pendingSpawnsByEndpoint.clear();+}++/**+ * Claim a local-endpoint spawn slot for `task`, or report why it must wait.+ *+ * This is the AUTHORITATIVE cap. The scheduler-side check in `dequeueNextTask`+ * only avoids emitting a `task:ready` that would be held anyway; six other+ * emitters (evaluateTasks, forceSpawnTask, cosJobScheduler, the Creative+ * Director bridge, …) reach the spawner without passing through it, so the gate+ * has to live where all of them funnel — subAgentSpawner's `task:ready`+ * listener.+ *+ * `{ ok: true }` with a no-op release when the task has no local endpoint.+ * Callers MUST invoke `release()` in a `finally` once the spawn settles.+ *+ * @param {object} task+ * @param {object} agents - `state.agents`, the running-agent map+ * @returns {Promise<{ ok: true, release: () => void } | { ok: false, reason: string }>}+ */+export async function acquireLocalEndpointSpawnSlot(task, agents) {+ const slots = await buildLocalEndpointSlotContext();+ const endpoint = slots.resolveLocalEndpoint(task);+ if (!endpoint) return { ok: true, release: NOOP_RELEASE };++ const running = countRunningAgentsByLocalEndpoint(agents, slots.endpointForAgent)[endpoint] || 0;+ const inFlight = running + pendingLocalEndpointSpawns(endpoint);+ if (inFlight >= slots.limit) {+ return { ok: false, reason: `local endpoint ${endpoint} is at capacity (${inFlight}/${slots.limit})` };+ }+ return { ok: true, release: reserveLocalEndpointSpawn(endpoint) };+}diff --git a/server/services/subAgentSpawner.js b/server/services/subAgentSpawner.jsindex f79ba3a1e5..c300989524 100644--- a/server/services/subAgentSpawner.js+++ b/server/services/subAgentSpawner.js@@ -47,6 +47,8 @@ import { runnerAgents, setUseRunner, useRunner } from './agentState.js';import { releaseAppReviewMarker } from './appActivity.js';import { isUpdateInProgress } from './updateChecker.js';import { releaseMissionSubTask } from './missions.js';+import { loadState } from './cosState.js';+import { acquireLocalEndpointSpawnSlot } from './cosLocalEndpointSlots.js';// This module's own event wiring drives three LIFECYCLE TRANSITIONS, so it takes// them from the facade rather than from the three separate leaves that happen to// implement them (#3450). It can: nothing the facade imports imports this module@@ -83,8 +85,9 @@ let runnerRecovery = Promise.resolve();* revert, the sub-task is stranded for good: there is no record left queued,* and generation only ever re-picks `pending` sub-tasks.*- * Shared by every hold condition (self-update in progress, runner down, and any- * that follow) so a new one can't ship with only half the releases.+ * Shared by every hold condition (self-update in progress, runner down, local+ * inference endpoint at capacity, and any that follow) so a new one can't ship+ * with only half the releases.*/async function holdTask(task, reason) {emitLog('debug', `⏸️ Holding task ${task.id} — ${reason}`, { taskId: task.id });@@ -368,6 +371,19 @@ async function runInitSpawner() {if (useRunner && !(await isRunnerReachable())) {return holdTask(task, 'CoS Runner is down');}+ // 3. Local inference endpoint at capacity (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 — without this, two agents+ // can be dispatched at one GPU and the runtime kills a turn with an+ // accelerator OOM. Held HERE because `dequeueNextTask` is only one of the+ // emitters: evaluateTasks, forceSpawnTask, the job scheduler and the+ // Creative Director bridge all reach this listener directly. The slot is+ // reserved across the spawn window and released below, since the agent+ // record isn't countable until it reaches `running`.+ const localSlot = await acquireLocalEndpointSpawnSlot(task, (await loadState()).agents);+ if (!localSlot.ok) {+ return holdTask(task, localSlot.reason);+ }try {await spawnAgentForTask(task);} catch (err) {@@ -376,6 +392,8 @@ async function runInitSpawner() {if (jobId) {cosEvents.emit('job:spawn-failed', { jobId });}+ } finally {+ localSlot.release();}});