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
fold untrusted-content context window onto the shared num_ctx clamp
[._.]/ Adam Eivy190ca1a90289
diff --git a/server/lib/README.md b/server/lib/README.mdindex 508d5bba1e..c0052ccde3 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -176,7 +176,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| Module | Purpose ||---|---|-| `aiToolkit/` | Vendored toolkit (providers + runner + prompts + status). See `aiToolkit/index.js`. `aiToolkit/endpointGuard.js` is the public SSRF / key-exfiltration guard for provider `endpoint` URLs (`evaluateSecretEndpoint` / `assertSecretEndpoint`) — import it from there, not from `internal/`. `aiToolkit/internal/ollamaBacked.js` also declares `clampToRuntimeContextWindow(provider, planned)` — what an Ollama `num_ctx` means to a context window: an upper bound over every planning rung (a typed override included), and the answer when nothing else declared one. The budgeter (`services/stageRunner.js`), the pre-dispatch gate (`aiToolkit/providerStatus.js#knownContextWindow`) and the browser's provider-card meter all import it from there rather than restating it (#7466). |+| `aiToolkit/` | Vendored toolkit (providers + runner + prompts + status). See `aiToolkit/index.js`. `aiToolkit/endpointGuard.js` is the public SSRF / key-exfiltration guard for provider `endpoint` URLs (`evaluateSecretEndpoint` / `assertSecretEndpoint`) — import it from there, not from `internal/`. `aiToolkit/internal/ollamaBacked.js` also declares `clampToRuntimeContextWindow(provider, planned)` — what an Ollama `num_ctx` means to a context window: an upper bound over every planning rung (a typed override included), and the answer when nothing else declared one. The budgeter (`services/stageRunner.js`), the pre-dispatch gate (`aiToolkit/providerStatus.js#knownContextWindow`), the untrusted-content abuse guard (`services/untrustedContent.js`, via `knownContextWindow` — a deep import kept off `stageRunner.js`'s heavier closure since it sits on a request path) and the browser's provider-card meter all import it from there rather than restating it (#7466, #7473). || `aiToolkitState.js` | Module-level singleton for the toolkit instance shared by the `providers`/`runner`/`promptService` shims — `setAIToolkitInstance` / `requireToolkit` (throws `AI_TOOLKIT_NOT_INITIALIZED`) / `getAIToolkitInstance` (no-throw for cleanup paths). || `antigravity.js` | Antigravity (`agy`) CLI provider helpers — id/sentinel constants (`ANTIGRAVITY_CLI_ID`, `ANTIGRAVITY_CONFIGURED_DEFAULT`, `LEGACY_GEMINI_*`), `isAntigravityCommand`/`isAntigravityCliProvider` predicates, and `ensureAntigravityPrintArgs(args, {model, effort})`/`ensureAntigravityTuiArgs(args, {model, effort})`/`stripAntigravityUnsupportedArgs` argv normalizers. `parseAntigravityModelList(stdout)` parses `agy models` rows — accepts both the modern `<id>\t<Label>` shape and the older bare-id-per-line one, deduped, sentinel dropped (mirrored in the vendored toolkit's `internal/antigravity.js`; used by both the provider-catalog refresh and Image Gen's agy model picker). `isAntigravityModelId(id)` is the same id shape as a bare predicate, for spawn sites building an `agy --model` argv from a value no route schema bounded. The strip drops legacy Gemini `--yolo`/`-m`/`--output-format` but PRESERVES the long `--model` (agy accepts it as a per-session flag, so a user-baked pin is a real selection and suppresses the injected one); the two builders inject `--model`/`--effort` from the per-run overrides, always ahead of the trailing `--print` marker whose value is the prompt. || `llmText.js` | Pure LLM-output text helpers — `stripCodeFences` (unfence a model reply) and `parseLLMJSON` (unfence then JSON.parse with a descriptive throw). Below the provider layer, so lib can clean model output without importing provider orchestration. |diff --git a/server/lib/aiToolkit/AGENTS.md b/server/lib/aiToolkit/AGENTS.mdindex b9ce32f224..872d45ddc5 100644--- a/server/lib/aiToolkit/AGENTS.md+++ b/server/lib/aiToolkit/AGENTS.md@@ -4,7 +4,7 @@ The AI provider/runner/prompt toolkit is vendored in-tree here. (It was previous**Key points:**- `index.js` exports `createAIToolkit`, `createProviderStatusService`, the four Router factories (providers / runs / prompts / providerStatus), and the context-fit pair `knownContextWindow` / `contextWindowRejection` — the host applies the same rule to the EXPLICITLY requested provider, which `getFallbackProvider` never sees. Both answer `null` for an unknown window, which every caller must keep reading as "no constraint"; nothing infers a window from a model id.-- **The Ollama `num_ctx` ceiling is declared ONCE, in `internal/ollamaBacked.js`** (`clampToRuntimeContextWindow`), beside the predicate that gates it. `knownContextWindow` applies it through that helper and must never restate the `Math.min` inline — the host's prompt budgeter (`server/services/stageRunner.js#effectiveContextWindow`) and the browser's provider-card meter call the same function, and when the rule was stated twice they drifted (#7466). It is an upper BOUND over every planning rung, a user's explicit `contextWindow` included, and the answer outright when nothing else declared one. Host callers import the `internal/` leaf directly: the public barrel reaches `fs` and `child_process`, and `stageRunner.js` sits inside the server suite's import budget.+- **The Ollama `num_ctx` ceiling is declared ONCE, in `internal/ollamaBacked.js`** (`clampToRuntimeContextWindow`), beside the predicate that gates it. `knownContextWindow` applies it through that helper and must never restate the `Math.min` inline — the host's prompt budgeter (`server/services/stageRunner.js#effectiveContextWindow`), the untrusted-content abuse guard (`server/services/untrustedContent.js#runUntrustedContentAnalysis`, which held its own hand-rolled `Math.min` pair until #7473) and the browser's provider-card meter call the same function, and when the rule was stated twice they drifted (#7466). It is an upper BOUND over every planning rung, a user's explicit `contextWindow` included, and the answer outright when nothing else declared one. Host callers import the `internal/` leaf directly, or `knownContextWindow`/`contextWindowRejection` straight off `providerStatus.js` (both deep imports skip the public barrel's `fs`/`child_process` reach): `stageRunner.js` sits inside the server suite's import budget, and `untrustedContent.js` — a request-path module — deliberately imports `providerStatus.js` rather than `stageRunner.js`, whose own closure would cost that budget ~40 extra module instantiations per reaching test file for no behavior it needs.- **A rung of that ceiling this directory cannot resolve arrives as DATA, never as an import out.** PortOS also sets the daemon-wide window through the ambient `OLLAMA_CONTEXT_LENGTH` (`server/lib/ollamaContext.js#resolveOllamaContextLength`), which the toolkit may not reach and the browser cannot read at all — so the host resolves it and stamps it onto an in-memory provider projection with `withRuntimeContextWindow`, declared in the same file as the clamp that reads it. `runtimeContextWindow` ranks BELOW `provider.numCtx`, exactly as `resolveOllamaContextLength` ranks the two, and is never persisted to `providers.json` (it describes the process running right now). Adding another host-resolved rung follows the same shape: stamp a field beside the reader, do not import out. Precedent: #7472.- Provider configuration (models, tiers, fallbacks) lives in `providers.js`- `loadProviders()` auto-migrates legacy codex configs to the `codex-configured-default` sentinel; `server/index.js` warms it at startup so the rewrite happens before any requestdiff --git a/server/services/untrustedContent.js b/server/services/untrustedContent.jsindex a906709b6f..7e7a7e1875 100644--- a/server/services/untrustedContent.js+++ b/server/services/untrustedContent.js@@ -6,6 +6,14 @@ import { evaluateSecretEndpoint } from '../lib/aiToolkit/endpointGuard.js';import { getAllProviders } from './providers.js';import { modelAbuseContentFingerprint } from '../lib/modelAbuseGuard.js';import { formatUntrustedContent, isUntrustedContentProvider, resolveUntrustedContentPolicy, UNTRUSTED_CONTENT_INSTRUCTIONS } from '../lib/untrustedContent.js';+// Deep imports on purpose (#7473): both leaves are cheap (`ollamaContext.js`+// is zero-dependency, `providerStatus.js` reaches only the `num_ctx` clamp it+// already shares), unlike `services/stageRunner.js#effectiveContextWindow`,+// which would drag this request-path module across the ~44-module prompt+// budgeter closure that `server/lib/importScoping.test.js` has little+// headroom for.+import { withOllamaRuntimeContextWindow } from '../lib/ollamaContext.js';+import { knownContextWindow } from '../lib/aiToolkit/providerStatus.js';const failure = (code, message) => ({ ok: false, safe: false, code, message });@@ -48,8 +56,26 @@ export async function runUntrustedContentAnalysis({ provider, model, content, prconst taskPrompt = `${UNTRUSTED_CONTENT_INSTRUCTIONS}\n\nTRUSTED TASK:\n${prompt}`;const evidence = formatUntrustedContent(content);const local = isUntrustedContentProvider(selected, 'messages');- const contextWindow = Math.min(Number(selected.contextWindow) || Number(selected.numCtx) || 4096,- Number(selected.numCtx) || (local ? 4096 : Number(selected.contextWindow) || 4096));+ // The runtime projection folds in the ambient `OLLAMA_CONTEXT_LENGTH`+ // ceiling before the shared ladder resolves anything, so an Ollama daemon+ // configured through the env var alone (numCtx unset) still budgets at+ // what it actually serves rather than an unenforced catalog window (#7472).+ // `knownContextWindow` then resolves through the one shared `num_ctx`+ // clamp (`aiToolkit/internal/ollamaBacked.js#clampToRuntimeContextWindow`)+ // instead of this guard's own Math.min pair, so it picks up the provider's+ // own `/models` catalog window and only clamps on `numCtx` for an+ // Ollama-backed provider — every other OpenAI-compatible local endpoint+ // (LM Studio, vLLM, …) ignores `num_ctx` entirely and must not be shrunk+ // by it.+ const runtimeProvider = withOllamaRuntimeContextWindow(selected);+ const claimedWindow = knownContextWindow(runtimeProvider, effectiveModel) ?? 4096;+ // A local endpoint with no explicit `numCtx` keeps this guard's own harder+ // floor rather than trusting a declared/catalog window an unconfigured+ // local endpoint has no confirmed way to honor — this is a security guard+ // that must stay conservative, not a budgeting nicety. Preserved verbatim+ // from the pre-#7473 behavior; it only ever LOWERS the shared ladder's+ // answer, so it never re-opens the catalog-window blind spot #7472 closed.+ const contextWindow = local && !(Number(selected.numCtx) > 0) ? Math.min(claimedWindow, 4096) : claimedWindow;const maxTokens = Math.min(8192, config.maxOutputChars, Math.floor(contextWindow / 4));// UTF-8 bytes are a conservative upper bound for byte-fallback text tokens.// Never clip evidence to make an undersized context appear successful.diff --git a/server/services/untrustedContent.test.js b/server/services/untrustedContent.test.jsindex 24e241af75..63d65d9445 100644--- a/server/services/untrustedContent.test.js+++ b/server/services/untrustedContent.test.js@@ -63,6 +63,24 @@ describe('shared external-content boundary', () => {}expect(mocks.fetch).not.toHaveBeenCalled();});+ it('resolves the context window through the shared num_ctx clamp rather than a hand-rolled pair', async () => {+ // A non-Ollama local endpoint (LM Studio/vLLM-style) with `numCtx` set+ // must NOT be shrunk by it — that endpoint ignores `num_ctx` entirely,+ // unlike an Ollama-backed one (#7473).+ const lmStudio = { ...local, id: 'lm-studio', endpoint: 'http://127.0.0.1:1234/v1', contextWindow: 32_768, numCtx: 2048 };+ const wideContent = 'a'.repeat(2000);+ expect(await runUntrustedContentAnalysis({ ...args, provider: lmStudio, content: wideContent })).toMatchObject({ ok: true });+ // The provider's own `/models` catalog window (`modelContextWindows`)+ // outranks the hardcoded 4096 default the old expression always fell+ // back to. A cloud (non-loopback) provider is only eligible for a+ // non-private source, so this exercises the guard's other ingress path.+ const catalogProvider = { ...cloud, id: 'catalog', modelContextWindows: { 'example-text': 50_000 } };+ expect(await runUntrustedContentAnalysis({ ...args, source: 'github-issue', provider: catalogProvider, content: wideContent })).toMatchObject({ ok: true });+ // A genuinely undersized window still refuses rather than clipping+ // evidence to make it look like it fit.+ const tinyCloud = { ...cloud, id: 'tiny-cloud', contextWindow: 500 };+ expect(await runUntrustedContentAnalysis({ ...args, source: 'github-issue', provider: tinyCloud, content: 'x'.repeat(400) })).toMatchObject({ code: 'untrusted-content-context-too-small' });+ });it('honors source policies and explicit caller pins without inheriting another provider model', async () => {mocks.read.mockResolvedValue({ corrupt: false, settings: { untrustedContent: { defaults: { providerId: 'local', model: 'local-only' }, sources: { 'github-issue': { providerId: 'cloud', classifierMode: 'optional' } } } } });expect(await runUntrustedContentAnalysis({ ...args, source: 'github-issue' })).toMatchObject({ ok: true, providerId: 'cloud' });