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
refactor([issue-3615]): extract the shared `<bin> models` probe scaffolding
Adam Eivy0626cabcda63
diff --git a/server/lib/aiToolkit/internal/antigravity.js b/server/lib/aiToolkit/internal/antigravity.jsindex 75a6eecf18..127aa0bc09 100644--- a/server/lib/aiToolkit/internal/antigravity.js+++ b/server/lib/aiToolkit/internal/antigravity.js@@ -5,6 +5,8 @@* (no imports out to sibling PortOS modules). Keep in sync with upstream.*/+import { commandBasename } from './commandBasename.js';+export const ANTIGRAVITY_CLI_ID = 'antigravity-cli';export const ANTIGRAVITY_TUI_ID = 'antigravity-tui';export const LEGACY_GEMINI_CLI_ID = 'gemini-cli';@@ -12,15 +14,34 @@ export const LEGACY_GEMINI_TUI_ID = 'gemini-tui';export const ANTIGRAVITY_CONFIGURED_DEFAULT = 'antigravity-configured-default';// Match by normalized binary basename so a path- or `.exe`-configured provider-// (`/opt/homebrew/bin/agy`, `agy.exe`) is still recognized. Inlined (not the-// shared commandBasename) to keep the vendored toolkit self-contained. Keep in-// sync with server/lib/antigravity.js#isAntigravityCommand.+// (`/opt/homebrew/bin/agy`, `agy.exe`) is still recognized. Uses the toolkit's+// own ./commandBasename.js rather than the shared server/lib one, to keep the+// vendored toolkit self-contained. Keep in sync with+// server/lib/antigravity.js#isAntigravityCommand.export function isAntigravityCommand(command) {- if (typeof command !== 'string' || command === '') return false;- const base = command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');+ const base = commandBasename(command);return base === 'agy' || base === 'antigravity';}+// `agy models` prints one bare model id per line. Toolkit-native (there is no+// upstream counterpart to keep in sync) — it lives here so it sits next to+// ./cursor.js#parseCursorModelList and gets direct unit coverage, rather than+// being reachable only by spawning a fake binary through the provider service.+const ANTIGRAVITY_MODEL_LINE = /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/;++/**+ * Parse the ids out of `agy models` output, dropping blanks, banner/status+ * prose, and the configured-default sentinel (which the caller re-prepends).+ * @param {string} stdout - raw stdout from `agy models`+ * @returns {string[]} ids in the order the binary listed them (not deduped)+ */+export function parseAntigravityModelList(stdout) {+ return String(stdout || '')+ .split(/\r?\n/)+ .map(line => line.trim())+ .filter(line => ANTIGRAVITY_MODEL_LINE.test(line) && line !== ANTIGRAVITY_CONFIGURED_DEFAULT);+}+export function isAntigravityCliProvider(provider) {return provider?.id === ANTIGRAVITY_CLI_ID || isAntigravityCommand(provider?.command);}diff --git a/server/lib/aiToolkit/internal/commandBasename.js b/server/lib/aiToolkit/internal/commandBasename.jsnew file mode 100644index 0000000000..efbf2f27d7--- /dev/null+++ b/server/lib/aiToolkit/internal/commandBasename.js@@ -0,0 +1,21 @@+/**+ * Normalize a provider command to its comparable binary basename.+ *+ * A toolkit-local twin of `commandBasename` in server/lib/providerModels.js —+ * the vendored toolkit may not import out to sibling PortOS modules (see+ * ../CLAUDE.md), and this rule was previously inlined once per vendor predicate+ * inside `internal/`. One copy inside the boundary is unavoidable; two were not.+ *+ * Strips the directory, lowercases, and drops a Windows `.exe` suffix so a+ * provider configured as `/opt/homebrew/bin/agy`, `AGY`, or `cursor-agent.exe`+ * still matches the bare name. Deliberately does NOT strip `.cmd`/`.bat`: those+ * are npm shim wrappers whose behavior can differ from the native binary, so a+ * predicate that wants them must say so.+ *+ * @param {string|null|undefined} command+ * @returns {string} the normalized basename, or '' for a non-string/empty input+ */+export function commandBasename(command) {+ if (typeof command !== 'string' || command === '') return '';+ return command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');+}diff --git a/server/lib/aiToolkit/internal/cursor.js b/server/lib/aiToolkit/internal/cursor.jsindex 8ac97c7555..7da56e2103 100644--- a/server/lib/aiToolkit/internal/cursor.js+++ b/server/lib/aiToolkit/internal/cursor.js@@ -1,25 +1,29 @@/*** Cursor Agent constants and catalog parsing for the aiToolkit.*- * Duplicated from server/lib/cursor.js so the toolkit stays self-contained- * (no imports out to sibling PortOS modules — see ../CLAUDE.md). Keep in sync- * with upstream, the same arrangement as ./antigravity.js.+ * `CURSOR_COMMAND` and `isCursorCommand` are duplicated from+ * server/lib/cursor.js so the toolkit stays self-contained (no imports out to+ * sibling PortOS modules — see ../CLAUDE.md); keep those two in sync with+ * upstream, the same arrangement as ./antigravity.js.+ *+ * `CURSOR_TUI_ID`, `CURSOR_MODEL_LINE` and `parseCursorModelList` are+ * toolkit-native and have NO upstream counterpart — server/lib/cursor.js owns+ * argv construction, not model-catalog parsing, and should not grow a copy of+ * this. A sync pass should not go looking for one.*/-export const CURSOR_CLI_ID = 'cursor-cli';+import { commandBasename } from './commandBasename.js';+export const CURSOR_TUI_ID = 'cursor-tui';/** The binary basename. Deliberately NOT `cursor` — that is the GUI editor. */export const CURSOR_COMMAND = 'cursor-agent';// Match by normalized binary basename so a path- or `.exe`-configured provider-// (`~/.local/bin/cursor-agent`, `cursor-agent.exe`) is still recognized. Inlined-// (not the shared commandBasename) to keep the vendored toolkit self-contained.-// Keep in sync with server/lib/cursor.js#isCursorCommand.+// (`~/.local/bin/cursor-agent`, `cursor-agent.exe`) is still recognized. Keep in+// sync with server/lib/cursor.js#isCursorCommand.export function isCursorCommand(command) {- if (typeof command !== 'string' || command === '') return false;- const base = command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');- return base === CURSOR_COMMAND;+ return commandBasename(command) === CURSOR_COMMAND;}// `cursor-agent models` prints `<id> - <Label>` rows wrapped in a header linediff --git a/server/lib/aiToolkit/internal/cursor.test.js b/server/lib/aiToolkit/internal/cursor.test.jsindex 2f197ea95e..74ff79a29d 100644--- a/server/lib/aiToolkit/internal/cursor.test.js+++ b/server/lib/aiToolkit/internal/cursor.test.js@@ -1,5 +1,8 @@import { describe, it, expect } from 'vitest';-import { CURSOR_COMMAND, CURSOR_CLI_ID, CURSOR_TUI_ID, isCursorCommand, parseCursorModelList } from './cursor.js';+import { CURSOR_COMMAND, CURSOR_TUI_ID, isCursorCommand, parseCursorModelList } from './cursor.js';+// The toolkit SOURCE may not import out to server/lib (see ../CLAUDE.md); a test+// may, and this is the only way to actually pin the duplication it documents.+import { CURSOR_COMMAND as UPSTREAM_COMMAND, isCursorCommand as upstreamIsCursorCommand } from '../../cursor.js';// A verbatim excerpt of `cursor-agent models` (2026.08.04) — the header line,// the blank line under it, a run of `<id> - <Label>` rows, and the trailing@@ -96,10 +99,25 @@ describe('parseCursorModelList', () => {});});-describe('cursor toolkit constants', () => {- it('mirror the shipped provider ids and binary name', () => {- expect(CURSOR_COMMAND).toBe('cursor-agent');- expect(CURSOR_CLI_ID).toBe('cursor-cli');+describe('vendored copy stays in sync with server/lib/cursor.js', () => {+ // The file header promises these two track upstream. Assert it rather than+ // asserting each constant equals its own literal, which only re-states the+ // source and would stay green through exactly the drift that matters.+ it('agrees with upstream on the binary name', () => {+ expect(CURSOR_COMMAND).toBe(UPSTREAM_COMMAND);+ });++ it('agrees with upstream on every command-matching case', () => {+ const cases = [+ 'cursor-agent', '/opt/homebrew/bin/cursor-agent', 'C:\\Tools\\cursor-agent.exe',+ 'CURSOR-AGENT', 'cursor', '/usr/local/bin/cursor', 'cursor-agent.cmd', 'claude', '',+ ];+ for (const c of cases) {+ expect(isCursorCommand(c), `disagreement on ${JSON.stringify(c)}`).toBe(upstreamIsCursorCommand(c));+ }+ });++ it('exposes the shipped TUI provider id (toolkit-native, no upstream twin)', () => {expect(CURSOR_TUI_ID).toBe('cursor-tui');});});diff --git a/server/lib/aiToolkit/providers.js b/server/lib/aiToolkit/providers.jsindex 89adc6e1fc..8de60abe1b 100644--- a/server/lib/aiToolkit/providers.js+++ b/server/lib/aiToolkit/providers.js@@ -15,6 +15,7 @@ import {isAntigravityCommand,LEGACY_GEMINI_CLI_ID,LEGACY_GEMINI_TUI_ID,+ parseAntigravityModelList,} from './internal/antigravity.js';import {CURSOR_COMMAND,@@ -771,6 +772,13 @@ export function createProviderService(config = {}) {// interactive session too — the binary's own `Tip:` line documents// both `--model <id>` and the in-session `/model <id>` — so its// catalog must refresh like the CLI's.+ // The id test alongside the command one (which the CLI arm below+ // deliberately does without) carries none of that arm's hazard: it is+ // an EXACT shipped-id match, not a name substring, so it can only+ // admit the provider PortOS itself seeds — and if the user repointed+ // its command at a wrapper, probing that wrapper is the right answer.+ // Shaped to match the antigravity arm above; both collapse together+ // when the dispatch becomes a table (#3620).models = await this._fetchCursorModels(provider);}} catch (error) {@@ -885,25 +893,48 @@ export function createProviderService(config = {}) {* the authoritative catalog for this user's plan and binary version, which* a hardcoded list can only go stale against.*- * THROWS rather than falling back to `ANTIGRAVITY_MODEL_CATALOG` when the- * probe can't run (agy not installed, the service PATH can't resolve it, a- * timeout, a non-zero exit) or comes back with nothing parseable. The- * shipped catalog is for *seeding and migration* — surfacing it from a- * refresh would make a failed probe indistinguishable from a real fetch:- * `refreshProviderModels` would persist it and the UI would toast "Models- * refreshed", so a user whose PATH can't see agy would pick a model their- * plan doesn't have and only find out when the run dies. Throwing makes- * `refreshProviderModels` return null → an explicit error toast, and leaves- * the existing list untouched (nothing is persisted). Same posture as- * `_fetchOllamaToolCapableModels`, and the root CLAUDE.md rule that a- * reachable-but-list-failed backend must surface an explicit error rather- * than a plausible-looking empty/default result.+ * Throws rather than falling back to `ANTIGRAVITY_MODEL_CATALOG` on a failed+ * or unparseable probe — see `_execCliModelList` for why that matters. The+ * shipped catalog is for *seeding and migration* only.** The sentinel is always re-prepended: it is what keeps "use agy's own* configured default" selectable after a refresh.*/async _fetchAntigravityModels(provider) {- const bin = provider?.command || 'agy';+ const listed = await this._execCliModelList(provider, 'agy', parseAntigravityModelList);+ return [ANTIGRAVITY_CONFIGURED_DEFAULT, ...new Set(listed)];+ },++ /**+ * Shared scaffolding for every "shell `<bin> models` and parse stdout"+ * fetcher. Owns the spawn conventions the vendors agree on — the Windows-safe+ * invocation, the 15s cap, the provider `envVars` merge, closing the child's+ * stdin, and the two failure messages — so a change to any of them (adding+ * stderr to the error, reacting to a spawn quirk) is one edit rather than one+ * per vendor. What differs per vendor is only the default binary and the+ * parser; a sentinel prepend, if any, belongs to the caller.+ *+ * THROWS on a probe that can't run (binary not installed, service PATH can't+ * resolve it, timeout, non-zero exit) AND on one that returns nothing+ * parseable — never returns an empty list. That is the load-bearing part:+ * every caller's alternative would be its shipped seed catalog, and+ * surfacing that from a refresh would make a failed probe indistinguishable+ * from a real fetch — `refreshProviderModels` would persist it and the UI+ * would toast "Models refreshed", so a user whose PATH can't see the binary+ * would pick a model their plan doesn't have and only find out when the run+ * dies. Throwing makes `refreshProviderModels` return null → an explicit+ * error toast, with the stored list left untouched. Same posture as+ * `_fetchOllamaToolCapableModels`, and the root CLAUDE.md rule that a+ * reachable-but-list-failed backend must surface an explicit error rather+ * than a plausible-looking empty/default result.+ *+ * @param {object} provider+ * @param {string} defaultBin - binary to use when the provider pins no command+ * @param {(stdout: string) => string[]} parse - vendor's stdout → ids parser+ * @returns {Promise<string[]>} a non-empty id list+ */+ async _execCliModelList(provider, defaultBin, parse) {+ const bin = provider?.command || defaultBin;const { command, args } = prepareWindowsSafeSpawn(bin, ['models']);const pending = execFileAsync(command, args, {timeout: 15000,@@ -913,21 +944,20 @@ export function createProviderService(config = {}) {// stdin and prints NOTHING until it closes — with execFile's default pipe// that's a full 15s hang ending in SIGTERM and an empty catalog. (execFile// ignores an `stdio` option, so ending the stream is the way to do it.)+ // Not every vendor needs it — cursor-agent 2026.08.04 answers in well+ // under a second either way (measured 848ms with stdin open vs 825ms+ // closed) — but it costs one FD close and makes the probe immune whether+ // or not a given binary has the behavior.pending.child?.stdin?.end();const { stdout } = await pending.catch((err) => {throw new Error(`'${bin} models' failed: ${err?.message || 'could not run the binary'}`);});- const listed = (stdout || '')- .split(/\r?\n/)- .map(line => line.trim())- // Drop blanks, banner/status lines, and anything that isn't a bare id.- .filter(line => /^[A-Za-z0-9][A-Za-z0-9._:/-]*$/.test(line) && line !== ANTIGRAVITY_CONFIGURED_DEFAULT);-+ const listed = parse(stdout);if (listed.length === 0) {throw new Error(`'${bin} models' returned no model ids`);}- return [ANTIGRAVITY_CONFIGURED_DEFAULT, ...new Set(listed)];+ return listed;},/**@@ -938,18 +968,8 @@ export function createProviderService(config = {}) {* sentinel), cursor can answer for itself, so a refresh asks it rather than* re-serving a list that can only go stale.*- * THROWS rather than falling back to the shipped seed when the probe can't- * run (cursor-agent not installed, the service PATH can't resolve it, a- * timeout, a non-zero exit) or comes back with nothing parseable — same- * posture and same reasoning as `_fetchAntigravityModels`: persisting the- * seed here would make a failed probe indistinguishable from a real fetch,- * so `refreshProviderModels` would save it and the UI would toast "Models- * refreshed", leaving a user whose PATH can't see cursor-agent to pick a- * model their account may not have and find out when the run dies. Throwing- * returns null instead → an explicit error toast, with the stored list left- * untouched. Matches the root CLAUDE.md rule that a reachable-but-list-- * failed backend must surface an explicit error rather than a plausible-- * looking default.+ * Throws rather than falling back to the shipped 27-id seed on a failed or+ * unparseable probe — see `_execCliModelList` for why that matters.** No sentinel is prepended (the one structural difference from the agy* fetcher): cursor exposes a real `auto` id — its own server-side router,@@ -962,28 +982,7 @@ export function createProviderService(config = {}) {* the stored list stays faithful to what the binary will actually accept.*/async _fetchCursorModels(provider) {- const bin = provider?.command || CURSOR_COMMAND;- const { command, args } = prepareWindowsSafeSpawn(bin, ['models']);- const pending = execFileAsync(command, args, {- timeout: 15000,- env: { ...process.env, ...provider?.envVars },- });- // Defensive, not load-bearing. `agy models` prints NOTHING until stdin- // closes, so with execFile's default pipe it hangs the full 15s and exits- // on SIGTERM; cursor-agent does not share that behavior — measured against- // 2026.08.04 it answers in well under a second either way (848ms with- // stdin open vs 825ms closed). Ending the stream anyway costs nothing and- // keeps the probe immune if a later build grows the agy behavior.- pending.child?.stdin?.end();- const { stdout } = await pending.catch((err) => {- throw new Error(`'${bin} models' failed: ${err?.message || 'could not run the binary'}`);- });-- const listed = parseCursorModelList(stdout);- if (listed.length === 0) {- throw new Error(`'${bin} models' returned no model ids`);- }- return listed;+ return await this._execCliModelList(provider, CURSOR_COMMAND, parseCursorModelList);},async _fetchOllamaToolCapableModels(provider) {diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.jsindex b5e75159a5..a44aa60ecd 100644--- a/server/lib/aiToolkit/providers.test.js+++ b/server/lib/aiToolkit/providers.test.js@@ -1,5 +1,5 @@import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';-import { mkdir, rm, writeFile } from 'fs/promises';+import { chmod, mkdir, rm, writeFile } from 'fs/promises';import { existsSync } from 'fs';import { join } from 'path';import { createProviderService, isOllamaBackedProvider } from './providers.js';@@ -824,10 +824,9 @@ describe('Provider Service', () => {// of `cursor-agent models` — header line, blank line, `<id> - <Label>` rows,// trailing `Tip:` paragraph. Shell-script based, so POSIX only; CI is// ubuntu-latest and the assertions below are about parsing, not spawning.- const writeFakeCursor = async (body, { exitCode = 0 } = {}) => {+ const writeFakeCursor = async (body) => {const path = join(TEST_DATA_DIR, 'cursor-agent');- await writeFile(path, `#!/bin/sh\ncat <<'EOF'\n${body}\nEOF\nexit ${exitCode}\n`);- const { chmod } = await import('fs/promises');+ await writeFile(path, `#!/bin/sh\ncat <<'EOF'\n${body}\nEOF\n`);await chmod(path, 0o755);return path;};