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

add a shared Qwen tool/reasoning parser table so runtimes stop copying the wrong spelling (#4778)

[._.]/ Adam Eivy28427a20e758
diff --git a/docs/features/qwen38-rtx3090.md b/docs/features/qwen38-rtx3090.md
index e295e09e97..a79d0e045f 100644
--- a/docs/features/qwen38-rtx3090.md
+++ b/docs/features/qwen38-rtx3090.md
@@ -118,6 +118,12 @@ With the right parser the same request comes back as `finish_reason:
without which the whole point of the preset — a CoS agent editing files — does
not work.
+The value is produced by `vllmExtraArgs()` in
+[`server/lib/qwenAgentParsers.js`](../../server/lib/qwenAgentParsers.js), the one
+table holding the per-runtime parser spellings (SGLang needs different ones for
+the same model). Edit it there, not here — `qwenAgentParsers.test.js` asserts
+this doc still quotes the table, so the two cannot drift apart.
+
### 1a. Extra requirements on WSL2
Three settings native Linux does not need. Each one fails in a way that points
diff --git a/server/lib/README.md b/server/lib/README.md
index af3ccd1ede..2caa9d615b 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -142,6 +142,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `managedDaemon.js` | Shared mechanism for the local daemons PortOS runs as optional PM2 processes (`services/llamaServerManager.js` → `portos-llama-server`, `services/mtplxServerManager.js` → `portos-mtplx`). `createDaemonLogBuffer({maxLines?})` is the bounded timestamped ring buffer of what PortOS logged around a launch, plus `withPm2Logs(output)` → that buffer followed by anything `pm2 logs` has which it doesn't already hold, deduped and re-capped (PM2's lines are a VIEW, never folded into the buffer — PM2 owns them and re-reads them every status call). `pm2ArgValue(args, flag)` reads one value back out of a PM2 process's recorded argv so a manager can recover a still-online daemon's launch config after a PortOS restart; `null` means the flag was absent, which a relaunch must leave off rather than defaulting. Deliberately mechanism only — what a launch line means and when a daemon may start is exactly what differs between the two. |
| `mtplxModels.js` | `listMtplxCachedModels({command?})` → `{models, error}` from `mtplx models --json` (a local directory listing — no network, no model load) and `pickMtplxCachedModel(models)` → the repo id to hand `mtplx serve --model`. `models: null` means the cache could not be READ (no binary, command failed, unparseable) and is deliberately distinct from `[]` (read, and empty), because `services/localRuntimeSetup.js` starts MTPLX on its own default in the first case and refuses with the `mtplx pull` command in the second. Exists because `mtplx serve` defaults `--model` to one hard-coded checkpoint and exits 1 before binding when that repo is not cached — even on a host holding a different MTP model that serves fine. Picks only entries MTPLX itself calls complete (`validation.ok !== false`, so a half-finished pull is not served), preferring one with a recorded `mtplx_runtime.json` exactness contract. `describeMtplxCache(cache)` → `{state: 'unknown'\|'empty'\|'partial'\|'ready', model, count, error}` folds both into the one value `services/providerReadiness.js` puts on the checklist and `describeRuntimeSetup` picks a button from — so an empty cache is named up front instead of only inside the failure of a Start that could never work. |
| `vllmQwenProject.js` | `resolveVllmProjectDir()` / `inspectVllmQwenProject()` → `{dir, hasProject, composeFile, hasWeights, weightsRoot}` for the operator-cloned syv-ai/qwen38-27b-rtx3090 compose project, plus `vllmStartBlockedReason(project)` → the prose refusal (or `null`). Directory reads only — never runs docker or touches a registry. `hasWeights` is tri-state: `true` found / `false` caches read and empty / `null` no cache readable (a docker-volume cache is invisible from a native-Win32 PortOS), and `services/localRuntimeSetup.js` refuses to `docker compose up` on anything but `true` so the start button can never kick off the ~20 GB prepare. Overrides: `VLLM_QWEN_PROJECT_DIR`, `VLLM_QWEN_WEIGHTS_DIR`. |
+| `qwenAgentParsers.js` | The tool-call / reasoning parser flags a local runtime MUST carry to serve a Qwen3-family model to a coding agent — one table PortOS owns instead of three docs. `QWEN_AGENT_PARSERS` maps runtime → `{toolCallParser, reasoningParser, enableAutoToolChoice}` (vLLM `qwen3_xml` + `--enable-auto-tool-choice`, SGLang `qwen3_coder` + `--reasoning-parser qwen3`, llama both `null` — a positive "no such flag today", not a placeholder). `parserFlagsFor(runtime)` returns the argv fragment (always an array, so no caller type-checks) and `vllmExtraArgs()` its string form for the compose project's `.env` `EXTRA_ARGS`; an unknown runtime THROWS, because the failure it prevents is silent — a parser-less server answers fluently and returns tool markup as ordinary text with `tool_calls: null`, so the agent never touches a file. Spellings are empirical (`docs/research/2026-08-21-qwen38-rtx3090-vllm.md`, `…-sglang-qwen38-27b.md`); never auto-detect one from the chat template — that is how `hermes` got picked. Pure. |
| `openAiModelsProbe.js` | `probeOpenAiModels(baseUrl, { timeoutMs, apiKey })` → `{ reachable, models, error }` — the one `GET {base}/models` probe for the local OpenAI-compatible daemons, shared by `services/providerReadiness.js` and `services/llamaServerManager.js`. Distinguishes unreachable from reachable-but-unlistable (`models: null`) from up-with-nothing-loaded (`[]`), names the real transport failure via `describeFetchError` (undici reports every one as a bare `fetch failed`), and cancels an unread body on a non-OK response. `apiKey` attaches a Bearer header for a key-gated daemon (vLLM's compose stack), and a 401/403 answers `reachable: true` with `error: 'authentication required'` — a server that refused the request is definitively running, and calling it unreachable would send the user to start it again. Consolidated after the two copies drifted — one passed its timeout as a `timeout` key inside the fetch init object, where it is not an option, silently running a 500ms poll loop on the 15s default. |
| `openAiChatStream.js` | `streamOpenAiChat({ endpoint, apiKey, model, messages, temperature, maxTokens, extraBody, signal, onChunk, onStats })` → the streamed text — one streaming `POST {base}/chat/completions` against any local OpenAI-compatible daemon; `streamOllamaChat(...)` is the assessment-only native `/api/chat` transport that preserves Ollama's exact eval counts and nanosecond timings. Also exports `buildMessages`, `parseStreamFrame`, `parseOllamaStreamFrame`, `normalizeUsage` (snake/camel/Ollama token-count keys → `{completionTokens, promptTokens}`, `null` = not reported), and `resolvePartialOutput`. Registering `onStats` on the OpenAI path asks for token counts; a daemon that rejects `stream_options` is retried once without it and remembered per endpoint. Sibling of `openAiModelsProbe.js`. Shared by `services/localLlmPlayground.js` (provider-backed runs with a `/runs` record) and its `runEndpointLlmTest` (a bare loopback daemon PortOS holds no provider record for, which is how `services/localModelAssessments.js` measures llama.cpp / MTPLX / vLLM). An abort mid-stream throws with `.partialOutput` carrying what already streamed. |
| `cliChildEnv.js` | The one place the AI-CLI child environment is composed, replacing the hand-rolled copy every spawn site carried — which made each env-level fix an N-file sweep (#3194). `buildCliChildEnv({ baseEnv, before, provider, model, cwd, extra, guard })` returns a COMPLETE env for `spawn`: layers `baseEnv → before → Ollama-Claude defaults → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. The Ollama-Claude layer raises Claude Code's default output ceiling to 65,536 tokens so a thinking-capable local model cannot finish its reasoning past the stock 32K ceiling and die before its final tool call; an explicit provider env value wins. `composeProviderEnv({ before, provider, model, extra })` returns just the ordered provider layers, for sites that build a DELTA someone else bases and spawns (the CoS runner payload, a shell-session overlay). The two slots are not interchangeable: `before` sits UNDER `provider.envVars` (forgeTokenEnv/claudeSettingsEnv, so a provider override still wins), `extra` sits OVER it (TERM/COLORTERM for a PTY). `cliChildEnv.test.js` asserts the composed order per call site and **discovers** any new site that hand-rolls the tuple instead of calling these — so the call-site list stays in the test, not in prose here. |
diff --git a/server/lib/index.js b/server/lib/index.js
index c594538b32..bb5146ea60 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -158,6 +158,7 @@ export * from './localProviderRuntime.js';
export * from './mtplxModels.js';
export * from './managedDaemon.js';
export * from './vllmQwenProject.js';
+export * from './qwenAgentParsers.js';
export * from './openAiModelsProbe.js';
export * from './openAiChatStream.js';
// `runners.js` re-defines `isFlux2`/`isZImage`/`isErnie` that also live in
diff --git a/server/lib/qwenAgentParsers.js b/server/lib/qwenAgentParsers.js
new file mode 100644
index 0000000000..4dca4285a1
--- /dev/null
+++ b/server/lib/qwenAgentParsers.js
@@ -0,0 +1,112 @@
+/**
+ * Tool-call / reasoning parser flags every local runtime MUST carry to serve a
+ * Qwen3-family model to a CoS coding agent.
+ *
+ * ## Why this is a table and not prose
+ *
+ * The spelling is runtime-specific and the failure is SILENT. The server starts,
+ * the model answers, the agent looks alive — and tool markup comes back as
+ * ordinary assistant text with `tool_calls: null`, so the agent never reads or
+ * writes a file. There is no error anywhere that names the parser.
+ *
+ * Measured, not guessed:
+ * - vLLM on the 3090 preset needs `--tool-call-parser qwen3_xml`
+ * (`docs/research/2026-08-21-qwen38-rtx3090-vllm.md`). `hermes` LOOKS right
+ * because the chat template emits `<tool_call>` markers, but Qwen3.8 writes
+ * its calls as XML (`<function=name><parameter=path>…`), not the Hermes JSON
+ * body — vLLM accepts the flag and then cannot parse a single call.
+ * - SGLang's verified cookbook cells all ship `--tool-call-parser qwen3_coder`
+ * AND `--reasoning-parser qwen3` (`docs/research/2026-08-21-sglang-qwen38-27b.md`).
+ * Without the reasoning parser the thinking block leaks into the reply.
+ *
+ * Two runtimes, two different spellings for the same model family. Left in prose,
+ * the third runtime copies whichever doc ranks first. So: one table PortOS owns,
+ * and every launch path reads it instead of typing a string.
+ *
+ * ## Do NOT auto-detect the parser from the chat template
+ *
+ * That is exactly how `hermes` got chosen. The template's markers describe how
+ * the model is PROMPTED, not how it ANSWERS. The mapping below is empirical —
+ * extend it only from a runtime's own verified launch line.
+ *
+ * ## Adding a runtime
+ *
+ * Add a row here (and a `parserFlagsFor` case is not needed — the builder is
+ * generic). A row with both parsers `null` is a POSITIVE assertion that the
+ * runtime has no equivalent flag today, not a placeholder: that is why `llama`
+ * is listed. An unknown runtime throws rather than serving parser-less, because
+ * a parser-less agent server is indistinguishable from a working one until a
+ * whole session has been wasted.
+ */
+
+/**
+ * runtime → flags that MUST be on the serve line for Qwen3-family coding agents.
+ *
+ * `enableAutoToolChoice` is vLLM-only and not cosmetic: vLLM rejects every
+ * request that offers tools with `"auto" tool choice requires
+ * --enable-auto-tool-choice and --tool-call-parser to be set`, so the parser
+ * flag alone still kills the session on the agent's first turn. SGLang enables
+ * tool choice implicitly once a parser is named and has no such flag.
+ */
+export const QWEN_AGENT_PARSERS = {
+ vllm: { toolCallParser: 'qwen3_xml', reasoningParser: null, enableAutoToolChoice: true },
+ sglang: { toolCallParser: 'qwen3_coder', reasoningParser: 'qwen3', enableAutoToolChoice: false },
+ // llama-server has no tool-call/reasoning parser flags today — the null row is
+ // the decision, so a future author does not go looking for one.
+ llama: { toolCallParser: null, reasoningParser: null, enableAutoToolChoice: false },
+};
+
+/** Runtime keys this table knows about, in table order. */
+export const QWEN_AGENT_RUNTIMES = Object.keys(QWEN_AGENT_PARSERS);
+
+/**
+ * The parser row for a runtime, or throw naming the runtimes that exist.
+ *
+ * Fail-fast is the point: a caller that fell through to "no flags" would launch
+ * a server that answers fluently and never calls a tool.
+ */
+export function qwenAgentParsersFor(runtime) {
+ // `hasOwn`, not truthiness: `QWEN_AGENT_PARSERS['toString']` is a live
+ // prototype method, and a plain lookup would hand a caller an all-undefined
+ // "row" that renders as zero flags — the exact silent-serve this throws for.
+ const row = Object.hasOwn(QWEN_AGENT_PARSERS, runtime) ? QWEN_AGENT_PARSERS[runtime] : null;
+ if (!row) {
+ throw new Error(
+ `Unknown Qwen agent runtime '${runtime}' — known runtimes: ${QWEN_AGENT_RUNTIMES.join(', ')}. ` +
+ 'Add a row to QWEN_AGENT_PARSERS (server/lib/qwenAgentParsers.js) from that runtime\'s verified launch line; do not serve without a tool-call parser.',
+ );
+ }
+ return row;
+}
+
+/**
+ * The argv fragment a runtime's serve line needs, e.g.
+ * `['--tool-call-parser', 'qwen3_coder', '--reasoning-parser', 'qwen3']`.
+ *
+ * Always an array — including for vLLM, whose `.env` transport is a string.
+ * A helper that returned an array for one runtime and a string for another
+ * would push every caller into a typeof check; `vllmExtraArgs()` below joins
+ * the same fragment for the one transport that needs the string form.
+ * A runtime with no parser flags (llama) returns `[]`; an unknown one throws.
+ */
+export function parserFlagsFor(runtime) {
+ const { toolCallParser, reasoningParser, enableAutoToolChoice } = qwenAgentParsersFor(runtime);
+ return [
+ ...(enableAutoToolChoice ? ['--enable-auto-tool-choice'] : []),
+ ...(toolCallParser ? ['--tool-call-parser', toolCallParser] : []),
+ ...(reasoningParser ? ['--reasoning-parser', reasoningParser] : []),
+ ];
+}
+
+/**
+ * The vLLM `EXTRA_ARGS` value — the string form of `parserFlagsFor('vllm')`,
+ * appended to `vllm serve` by the syv-ai compose project's start script.
+ *
+ * This is what the guided install (#4767) writes into `.env`, and what
+ * `docs/features/qwen38-rtx3090.md` documents; `qwenAgentParsers.test.js`
+ * asserts the doc still quotes exactly this, so the snippet cannot drift away
+ * from the table.
+ */
+export function vllmExtraArgs() {
+ return parserFlagsFor('vllm').join(' ');
+}
diff --git a/server/lib/qwenAgentParsers.test.js b/server/lib/qwenAgentParsers.test.js
new file mode 100644
index 0000000000..827d578b86
--- /dev/null
+++ b/server/lib/qwenAgentParsers.test.js
@@ -0,0 +1,110 @@
+import { describe, it, expect } from 'vitest';
+import { readFileSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import { execFileSync } from './childProcess.js';
+import {
+ QWEN_AGENT_PARSERS,
+ QWEN_AGENT_RUNTIMES,
+ parserFlagsFor,
+ qwenAgentParsersFor,
+ vllmExtraArgs,
+} from './qwenAgentParsers.js';
+
+const REPO_ROOT = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
+
+describe('QWEN_AGENT_PARSERS', () => {
+ it('pins the measured vLLM spelling (qwen3_xml, never hermes)', () => {
+ // docs/research/2026-08-21-qwen38-rtx3090-vllm.md: hermes parses nothing
+ // because Qwen3.8 emits XML, and vLLM reports the failure as plain text.
+ const flags = parserFlagsFor('vllm');
+ expect(flags).toContain('qwen3_xml');
+ expect(flags).not.toContain('qwen3_coder');
+ expect(flags).not.toContain('hermes');
+ });
+
+ it('carries --enable-auto-tool-choice for vLLM, which 400s without it', () => {
+ expect(parserFlagsFor('vllm')).toEqual([
+ '--enable-auto-tool-choice',
+ '--tool-call-parser',
+ 'qwen3_xml',
+ ]);
+ });
+
+ it('pins the SGLang cookbook spellings (tool AND reasoning parser)', () => {
+ expect(parserFlagsFor('sglang')).toEqual([
+ '--tool-call-parser',
+ 'qwen3_coder',
+ '--reasoning-parser',
+ 'qwen3',
+ ]);
+ });
+
+ it('returns no flags for llama, whose server has no equivalent today', () => {
+ expect(parserFlagsFor('llama')).toEqual([]);
+ });
+
+ it('throws on an unknown runtime rather than serving parser-less', () => {
+ expect(() => parserFlagsFor('nope')).toThrow(/Unknown Qwen agent runtime 'nope'/);
+ // The message has to name the alternatives — a bare throw sends the next
+ // author back to grepping for the table.
+ expect(() => qwenAgentParsersFor('nope')).toThrow(/vllm, sglang, llama/);
+ });
+
+ it('throws on prototype keys, not just absent ones', () => {
+ expect(() => parserFlagsFor('toString')).toThrow(/Unknown Qwen agent runtime/);
+ expect(() => parserFlagsFor('constructor')).toThrow(/Unknown Qwen agent runtime/);
+ });
+
+ it('declares every runtime with an explicit decision for both parsers', () => {
+ expect(QWEN_AGENT_RUNTIMES).toEqual(['vllm', 'sglang', 'llama']);
+ for (const [runtime, row] of Object.entries(QWEN_AGENT_PARSERS)) {
+ // `null` is a positive "this runtime has no such flag" decision; the row
+ // must never simply omit the key, which reads as an oversight.
+ expect(Object.keys(row).sort(), `${runtime} row shape`).toEqual([
+ 'enableAutoToolChoice',
+ 'reasoningParser',
+ 'toolCallParser',
+ ]);
+ expect(typeof row.enableAutoToolChoice, `${runtime}.enableAutoToolChoice`).toBe('boolean');
+ }
+ });
+});
+
+describe('vllmExtraArgs', () => {
+ it('is the string form of the vLLM argv fragment', () => {
+ expect(vllmExtraArgs()).toBe('--enable-auto-tool-choice --tool-call-parser qwen3_xml');
+ expect(vllmExtraArgs()).toBe(parserFlagsFor('vllm').join(' '));
+ });
+
+ it('matches the EXTRA_ARGS line documented in the 3090 feature doc', () => {
+ // The doc's copy-paste snippet is the de-facto install instruction until
+ // #4767 writes .env itself. If someone edits either side, this fails rather
+ // than letting the doc and the table drift into two different spellings.
+ const doc = readFileSync(join(REPO_ROOT, 'docs', 'features', 'qwen38-rtx3090.md'), 'utf8');
+ expect(doc).toContain(`EXTRA_ARGS=${vllmExtraArgs()}`);
+ });
+});
+
+describe('qwen parser spellings live only in the table', () => {
+ it('no other tracked source file hard-codes a qwen3 parser spelling', () => {
+ // Acceptance criterion of #4778: the SGLang runtime (#4776) and the vLLM
+ // guided install (#4767) must import this table instead of retyping the
+ // string. Scoped to git-tracked JS so scratch files never flake it.
+ const tracked = execFileSync('git', ['ls-files', '*.js', '*.jsx', '*.cjs', '*.mjs'], {
+ cwd: REPO_ROOT,
+ encoding: 'utf8',
+ })
+ .split('\n')
+ .filter(Boolean);
+ const allowed = new Set(['server/lib/qwenAgentParsers.js', 'server/lib/qwenAgentParsers.test.js']);
+ const offenders = tracked.filter((rel) => {
+ if (allowed.has(rel)) return false;
+ return /qwen3_xml|qwen3_coder/.test(readFileSync(join(REPO_ROOT, rel), 'utf8'));
+ });
+ expect(
+ offenders,
+ `These files hard-code a Qwen tool-call parser spelling — import parserFlagsFor() from server/lib/qwenAgentParsers.js instead: ${offenders.join(', ')}`,
+ ).toEqual([]);
+ });
+});