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

feat: ship Cursor Agent as a CLI and TUI provider

Adam Eivy4ecd49a7edbb
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index fca52a7241..6dbce45723 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -5,6 +5,8 @@
- **[issue-3606] A Review Loop reviewer whose CLI isn't installed is now flagged up front.** Previously the only way to find out a configured reviewer (Claude, Antigravity, Codex, or Grok) couldn't actually run was to wait for the review loop itself to discover its command was missing — after PortOS had already opened the PR and spent an agent run. The Code Review Defaults panel, task form, schedule config, and `/do:next` run drawer now show a "not installed" badge next to any reviewer whose CLI binary isn't found on this machine. It's informational only — the reviewer stays selectable, since a federated peer machine (or a later install) may still be able to run it.
## Added
+- **Cursor's agent CLI ships as a provider, in both CLI and TUI flavors.** `cursor-agent` is a harness-capable coding agent, but PortOS had no entry for it — using it meant hand-rolling a custom provider and guessing at its flags. It now ships as `cursor-cli` (headless one-shot) and `cursor-tui` (interactive PTY), mirroring the Codex/Antigravity/Grok/Kimi pairs. Both ship disabled, so nothing changes until you enable them, and once enabled they're selectable anywhere a process provider is — CoS agents, runners, pipeline stages, TUI sessions. The headless path runs `cursor-agent --print` with the prompt on stdin; the TUI path runs the interactive agent. Both inject `--force`, which is doing more work than the name suggests: besides auto-approving tool calls, it clears Cursor's workspace-trust gate, and without it `cursor-agent` prints "Workspace Trust Required" and exits — which in a fresh CoS worktree is every single run. The model list is a 27-entry slice of the account catalog (Composer, Claude, GPT, Gemini families), each id verified against the live binary; the default is Cursor's own `auto` router, so unlike Grok/Kimi/Antigravity no configured-default sentinel was needed. Cursor bakes reasoning effort into the model id (`…-thinking-high`, `…-xhigh`, `…-max`) rather than exposing a flag, so no Effort control is offered for it. Existing installs pick the pair up on restart via migration `231-cursor-providers`. If your account offers a model outside the shipped 27 (the full catalog runs to 177 ids, most of them `-fast` twins), you can still add it to the provider's model list by hand.
+
- **X account diagnostics and review-gated compose handoffs.** Comms now has an X page that stores bounded public snapshots, checks profile/search visibility and post reach through the managed browser, captures visible metrics, and routes drafts through Review Hub before opening X for a final manual submission. It does not store X credentials, post automatically, or claim that ordinary low reach proves a shadowban.
- **The claim-issue author gate has a "Me + collaborators" setting.** Until now the only way to let an agent work on a teammate's issue was "Any author", which also opens the queue to drive-by issues from strangers — so a repo with any real collaborators had to choose between ignoring their issues and claiming everyone's. The new option trusts you plus every account the forge already grants access to (GitHub collaborators, GitLab project members including group-inherited ones), which is the same set that could push the code anyway. It sits between "Filed by me only" (still the default) and "Any author" in the CoS → Schedule author-filter dropdown, in the per-app override, and in the `/do:next` run drawer, and applies to `claim-issue` and `claim-work` alike. Neither CLI's `--author` flag accepts more than one account, so the gate is applied to the issue listing rather than pushed into the query — both the work detector and the agent prompt resolve the trusted set first, then filter. If that lookup fails (a token without push access can't read the collaborator list), PortOS reports it and retries rather than quietly narrowing back to your own issues or widening to everybody — and because that failure repeats identically on every retry, both the run drawer and the "Run now" toast name the filter and the way out instead of the generic "try again shortly".
@@ -12,6 +14,7 @@
- **Updated documentation index and feature references.** Added missing feature deep dive links for Quota-burn automation (`QUOTA-BURN.md`), Three.js procedural 3D models (`THREEJS_MODELS.md`), Stacker News stewardship (`stacker-news.md`), and the PortDeck native companion app API contract (`COMPANION_APP_API.md`) across `README.md` and `docs/README.md`. Improved inline JSDoc comments for client and server utility modules.
## Fixed
+- **On a Bedrock box, a TUI provider that isn't Claude Code no longer has its model id rewritten.** Claude Code on AWS Bedrock needs region-prefixed model ids (`global.anthropic.claude-opus-5`), so PortOS rewrites bare Claude ids just-in-time when `CLAUDE_CODE_USE_BEDROCK` is set. That rewrite keyed only on the *model id* containing "claude" and was applied by default to every TUI provider — so any vendor that labels Anthropic models under its own ids got captured by it. Cursor is exactly that case: `claude-opus-5-thinking-high` would have been sent to Cursor's router as `global.anthropic.claude-opus-5-thinking-high`, an id it has never heard of. The rewrite now keys on the launch command actually being Claude Code, which is what it always meant. Two independent copies of that model-injection step (the one-shot TUI prompt path and the CoS-agent TUI spawn path) had already drifted apart on this; both now share one implementation, so the next provider can't be fixed in one and missed in the other. No shipped provider's behavior changes; a *custom* TUI provider running a non-`claude` binary against a claude-ish model id will stop being rewritten, which is the correct result for a non-Claude-Code binary.
- **The Antigravity card on the Usage page loads quota again after `agy` 1.1.x renamed its limit rows.** The `/usage` panel still groups Gemini / Claude+GPT windows the same way, but each window header grew a trailing "Remaining" (`Weekly Limit Remaining`, `Five Hour Limit Remaining`). The parser required the line to end on bare `Limit`, so it found the groups and returned zero meters — the card looked broken with "No quota data found." Both the new labels and the older bare-`Limit` form parse to the same keys.
- **Grok and Kimi agents now actually start, and an agent that fails to spawn says why.** Picking the Grok or Kimi provider for a CoS agent produced a task that never opened a shell: the durable agent runner keeps an allowlist of CLI commands it is permitted to spawn, and `grok` and `kimi` were never added to it even though both ship as selectable providers. Both are allowlisted now, and a test keeps that list in step with the shipped provider catalog so the next provider added without an entry fails in CI rather than in a silent agent. The reporting around it was the worse half of the bug: a rejected spawn was logged and dropped, never reaching the agent record. A TUI agent sat in "initializing" for a minute until the zombie sweeper finalized it as "Agent process terminated unexpectedly" — a message that named no cause — and the CLI equivalent was worse still, staying "working" indefinitely because the stale in-memory entry made every cleanup sweep skip it. Both paths now finalize immediately with the runner's actual error, the runner names the offending command instead of returning one opaque "missing or invalid fields", and an agent reaped without ever having recorded a process id is reported as never having started rather than as a crash.
- **The labels on LoRA training dataset images are readable again.** The source chip ("upload", "generated", "sheet crop", "gallery") and the view label ("front three-quarter") were tinted overlays — 20%-opacity color on top of whatever the training image happened to be — so over a bright photo, or under a light theme, the text all but disappeared. They were also pinned to opposite corners of the thumbnail, so a long view label collided with the source chip in a narrow column and the two printed on top of each other. Both chips now carry their own near-opaque plate with light text, and they share one wrapping row so a long label drops to a second line instead of overlapping.
diff --git a/client/src/pages/AIProviders.jsx b/client/src/pages/AIProviders.jsx
index b121bf4cdc..de8f3b79ab 100644
--- a/client/src/pages/AIProviders.jsx
+++ b/client/src/pages/AIProviders.jsx
@@ -2,7 +2,7 @@ import { useState, useEffect, useCallback } from 'react';
import toast from '../components/ui/Toast';
import * as api from '../services/api';
import socket from '../services/socket';
-import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isOllamaBackedProvider, isAntigravityProvider, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow } from '../utils/providers';
+import { filterSelectableModels, filterGenerationModels, isEmbeddingModel, mergeModelLists, configuredDefaultIn, localBackendForProvider, modelOptionLabel, providerTypeClass, isTuiProvider, isApiProvider, isProcessProvider, isOllamaBackedProvider, isAntigravityProvider, isCursorCommand, isGrokBuildCli, isLocalEndpoint, effectiveModelContextWindow } from '../utils/providers';
import useLocalModels from '../hooks/useLocalModels';
import BrailleSpinner from '../components/BrailleSpinner';
import EmptyState from '../components/EmptyState';
@@ -177,6 +177,14 @@ export default function AIProviders() {
if (provider.type === 'cli' && (provider.command === 'gemini' || provider.command === 'grok')) {
return false;
}
+ // Cursor is hidden for the OPPOSITE reason, so it gets its own clause rather
+ // than joining the two above: `cursor-agent models` does print an
+ // authoritative per-account catalog, there just isn't a server-side fetcher
+ // for it yet, so the button could only ever produce an error toast. This
+ // clause is temporary where theirs are permanent.
+ if (provider.type === 'cli' && isCursorCommand(provider.command)) {
+ return false;
+ }
// All other providers support refresh (API and CLI)
return true;
};
diff --git a/client/src/utils/providers.js b/client/src/utils/providers.js
index c30b9123c0..b4b214f03e 100644
--- a/client/src/utils/providers.js
+++ b/client/src/utils/providers.js
@@ -114,6 +114,17 @@ export const isAntigravityProvider = (provider) => {
return base === 'agy' || base === 'antigravity';
};
+/**
+ * True when a provider command points at Cursor's agent binary. MIRROR of
+ * `isCursorCommand` in server/lib/cursor.js — keep in lockstep.
+ *
+ * Matches ONLY `cursor-agent`, never a bare `cursor`: that is Cursor's GUI
+ * editor launcher, not the coding agent.
+ * @param {string|null|undefined} command
+ * @returns {boolean}
+ */
+export const isCursorCommand = (command) => commandBasename(command) === 'cursor-agent';
+
export const knownProviderContextWindow = (provider) => {
if (!isProcessProvider(provider)) return null;
const id = String(provider?.id || '').toLowerCase();
diff --git a/client/src/utils/providers.test.js b/client/src/utils/providers.test.js
index 4bec496387..448810629a 100644
--- a/client/src/utils/providers.test.js
+++ b/client/src/utils/providers.test.js
@@ -34,6 +34,8 @@ import {
isOllamaBackedProvider,
isGrokBuildCli,
isKimiProvider,
+ isCodexProvider,
+ isCursorCommand,
isAntigravityProvider,
effortLevelsForProvider,
resolveCliEffort,
@@ -730,6 +732,37 @@ describe('isKimiProvider (mirror of server providerModels)', () => {
});
});
+describe('isCursorCommand (mirror of server lib/providerModels.js)', () => {
+ it('matches the agent binary bare, by path, and with a Windows .exe', () => {
+ expect(isCursorCommand('cursor-agent')).toBe(true);
+ expect(isCursorCommand('/Users/x/.local/bin/cursor-agent')).toBe(true);
+ expect(isCursorCommand('C:\\tools\\Cursor-Agent.exe')).toBe(true);
+ });
+
+ it('does NOT match a bare `cursor` — that is the GUI editor launcher', () => {
+ expect(isCursorCommand('cursor')).toBe(false);
+ expect(isCursorCommand('/usr/local/bin/cursor')).toBe(false);
+ });
+
+ it('rejects other CLIs and nullish input', () => {
+ expect(isCursorCommand('claude')).toBe(false);
+ expect(isCursorCommand('')).toBe(false);
+ expect(isCursorCommand(null)).toBe(false);
+ });
+
+ it('offers no effort ladder — cursor bakes the reasoning tier into the model id', () => {
+ expect(effortLevelsForProvider({ id: 'cursor-cli', command: 'cursor-agent' })).toBeNull();
+ expect(effortLevelsForProvider({ id: 'cursor-tui', command: 'cursor-agent' }, 'claude-opus-5-thinking-high')).toBeNull();
+ });
+
+ it('is not mistaken for a claude/codex/antigravity provider by its model ids', () => {
+ const cursor = { id: 'cursor-cli', command: 'cursor-agent', models: ['claude-opus-5-thinking-high'] };
+ expect(isCodexProvider(cursor)).toBe(false);
+ expect(isAntigravityProvider(cursor)).toBe(false);
+ expect(isKimiProvider(cursor)).toBe(false);
+ });
+});
+
describe('effectiveModelContextWindow', () => {
it('matches known model windows before provider defaults', () => {
expect(effectiveModelContextWindow({ type: 'tui' }, 'gpt-5.5')).toBe(1_000_000);
diff --git a/data.reference/providers.json b/data.reference/providers.json
index 4e37e9dd3e..5fb58a8c61 100644
--- a/data.reference/providers.json
+++ b/data.reference/providers.json
@@ -353,6 +353,40 @@
"secretEnvVars": [],
"tuiPromptDelayMs": 2500,
"tuiIdleTimeoutMs": 180000
+ },
+ "cursor-cli": {
+ "id": "cursor-cli",
+ "name": "Cursor Agent CLI",
+ "type": "cli",
+ "command": "cursor-agent",
+ "args": ["--print", "--force"],
+ "models": ["auto", "composer-2.5", "claude-opus-5-high", "claude-opus-5-thinking-high", "claude-opus-5-thinking-xhigh", "claude-opus-5-thinking-max", "claude-sonnet-5-high", "claude-sonnet-5-thinking-high", "claude-sonnet-5-thinking-xhigh", "claude-fable-5-high", "claude-fable-5-thinking-high", "claude-opus-4-8-high", "claude-opus-4-8-thinking-high", "claude-4.6-sonnet-medium", "gpt-5.6-sol-high", "gpt-5.6-sol-xhigh", "gpt-5.6-luna-high", "gpt-5.6-terra-high", "gpt-5.5-high", "gpt-5.4-high", "gpt-5.4-mini-high", "gpt-5.3-codex", "gpt-5.3-codex-high", "gpt-5.3-codex-xhigh", "gpt-5.2-high", "gemini-3.1-pro", "gemini-3.5-flash"],
+ "defaultModel": "auto",
+ "lightModel": "composer-2.5",
+ "mediumModel": "claude-sonnet-5-thinking-high",
+ "heavyModel": "claude-opus-5-thinking-high",
+ "timeout": 300000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": []
+ },
+ "cursor-tui": {
+ "id": "cursor-tui",
+ "name": "Cursor Agent TUI",
+ "type": "tui",
+ "command": "cursor-agent",
+ "args": ["--force"],
+ "models": ["auto", "composer-2.5", "claude-opus-5-high", "claude-opus-5-thinking-high", "claude-opus-5-thinking-xhigh", "claude-opus-5-thinking-max", "claude-sonnet-5-high", "claude-sonnet-5-thinking-high", "claude-sonnet-5-thinking-xhigh", "claude-fable-5-high", "claude-fable-5-thinking-high", "claude-opus-4-8-high", "claude-opus-4-8-thinking-high", "claude-4.6-sonnet-medium", "gpt-5.6-sol-high", "gpt-5.6-sol-xhigh", "gpt-5.6-luna-high", "gpt-5.6-terra-high", "gpt-5.5-high", "gpt-5.4-high", "gpt-5.4-mini-high", "gpt-5.3-codex", "gpt-5.3-codex-high", "gpt-5.3-codex-xhigh", "gpt-5.2-high", "gemini-3.1-pro", "gemini-3.5-flash"],
+ "defaultModel": "auto",
+ "lightModel": "composer-2.5",
+ "mediumModel": "claude-sonnet-5-thinking-high",
+ "heavyModel": "claude-opus-5-thinking-high",
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
}
}
}
diff --git a/scripts/migrations/231-cursor-providers.js b/scripts/migrations/231-cursor-providers.js
new file mode 100644
index 0000000000..542df80602
--- /dev/null
+++ b/scripts/migrations/231-cursor-providers.js
@@ -0,0 +1,149 @@
+/**
+ * Ship the Cursor Agent process-provider pair (CLI + TUI) to existing installs.
+ *
+ * Cursor's `cursor-agent` binary runs as a harness-capable coding agent, so PortOS
+ * adds two process-provider entries: `cursor-cli` (headless one-shot via
+ * `cursor-agent --print`, prompt on stdin) and `cursor-tui` (interactive PTY).
+ * The CLI/TUI argv conventions live in server/lib/cursor.js — notably `--force`,
+ * which clears cursor's workspace-trust gate (without it a headless run prints
+ * "Workspace Trust Required" and exits) as well as auto-approving tool calls.
+ *
+ * Unlike Grok/Kimi/Antigravity, cursor needs no configured-default sentinel: its
+ * `auto` router is a real model id, so it is stored as `defaultModel` and passed
+ * through as a normal `--model auto`.
+ *
+ * `setup-data.js` merges *missing* provider entries from data.reference, but only
+ * when an install re-runs setup. This migration delivers the providers on a plain
+ * server restart too, and is the canonical path for deployed installs to pick them
+ * up. Purely additive: brand-new ids, so there's no rename or pinned-id rewrite —
+ * existing keys are left untouched (idempotent).
+ *
+ * Kept in lockstep with data.reference/providers.json and
+ * server/lib/aiToolkit/defaults/providers.sample.json. Frozen here as the
+ * historical record this migration installs; later default changes ride their own
+ * migrations rather than mutating this one.
+ */
+
+import { readFile, writeFile } from 'fs/promises';
+import { join } from 'path';
+
+const PROVIDERS_REL_PATH = 'data/providers.json';
+
+// Curated from `cursor-agent models` (177 ids as of 2026-08-07). The full account
+// catalog enumerates every reasoning tier AND a `-fast` priority-compute twin of
+// each, which would make an unusable dropdown — this is the current-generation
+// slice, one row per useful (family, tier). Any other id the account offers can
+// still be typed into the provider's model list by hand.
+const CURSOR_MODELS = [
+ 'auto',
+ 'composer-2.5',
+ 'claude-opus-5-high',
+ 'claude-opus-5-thinking-high',
+ 'claude-opus-5-thinking-xhigh',
+ 'claude-opus-5-thinking-max',
+ 'claude-sonnet-5-high',
+ 'claude-sonnet-5-thinking-high',
+ 'claude-sonnet-5-thinking-xhigh',
+ 'claude-fable-5-high',
+ 'claude-fable-5-thinking-high',
+ 'claude-opus-4-8-high',
+ 'claude-opus-4-8-thinking-high',
+ 'claude-4.6-sonnet-medium',
+ 'gpt-5.6-sol-high',
+ 'gpt-5.6-sol-xhigh',
+ 'gpt-5.6-luna-high',
+ 'gpt-5.6-terra-high',
+ 'gpt-5.5-high',
+ 'gpt-5.4-high',
+ 'gpt-5.4-mini-high',
+ 'gpt-5.3-codex',
+ 'gpt-5.3-codex-high',
+ 'gpt-5.3-codex-xhigh',
+ 'gpt-5.2-high',
+ 'gemini-3.1-pro',
+ 'gemini-3.5-flash',
+];
+
+const CURSOR_TIERS = {
+ defaultModel: 'auto',
+ lightModel: 'composer-2.5',
+ mediumModel: 'claude-sonnet-5-thinking-high',
+ heavyModel: 'claude-opus-5-thinking-high',
+};
+
+const CURSOR_CLI = {
+ id: 'cursor-cli',
+ name: 'Cursor Agent CLI',
+ type: 'cli',
+ command: 'cursor-agent',
+ args: ['--print', '--force'],
+ models: CURSOR_MODELS,
+ ...CURSOR_TIERS,
+ timeout: 300000,
+ enabled: false,
+ envVars: {},
+ secretEnvVars: [],
+};
+
+const CURSOR_TUI = {
+ id: 'cursor-tui',
+ name: 'Cursor Agent TUI',
+ type: 'tui',
+ command: 'cursor-agent',
+ args: ['--force'],
+ models: CURSOR_MODELS,
+ ...CURSOR_TIERS,
+ timeout: 600000,
+ enabled: false,
+ envVars: {},
+ secretEnvVars: [],
+ tuiPromptDelayMs: 2500,
+ tuiIdleTimeoutMs: 180000,
+};
+
+export default {
+ async up({ rootDir }) {
+ const providersPath = join(rootDir, PROVIDERS_REL_PATH);
+ const raw = await readFile(providersPath, 'utf-8').catch((err) => {
+ if (err.code === 'ENOENT') return null;
+ throw err;
+ });
+ if (raw == null) {
+ console.log(`📄 ${PROVIDERS_REL_PATH} not present — skipping (fresh install seeds Cursor from data.reference)`);
+ return;
+ }
+
+ let config;
+ try {
+ config = JSON.parse(raw);
+ } catch (err) {
+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: invalid JSON, skipping (${err.message})`);
+ return;
+ }
+
+ if (!config || typeof config !== 'object' || !config.providers || typeof config.providers !== 'object') {
+ console.log(`⚠️ ${PROVIDERS_REL_PATH}: unexpected shape, skipping`);
+ return;
+ }
+
+ const providers = config.providers;
+ let changed = false;
+
+ for (const def of [CURSOR_CLI, CURSOR_TUI]) {
+ if (!providers[def.id]) {
+ // structuredClone fully detaches the shipped def (nested arrays/objects
+ // included — CURSOR_MODELS is shared by both entries) so a later mutation
+ // of the install can't corrupt it or leak across the two providers.
+ providers[def.id] = structuredClone(def);
+ changed = true;
+ console.log(`📝 ${PROVIDERS_REL_PATH}: added ${def.id} provider`);
+ }
+ }
+
+ if (changed) {
+ await writeFile(providersPath, `${JSON.stringify(config, null, 2)}\n`);
+ } else {
+ console.log(`✅ ${PROVIDERS_REL_PATH}: Cursor providers already present — no change`);
+ }
+ },
+};
diff --git a/scripts/migrations/231-cursor-providers.test.js b/scripts/migrations/231-cursor-providers.test.js
new file mode 100644
index 0000000000..383a1ffb36
--- /dev/null
+++ b/scripts/migrations/231-cursor-providers.test.js
@@ -0,0 +1,127 @@
+/**
+ * Test for migration 231 — add the Cursor Agent process-provider pair (CLI + TUI)
+ * to existing installs. Picked up by server/vitest.config.js's
+ * `../scripts/**\/*.test.js` glob.
+ */
+import { describe, it, expect, beforeEach, afterEach } from 'vitest';
+import { mkdtempSync, rmSync, writeFileSync, readFileSync, mkdirSync, existsSync } from 'fs';
+import { tmpdir } from 'os';
+import { join } from 'path';
+
+import migration from './231-cursor-providers.js';
+
+const writeJson = (path, value) => writeFileSync(path, JSON.stringify(value, null, 2) + '\n');
+const readJson = (path) => JSON.parse(readFileSync(path, 'utf-8'));
+
+describe('migration 231 — Cursor providers', () => {
+ let rootDir;
+ let providersPath;
+
+ beforeEach(() => {
+ rootDir = mkdtempSync(join(tmpdir(), 'migration-231-'));
+ mkdirSync(join(rootDir, 'data'), { recursive: true });
+ providersPath = join(rootDir, 'data/providers.json');
+ });
+
+ afterEach(() => {
+ rmSync(rootDir, { recursive: true, force: true });
+ });
+
+ it('adds the cli and tui Cursor providers to an existing install', async () => {
+ writeJson(providersPath, {
+ activeProvider: 'claude-code',
+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
+ });
+
+ await migration.up({ rootDir });
+
+ const out = readJson(providersPath);
+
+ const cli = out.providers['cursor-cli'];
+ expect(cli.type).toBe('cli');
+ expect(cli.command).toBe('cursor-agent');
+ // `--force` clears the workspace-trust gate as well as auto-approving tools;
+ // without it a headless run exits before doing any work.
+ expect(cli.args).toEqual(['--print', '--force']);
+ expect(cli.defaultModel).toBe('auto');
+ expect(cli.models).toContain('auto');
+ expect(cli.enabled).toBe(false);
+
+ const tui = out.providers['cursor-tui'];
+ expect(tui.type).toBe('tui');
+ expect(tui.command).toBe('cursor-agent');
+ expect(tui.args).toEqual(['--force']);
+ expect(tui.tuiPromptDelayMs).toBe(2500);
+ expect(tui.tuiIdleTimeoutMs).toBe(180000);
+
+ // unrelated providers + active provider untouched
+ expect(out.providers['claude-code']).toBeDefined();
+ expect(out.activeProvider).toBe('claude-code');
+ });
+
+ it('does not overwrite a user-customized cursor entry', async () => {
+ writeJson(providersPath, {
+ providers: {
+ 'cursor-cli': { id: 'cursor-cli', type: 'cli', command: 'cursor-agent', enabled: true, defaultModel: 'composer-2.5' },
+ },
+ });
+
+ await migration.up({ rootDir });
+
+ const out = readJson(providersPath);
+ // existing entry preserved untouched
+ expect(out.providers['cursor-cli'].enabled).toBe(true);
+ expect(out.providers['cursor-cli'].defaultModel).toBe('composer-2.5');
+ // the still-missing TUI sibling is added alongside it
+ expect(out.providers['cursor-tui']).toBeDefined();
+ });
+
+ it('deep-copies shipped arrays/objects so mutating the install cannot corrupt the frozen defaults', async () => {
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ const first = readJson(providersPath);
+ first.providers['cursor-cli'].models.push('mutated');
+
+ // A second install run must still ship the pristine model list.
+ const rootDir2 = mkdtempSync(join(tmpdir(), 'migration-231-b-'));
+ mkdirSync(join(rootDir2, 'data'), { recursive: true });
+ const providersPath2 = join(rootDir2, 'data/providers.json');
+ writeJson(providersPath2, { providers: {} });
+ await migration.up({ rootDir: rootDir2 });
+ expect(readJson(providersPath2).providers['cursor-cli'].models).not.toContain('mutated');
+ rmSync(rootDir2, { recursive: true, force: true });
+ });
+
+ it('gives the CLI and TUI entries independent model arrays (they share one source list)', async () => {
+ writeJson(providersPath, { providers: {} });
+ await migration.up({ rootDir });
+ const out = readJson(providersPath);
+ out.providers['cursor-cli'].models.push('leaked');
+ expect(out.providers['cursor-tui'].models).not.toContain('leaked');
+ });
+
+ it('is idempotent — a second run makes no changes', async () => {
+ writeJson(providersPath, {
+ providers: { 'claude-code': { id: 'claude-code', type: 'cli', command: 'claude' } },
+ });
+
+ await migration.up({ rootDir });
+ const afterFirst = readFileSync(providersPath, 'utf-8');
+ await migration.up({ rootDir });
+ expect(readFileSync(providersPath, 'utf-8')).toBe(afterFirst);
+ });
+
+ it('is a no-op when data/providers.json does not exist (fresh install)', async () => {
+ await migration.up({ rootDir });
+ expect(existsSync(providersPath)).toBe(false);
+ });
+
+ it('does not modify the file on invalid JSON', async () => {
+ writeFileSync(providersPath, '{ not valid json');
+ const before = readFileSync(providersPath, 'utf-8');
+
+ await migration.up({ rootDir });
+
+ expect(readFileSync(providersPath, 'utf-8')).toBe(before);
+ });
+});
diff --git a/server/cos-runner/allowedCommands.js b/server/cos-runner/allowedCommands.js
index b1a6f741e2..f1c2c0fc6b 100644
--- a/server/cos-runner/allowedCommands.js
+++ b/server/cos-runner/allowedCommands.js
@@ -21,6 +21,7 @@ export const ALLOWED_COMMANDS = new Set([
'codex',
'copilot',
'agy',
+ 'cursor-agent',
'gemini',
'grok',
'kimi',
diff --git a/server/lib/README.md b/server/lib/README.md
index 1f38fe5b91..13189a2637 100644
--- a/server/lib/README.md
+++ b/server/lib/README.md
@@ -116,6 +116,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub
| `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 → provider.envVars → buildOpencodeEnvVars → extra`, pins `PWD` to `cwd`, strips `CLAUDECODE`, and (with `guard: true`) prepends the pm2 guard shim onto the final `PATH`. `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. |
| `cliProviderArgs.js` | Per-CLI argv conventions (`buildCliArgs`) for stdin prompt delivery — dependency-light extraction from runner.js so out-of-process callers (autofixer) can import it. |
| `cliProviderRun.js` | One-shot CLI provider invocation (`pickCliProvider` + `runCliProviderPrompt`) — lightweight path for the autofixer + calendar MCP sync to honor the configured provider/model. |
+| `cursor.js` | Cursor Agent (`cursor-agent`) provider helpers — id/command constants (`CURSOR_CLI_ID`/`CURSOR_TUI_ID`/`CURSOR_COMMAND`), `isCursorCommand`/`isCursorCliProvider`/`isCursorTuiProvider` predicates, and `ensureCursorHeadlessArgs` (`--print --force`) / `ensureCursorTuiArgs` (`--force`) argv builders. `--force` is load-bearing beyond approvals: it also clears cursor's workspace-trust gate, which otherwise EXITS a headless run before any work happens. The prompt rides raw stdin (like claude/codex, unlike grok/kimi), and cursor needs no configured-default sentinel — its `auto` router is a real model id passed straight to `--model`. |
| `grok.js` | xAI Grok Build (`grok`) provider helpers — id/endpoint constants (`GROK_API_ID`/`GROK_CLI_ID`/`GROK_TUI_ID`/`GROK_API_ENDPOINT`), `isGrokCommand`/`isGrokCliProvider`/`isGrokTuiProvider` predicates, `ensureGrokHeadlessArgs`/`ensureGrokTuiArgs` argv builders (grok reads its prompt from `--prompt-file /dev/stdin`, not raw stdin; model selection uses the `GROK_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Antigravity), and `prepareGrokPromptFile` (Windows temp-file delivery fallback). |
| `grokVideoClip.js` | Clip lengths grok's `image_to_video` actually delivers — `GROK_VIDEO_DURATIONS` (`[6, 10]`, measured in #3022: a 2s/3s request returns the same 6.04s clip), `GROK_VIDEO_DEFAULT_DURATION`, `resolveGrokDuration()` (validate an already-grok-shaped request, else default), and `nearestGrokDuration()` (round a length authored against another backend's continuous contract UP to the shortest clip that covers it — for translating a CD/commission `targetDurationSeconds`). Dependency-free so `validation.js` / `routes/videoGen.js` can derive their schemas from the same list the services gate on. |
| `kimi.js` | Moonshot AI Kimi Code (`kimi`) provider helpers — id constants (`KIMI_CLI_ID`/`KIMI_TUI_ID`), `isKimiCommand`/`isKimiCliProvider`/`isKimiTuiProvider` predicates, `ensureKimiHeadlessArgs` (`--print`, implies `--afk`) / `ensureKimiTuiArgs` (`--yolo`) argv builders (model selection uses the `KIMI_CONFIGURED_DEFAULT` sentinel in `providerModels.js` so PortOS omits `--model` like Grok/Antigravity), and `prepareKimiPrompt` (delivers the prompt as the `--prompt <value>` argv, not stdin). |
diff --git a/server/lib/aiToolkit/defaults/providers.sample.json b/server/lib/aiToolkit/defaults/providers.sample.json
index f208b7853e..b93aa563e9 100644
--- a/server/lib/aiToolkit/defaults/providers.sample.json
+++ b/server/lib/aiToolkit/defaults/providers.sample.json
@@ -368,6 +368,40 @@
"secretEnvVars": [],
"tuiPromptDelayMs": 2500,
"tuiIdleTimeoutMs": 180000
+ },
+ "cursor-cli": {
+ "id": "cursor-cli",
+ "name": "Cursor Agent CLI",
+ "type": "cli",
+ "command": "cursor-agent",
+ "args": ["--print", "--force"],
+ "models": ["auto", "composer-2.5", "claude-opus-5-high", "claude-opus-5-thinking-high", "claude-opus-5-thinking-xhigh", "claude-opus-5-thinking-max", "claude-sonnet-5-high", "claude-sonnet-5-thinking-high", "claude-sonnet-5-thinking-xhigh", "claude-fable-5-high", "claude-fable-5-thinking-high", "claude-opus-4-8-high", "claude-opus-4-8-thinking-high", "claude-4.6-sonnet-medium", "gpt-5.6-sol-high", "gpt-5.6-sol-xhigh", "gpt-5.6-luna-high", "gpt-5.6-terra-high", "gpt-5.5-high", "gpt-5.4-high", "gpt-5.4-mini-high", "gpt-5.3-codex", "gpt-5.3-codex-high", "gpt-5.3-codex-xhigh", "gpt-5.2-high", "gemini-3.1-pro", "gemini-3.5-flash"],
+ "defaultModel": "auto",
+ "lightModel": "composer-2.5",
+ "mediumModel": "claude-sonnet-5-thinking-high",
+ "heavyModel": "claude-opus-5-thinking-high",
+ "timeout": 300000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": []
+ },
+ "cursor-tui": {
+ "id": "cursor-tui",
+ "name": "Cursor Agent TUI",
+ "type": "tui",
+ "command": "cursor-agent",
+ "args": ["--force"],
+ "models": ["auto", "composer-2.5", "claude-opus-5-high", "claude-opus-5-thinking-high", "claude-opus-5-thinking-xhigh", "claude-opus-5-thinking-max", "claude-sonnet-5-high", "claude-sonnet-5-thinking-high", "claude-sonnet-5-thinking-xhigh", "claude-fable-5-high", "claude-fable-5-thinking-high", "claude-opus-4-8-high", "claude-opus-4-8-thinking-high", "claude-4.6-sonnet-medium", "gpt-5.6-sol-high", "gpt-5.6-sol-xhigh", "gpt-5.6-luna-high", "gpt-5.6-terra-high", "gpt-5.5-high", "gpt-5.4-high", "gpt-5.4-mini-high", "gpt-5.3-codex", "gpt-5.3-codex-high", "gpt-5.3-codex-xhigh", "gpt-5.2-high", "gemini-3.1-pro", "gemini-3.5-flash"],
+ "defaultModel": "auto",
+ "lightModel": "composer-2.5",
+ "mediumModel": "claude-sonnet-5-thinking-high",
+ "heavyModel": "claude-opus-5-thinking-high",
+ "timeout": 600000,
+ "enabled": false,
+ "envVars": {},
+ "secretEnvVars": [],
+ "tuiPromptDelayMs": 2500,
+ "tuiIdleTimeoutMs": 180000
}
}
}
diff --git a/server/lib/aiToolkit/defaults/providersSeedParity.test.js b/server/lib/aiToolkit/defaults/providersSeedParity.test.js
index 86c73f115c..62360d8675 100644
--- a/server/lib/aiToolkit/defaults/providersSeedParity.test.js
+++ b/server/lib/aiToolkit/defaults/providersSeedParity.test.js
@@ -3,7 +3,7 @@
* data.reference/providers.json (PortOS's own install seed)
* server/lib/aiToolkit/defaults/providers.sample.json (the toolkit's fallback seed)
*
- * Both files describe the same 21 providers, and `loadProviders()` falls
+ * Both files describe the same 23 providers, and `loadProviders()` falls
* through to the toolkit sample when the install seed is absent — so a model
* bump that updates one and not the other silently gives some fresh installs a
* stale tier. That failure then compounds: the provider-bump migrations
diff --git a/server/lib/cliProviderArgs.js b/server/lib/cliProviderArgs.js
index b05092dcfc..e65370cc8c 100644
--- a/server/lib/cliProviderArgs.js
+++ b/server/lib/cliProviderArgs.js
@@ -15,6 +15,7 @@
* - Gemini CLI: legacy prompt piped to stdin (+ `-m <model>`)
* - Grok Build: `grok --prompt-file /dev/stdin` (+ `--model <id>`, see grok.js)
* - Kimi Code: `kimi --print --prompt <value>` (argv value, not stdin; see kimi.js)
+ * - Cursor: `cursor-agent --print --force` (prompt on stdin; see cursor.js)
* - Claude Code: `-p -` (+ `--model <id>`)
*/
@@ -22,6 +23,7 @@ import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeMo
import { ensureAntigravityPrintArgs, isAntigravityCliProvider, isAntigravityCommand, prepareAntigravityPrompt } from './antigravity.js';
import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from './grok.js';
import { isKimiCommand, ensureKimiHeadlessArgs, prepareKimiPrompt } from './kimi.js';
+import { isCursorCommand, ensureCursorHeadlessArgs } from './cursor.js';
/**
* Build CLI args based on provider type. Each CLI provider has different
@@ -102,6 +104,16 @@ export function buildCliArgs(provider) {
return ensureKimiHeadlessArgs(baseArgs, effectiveDefaultModel);
}
+ // Cursor Agent CLI (`cursor-agent`): headless one-shot. `--print` reads the
+ // prompt from raw stdin (so the shared stdin delivery works unchanged) and
+ // `--force` clears cursor's workspace-trust gate — which otherwise EXITS
+ // instead of running — while also auto-approving tool calls. Both are injected
+ // by ensureCursorHeadlessArgs unless the user pinned their own. Cursor's `auto`
+ // model is a real id, not a sentinel, so it rides `--model` like any other.
+ if (isCursorCommand(provider?.command)) {
+ return ensureCursorHeadlessArgs(baseArgs, effectiveDefaultModel);
+ }
+
// OpenCode CLI (`opencode run`): the headless, non-interactive subcommand. It
// reads the prompt from stdin (the runner's shell-pipeline delivery, same as
// every other CLI here) and selects the model with `-m provider/model`. The
@@ -163,8 +175,9 @@ export function buildCliArgs(provider) {
* (kimi does NOT read stdin in --print mode) → `useStdin: false`.
* - Grok on Windows: the `/dev/stdin` prompt-file is rewritten to a temp file
* → `useStdin: false` with a real `cleanup`.
- * - Every other provider (Claude Code `-p -`, Codex `exec -`, OpenCode `run`):
- * unchanged, prompt delivered over stdin → `useStdin: true`.
+ * - Every other provider (Claude Code `-p -`, Codex `exec -`, OpenCode `run`,
+ * Cursor `cursor-agent --print`): unchanged, prompt delivered over stdin →
+ * `useStdin: true`.
*
* @param {string} command - provider.command (e.g. 'agy', 'claude', 'grok')
* @param {string[]} args - argv as built by buildCliArgs
diff --git a/server/lib/cliProviderArgs.test.js b/server/lib/cliProviderArgs.test.js
index 9f8671cfd3..737cb6a691 100644
--- a/server/lib/cliProviderArgs.test.js
+++ b/server/lib/cliProviderArgs.test.js
@@ -193,6 +193,47 @@ describe('cliProviderArgs', () => {
});
});
+ describe('buildCliArgs — Cursor Agent CLI', () => {
+ it('builds a headless --print --force invocation with the model (seeded args)', () => {
+ const args = buildCliArgs({ id: 'cursor-cli', command: 'cursor-agent', args: ['--print', '--force'], defaultModel: 'auto' });
+ expect(args).toEqual(['--print', '--force', '--model', 'auto']);
+ });
+
+ it('adds --print and --force when the saved args omit them', () => {
+ const args = buildCliArgs({ id: 'cursor-cli', command: 'cursor-agent', args: [], defaultModel: null });
+ expect(args).toEqual(['--print', '--force']);
+ });
+
+ it('is path/exe tolerant', () => {
+ const args = buildCliArgs({ id: 'my-cursor', command: '/Users/x/.local/bin/cursor-agent', args: [], defaultModel: 'composer-2.5' });
+ expect(args).toEqual(['--print', '--force', '--model', 'composer-2.5']);
+ });
+
+ it('respects a user-baked --model and does not duplicate it', () => {
+ const args = buildCliArgs({ id: 'cursor-cli', command: 'cursor-agent', args: ['--print', '--force', '--model', 'mine'], defaultModel: 'auto' });
+ expect(args.filter((a) => a === '--model')).toHaveLength(1);
+ expect(args).toContain('mine');
+ expect(args).not.toContain('auto');
+ });
+
+ it('respects a user-pinned trust/approval posture instead of adding --force', () => {
+ const args = buildCliArgs({ id: 'cursor-cli', command: 'cursor-agent', args: ['--print', '--auto-review'], defaultModel: null });
+ expect(args).toEqual(['--print', '--auto-review']);
+ });
+
+ it('delivers the prompt over stdin (useStdin true) — cursor reads raw stdin in print mode', () => {
+ const built = buildCliArgs({ id: 'cursor-cli', command: 'cursor-agent', args: ['--print', '--force'], defaultModel: 'auto' });
+ const { args, useStdin } = prepareCliPrompt('cursor-agent', built, 'write a haiku');
+ expect(args).toEqual(built);
+ expect(useStdin).toBe(true);
+ });
+
+ it('does not fall through to the Claude Code branch (no `-p -` stdin marker)', () => {
+ const args = buildCliArgs({ id: 'cursor-cli', command: 'cursor-agent', args: [], defaultModel: 'auto' });
+ expect(args).not.toContain('-');
+ });
+ });
+
// `provider.effort` is how promptRunner hands a per-run reasoning-effort
// override down to the arg builders (there is no `effort` parameter on
// executeCliRun) — see executeProviderRunOnce's providerForRun clone.
diff --git a/server/lib/cursor.js b/server/lib/cursor.js
new file mode 100644
index 0000000000..4ab3aa383b
--- /dev/null
+++ b/server/lib/cursor.js
@@ -0,0 +1,116 @@
+/**
+ * Per-CLI conventions for Cursor's agentic coding CLI (binary: `cursor-agent`).
+ *
+ * Cursor ships two PortOS process-provider shapes:
+ * - `cursor-cli` (type `cli`) — headless one-shot via `cursor-agent --print`.
+ * - `cursor-tui` (type `tui`) — the interactive Cursor Agent TUI over a PTY.
+ *
+ * Prompt delivery (headless): `cursor-agent --print` reads the prompt from raw
+ * stdin when no trailing prompt argument is given — the same convention as
+ * claude/codex — so the shared `prepareCliPrompt` dispatcher needs no cursor
+ * branch and the existing `stdin.write(prompt)` at every spawn site feeds it
+ * unchanged. (Verified against cursor-agent 2026.08.04: `echo … | cursor-agent
+ * -p --force` returns the reply on stdout and exits 0.)
+ *
+ * Workspace trust: cursor-agent refuses to run in a directory it has not been
+ * told to trust, printing a "Workspace Trust Required" block and exiting instead
+ * of doing any work — fatal for a headless agent, which has no one to answer it.
+ * `--force` satisfies that gate (the binary's own message names `--trust`,
+ * `--yolo`, or `-f`) AND auto-approves tool calls, so it is the single flag that
+ * covers both, mirroring claude's `--dangerously-skip-permissions` / codex's
+ * `--dangerously-bypass-approvals-and-sandbox` / kimi's `--yolo`.
+ *
+ * Output format: PortOS runs cursor in its default PLAIN TEXT mode, so the
+ * live-output handler falls through to its default text path (like
+ * grok/kimi/opencode). cursor-agent does offer `--output-format stream-json`
+ * whose frames closely resemble Claude Code's, but its assistant text arrives on
+ * `type: "assistant"` message frames rather than the `stream_event` /
+ * `content_block_delta` frames `createStreamJsonParser` extracts live text from —
+ * so selecting it today would yield a final result with no streaming output.
+ * Teaching the parser that dialect is tracked separately.
+ *
+ * Model selection: unlike Grok/Kimi/Antigravity, cursor needs NO configured-
+ * default sentinel — it exposes a real `auto` model id (its own server-side
+ * router, and the binary's own default), so `auto` is stored as `defaultModel`
+ * and passed through as a normal `--model auto`. Effort is baked into the model
+ * ids themselves (`…-low` / `…-high` / `…-xhigh` / `…-max`) rather than exposed
+ * as a flag, so cursor has no `--effort` control and `effortLevelsForProvider`
+ * correctly reports none for it.
+ *
+ * Dependency-light on purpose: imports only `providerModels.js` helpers,
+ * mirroring `grok.js`/`kimi.js`/`antigravity.js` so it stays importable from the
+ * standalone autofixer.
+ */
+
+import { argvHasFlag, commandBasename, hasModelFlag } from './providerModels.js';
+
+/** The binary basename. Deliberately NOT `cursor` — that is the GUI editor. */
+export const CURSOR_COMMAND = 'cursor-agent';
+
+/**
+ * True when a provider command points at the Cursor Agent binary — the bare
+ * `cursor-agent` on PATH, an absolute/relative path to it, or an optional
+ * Windows `.exe` suffix (same matching rules as `isGrokCommand`/`isKimiCommand`).
+ *
+ * Matches ONLY `cursor-agent`, never a bare `cursor`: that is Cursor's GUI
+ * editor launcher, and spawning it from a headless agent would open a window
+ * (or hang) rather than run the coding agent.
+ * @param {string|null|undefined} command
+ * @returns {boolean}
+ */
+export function isCursorCommand(command) {
+ return commandBasename(command) === CURSOR_COMMAND;
+}
+
+// `--print` (`-p`) puts cursor-agent in non-interactive print mode.
+const PRINT_FLAGS = ['--print', '-p'];
+// Approval/trust postures. `--force`/`-f`/`--yolo` run everything unprompted and
+// also satisfy the workspace-trust gate; `--auto-review` is the server-classifier
+// middle ground; `--trust` clears trust only. Any one present means the user
+// pinned their own posture — don't add another.
+const APPROVAL_FLAGS = ['--force', '-f', '--yolo', '--auto-review', '--trust'];
+
+/**
+ * Build the headless (one-shot) argv for the Cursor Agent CLI. Ensures, when not
+ * already pinned by the user's saved `args`:
+ * - `--print` — non-interactive print mode (prompt read from stdin).
+ * - `--force` — clears the workspace-trust gate AND auto-approves tool
+ * calls, so an unattended run neither exits on the trust
+ * block nor stalls on an approval prompt.
+ * - `--model <id>` — gated on `model` being set AND no user-baked model flag.
+ * The prompt itself is NOT added here — it rides on stdin at spawn time.
+ * @param {string[]} baseArgs - user/legacy args (already model-flag-sanitized)
+ * @param {string|null|undefined} model - defaultModel to pin, or null to omit
+ * @returns {string[]}
+ */
+export function ensureCursorHeadlessArgs(baseArgs = [], model) {
+ const out = [...baseArgs];
+ if (!argvHasFlag(out, PRINT_FLAGS)) {
+ out.push('--print');
+ }
+ if (!argvHasFlag(out, APPROVAL_FLAGS)) {
+ out.push('--force');
+ }
+ if (model && !hasModelFlag(out)) {
+ out.push('--model', model);
+ }
+ return out;
+}
+
+/**
+ * Ensure the interactive Cursor TUI argv clears the workspace-trust gate and
+ * auto-approves tool executions, so a file-writing agent is neither refused at
+ * startup nor stranded on an approval prompt (mirrors the codex
+ * `--dangerously-bypass-approvals-and-sandbox` / claude-code-tui
+ * `--dangerously-skip-permissions` / kimi `--yolo` TUI defaults). Idempotent
+ * when the user already pinned a trust/approval posture.
+ * @param {string[]} args
+ * @returns {string[]}
+ */
+export function ensureCursorTuiArgs(args = []) {
+ const out = [...args];
+ if (!argvHasFlag(out, APPROVAL_FLAGS)) {
+ out.push('--force');
+ }
+ return out;
+}
diff --git a/server/lib/cursor.test.js b/server/lib/cursor.test.js
new file mode 100644
index 0000000000..e128d94487
--- /dev/null
+++ b/server/lib/cursor.test.js
@@ -0,0 +1,100 @@
+import { describe, it, expect } from 'vitest';
+import {
+ CURSOR_COMMAND,
+ isCursorCommand,
+ ensureCursorHeadlessArgs,
+ ensureCursorTuiArgs,
+} from './cursor.js';
+
+describe('isCursorCommand', () => {
+ it('matches the bare binary, a path to it, and a Windows .exe', () => {
+ expect(isCursorCommand('cursor-agent')).toBe(true);
+ expect(isCursorCommand('/Users/x/.local/bin/cursor-agent')).toBe(true);
+ expect(isCursorCommand('C:\\tools\\cursor-agent.exe')).toBe(true);
+ expect(isCursorCommand('CURSOR-AGENT')).toBe(true);
+ });
+
+ it('does NOT match a bare `cursor` — that is the GUI editor launcher', () => {
+ expect(isCursorCommand('cursor')).toBe(false);
+ expect(isCursorCommand('/usr/local/bin/cursor')).toBe(false);
+ });
+
+ it('is false for other CLIs and for empty/nullish input', () => {
+ expect(isCursorCommand('claude')).toBe(false);
+ expect(isCursorCommand('')).toBe(false);
+ expect(isCursorCommand(null)).toBe(false);
+ expect(isCursorCommand(undefined)).toBe(false);
+ });
+});
+
+describe('ensureCursorHeadlessArgs', () => {
+ it('injects print mode, the trust/approval posture, and the model', () => {
+ expect(ensureCursorHeadlessArgs([], 'auto')).toEqual(['--print', '--force', '--model', 'auto']);
+ });
+
+ it('omits --model when no model is given (cursor falls back to its own default)', () => {
+ expect(ensureCursorHeadlessArgs([], null)).toEqual(['--print', '--force']);
+ expect(ensureCursorHeadlessArgs([], '')).toEqual(['--print', '--force']);
+ });
+
+ it('does not duplicate print mode pinned in either form', () => {
+ expect(ensureCursorHeadlessArgs(['--print'], null)).toEqual(['--print', '--force']);
+ expect(ensureCursorHeadlessArgs(['-p'], null)).toEqual(['-p', '--force']);
+ });
+
+ it('respects any user-pinned trust/approval posture instead of adding --force', () => {
+ for (const flag of ['--force', '-f', '--yolo', '--auto-review', '--trust']) {
+ expect(ensureCursorHeadlessArgs(['--print', flag], null)).toEqual(['--print', flag]);
+ }
+ });
+
+ it('respects a joined posture flag (--force=true style)', () => {
+ expect(ensureCursorHeadlessArgs(['--print', '--force=true'], null)).toEqual(['--print', '--force=true']);
+ });
+
+ it('respects a user-baked model flag rather than emitting a second one', () => {
+ expect(ensureCursorHeadlessArgs(['--print', '--force', '--model', 'mine'], 'auto'))
+ .toEqual(['--print', '--force', '--model', 'mine']);
+ expect(ensureCursorHeadlessArgs(['--print', '--force', '--model=mine'], 'auto'))
+ .toEqual(['--print', '--force', '--model=mine']);
+ });
+
+ it('does not mutate the caller-supplied args array', () => {
+ const base = ['--print'];
+ ensureCursorHeadlessArgs(base, 'auto');
+ expect(base).toEqual(['--print']);
+ });
+
+ it('is idempotent', () => {
+ const once = ensureCursorHeadlessArgs([], 'auto');
+ expect(ensureCursorHeadlessArgs(once, 'auto')).toEqual(once);
+ });
+});
+
+describe('ensureCursorTuiArgs', () => {
+ it('injects --force so the PTY session clears trust and auto-approves tools', () => {
+ expect(ensureCursorTuiArgs([])).toEqual(['--force']);
+ });
+
+ it('leaves a user-pinned posture alone', () => {
+ for (const flag of ['--force', '-f', '--yolo', '--auto-review', '--trust']) {
+ expect(ensureCursorTuiArgs([flag])).toEqual([flag]);
+ }
+ });
+
+ it('does not mutate the caller-supplied args array and is idempotent', () => {
+ const base = [];
+ const once = ensureCursorTuiArgs(base);
+ expect(base).toEqual([]);
+ expect(ensureCursorTuiArgs(once)).toEqual(once);
+ });
+});
+
+describe('CURSOR_COMMAND', () => {
+ // Consumed by inferTuiCommand + the CLI spawn fallback, so a rename here has
+ // to stay in step with the seeds' `command` field.
+ it('is the agent binary the shipped providers name', () => {
+ expect(CURSOR_COMMAND).toBe('cursor-agent');
+ expect(isCursorCommand(CURSOR_COMMAND)).toBe(true);
+ });
+});
diff --git a/server/lib/grok.js b/server/lib/grok.js
index 623acd6568..246ba6f3c6 100644
--- a/server/lib/grok.js
+++ b/server/lib/grok.js
@@ -25,15 +25,10 @@ import os from 'os';
import { writeFileSync, unlinkSync } from 'fs';
import { join } from 'path';
import { randomUUID } from 'crypto';
-import { hasModelFlag, commandBasename } from './providerModels.js';
+import { argvHasFlag, hasModelFlag, commandBasename } from './providerModels.js';
const NOOP_CLEANUP = () => {};
-// True when argv contains any of `flags`, in either separated (`--flag`) or
-// joined (`--flag=value`) form. The generic scan behind the grok arg builders.
-const argvHasFlag = (args = [], flags) =>
- args.some((a) => typeof a === 'string' && flags.some((f) => a === f || a.startsWith(`${f}=`)));
-
export const GROK_API_ID = 'grok';
export const GROK_CLI_ID = 'grok-cli';
export const GROK_TUI_ID = 'grok-tui';
diff --git a/server/lib/index.js b/server/lib/index.js
index 90c14532ae..2e1f8fc7fd 100644
--- a/server/lib/index.js
+++ b/server/lib/index.js
@@ -95,6 +95,7 @@ export * from './cliProviderRun.js';
export * from './codexAssistantExtract.js';
export * from './codexCliOutput.js';
export * from './contextBudget.js';
+export * from './cursor.js';
export * from './grok.js';
export * from './grokVideoClip.js';
export * from './hfToken.js';
diff --git a/server/lib/kimi.js b/server/lib/kimi.js
index 3e14e74edb..6693d1e633 100644
--- a/server/lib/kimi.js
+++ b/server/lib/kimi.js
@@ -46,15 +46,10 @@
* every headless run fail at startup.
*/
-import { commandBasename, hasModelFlag } from './providerModels.js';
+import { argvHasFlag, commandBasename, hasModelFlag } from './providerModels.js';
const NOOP_CLEANUP = () => {};
-// True when argv contains any of `flags`, in either separated (`--flag`) or
-// joined (`--flag=value`) form. The generic scan behind the kimi arg builders.
-const argvHasFlag = (args = [], flags) =>
- args.some((a) => typeof a === 'string' && flags.some((f) => a === f || a.startsWith(`${f}=`)));
-
// True when a token looks like an option flag (leading `-`), so a prompt VALUE is
// never mistaken for one when deciding whether a separated `--prompt` already
// carries a value. A prompt beginning with `-` after a bare trailing `--prompt` is
diff --git a/server/lib/providerModels.js b/server/lib/providerModels.js
index 0551435a3a..450b8007a4 100644
--- a/server/lib/providerModels.js
+++ b/server/lib/providerModels.js
@@ -41,6 +41,22 @@ export function commandBasename(command) {
return command.split(/[\\/]/).pop().toLowerCase().replace(/\.exe$/, '');
}
+/**
+ * True when argv contains any of `flags`, in either separated (`--flag`) or
+ * joined (`--flag=value`) form. The generic scan behind the per-vendor argv
+ * builders (`grok.js`, `kimi.js`, `cursor.js`), which each carried a private
+ * byte-identical copy until the third one made it a rule. Lives here next to
+ * its siblings `hasModelFlag` / `hasEffortFlag` / `hasCodexUpdateCheckConfig`,
+ * so a fix to the matching rule is one edit rather than an N-file sweep.
+ * Non-string argv entries are skipped.
+ * @param {unknown[]} args
+ * @param {string[]} flags
+ * @returns {boolean}
+ */
+export function argvHasFlag(args = [], flags = []) {
+ return args.some((a) => typeof a === 'string' && flags.some((f) => a === f || a.startsWith(`${f}=`)));
+}
+
/**
* Returns the model string to pass to a CLI's --model flag, or null if the
* caller should omit --model entirely (configured-default sentinels — the CLI
@@ -398,6 +414,7 @@ export function isOpencodeCommand(command) {
return commandBasename(command) === 'opencode';
}
+
/**
* OpenCode addresses models as `provider/model` (e.g. `ollama/qwen2.5:7b`). The
* OpenCode Ollama provider declares its local daemon under the config-provider
@@ -531,6 +548,46 @@ export function resolveBedrockCliModel(id, { env = process.env, providerId } = {
return mapped;
}
+/**
+ * The model string a TUI spawn should actually pass to `--model`, given the
+ * resolved launch command. The single home for a decision that used to be
+ * open-coded in TWO parallel ladders — `tuiHandshake.js#buildTuiInvocation`
+ * (one-shot TUI prompt runs) and `agentTuiSpawning.js#appendModelArgs` (CoS
+ * agent / TUI-session spawns) — which is exactly how cursor's exemption landed
+ * in one and not the other. Callers keep their own `hasModelFlag` gating; this
+ * only answers "which id".
+ *
+ * - OpenCode: namespace a bare Ollama id (`ollama/<id>`); never Bedrock-mapped.
+ * - Claude Code: map a bare Claude id to its region-prefixed Bedrock form when
+ * the box is in Bedrock mode (no-op off Bedrock / for non-Claude ids).
+ * - Anything else: passed through verbatim.
+ *
+ * The Bedrock arm is deliberately OPT-IN on the launch command rather than the
+ * default. Bedrock is a Claude *Code* transport, but `toBedrockModelId` gates
+ * only on the model id matching `/claude/i` — so as the default it silently
+ * captured any vendor that labels Anthropic models under its own ids. Cursor is
+ * exactly that case (`claude-opus-5-thinking-high`), and on a Bedrock box it was
+ * being rewritten to `global.anthropic.claude-opus-5-thinking-high`, an id
+ * cursor's router has never heard of. Opting out per-vendor meant every future
+ * vendor had to remember to; keying on `isClaudeCommand` inverts that default so
+ * they don't. (`isClaudeCommand` treats a blank command as Claude, matching both
+ * callers' blank→`claude` spawn fallback, so this is behavior-preserving for
+ * every shipped provider.)
+ *
+ * @param {string} model - the already-resolved (non-sentinel) model id
+ * @param {{id?:string, command?:string, ollamaBacked?:boolean, envVars?:Record<string,string>}|null|undefined} provider
+ * @param {string} [command] - resolved launch command (may differ from provider.command)
+ * @returns {string}
+ */
+export function resolveInjectedTuiModel(model, provider, command = provider?.command) {
+ if (isOpencodeCommand(command)) return prefixOpencodeModel(provider, model);
+ if (!isClaudeCommand(command)) return model;
+ return resolveBedrockCliModel(model, {
+ env: { ...process.env, ...provider?.envVars },
+ providerId: provider?.id,
+ });
+}
+
/**
* Strip configured-default sentinels from a model list — the user-selectable view.
* @param {string[]} models
diff --git a/server/lib/providerModels.test.js b/server/lib/providerModels.test.js
index 52eb6b14c2..cf0d7091e3 100644
--- a/server/lib/providerModels.test.js
+++ b/server/lib/providerModels.test.js
@@ -38,8 +38,12 @@ import {
isKimiProvider,
splitAntigravityModel,
antigravityBaseModels,
- antigravityModelEffortLevels
+ antigravityModelEffortLevels,
+ resolveInjectedTuiModel
} from './providerModels.js';
+import { readFileSync } from 'fs';
+import { resolve, dirname } from 'path';
+import { fileURLToPath } from 'url';
// The catalog `agy models` prints — the shipped provider list mirrors it.
const AGY_CATALOG = [
@@ -719,6 +723,70 @@ describe('providerModels', () => {
});
});
+ // Both TUI spawn paths (tuiHandshake.js#buildTuiInvocation and
+ // agentTuiSpawning.js#appendModelArgs) delegate here, so this is the single
+ // place the "which model id do we actually pass" rule is decided. It used to
+ // be open-coded in both, which is how cursor's exemption landed in one and not
+ // the other — a Bedrock box mangled every cursor CoS agent's model id.
+ describe('resolveInjectedTuiModel', () => {
+ const BEDROCK = { CLAUDE_CODE_USE_BEDROCK: '1' };
+ const withBedrock = (fn) => {
+ const prev = process.env.CLAUDE_CODE_USE_BEDROCK;
+ Object.assign(process.env, BEDROCK);
+ try { return fn(); } finally {
+ if (prev === undefined) delete process.env.CLAUDE_CODE_USE_BEDROCK;
+ else process.env.CLAUDE_CODE_USE_BEDROCK = prev;
+ }
+ };
+
+ it('maps a bare Claude id on a Bedrock box', () => {
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ withBedrock(() => {
+ expect(resolveInjectedTuiModel('claude-opus-4-8', { id: 'claude-code-tui' }, 'claude'))
+ .toBe('global.anthropic.claude-opus-4-8');
+ });
+ spy.mockRestore();
+ });
+
+ it('namespaces an Ollama id for opencode and never Bedrock-maps it', () => {
+ const provider = { id: 'opencode-ollama-tui', command: 'opencode', ollamaBacked: true };
+ expect(resolveInjectedTuiModel('qwen2.5:7b', provider, 'opencode')).toBe('ollama/qwen2.5:7b');
+ });
+
+ // The regression this helper exists for: cursor labels Anthropic models with
+ // its OWN ids, which match toBedrockModelId's /claude/i gate.
+ it('passes a cursor model through verbatim on a Bedrock box', () => {
+ withBedrock(() => {
+ expect(resolveInjectedTuiModel('claude-opus-5-thinking-high', { id: 'cursor-tui' }, 'cursor-agent'))
+ .toBe('claude-opus-5-thinking-high');
+ });
+ });
+
+ // Discovery test: walks the SHIPPED catalog so a future vendor that labels
+ // Anthropic models under its own ids is covered without anyone remembering
+ // to add a case. Only `claude` may rewrite; everything else is verbatim.
+ it('rewrites the model id for no shipped non-claude TUI command', () => {
+ const __dirname = dirname(fileURLToPath(import.meta.url));
+ const seed = JSON.parse(readFileSync(resolve(__dirname, '../../data.reference/providers.json'), 'utf8'));
+ const commands = [...new Set(
+ Object.values(seed.providers)
+ .filter((p) => p.type === 'tui' && typeof p.command === 'string')
+ .map((p) => p.command),
+ )];
+ expect(commands.length).toBeGreaterThan(1);
+ const spy = vi.spyOn(console, 'error').mockImplementation(() => {});
+ withBedrock(() => {
+ for (const command of commands.filter((c) => c !== 'claude')) {
+ expect(
+ resolveInjectedTuiModel('claude-opus-5-thinking-high', { id: `${command}-tui` }, command),
+ `${command} must not have its model id Bedrock-rewritten`,
+ ).toBe('claude-opus-5-thinking-high');
+ }
+ });
+ spy.mockRestore();
+ });
+ });
+
describe('isClaudeCommand', () => {
it('matches bare, pathed, and Windows forms of the claude binary', () => {
expect(isClaudeCommand('claude')).toBe(true);
diff --git a/server/lib/tuiHandshake.js b/server/lib/tuiHandshake.js
index a1b6c41ccf..afe3ca0b49 100644
--- a/server/lib/tuiHandshake.js
+++ b/server/lib/tuiHandshake.js
@@ -12,10 +12,11 @@
* No cycle risk: this module imports nothing from either consumer.
*/
-import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeModel, isOpencodeCommand, buildCodexStartupArgs, buildEffortArgs, commandBasename } from './providerModels.js';
+import { resolveCliModel, hasModelFlag, resolveInjectedTuiModel, buildCodexStartupArgs, buildEffortArgs, commandBasename } from './providerModels.js';
import { ensureAntigravityTuiArgs, isAntigravityCommand, resolveAntigravityModelAndEffort } from './antigravity.js';
import { ensureGrokTuiArgs, isGrokCommand } from './grok.js';
import { ensureKimiTuiArgs, isKimiCommand } from './kimi.js';
+import { CURSOR_COMMAND, ensureCursorTuiArgs, isCursorCommand } from './cursor.js';
// ─── Paste handshake constants ────────────────────────────────────────────
@@ -866,6 +867,7 @@ export function inferTuiCommand(id) {
if (!id) return 'claude';
if (id.includes('codex')) return 'codex';
if (id.includes('antigravity')) return 'agy';
+ if (id.includes('cursor')) return CURSOR_COMMAND;
if (id.includes('gemini')) return 'gemini';
if (id.includes('kimi')) return 'kimi';
if (id.includes('grok')) return 'grok';
@@ -921,6 +923,9 @@ export function applyCommandDefaults(command, args) {
if (isKimiCommand(command)) {
return ensureKimiTuiArgs(args);
}
+ if (isCursorCommand(command)) {
+ return ensureCursorTuiArgs(args);
+ }
return args;
}
@@ -984,19 +989,12 @@ export function buildTuiInvocation(provider, model) {
const effectiveModel = resolveCliModel(model);
const shouldInject = !!effectiveModel && !hasModelFlag(baseArgs);
- // OpenCode TUI: namespace the bare Ollama id (`opencode --model ollama/<id>`).
- // Otherwise map a bare Claude id to its Bedrock form when the box is in Bedrock
- // mode (no-op otherwise / for non-Claude ids) — mirrors buildCliArgs for the
- // claude-code-tui runner.
- const injectedModel = !shouldInject
- ? effectiveModel
- : isOpencodeCommand(command)
- ? prefixOpencodeModel(provider, effectiveModel)
- : resolveBedrockCliModel(effectiveModel, {
- env: { ...process.env, ...provider?.envVars },
- providerId: provider?.id,
- });
- const withModel = shouldInject ? [...baseArgs, '--model', injectedModel] : baseArgs;
+ // Per-command model rewriting (OpenCode namespacing, cursor passthrough,
+ // Bedrock mapping) lives in resolveInjectedTuiModel — shared with
+ // agentTuiSpawning.js#appendModelArgs so the two spawn paths can't diverge.
+ const withModel = shouldInject
+ ? [...baseArgs, '--model', resolveInjectedTuiModel(effectiveModel, provider, command)]
+ : baseArgs;
return {
command,
args: [...withModel, ...buildEffortArgs(effort, { id: provider?.id, command }, withModel)],
diff --git a/server/lib/tuiHandshake.test.js b/server/lib/tuiHandshake.test.js
index b1ed67086f..6cc2c32f8b 100644
--- a/server/lib/tuiHandshake.test.js
+++ b/server/lib/tuiHandshake.test.js
@@ -466,6 +466,10 @@ describe('tuiHandshake.inferTuiCommand', () => {
['xai-grok-2', 'grok'],
['opencode-tui', 'opencode'],
['opencode-ollama-tui', 'opencode'],
+ // `cursor` must map to the AGENT binary, not the `cursor` GUI launcher, and
+ // must not fall through to the blank-command `claude` default.
+ ['cursor-tui', 'cursor-agent'],
+ ['cursor-cli', 'cursor-agent'],
])('inferTuiCommand(%p) → %p', (id, expected) => {
expect(inferTuiCommand(id)).toBe(expected);
});
@@ -609,6 +613,38 @@ describe('tuiHandshake.buildTuiInvocation', () => {
expect(out.args).toEqual(['--yolo', '--model', 'kimi-k2']);
});
+ it('builds the Cursor TUI with --force and appends the model', () => {
+ const provider = { id: 'cursor-tui', command: 'cursor-agent', args: ['--force'] };
+ const out = buildTuiInvocation(provider, 'auto');
+ expect(out.command).toBe('cursor-agent');
+ expect(out.args).toEqual(['--force', '--model', 'auto']);
+ });
+
+ it('injects --force when a cursor provider’s saved args dropped it', () => {
+ const out = buildTuiInvocation({ id: 'cursor-tui', command: 'cursor-agent', args: [] }, null);
+ expect(out.args).toEqual(['--force']);
+ });
+
+ it('emits no --effort for cursor — its reasoning tier is baked into the model id', () => {
+ const provider = { id: 'cursor-tui', command: 'cursor-agent', args: ['--force'], effort: 'high' };
+ const out = buildTuiInvocation(provider, 'claude-opus-5-thinking-high');
+ expect(out.args).not.toContain('--effort');
+ });
+
+ it('does not Bedrock-map a cursor model id that merely contains "claude"', () => {
+ const prev = process.env.CLAUDE_CODE_USE_BEDROCK;
+ process.env.CLAUDE_CODE_USE_BEDROCK = '1';
+ try {
+ const provider = { id: 'cursor-tui', command: 'cursor-agent', args: ['--force'] };
+ const out = buildTuiInvocation(provider, 'claude-opus-5-thinking-high');
+ expect(out.args).toEqual(['--force', '--model', 'claude-opus-5-thinking-high']);
+ expect(out.args.join(' ')).not.toContain('anthropic.');
+ } finally {
+ if (prev === undefined) delete process.env.CLAUDE_CODE_USE_BEDROCK;
+ else process.env.CLAUDE_CODE_USE_BEDROCK = prev;
+ }
+ });
+
it('appends --model when caller passes a model and provider.args has no model flag', () => {
const provider = { id: 'claude', args: ['-p', '-'] };
const out = buildTuiInvocation(provider, 'claude-opus-4-7');
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 48c694e0d6..6897df1630 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -29,6 +29,7 @@ import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
+import { CURSOR_COMMAND, isCursorCommand, ensureCursorHeadlessArgs } from '../lib/cursor.js';
import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';
import { isKimiCommand, ensureKimiHeadlessArgs } from '../lib/kimi.js';
import { resolveCliModel, buildEffortArgs, buildCodexStartupArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken, isOllamaClaudeProvider } from '../lib/providerModels.js';
@@ -364,6 +365,23 @@ export function buildCliSpawnConfig(provider, model, settingsEnv = {}, { systemP
};
}
+ // Cursor Agent CLI (`cursor-agent`): headless one-shot. `--print` reads the
+ // combined contract+task prompt from raw stdin (like claude/codex, unlike
+ // grok/kimi). `--force` is load-bearing beyond approvals: without a trust
+ // posture cursor-agent prints "Workspace Trust Required" and EXITS without
+ // doing any work — in a fresh CoS worktree that is every run. Emits plain text
+ // (the live-output handler falls through to its default text path, like
+ // grok/kimi/opencode — see cursor.js on why stream-json isn't selected yet). A
+ // non-Claude command, so agentLifecycle keeps the operating contract in the
+ // stdin prompt (no system-prompt-file split), matching the other CLIs above.
+ if (isCursorCommand(provider?.command)) {
+ return {
+ command: provider?.command || CURSOR_COMMAND,
+ args: ensureCursorHeadlessArgs(provider?.args || [], effectiveModel),
+ stdinMode: 'prompt',
+ };
+ }
+
// Default: Claude Code CLI. applyLeanClaudeArgs adds `--bare
// --strict-mcp-config` for Ollama-backed claude sessions (no-op otherwise,
// idempotent against user-baked flags); the system-prompt contract file
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index fb7d8c4138..b1e03f58d9 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -303,6 +303,33 @@ describe('buildCliSpawnConfig', () => {
expect(config.args).toEqual(['--print', '--model', 'kimi-k2']);
});
+ it('runs `cursor-agent` headless with --print --force and the model on stdin', () => {
+ const config = buildCliSpawnConfig({ id: 'cursor-cli', command: 'cursor-agent', args: ['--print', '--force'] }, 'auto');
+ expect(config.command).toBe('cursor-agent');
+ expect(config.stdinMode).toBe('prompt');
+ expect(config.args).toEqual(['--print', '--force', '--model', 'auto']);
+ // Cursor is non-Claude, so no claude-only flags leak in.
+ expect(config.args).not.toContain('--dangerously-skip-permissions');
+ expect(config.args).not.toContain('--append-system-prompt-file');
+ // Plain text output — no stream-json parser is claimed for cursor (see cursor.js).
+ expect(config.streamFormat).toBeUndefined();
+ });
+
+ it('adds --force to a cursor provider whose saved args dropped it (trust gate is fatal without it)', () => {
+ const config = buildCliSpawnConfig({ id: 'cursor-cli', command: 'cursor-agent', args: [] }, null);
+ expect(config.args).toEqual(['--print', '--force']);
+ });
+
+ it('does not Bedrock-map a cursor model id that merely contains "claude"', () => {
+ const config = buildCliSpawnConfig(
+ { id: 'cursor-cli', command: 'cursor-agent', args: ['--print', '--force'] },
+ 'claude-opus-5-thinking-high',
+ { CLAUDE_CODE_USE_BEDROCK: '1' },
+ );
+ expect(config.args).toEqual(['--print', '--force', '--model', 'claude-opus-5-thinking-high']);
+ expect(config.args.join(' ')).not.toContain('anthropic.');
+ });
+
it('adds lean-mode flags and the system-prompt file for an Ollama-backed claude CLI', () => {
const config = buildCliSpawnConfig(
{ id: 'claude-ollama', command: 'claude', ollamaBacked: true },
diff --git a/server/services/agentTuiSpawning.js b/server/services/agentTuiSpawning.js
index 46ae505a5b..7f3738ef3a 100644
--- a/server/services/agentTuiSpawning.js
+++ b/server/services/agentTuiSpawning.js
@@ -27,7 +27,7 @@ import * as git from './git.js';
import { resolveReviewLoopOptions } from './codeReview.js';
import { spawnTuiSessionViaRunner } from './cosRunnerClient.js';
import { shellQuote } from '../lib/shellQuote.js';
-import { resolveCliModel, buildEffortArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
+import { resolveCliModel, buildEffortArgs, resolveInjectedTuiModel, hasModelFlag, isOpencodeCommand, isClaudeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { createStreamingAnsiStripper, stripAnsi } from '../lib/ansiStrip.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { isMachineOnline } from '../lib/connectivity.js';
@@ -226,23 +226,17 @@ function appendModelArgs(args, model, command, provider) {
const effectiveModel = resolveCliModel(model);
if (!effectiveModel) return args;
// OpenCode TUI launches with `opencode --model ollama/<id>` (the top-level
- // flag preselects the model). Namespace the bare Ollama id; no Bedrock mapping.
- // Respect a user-baked --model/-m pin (mirrors buildTuiInvocation/buildCliArgs)
- // rather than appending a second flag that overrides it.
- if (isOpencodeCommand(command)) {
- if (hasModelFlag(args)) return args;
- return [...args, '--model', prefixOpencodeModel(provider, effectiveModel)];
- }
+ // flag preselects the model). Respect a user-baked --model/-m pin (mirrors
+ // buildTuiInvocation/buildCliArgs) rather than appending a second flag that
+ // overrides it.
+ if (isOpencodeCommand(command) && hasModelFlag(args)) return args;
// Antigravity never reaches here: buildTuiSpawnConfig resolves its model and
// effort together up front (agy validates the pair) — see antigravity.js.
- // Bedrock box: map a bare Claude id to its region-prefixed form just-in-time
- // (no-op off Bedrock / for non-Claude ids).
- const injectedModel = resolveBedrockCliModel(effectiveModel, {
- env: { ...process.env, ...provider?.envVars },
- providerId: provider?.id,
- });
- return [...args, '--model', injectedModel];
+ // Which id to actually pass (OpenCode namespacing / cursor passthrough /
+ // Bedrock mapping) is shared with tuiHandshake.js#buildTuiInvocation, so the
+ // two spawn paths can't drift — they already had, on cursor.
+ return [...args, '--model', resolveInjectedTuiModel(effectiveModel, provider, command)];
}
export function buildTuiSpawnConfig(provider, model, { systemPromptFile = null, effort = null } = {}) {