Self-hosted, Self-Improving, Federated Everything App — dev management, agent orchestration, persistent mind, digital twin, second brain, and creative pipeline from a single dashboard over Tailscale to port the user into the OS
JavaScript ai-agentsdashboarddeveloper-toolsdigital-twinquantified-selfsecond-brainself-hostedtailscale
fix: stop Ask and AI app detection from running a permission-bypassing agent on caller text (#9008)
[._.]/ Adam Eivyfb9a97631201
diff --git a/server/lib/README.md b/server/lib/README.mdindex ee7e3439f8..f029663d64 100644--- a/server/lib/README.md+++ b/server/lib/README.md@@ -232,7 +232,7 @@ The barrel `server/lib/index.js` is a machine-checkable enumeration of every pub| `videoTextEncoders.js` | Swappable prompt conditioners for local video runtimes. MiniMax H3 reads the *unnormalized* hidden state after Qwen3-VL language layer 49 (layers 50-63, the final norm and `lm_head` are never evaluated), so any checkpoint carrying the same embedding + layers 0-49 + vision tower is a drop-in conditioner — swapping it changes how the model reads a prompt without touching the diffusion weights. `TEXT_ENCODERS_BY_RUNTIME` declares the shipped options per runtime (pinned repo/revision plus an explicit `files` LIST — one repackaged safetensors, or just the shards of an upstream checkpoint that carry parameters the loader actually builds; in code rather than the media-models registry so a stale `data/media-models.json` can't name a file the runner can't map); `videoTextEncoderOptions(model)` returns the TRUE list stock-first (it deliberately does NOT collapse a one-entry runtime to `[]` — that is a presentation rule, and folding it in here would change what the server believes a model supports and empty the "offers …" list in the error; `TextEncoderPicker` owns the hide-when-there-is-no-real-choice check), `isStockTextEncoder(id)` makes absence and the `stock` sentinel the same request, `resolveVideoTextEncoder(model, id)` returns `null` for the stock choice or throws `VIDEO_TEXT_ENCODER_UNSUPPORTED` (with the non-throwing `supportsVideoTextEncoder` + `videoTextEncoderUnsupportedError` split out so the request path can reject before staging uploads), and `downloadableVideoTextEncoders()` (deduped by id — the table is keyed by RUNTIME, so one conditioner can be offered by two) / `downloadableVideoTextEncoder(id)` feed the `/api/video-gen/text-encoders/:id/(download\|repair)` lane. Two loader-mechanics fields exist because a ComfyUI-packaged conditioner is namespaced differently from the HF checkpoint the MLX port matches: `keyPrefixMap` (`model.` → `model.language_model.`, `visual.` → `model.visual.`) is applied to every checkpoint key by `scripts/generate_minimax_h3.py` BEFORE the pinned loader sees it — no fork of the pinned runtime — and `finalNormKey` names where the runner synthesizes a ones-filled `norm.weight` for a checkpoint published without one (correct upstream, since H3 reads the state *before* the norm, but the pinned loader refuses to load with any parameter missing). Both are absent for an UPSTREAM Qwen3-VL-32B checkpoint, which already uses the loader namespace and ships its own norm. A candidate must BE Qwen3-VL-32B (the shim reuses upstream's config/tokenizer/processor) — a different Qwen generation is not a substitute however close its conditioning width looks; see docs/features/video-text-encoders.md. `publicTextEncoderOption(entry)` is the client projection and deliberately drops both, so the UI can't reimplement the remap. The `ltx25` table (#4320) uses a third mechanic, `configOverrides`, because an LTX-2.5 pack's OWN Gemma 4 tower wins over `--gemma` inside the pinned fork: the substitution is a standalone shim directory whose generated `config.json` is the substitute's own with these keys merged over it (only ever the `model_type` label a unified checkpoint gets wrong — never `text_config`/`quantization`), and a candidate must BE Gemma 4 12B at 48 layers / hidden 3840 / vocab 262144 / `k_eq_v`. `verified` gates a substitute out of BOTH lanes (picker AND download) until it has been A/B-rendered against its runtime's stock conditioner — required on every non-built-in entry and fail-closed on absence, so a new entry is unreachable until someone states a verdict; both ltx25 substitutes are `verified: false` today. `declaredVideoTextEncoders()` is the UNFILTERED table for shape/invariant checks only — never the render or download path, and `videoTextEncoderRuntimes()` enumerates the table's runtime keys so parity/shape tests cover every runtime rather than the one that happened to exist when they were written. || `pi.js` | Pi command identity, headless/TUI arguments, and positional prompt delivery. || `providerModels.js` | Provider model resolution sentinels + helpers (`CODEX_CONFIGURED_DEFAULT` / `ANTIGRAVITY_CONFIGURED_DEFAULT` / `GROK_CONFIGURED_DEFAULT` / `KIMI_CONFIGURED_DEFAULT`, `resolveCliModel`, `filterSelectableModels`, Bedrock/OpenCode model mappers, `localRuntimeNamespace(provider)` — the OpenCode namespace only when it names a LOCAL daemon, i.e. the composed "namespace and not a hosted gateway" test that `cliChildEnv.js`, `localProviderRuntime.js` and `providerVendors.js` all key on, `CODEX_OSS_LOCAL_PROVIDERS` / `CODEX_OSS_MIN_VERSION` / `codexOssLocalProvider` / `codexUnsupportedLocalRuntime` — the codex half of that same axis: which local runtimes Codex's `--local-provider` can serve, and which marked runtime it cannot, kept here beside the namespace they wrap so `providerPrerequisites.js` classifies a codex record without importing `codex.js` (the argv emitter, `buildCodexOssArgs`, stays there), `OPENCODE_PUBLIC_REVIEW_AGENT` — the read-only OpenCode agent a no-tool public-review stage runs as, kept in this leaf because `providerVendors.js` must not import `opencodeConfig.js`, `parseOpencodeConfigContent` — the shared "is this stored OPENCODE_CONFIG_CONTENT usable?" read — plus `opencodeConfigIsLocalOnly` / `opencodeProviderIsLocalOnly`, the ONE locality rule `providerVendors.js` (gate eligibility) and `cliChildEnv.js` (public-review env allowlist) must not disagree about: if eligibility says yes where the allowlist strips the config, the stage spawns against the user's own ~/.config/opencode with tools intact while still reporting an enforced tool-free gate, `normalizeClaudeModelId` / `resolveClaudeCliModel` — the Claude-argv chokepoint that rewrites a dotted first-party version (`claude-fable-5.1`) to the dashed id Claude Code actually serves before the Bedrock mapping runs, model-flag scan helpers incl. `stripBrokenModelFlags` and `stripProviderPinArgs` (explicit per-run selections override baked CLI pins), `isCodexProvider`, `isKimiProvider`, `isAntigravityProvider`, `isCursorProvider`) plus the agy catalog family, which reads an `agy models` list as base ids paired with effort tiers (`splitAntigravityModel`, `antigravityBaseModels`, `antigravityModelEffortLevels`, `antigravityCatalogListsModel` — is a stored pin still served? — and `pickAntigravityRelayModel` — the cheapest tier to relay one tool call on when a vendor retires the pin PortOS shipped) plus reasoning-effort helpers for the claude/codex/agy/cursor CLIs (`CLAUDE_EFFORT_LEVELS` / `CODEX_EFFORT_LEVELS` / `ANTIGRAVITY_EFFORT_LEVELS` / `CURSOR_EFFORT_LEVELS` / `EFFORT_LEVELS`, `effortLevelsForProvider`, `resolveCliEffort` — clamps an out-of-range effort to the nearest level the target CLI accepts rather than dropping it, so a value saved against a wider ladder survives a provider switch — `clampEffortToLadder` (that clamp over an explicit ladder; the client's own `resolveCliEffort` runs its published-field ladder through it), `hasEffortFlag`, `buildEffortArgs` — the one emitter of `--effort <level>` / `-c model_reasoning_effort=<level>`, and deliberately silent for cursor — and `foldCursorEffortIntoModel`, which carries a cursor level inside `--model` as Cursor’s own variant syntax (`gpt-5[effort=max]`) because `cursor-agent` has no `--effort` flag) plus codex startup-arg helpers (`CODEX_EFFORT_KEY`, `CODEX_UPDATE_CHECK_KEY`, `hasCodexUpdateCheckConfig`, `buildCodexStartupArgs` — the one emitter of `-c check_for_update_on_startup=false`, spread by every codex spawn builder to disable the blocking startup update modal) plus `PORTOS_CLI_CONFIG_KEYS` / `isPortosSuppliedConfigKey` — the exhaustive list of `-c <key>=<value>` config keys PortOS injects, read by the `cli-config-invalid` error analyzer to tell a rejected PortOS override apart from a bad line in the user's own CLI config file.; `isOpencodeLocalProvider` (the OpenCode-on-a-local-backend-or-gateway gate behind the OpenCode effort ladder) and `isCodexSubscriptionProvider` (the ChatGPT-subscription readiness key, housed here so the browser re-export skips `codexAccount.js`'s protocol tables) |-| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Dependency-light on purpose, mirroring those files. |+| `providerVendors.js` | `PROVIDER_VENDORS` — one row per coding-agent CLI/TUI vendor (claude/codex/antigravity/opencode/grok/kimi/cursor, plus a deliberately-incomplete legacy `gemini-cli` row), consumed by every dispatch site that used to hand-roll its own vendor if-chain across ~8 branches in 5 files (#3618): `applyCommandDefaults`/`prepareCliPrompt` (re-exported from `tuiHandshake.js`/`cliProviderArgs.js`), `buildVendorCliArgs`/`buildVendorSpawnConfig` (consumed by `cliProviderArgs.js#buildCliArgs` / `agentCliSpawning.js#buildCliSpawnConfig`), `inferTuiCommand` (re-exported from `tuiHandshake.js`), and `injectTuiModelAndEffort` — the shared antigravity-validates-the-pair-vs-everyone-else `--model`/`--effort` injection used by both `tuiHandshake.js#buildTuiInvocation` and `agentTuiSpawning.js#buildTuiSpawnConfig`, replacing a second copy of that split that had already drifted once before this file existed. Doesn't rewrite any vendor's argv-building logic — that stays in `antigravity.js`/`grok.js`/`kimi.js`/`cursor.js`/`codex.js`. Also `toolFreeOneShotArgs` / `isToolFreeOneShotProvider` / `toolFreeOneShotRefusal` (#9008): the one-shot-over-caller-text posture Ask and AI app detection run — every approval-bypass flag stripped, the vendor tool-disable switch applied where one exists (claude, grok, pi), and host control required for every other CLI. Dependency-light on purpose, mirroring those files. || `publicReviewSpawnGate.js` | The ordered spawn-time preconditions a public-content review stage must clear before `runAgentSpawn` starts an agent for it — `checkPublicReviewSpawnPreconditions` returns the FIRST failing gate as `{ reason, category, emit }` (or null), running them in the order that is the contract: `publicReviewScanBlock` (the model-abuse scan cleared at least one PR), `publicReviewEligibilityBlock` (a complete eligibility verdict COVERING every PR the issue watcher saw — a partial gate is not a pass), `publicReviewProviderBlock` from `providerVendors.js` (the vendor row declares a maintained recipe for the requested posture; it owns the ordinary-task `null` posture, the re-derivation #5866 got wrong), then the model itself. `emit` tells the caller how to announce it: `warn-log` for the two fail-closed CONTENT gates, whose block must not raise an investigator that could retry the same unvalidated input, `agent:error` for a provider/model misconfiguration that should. `validateModel` is injected rather than imported — it is the one gate that probes a live runtime, so taking it as a parameter keeps this leaf out of the local-LLM graph and makes the gate ORDER testable with a stub. || `modelCapabilityTests.js` | Catalog + scoring for the CAPABILITY tests on `/models/performance` (run by `services/modelCapabilityTests.js`): `CAPABILITY_TESTS` (sandbox repair / image analysis / story outline / fiction scene / rhetoric evaluator, each gated on the capability badges the install catalog already shows), `applicabilityFor` + `applicableTests` (`applicable` / `not-applicable` / `unknown` — an UNCLAIMED capability is never a failure, and `null` capabilities mean the runtime reported none, which is distinct from `[]`), `scoreKeywords` + `VISION_FIXTURE_KEYWORDS` (required vs bonus terms, word-boundary matched with a negation guard so "no dog" doesn't score a dog), `scoreStoryBeats` + `HEROS_JOURNEY_BEATS` (coverage AND ordering, judged only over the beats present), `scoreSandboxRepair` (verdict from observed disk facts — editing the test instead of the module fails outright), `formatAgentEvent` (one agent stream frame → a transcript line), `rollUpVerdict`, and the verbatim `CAPABILITY_TEST_PROMPTS` / `SANDBOX_TASK_PROMPT` the consent gate shows. Pure, so any stored transcript can be re-scored with no provider call. || `modelPinMembership.js` | THE model-pin membership rule, and the local-daemon classification it rests on — `modelPinIsOffered(provider, model)` (may this provider be handed this model? a configured-default sentinel, an empty catalog and a local daemon's cached snapshot are all pass-throughs, so a freshly pulled Ollama model is never rejected as "not offered"; beyond those the match is exact, with two same-model-spelled-differently tolerances: agy compares on BASE ids, since `--effort` carries the tier and the spawner splits a suffixed pin into exactly that, and OpenCode's `namespace/model` form matches a bare pin, since pins are stored bare and namespaced at spawn), plus `localRuntimeKind(provider)` (the `*Backed` markers first, then the endpoint/name classifier; `orcarouter` excluded as a remote API) and `localBackendForProvider`. Split out of `localProviderRuntime.js` — which re-exports all three, so existing importers are untouched — because the browser needs this rule for a picker and must not pull that module's endpoint graph (`opencodeConfig.js` → `zod`, not a client dependency) to get it. Carries `LOCAL_RUNTIME_MANAGE_URLS` for the same reason (#7414): the route that manages each local runtime — Models → Runtimes for the servers, Models → LLMs for the weights catalog, `null` for the operator-owned compose projects — read by `LOCAL_RUNTIMES[*].manageUrl` and by the client surfaces that must name the same page. Consumed by `cliProviderRun.js`, `routes/brainSettings.js`, `services/agentProviderResolution.js`, `modelPinReconcile.js` and `client/src/utils/providerModels.js` — one answer for all five (#7327). |diff --git a/server/lib/cliProviderArgs.js b/server/lib/cliProviderArgs.jsindex 0ccddc329b..49cc0d8067 100644--- a/server/lib/cliProviderArgs.js+++ b/server/lib/cliProviderArgs.js@@ -25,7 +25,7 @@ import { resolveCliModel, stripBrokenModelFlags } from './providerModels.js';// registry (#3618) instead of a hand-rolled per-vendor if-chain — see// providerVendors.js for the vendor rows and its own dependency-light note// (this module must stay importable from the standalone autofixer process).-import { buildVendorCliArgs, prepareCliPrompt } from './providerVendors.js';+import { buildVendorCliArgs, prepareCliPrompt, toolFreeOneShotArgs } from './providerVendors.js';/*** Build CLI args based on provider type. Each CLI provider has different@@ -43,8 +43,10 @@ import { buildVendorCliArgs, prepareCliPrompt } from './providerVendors.js';* with both pinned (see `promptRunner.js#executeProviderRunOnce`). It becomes* `--effort <level>` on claude/agy and `-c model_reasoning_effort=<level>` on* codex, and is suppressed when the saved args already bake an effort pin.+ *+ * `toolFree` (#9008): see `toolFreeOneShotArgs` in providerVendors.js.*/-export function buildCliArgs(provider) {+export function buildCliArgs(provider, { toolFree = false } = {}) {const effort = provider?.effort || null;// Sanitize: drop any broken/dangling `--model` / `-m` tokens before// appending. hasModelFlag (in providerVendors.js's per-vendor arg builders)@@ -55,7 +57,11 @@ export function buildCliArgs(provider) {// Configured-default sentinels (Codex / Antigravity / Grok Build) resolve to// null so the CLI uses its own latest/default model without a --model flag.const effectiveDefaultModel = resolveCliModel(provider.defaultModel);- return buildVendorCliArgs(provider, baseArgs, { model: effectiveDefaultModel, effort });+ const args = buildVendorCliArgs(provider, baseArgs, { model: effectiveDefaultModel, effort, toolFree });+ // A one-shot over caller-supplied text (AI app detection, #9008) runs with+ // no approval bypass and, where the vendor has one, no tools. Applied to the+ // BUILT argv because several vendor builders append their bypass themselves.+ return toolFree ? toolFreeOneShotArgs(provider, args).args : args;}/**diff --git a/server/lib/grok.js b/server/lib/grok.jsindex c40bdb1d7f..8f59f628b2 100644--- a/server/lib/grok.js+++ b/server/lib/grok.js@@ -78,20 +78,24 @@ const OUTPUT_FORMAT_FLAGS = ['--output-format', '-o'];* - `--output-format plain` — PortOS parses CLI stdout as plain text.* - `--permission-mode bypassPermissions` — don't block file-writing agents on* approval prompts (grok's analog of `claude --dangerously-skip-permissions`).+ * With `toolFree` (a one-shot answer over caller text — Ask, AI app+ * detection, #9008) it is the read-only `plan` mode instead; the caller+ * then runs `toolFreeOneShotArgs` to empty the tool allowlist too.* - `--model <id>` — gated on no user-baked model flag.* - `--prompt-file /dev/stdin` — deliver the prompt over stdin (POSIX); the* spawn helper rewrites this to a temp file on Windows.* @param {string[]} baseArgs - user/legacy args (already model-flag-sanitized)* @param {string|null|undefined} model - defaultModel to pin, or null to omit+ * @param {{ toolFree?: boolean }} [options]* @returns {string[]}*/-export function ensureGrokHeadlessArgs(baseArgs = [], model) {+export function ensureGrokHeadlessArgs(baseArgs = [], model, { toolFree = false } = {}) {const out = [...baseArgs];if (!argvHasFlag(out, OUTPUT_FORMAT_FLAGS)) {out.push('--output-format', 'plain');}if (!argvHasFlag(out, PERMISSION_FLAGS)) {- out.push('--permission-mode', 'bypassPermissions');+ out.push('--permission-mode', toolFree ? 'plan' : 'bypassPermissions');}if (model && !hasModelFlag(out)) {out.push('--model', model);diff --git a/server/lib/hostControlRoutes.js b/server/lib/hostControlRoutes.jsindex 65ce317fa7..d8e2b9aa03 100644--- a/server/lib/hostControlRoutes.js+++ b/server/lib/hostControlRoutes.js@@ -34,6 +34,11 @@* already-configured values), and test, vision, refresh-models and* refresh-catalog (they run an already-configured provider on a fixed* prompt, as every AI feature does).+ * - The "already-configured provider" exemptions here hold only for+ * tool-free execution (#9008). POST /api/ask and POST /api/detect/ai hand+ * caller text to a caller-chosen provider, so they gate per request+ * instead: a provider that cannot run tool-free (`toolFreeOneShotArgs` in+ * lib/providerVendors.js) needs host control.* - pipeline and FableLoom: only autopilot start is gated — with gap filing* or self-improvement on it queues CoS agents. Every other pipeline route* generates text or media through an already-configured provider, thediff --git a/server/lib/providerVendors.js b/server/lib/providerVendors.jsindex c4a903f796..5f61bec882 100644--- a/server/lib/providerVendors.js+++ b/server/lib/providerVendors.js@@ -155,6 +155,115 @@ function defaultSpawnArgs(cliArgsFn, fallbackCommand) {});}+// ─── tool-free one-shot argv (#9008) ───────────────────────────────────────++// Approval/permission-bypass switches, in every vendor's spelling. A one-shot+// text call (Ask, AI app detection) hands the model caller-supplied text, so it+// must never carry one: with it, the CLI is an agent that runs shell commands+// with the PortOS user's privileges. Boolean flags; a `--flag=value` spelling is+// dropped too. Short aliases are vendor-specific (`-f` is not a bypass+// everywhere), so they live on the vendor rows as `bypassAliases`.+const APPROVAL_BYPASS_FLAGS = [+ '--dangerously-skip-permissions', // claude, agy+ '--allow-dangerously-skip-permissions', // claude+ '--dangerously-bypass-approvals-and-sandbox', // codex+ '--full-auto', // codex+ '--yolo', // codex, cursor, kimi+ '--auto', // kilo, kimi+ '--approve', // pi+ '--force', // cursor+ '--auto-review', // cursor+ '--always-approve', // grok+ '--yes-always', // aider+ '--allow-all-tools', // copilot+];+// Valued options whose VALUE is the bypass (`--permission-mode bypassPermissions`+// for claude and grok, codex's unsandboxed mode).+const APPROVAL_BYPASS_VALUES = new Map([+ ['--permission-mode', 'bypassPermissions'],+ ['--sandbox', 'danger-full-access'],+ ['-s', 'danger-full-access'],+]);++const flagMatches = (arg, flag) => arg === flag || arg.startsWith(`${flag}=`);++/**+ * Remove each option in `flags` together with its value(s): the joined+ * `--flag=value` spelling, or the separate tokens that follow it. `variadic`+ * options consume every following token up to the next flag (Claude's+ * `--tools <tools...>`); the others consume exactly one.+ */+function dropOptions(args, flags, { variadic = false } = {}) {+ const out = [];+ for (let i = 0; i < args.length; i += 1) {+ const arg = args[i];+ const flag = typeof arg === 'string' && flags.find((f) => flagMatches(arg, f));+ if (!flag) {+ out.push(arg);+ continue;+ }+ if (arg !== flag) continue; // joined form carries its own value+ if (!variadic) {+ i += 1;+ continue;+ }+ while (i + 1 < args.length && !(typeof args[i + 1] === 'string' && args[i + 1].startsWith('-'))) i += 1;+ }+ return out;+}++/** Strip every approval-bypass switch. `removed` says whether one was present. */+function stripApprovalBypassArgs(args, aliases = []) {+ const booleans = [...APPROVAL_BYPASS_FLAGS, ...aliases];+ const out = [];+ for (let i = 0; i < args.length; i += 1) {+ const arg = args[i];+ if (typeof arg !== 'string') { out.push(arg); continue; }+ if (booleans.some((f) => flagMatches(arg, f))) continue;+ const valued = [...APPROVAL_BYPASS_VALUES].find(([flag]) => flagMatches(arg, flag));+ if (valued) {+ const [flag, bypass] = valued;+ if (arg === `${flag}=${bypass}`) continue;+ if (arg === flag && args[i + 1] === bypass) { i += 1; continue; }+ }+ out.push(arg);+ }+ return { args: out, removed: out.length !== args.length };+}++// Claude Code: no built-in tools, no MCP servers (a project `.mcp.json` would+// otherwise start processes), and only the USER's settings — a project or local+// `.claude/settings*.json` in the working directory can declare hooks, which+// run shell commands without any tool call, and print mode skips the trust+// dialog that would otherwise gate them. `--restricted` is not used: it also+// drops user settings, where a Bedrock or gateway install keeps its env.+const CLAUDE_TOOL_FREE_ARGS = [+ '--tools', '',+ '--strict-mcp-config',+ '--mcp-config', '{"mcpServers":{}}',+ '--setting-sources', 'user',+];+function claudeToolFreeArgs(args) {+ const cleared = dropOptions(+ dropOptions(args, ['--tools', '--allowedTools', '--allowed-tools', '--mcp-config'], { variadic: true }),+ ['--setting-sources'],+ ).filter((arg) => arg !== '--strict-mcp-config');+ return [...cleared, ...CLAUDE_TOOL_FREE_ARGS];+}++// Grok's read-only permission mode plus an empty built-in tool allowlist — the+// same pair its no-tool public-review recipe enforces.+function grokToolFreeArgs(args) {+ return [...dropOptions(args, ['--permission-mode', '--tools']), '--permission-mode', 'plan', '--tools', ''];+}++// Pi: `--no-builtin-tools` alone leaves extension tools enabled, so extensions+// and skills go too (the no-tool public-review recipe's rule).+const PI_TOOL_FREE_ARGS = ['--no-approve', '--no-tools', '--no-builtin-tools', '--no-extensions', '--no-skills'];+function piToolFreeArgs(args) {+ return [...args.filter((arg) => !PI_TOOL_FREE_ARGS.includes(arg)), ...PI_TOOL_FREE_ARGS];+}+// ─── codex ──────────────────────────────────────────────────────────────────// The opt-in that pins a Codex run to the account PortOS believes it is using.@@ -550,8 +659,8 @@ const OPENCHAMBER = {// ─── grok ───────────────────────────────────────────────────────────────────-function grokCliArgs(baseArgs, { model }) {- return ensureGrokHeadlessArgs(baseArgs, model);+function grokCliArgs(baseArgs, { model, toolFree }) {+ return ensureGrokHeadlessArgs(baseArgs, model, { toolFree });}const GROK = {@@ -563,6 +672,7 @@ const GROK = {tuiArgs: ensureGrokTuiArgs,cliArgs: grokCliArgs,spawnArgs: defaultSpawnArgs(grokCliArgs, 'grok'),+ toolFreeOneShot: { matchCommand: isGrokCommand, toolFreeArgs: grokToolFreeArgs },publicReview: {[PUBLIC_REVIEW_NO_TOOL_POSTURE]: {spawnArgs: grokPublicReviewSpawnArgs,@@ -591,6 +701,8 @@ const KIMI = {cliArgs: kimiCliArgs,preparePrompt: prepareKimiPrompt,spawnArgs: defaultSpawnArgs(kimiCliArgs, 'kimi'),+ // No tool-disable switch: only the bypass alias is stripped.+ toolFreeOneShot: { matchCommand: isKimiCommand, bypassAliases: ['-y'] },};// ─── cursor ─────────────────────────────────────────────────────────────────@@ -613,6 +725,14 @@ const CURSOR = {tuiArgs: ensureCursorTuiArgs,cliArgs: cursorCliArgs,spawnArgs: defaultSpawnArgs(cursorCliArgs, CURSOR_COMMAND),+ // No tool-disable switch. `--force` also clears cursor's workspace-trust+ // gate, so when a bypass is stripped the narrow `--trust` (which approves+ // nothing) keeps the headless run from exiting on the trust block.+ toolFreeOneShot: {+ matchCommand: isCursorCommand,+ bypassAliases: ['-f'],+ afterStrip: (args) => (argvHasFlag(args, ['--trust']) ? args : [...args, '--trust']),+ },};// ─── gemini (legacy — see file header) ─────────────────────────────────────@@ -647,6 +767,7 @@ const PI = {cliArgs: piCliArgs,preparePrompt: preparePiPrompt,spawnArgs: defaultSpawnArgs(piCliArgs, PI_COMMAND),+ toolFreeOneShot: { matchCommand: isPiCommand, bypassAliases: ['-a'], toolFreeArgs: piToolFreeArgs },publicReview: {[PUBLIC_REVIEW_NO_TOOL_POSTURE]: {matchProvider: (provider) => isProcessProvider(provider) && isPiCommand(provider?.command),@@ -828,6 +949,9 @@ const CLAUDE = {matchCommand: () => true,cliArgs: claudeCliArgs,spawnArgs: claudeSpawnArgs,+ // Positive binary match: the row's always-true `matchCommand` must never+ // hand an unknown command claude's flags or a tool-free verdict.+ toolFreeOneShot: { matchCommand: isClaudeCommand, toolFreeArgs: claudeToolFreeArgs },publicReview: {// Claude is the historical always-true fallback row, so its posture// matcher must positively identify the binary — an unknown command must@@ -958,9 +1082,63 @@ export function prepareCliPrompt(command, args, prompt, options = {}) {}/** `buildCliArgs` (cliProviderArgs.js): headless one-shot argv per vendor. */-export function buildVendorCliArgs(provider, baseArgs, { model, effort }) {+export function buildVendorCliArgs(provider, baseArgs, { model, effort, toolFree = false }) {const vendor = PROVIDER_VENDORS.find((v) => v.cliArgs && matchesProvider(v, provider));- return vendor.cliArgs(baseArgs, { model, effort, provider });+ return vendor.cliArgs(baseArgs, { model, effort, provider, toolFree });+}++/**+ * Make a built one-shot CLI argv tool-free (#9008), for callers that hand the+ * model text they do not control — Ask and AI app detection. Run it on the+ * FINAL argv (after the vendor builder, before prompt delivery), because+ * several builders append their vendor's bypass flag themselves.+ *+ * Every approval-bypass switch is removed for every vendor. A vendor with a+ * maintained tool-disable switch (claude, grok, pi) then gets it appended and+ * reports `toolFree: true`; every other CLI — including agy, codex, opencode,+ * kilo and cursor, whose tool posture has no argv off switch — reports+ * `toolFree: false`, which callers treat as host control. An API provider runs+ * no process, so its argv is returned unchanged with `toolFree: true`.+ *+ * @param {object} provider - provider record (type, command)+ * @param {string[]} [args] - the built argv+ * @returns {{ args: string[], toolFree: boolean }}+ */+export function toolFreeOneShotArgs(provider, args = []) {+ if (provider?.type === PROVIDER_TYPES.API) return { args: [...args], toolFree: true };+ const spec = PROVIDER_VENDORS.find((v) => v.toolFreeOneShot?.matchCommand(provider?.command))?.toolFreeOneShot;+ const { args: stripped, removed } = stripApprovalBypassArgs(args, spec?.bypassAliases);+ if (spec?.toolFreeArgs) return { args: spec.toolFreeArgs(stripped), toolFree: true };+ return { args: removed && spec?.afterStrip ? spec.afterStrip(stripped) : stripped, toolFree: false };+}++/**+ * Whether a one-shot call on `provider` can run without host authority: an API+ * provider, or a headless CLI whose vendor has a tool-disable switch. A TUI+ * record is never tool-free — its interactive argv comes from the TUI spawn+ * path, which this module does not make tool-free.+ */+export function isToolFreeOneShotProvider(provider) {+ if (provider?.type === PROVIDER_TYPES.API) return true;+ return provider?.type === PROVIDER_TYPES.CLI && toolFreeOneShotArgs(provider).toolFree;+}++/**+ * The refusal for a one-shot over caller text whose provider cannot be made+ * tool-free and whose caller lacks host control, or null when it may run.+ * A plain `{ status, code, message }` so this module stays free of the server's+ * error classes; callers wrap it in a `ServerError`.+ *+ * @param {object} provider+ * @param {boolean} hasHostControl - the caller's server-derived authority+ */+export function toolFreeOneShotRefusal(provider, hasHostControl) {+ if (hasHostControl === true || isToolFreeOneShotProvider(provider)) return null;+ return {+ status: 403,+ code: 'HOST_CONTROL_FORBIDDEN',+ message: `Provider '${providerLabel(provider)}' cannot run without tools, so using it here requires host control: an operator session, or a local connection when no password is set. Choose an API provider or a tool-free CLI instead.`,+ };}/** How a provider names itself in an error a user has to act on. */diff --git a/server/lib/providerVendors.toolFree.test.js b/server/lib/providerVendors.toolFree.test.jsnew file mode 100644index 0000000000..20d34f2024--- /dev/null+++ b/server/lib/providerVendors.toolFree.test.js@@ -0,0 +1,123 @@+// #9008: Ask and AI app detection hand a caller-chosen provider caller text. A+// one-shot argv carrying an approval bypass turns that into remote shell access,+// so these pin the security guard directly: the bypass is gone for every vendor,+// and only a vendor with a real tool-disable switch reports itself tool-free.+import { readFileSync } from 'node:fs';+import { describe, expect, it } from 'vitest';+import { buildCliArgs } from './cliProviderArgs.js';+import { isToolFreeOneShotProvider, toolFreeOneShotArgs, toolFreeOneShotRefusal } from './providerVendors.js';++const SHIPPED_PROVIDERS = Object.values(+ JSON.parse(readFileSync(new URL('../../data.reference/providers.json', import.meta.url), 'utf8')).providers,+);++const BYPASS_TOKENS = [+ '--dangerously-skip-permissions', '--allow-dangerously-skip-permissions',+ '--dangerously-bypass-approvals-and-sandbox', '--full-auto', '--yolo', '--auto',+ '--approve', '--force', '--auto-review', '--always-approve', '--yes-always', '--allow-all-tools',+ 'bypassPermissions', 'danger-full-access',+];+const expectNoBypass = (args) => {+ for (const token of BYPASS_TOKENS) expect(args).not.toContain(token);+};+const cli = (command) => ({ type: 'cli', command });++describe('toolFreeOneShotArgs', () => {+ it.each([+ ['claude', ['--print', '--dangerously-skip-permissions', '--permission-mode', 'bypassPermissions', '--tools', 'Bash', 'Edit', '--allowedTools', 'mcp__x', '-p', '-']],+ ['grok', ['--permission-mode', 'bypassPermissions', '--always-approve', '--tools', 'bash', '--prompt-file', '/dev/stdin']],+ ['pi', ['--print', '--approve', '-a']],+ ])('%s keeps no bypass and gets its tool-disable switch', (command, args) => {+ const result = toolFreeOneShotArgs(cli(command), args);+ expect(result.toolFree).toBe(true);+ expectNoBypass(result.args);+ expect(result.args).not.toContain('Bash');+ expect(result.args).not.toContain('mcp__x');+ });++ it('empties claude\'s tool set and walls off project MCP servers and settings', () => {+ const { args } = toolFreeOneShotArgs(cli('claude'), ['--print', '--tools', 'Bash', '--setting-sources', 'user,project', '-p', '-']);+ expect(args).toEqual([+ '--print', '-p', '-',+ '--tools', '',+ '--strict-mcp-config', '--mcp-config', '{"mcpServers":{}}',+ '--setting-sources', 'user',+ ]);+ });++ it('pins grok to plan mode with an empty tool list, keeping its stdin prompt file', () => {+ const { args } = toolFreeOneShotArgs(cli('grok'), ['--output-format', 'plain', '--permission-mode=bypassPermissions', '--prompt-file', '/dev/stdin']);+ expect(args).toEqual(['--output-format', 'plain', '--prompt-file', '/dev/stdin', '--permission-mode', 'plan', '--tools', '']);+ });++ it.each([+ ['agy', ['--dangerously-skip-permissions', '--print']],+ ['codex', ['exec', '--dangerously-bypass-approvals-and-sandbox', '--sandbox', 'danger-full-access', '-']],+ ['kilo', ['run', '--auto']],+ ['kimi', ['-y', '--yolo']],+ ['opencode', ['run', '--agent', 'build']],+ ['aider', ['--yes-always', '--yolo']],+ ['copilot', ['--allow-all-tools']],+ ])('%s has no tool-disable switch: bypass stripped, reported not tool-free', (command, args) => {+ const result = toolFreeOneShotArgs(cli(command), args);+ expect(result.toolFree).toBe(false);+ expectNoBypass(result.args);+ expect(result.args).not.toContain('-y');+ });++ it('keeps agy\'s --print marker last so the prompt stays its value', () => {+ expect(toolFreeOneShotArgs(cli('agy'), ['--model', 'm', '--dangerously-skip-permissions', '--print']).args)+ .toEqual(['--model', 'm', '--print']);+ });++ it('swaps cursor\'s --force for the trust-only flag so the headless run still starts', () => {+ const result = toolFreeOneShotArgs(cli('cursor-agent'), ['--print', '-f']);+ expect(result).toEqual({ args: ['--print', '--trust'], toolFree: false });+ });++ it('never hands an unknown command claude\'s flags', () => {+ expect(toolFreeOneShotArgs(cli('aider'), ['--model', 'm']).args).toEqual(['--model', 'm']);+ });++ it('leaves an API provider alone and tool-free', () => {+ expect(toolFreeOneShotArgs({ type: 'api' }, ['x'])).toEqual({ args: ['x'], toolFree: true });+ });+});++describe('isToolFreeOneShotProvider / toolFreeOneShotRefusal', () => {+ it('treats API providers and claude/grok/pi CLIs as tool-free, TUI records and agent CLIs as host control', () => {+ expect(isToolFreeOneShotProvider({ type: 'api' })).toBe(true);+ expect(isToolFreeOneShotProvider(cli('claude'))).toBe(true);+ expect(isToolFreeOneShotProvider(cli('grok'))).toBe(true);+ expect(isToolFreeOneShotProvider(cli('pi'))).toBe(true);+ expect(isToolFreeOneShotProvider(cli('agy'))).toBe(false);+ expect(isToolFreeOneShotProvider(cli('codex'))).toBe(false);+ expect(isToolFreeOneShotProvider({ type: 'tui', command: 'claude' })).toBe(false);+ });++ it('refuses only a non-tool-free provider, and only without host control', () => {+ const agy = { id: 'antigravity-cli', ...cli('agy') };+ expect(toolFreeOneShotRefusal(agy, false)).toMatchObject({ status: 403, code: 'HOST_CONTROL_FORBIDDEN' });+ expect(toolFreeOneShotRefusal(agy, true)).toBeNull();+ expect(toolFreeOneShotRefusal(cli('claude'), false)).toBeNull();+ });+});++// The runner path AI app detection takes: vendor builders re-add their own+// bypass (agy, grok, kilo, cursor, pi), so the guard must hold on the FINAL argv+// of every CLI record PortOS ships.+describe('buildCliArgs(provider, { toolFree: true })', () => {+ const shippedCli = SHIPPED_PROVIDERS.filter((provider) => provider.type === 'cli');++ it.each(shippedCli.map((provider) => [provider.id, provider]))('%s carries no approval bypass', (_id, provider) => {+ expectNoBypass(buildCliArgs(provider, { toolFree: true }));+ });++ it('gives headless grok no bypassPermissions', () => {+ expect(buildCliArgs(cli('grok'), { toolFree: true })).toEqual(expect.arrayContaining(['--permission-mode', 'plan']));+ });++ it('leaves the agent path untouched', () => {+ expect(buildCliArgs(cli('grok'))).toContain('bypassPermissions');+ });+});diff --git a/server/routes/ask.js b/server/routes/ask.jsindex dfe510d8ba..63784647d6 100644--- a/server/routes/ask.js+++ b/server/routes/ask.js@@ -26,7 +26,8 @@ import { awaitWritableDrain } from '../lib/streamBackpressure.js';import { SSE_HEADERS } from '../lib/sseHeaders.js';import { onClientDisconnect } from '../lib/sseDownload.js';import * as convs from '../services/askConversations.js';-import { runAsk, VALID_MODES } from '../services/askService.js';+import { resolveAskProvider, runAsk, VALID_MODES } from '../services/askService.js';+import { requestHasHostControl } from '../services/authGate.js';import { ID_RE as CONV_ID_RE } from '../services/askConversations.js';import { promoteTurnById } from '../services/askPromote.js';@@ -126,6 +127,11 @@ router.post('/:id/turns/:turnId/promote', asyncHandler(async (req, res) => {router.post('/', asyncHandler(async (req, res) => {const body = validateRequest(askBodySchema, req.body ?? {});+ // Resolved before any write or SSE handshake so a caller refused the+ // provider (#9008: one that cannot run tool-free needs host control) gets a+ // plain 403 and nothing is spawned or persisted.+ const provider = await resolveAskProvider(body.providerId, { hasHostControl: requestHasHostControl(req) });+let conversation = body.conversationId? await convs.getConversation(body.conversationId): null;@@ -221,6 +227,7 @@ router.post('/', asyncHandler(async (req, res) => {timeWindow: body.timeWindow,maxSources: body.maxSources,providerId: body.providerId,+ provider,model: body.model,signal: abortController.signal,})) {diff --git a/server/routes/ask.test.js b/server/routes/ask.test.jsindex 1bcdd3bc85..d3d83946bc 100644--- a/server/routes/ask.test.js+++ b/server/routes/ask.test.js@@ -22,6 +22,7 @@ vi.mock('../services/askService.js', () => ({// type so zod validation matches what production sees.VALID_MODES: new Set(['ask', 'advise', 'draft']),runAsk: vi.fn(),+ resolveAskProvider: vi.fn(async () => null),}));vi.mock('../services/brain.js', () => ({@@ -319,6 +320,48 @@ describe('POST /api/ask (validation)', () => {});});+// #9008: the provider is resolved and gated before any write or SSE frame, from+// the server-derived authority — a refused caller leaves no conversation behind.+describe('POST /api/ask (host control)', () => {+ it('returns 403 before creating a conversation or running anything when the provider is refused', async () => {+ const { ServerError } = await import('../lib/errorHandler.js');+ svc.resolveAskProvider.mockRejectedValueOnce(new ServerError('needs host control', { status: 403, code: 'HOST_CONTROL_FORBIDDEN' }));+ const res = await request(makeApp())+ .post('/api/ask')+ .send({ question: 'hi', providerId: 'antigravity-cli', hasHostControl: true });+ expect(res.status).toBe(403);+ expect(res.body).toMatchObject({ code: 'HOST_CONTROL_FORBIDDEN' });+ // The body's hasHostControl is ignored: a bare test app carries no auth context.+ expect(svc.resolveAskProvider).toHaveBeenCalledWith('antigravity-cli', { hasHostControl: false });+ expect(convs.createConversation).not.toHaveBeenCalled();+ expect(convs.appendTurn).not.toHaveBeenCalled();+ expect(svc.runAsk).not.toHaveBeenCalled();+ });++ it('runs the turn on the provider it resolved', async () => {+ const provider = { id: 'claude-code', type: 'cli' };+ svc.resolveAskProvider.mockResolvedValueOnce(provider);+ convs.createConversation.mockResolvedValue({ id: 'ask_lwgnewabc_abcdef00', mode: 'ask', turns: [] });+ convs.appendTurn.mockImplementation((id, turn) => Promise.resolve({+ conversation: { id, mode: 'ask', turns: [{ ...turn, id: 'tid' }] },+ turn: { ...turn, id: 'tid' },+ }));+ svc.runAsk.mockImplementation(async function* () {+ yield { type: 'done', answer: 'ok', sources: [], providerId: 'claude-code', model: 'm' };+ });+ const app = express();+ app.use(express.json());+ app.use((req, _res, next) => { req.portosAuthContext = { enabled: false }; next(); });+ app.use('/api/ask', routes);+ app.use(errorMiddleware);++ await request(app).post('/api/ask').send({ question: 'hi', providerId: 'claude-code' });+ // Password-free install, loopback connection: the operator.+ expect(svc.resolveAskProvider).toHaveBeenCalledWith('claude-code', { hasHostControl: true });+ expect(svc.runAsk.mock.calls[0][0].provider).toBe(provider);+ });+});+describe('POST /api/ask (streaming happy path)', () => {it('streams open → sources → delta → done as SSE', async () => {convs.createConversation.mockResolvedValue({ id: 'ask_lwgnewabc_abcdef00', mode: 'ask', turns: [] });diff --git a/server/routes/detect.js b/server/routes/detect.jsindex 2b5cfd8376..fac9b4279c 100644--- a/server/routes/detect.js+++ b/server/routes/detect.js@@ -6,6 +6,7 @@ import { exec } from '../lib/childProcess.js';import { promisify } from 'util';import { listProcessesStrict } from '../services/pm2.js';import { detectAppWithAi } from '../services/aiDetect.js';+import { requestHasHostControl } from '../services/authGate.js';import { asyncHandler, ServerError } from '../lib/errorHandler.js';import { safeJSONParse, tryReadFile } from '../lib/fileUtils.js';import { isWithinAllowedRoots, outsideAllowedRootsMessage, WORKSPACE_ROOTS_CONFIGURED } from '../lib/workspaceRoots.js';@@ -268,6 +269,8 @@ router.post('/pm2', asyncHandler(async (req, res) => {// README, then ships them to a configured AI provider (possibly a hosted API) and// runs that provider's CLI with cwd set here — so the confinement check must run// BEFORE detectAppWithAi, or a refused path has already left the machine.+// A provider that cannot run tool-free needs host control (#9008): a remote+// caller on a password-free install gets 403 HOST_CONTROL_FORBIDDEN instead.router.post('/ai', asyncHandler(async (req, res) => {const { path, providerId } = req.body;@@ -280,7 +283,7 @@ router.post('/ai', asyncHandler(async (req, res) => {throw new ServerError(confinement.error, { status: 400, code: confinement.code });}- const result = await detectAppWithAi(path, providerId);+ const result = await detectAppWithAi(path, providerId, { hasHostControl: requestHasHostControl(req) });res.json(result);}));diff --git a/server/routes/detect.test.js b/server/routes/detect.test.jsindex c6548c476d..2d67a5e576 100644--- a/server/routes/detect.test.js+++ b/server/routes/detect.test.js@@ -41,6 +41,29 @@ describe('Detect Routes', () => {expect(response.body).toEqual({ success: false, error: 'No AI provider configured' });});+ // #9008: whether a non-tool-free provider may run is decided from the+ // server-derived authority, never from anything the caller sends.+ it('hands detection the server-derived host-control verdict, ignoring the body', async () => {+ detectAppWithAi.mockResolvedValue({ success: false, error: 'No AI provider configured' });+ const withAuth = (authContext) => {+ const scoped = express();+ scoped.use(express.json());+ scoped.use((req, _res, next) => { req.portosAuthContext = authContext; next(); });+ scoped.use('/api/detect', detectRoutes);+ scoped.use(errorMiddleware);+ return scoped;+ };++ // Password-free install, loopback connection: the operator.+ await request(withAuth({ enabled: false })).post('/api/detect/ai').send({ path: '/example/project' });+ expect(detectAppWithAi).toHaveBeenLastCalledWith('/example/project', undefined, { hasHostControl: true });++ // A peer credential on a password-gated install never qualifies.+ await request(withAuth({ enabled: true, authenticated: true, method: 'basic' }))+ .post('/api/detect/ai').send({ path: '/example/project', hasHostControl: true });+ expect(detectAppWithAi).toHaveBeenLastCalledWith('/example/project', undefined, { hasHostControl: false });+ });+it('returns the standard error envelope when AI detection throws', async () => {detectAppWithAi.mockRejectedValue(new Error('provider crashed'));@@ -168,7 +191,7 @@ describe('POST /api/detect/ai workspace-root confinement', () => {expect(response.status).toBe(200);expect(response.body).toEqual({ success: true, app: { name: 'example' } });- expect(detect).toHaveBeenCalledWith(OUTSIDE_DEFAULT_ROOTS, undefined);+ expect(detect).toHaveBeenCalledWith(OUTSIDE_DEFAULT_ROOTS, undefined, { hasHostControl: false });});it('stays unrestricted when PORTOS_WORKSPACE_ROOTS is unset', async () => {@@ -180,6 +203,6 @@ describe('POST /api/detect/ai workspace-root confinement', () => {.send({ path: OUTSIDE_DEFAULT_ROOTS });expect(response.status).toBe(200);- expect(detect).toHaveBeenCalledWith(OUTSIDE_DEFAULT_ROOTS, undefined);+ expect(detect).toHaveBeenCalledWith(OUTSIDE_DEFAULT_ROOTS, undefined, { hasHostControl: false });});});diff --git a/server/services/aiDetect.js b/server/services/aiDetect.jsindex 484d2809c3..74732d9fbc 100644--- a/server/services/aiDetect.js+++ b/server/services/aiDetect.js@@ -7,6 +7,8 @@ import { extractJson } from '../lib/jsonExtract.js';import { runPromptThroughProvider } from './promptRunner.js';import { fenceBlock, UNTRUSTED_CONTENT_NOTICE } from '../lib/promptFencing.js';import { validateCommand } from '../lib/commandSecurity.js';+import { toolFreeOneShotRefusal } from '../lib/providerVendors.js';+import { ServerError } from '../lib/errorHandler.js';const DEFAULT_AI_DETECT_TIMEOUT_MS = 60000;@@ -216,9 +218,21 @@ function parseAiResponse(response) {}/**- * Auto-detect app configuration using AI+ * Auto-detect app configuration using AI.+ *+ * The caller picks both the directory and the provider, and the prompt carries+ * that directory's README and config, so the run is tool-free (#9008): no+ * approval-bypass flag, and the vendor's tool-disable switch where it has one.+ * A provider that cannot be made tool-free (agy, codex, a TUI record, …) needs+ * `hasHostControl`, and without it fallback is off too, so the run cannot be+ * rerouted onto such a provider after this check.+ *+ * @param {string} dirPath+ * @param {string|null} [providerId]+ * @param {{ hasHostControl?: boolean }} [options] - the caller's server-derived+ * authority (`requestHasHostControl`); absent means none*/-export async function detectAppWithAi(dirPath, providerId = null) {+export async function detectAppWithAi(dirPath, providerId = null, { hasHostControl = false } = {}) {// Validate directoryif (!existsSync(dirPath)) {return { success: false, error: 'Directory does not exist' };@@ -242,6 +256,9 @@ export async function detectAppWithAi(dirPath, providerId = null) {return { success: false, error: 'AI provider is disabled' };}+ const refusal = toolFreeOneShotRefusal(provider, hasHostControl);+ if (refusal) throw new ServerError(refusal.message, { status: refusal.status, code: refusal.code });+// Gather contextconst context = await gatherProjectContext(dirPath);const prompt = buildAnalysisPrompt(context);@@ -253,6 +270,8 @@ export async function detectAppWithAi(dirPath, providerId = null) {source: 'ai-app-detect',timeout: provider.timeout || DEFAULT_AI_DETECT_TIMEOUT_MS,cwd: dirPath,+ toolFree: true,+ allowFallback: hasHostControl === true,});// Parse responsediff --git a/server/services/aiDetect.test.js b/server/services/aiDetect.test.jsindex 13aa48e21f..4b31f77db2 100644--- a/server/services/aiDetect.test.js+++ b/server/services/aiDetect.test.js@@ -78,7 +78,7 @@ describe('detectAppWithAi', () => {runPromptThroughProvider.mockResolvedValue({ text: VALID_DETECTION_JSON, runId: 'r1', model: 'm1' });await withProjectDir({ 'package.json': JSON.stringify({ name: 'my-app' }) }, async (dir) => {- const result = await detectAppWithAi(dir, 'claude-tui');+ const result = await detectAppWithAi(dir, 'claude-tui', { hasHostControl: true });expect(result.success).toBe(true);expect(result.provider).toBe('Claude TUI');@@ -88,9 +88,33 @@ describe('detectAppWithAi', () => {expect(call.source).toBe('ai-app-detect');expect(call.cwd).toBe(dir);expect(call.timeout).toBe(30000);+ expect(call.toolFree).toBe(true);+ expect(call.allowFallback).toBe(true);});});+ // #9008: the caller picks the directory and the provider, so the run is+ // tool-free, and an agent CLI that cannot be made so needs host control.+ it('refuses a provider that cannot run tool-free to a caller without host control, before any run', async () => {+ getProviderById.mockResolvedValue({ id: 'antigravity-cli', type: 'cli', command: 'agy', enabled: true });+ await withProjectDir({}, async (dir) => {+ await expect(detectAppWithAi(dir, 'antigravity-cli'))+ .rejects.toMatchObject({ status: 403, code: 'HOST_CONTROL_FORBIDDEN' });+ });+ expect(runPromptThroughProvider).not.toHaveBeenCalled();+ });++ it('runs a tool-free CLI for a caller without host control, with fallback off', async () => {+ getProviderById.mockResolvedValue({ id: 'claude-code', name: 'Claude', type: 'cli', command: 'claude', enabled: true });+ runPromptThroughProvider.mockResolvedValue({ text: VALID_DETECTION_JSON, runId: 'r1', model: 'm1' });+ await withProjectDir({}, async (dir) => {+ const result = await detectAppWithAi(dir, 'claude-code');+ expect(result.success).toBe(true);+ });+ // Fallback off: a failed tool-free run cannot be rerouted to an agent CLI.+ expect(runPromptThroughProvider.mock.calls[0][0]).toMatchObject({ toolFree: true, allowFallback: false });+ });+it('uses default 60s timeout when provider does not specify one', async () => {const provider = { id: 'p', name: 'P', type: 'api', enabled: true };getActiveProvider.mockResolvedValue(provider);@@ -128,7 +152,7 @@ describe('detectAppWithAi', () => {});await withProjectDir({}, async (dir) => {- const result = await detectAppWithAi(dir);+ const result = await detectAppWithAi(dir, null, { hasHostControl: true });expect(result.success).toBe(true);expect(result.detected.name).toBe('Test App');});@@ -257,7 +281,7 @@ describe('detectAppWithAi', () => {});await withProjectDir({ 'package.json': echoedPackageJson }, async (dir) => {- const result = await detectAppWithAi(dir);+ const result = await detectAppWithAi(dir, null, { hasHostControl: true });expect(result.success).toBe(true);expect(result.detected.name).toBe('Test App');expect(result.detected.uiPort).toBe(3000);diff --git a/server/services/askService.js b/server/services/askService.jsindex 334cc75bb8..2eac2da575 100644--- a/server/services/askService.js+++ b/server/services/askService.js@@ -37,6 +37,8 @@ import { isOpenchamberCommand, ensureOpenchamberHeadlessArgs } from '../lib/openimport { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';import { prepareCliPrompt } from '../lib/cliProviderArgs.js';+import { isToolFreeOneShotProvider, toolFreeOneShotArgs, toolFreeOneShotRefusal } from '../lib/providerVendors.js';+import { ServerError } from '../lib/errorHandler.js';import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';import { applyCredentialBootstrap, needsProcessGroup, trackDetachedGroup } from '../lib/credentialBootstrap.js';import { buildCliChildEnv } from '../lib/cliChildEnv.js';@@ -440,6 +442,27 @@ async function pickProvider(providerId) {throw new Error('No AI provider available');}+/**+ * The provider an Ask turn will run on, resolved up front so an HTTP caller can+ * be refused with a 403 before any conversation write or SSE handshake.+ *+ * Ask hands the model the caller's own question, so a provider that cannot run+ * tool-free (#9008) — an agent CLI such as agy — needs host control. Returns+ * null when no provider is available; `runAsk` reports that on the stream.+ *+ * @param {string} [providerId]+ * @param {{ hasHostControl?: boolean }} [options] - server-derived authority+ * @returns {Promise<object|null>}+ * @throws {ServerError} 403 HOST_CONTROL_FORBIDDEN+ */+export async function resolveAskProvider(providerId, { hasHostControl = false } = {}) {+ const provider = await pickProvider(providerId).catch(() => null);+ if (!provider) return null;+ const refusal = toolFreeOneShotRefusal(provider, hasHostControl);+ if (refusal) throw new ServerError(refusal.message, { status: refusal.status, code: refusal.code });+ return provider;+}+/*** Stream a completion from an API-style provider. Yields text chunks.* Falls back to a single-shot call for non-streaming providers (CLI).@@ -511,13 +534,13 @@ async function* streamCompletion(provider, model, prompt, signal) {// -m/--model pin (mirrors buildCliArgs) rather than duplicating the flag.if (cliModel && !hasModelFlag(args)) args.push('--model', prefixOpencodeModel(provider, cliModel));} else if (isGrokCommand(provider?.command)) {- // Grok reads its prompt from --prompt-file /dev/stdin and needs plain output- // + permission bypass; ensureGrokHeadlessArgs adds them (gated on user pins).- args = ensureGrokHeadlessArgs(args, cliModel);+ // Grok reads its prompt from --prompt-file /dev/stdin and needs plain output;+ // ensureGrokHeadlessArgs adds both, with the read-only permission mode+ // rather than its agent-path bypass.+ args = ensureGrokHeadlessArgs(args, cliModel, { toolFree: true });} else if (isKiloCommand(provider?.command)) {- // Kilo forks OpenCode's `run`, and adds the `--auto` approval posture an- // unattended answer needs — without it the run stalls on the first- // permission prompt with nobody to answer it.+ // Kilo forks OpenCode's `run`; its `--auto` approval posture is stripped+ // below with every other bypass.args = ensureKiloHeadlessArgs(args, cliModel);} else if (isOpenchamberCommand(provider?.command)) {// OpenChamber's prompt path is a control-plane action, not a flag: without@@ -527,13 +550,20 @@ async function* streamCompletion(provider, model, prompt, signal) {} else if (cliModel) {args.push('--model', cliModel);}+ // The question is caller text, so the answer runs tool-free (#9008): every+ // approval-bypass flag goes — whether saved in provider.args or added by a+ // vendor builder above — and claude/grok/pi get their tool-disable switch.+ // A vendor with no such switch was already refused for a caller without host+ // control (resolveAskProvider / runAsk).+ args = toolFreeOneShotArgs(provider, args).args;// Deliver the prompt per provider convention: antigravity gets it as the// --print VALUE (agy doesn't read stdin); grok's /dev/stdin sentinel via stdin// (POSIX) / temp file (Windows); everyone else via stdin (writePromptToStdin).const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(provider.command, args, prompt);// Shared composition (provider.envVars + OpenCode models map + CLAUDECODE// strip) — see buildCliChildEnv. No cwd is passed to spawn below, so there is- // no PWD to pin; no `guard` — Ask is a one-shot answer, not an agent. Routing+ // no PWD to pin; no `guard` — the argv above is tool-free for every vendor+ // that can be, and host-control-gated for the rest. Routing// through the shared builder also brings the OpenCode declared-models map here// for the first time, so the `--model` this path injects above isn't rejected// by an Ollama-backed OpenCode provider (the #2190 fix, previously applied@@ -634,6 +664,11 @@ async function* streamCompletion(provider, model, prompt, signal) {* @param {number} [opts.maxSources]* @param {string} [opts.providerId]* @param {string} [opts.model]+ * @param {object} [opts.provider] - already resolved and gated by+ * `resolveAskProvider`; skips resolution here.+ * @param {() => (boolean|Promise<boolean>)} [opts.hasHostControl] - the+ * caller's server-derived authority, consulted only when the resolved+ * provider cannot run tool-free (#9008). Absent means none.* @param {AbortSignal} [opts.signal] - Aborts retrieval/provider stream when* the caller (e.g. SSE client) disconnects, so we don't keep generating* tokens for a closed connection.@@ -646,6 +681,8 @@ export async function* runAsk({maxSources = 12,providerId,model,+ provider: resolvedProvider = null,+ hasHostControl,signal,}) {if (!question || typeof question !== 'string' || !question.trim()) {@@ -668,12 +705,21 @@ export async function* runAsk({if (signal?.aborted) return;yield { type: 'sources', sources };- let provider;- try {- provider = await pickProvider(providerId);- } catch (err) {- yield { type: 'error', error: err.message };- return;+ let provider = resolvedProvider;+ if (!provider) {+ try {+ provider = await pickProvider(providerId);+ } catch (err) {+ yield { type: 'error', error: err.message };+ return;+ }+ // Authority is asked for only when it matters: a voice turn re-verifies+ // its session on every call.+ if (!isToolFreeOneShotProvider(provider) && await hasHostControl?.() !== true) {+ const refusal = toolFreeOneShotRefusal(provider, false);+ yield { type: 'error', error: refusal.message, code: refusal.code };+ return;+ }}const effectiveModel = model || provider.defaultModel;// API providers will fail with a vague upstream 4xx if `model` is null —diff --git a/server/services/askService.test.js b/server/services/askService.test.jsindex 4f1f1e8e20..15ebaed108 100644--- a/server/services/askService.test.js+++ b/server/services/askService.test.js@@ -474,7 +474,7 @@ describe('runAsk', () => {spawn.mockReturnValue(child);const events = [];- for await (const evt of askService.runAsk({ question: 'test question' })) {+ for await (const evt of askService.runAsk({ question: 'test question', hasHostControl: () => true })) {events.push(evt);}@@ -506,7 +506,7 @@ describe('runAsk', () => {spawn.mockReturnValue(child);const events = [];- for await (const evt of askService.runAsk({ question: 'test question' })) {+ for await (const evt of askService.runAsk({ question: 'test question', hasHostControl: () => true })) {events.push(evt);}@@ -516,7 +516,7 @@ describe('runAsk', () => {expect(args[modelIdx + 1]).toBe('o4-mini');});- it('runs `grok` headless with plain output, permission bypass, and stdin prompt file (no --model for configured-default)', async () => {+ it('runs `grok` headless with plain output, read-only permission mode, no tools, and stdin prompt file (no --model for configured-default)', async () => {providers.getActiveProvider.mockResolvedValue({id: 'grok-cli',type: 'cli',@@ -551,10 +551,12 @@ describe('runAsk', () => {const expectedPromptFile = process.platform === 'win32'? expect.stringMatching(/grok-prompt-.*\.txt$/): '/dev/stdin';+ // #9008: Ask runs tool-free — never grok's agent-path bypassPermissions.expect(args).toEqual(['--output-format', 'plain',- '--permission-mode', 'bypassPermissions','--prompt-file', expectedPromptFile,+ '--permission-mode', 'plan',+ '--tools', '',]);expect(args).not.toContain('--model');// POSIX delivery: the prompt is piped in via stdin.@@ -584,7 +586,7 @@ describe('runAsk', () => {});spawn.mockReturnValue(child);- for await (const _evt of askService.runAsk({ question: 'test question' })) { /* drain */ }+ for await (const _evt of askService.runAsk({ question: 'test question', hasHostControl: () => true })) { /* drain */ }const [, args] = spawn.mock.calls.at(-1);// agy takes the prompt as the --print VALUE, so --print must be second-to-last@@ -593,7 +595,7 @@ describe('runAsk', () => {'--add-dir', '/tmp/x',// The suffixed id splits into base + `--effort` (equivalent invocation).'--model', 'gemini-3.1-pro', '--effort', 'high',- '--dangerously-skip-permissions',+ // #9008: the bypass ensureAntigravityPrintArgs adds is stripped.'--print',]);expect(args.at(-1)).toContain('test question');@@ -621,11 +623,11 @@ describe('runAsk', () => {});spawn.mockReturnValue(child);- for await (const _evt of askService.runAsk({ question: 'test question' })) { /* drain */ }+ for await (const _evt of askService.runAsk({ question: 'test question', hasHostControl: () => true })) { /* drain */ }const [, args] = spawn.mock.calls.at(-1);expect(args).not.toContain('--model');- expect(args.slice(0, -1)).toEqual(['--dangerously-skip-permissions', '--print']);+ expect(args.slice(0, -1)).toEqual(['--print']);expect(args.at(-1)).toContain('test question');});@@ -653,7 +655,7 @@ describe('runAsk', () => {spawn.mockReturnValue(child);const events = [];- for await (const evt of askService.runAsk({ question: 'test question' })) {+ for await (const evt of askService.runAsk({ question: 'test question', hasHostControl: () => true })) {events.push(evt);}@@ -690,7 +692,7 @@ describe('runAsk', () => {spawn.mockReturnValue(child);const events = [];- for await (const evt of askService.runAsk({ question: 'test question' })) {+ for await (const evt of askService.runAsk({ question: 'test question', hasHostControl: () => true })) {events.push(evt);}@@ -830,3 +832,73 @@ describe('runAsk', () => {});});});++// #9008: Ask hands a caller-chosen provider the caller's own question. A CLI+// that cannot be made tool-free is an agent, so it needs host control; one+// that can runs with its bypass stripped and its tool-disable switch applied.+describe('tool-free Ask (#9008)', () => {+ const AGY = { id: 'antigravity-cli', type: 'cli', enabled: true, command: 'agy', args: ['--print', '--dangerously-skip-permissions'], timeout: 5000 };+ const CLAUDE = {+ id: 'claude-code', type: 'cli', enabled: true, command: 'claude', timeout: 5000,+ // A saved bypass must not survive, and a saved tool list must not widen the set.+ args: ['--print', '--dangerously-skip-permissions', '--tools', 'Bash'],+ headlessArgs: ['--no-session-persistence', '--disable-slash-commands', '--tools', ''],+ };+ const fakeChild = () => {+ const child = new EventEmitter();+ child.stdout = new EventEmitter();+ child.stderr = new EventEmitter();+ child.stdin = { on: vi.fn(), end: vi.fn(), write: vi.fn() };+ child.kill = vi.fn();+ setImmediate(() => {+ child.stdout.emit('data', Buffer.from('answer text'));+ child.emit('close', 0);+ });+ return child;+ };++ it('refuses a provider that cannot run tool-free for a caller without host control, before spawning', async () => {+ providers.getProviderById.mockResolvedValue(AGY);+ await expect(askService.resolveAskProvider('antigravity-cli', { hasHostControl: false }))+ .rejects.toMatchObject({ status: 403, code: 'HOST_CONTROL_FORBIDDEN' });++ // The voice/palette path resolves inside runAsk and must fail closed the same way.+ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi', providerId: 'antigravity-cli', hasHostControl: async () => false })) events.push(evt);+ expect(events.at(-1)).toMatchObject({ type: 'error', code: 'HOST_CONTROL_FORBIDDEN' });+ expect(spawn).not.toHaveBeenCalled();+ });++ it('keeps every provider for a caller with host control, still without the bypass flag', async () => {+ providers.getProviderById.mockResolvedValue(AGY);+ await expect(askService.resolveAskProvider('antigravity-cli', { hasHostControl: true })).resolves.toBe(AGY);+ spawn.mockReturnValue(fakeChild());+ for await (const _evt of askService.runAsk({ question: 'hi', provider: AGY })) { /* drain */ }+ const [, args] = spawn.mock.calls.at(-1);+ expect(args).not.toContain('--dangerously-skip-permissions');+ });++ it('lets a caller without host control use claude-code with no tools and no bypass', async () => {+ providers.getProviderById.mockResolvedValue(CLAUDE);+ const provider = await askService.resolveAskProvider('claude-code', { hasHostControl: false });+ expect(provider).toBe(CLAUDE);+ spawn.mockReturnValue(fakeChild());+ const events = [];+ for await (const evt of askService.runAsk({ question: 'hi', provider })) events.push(evt);+ expect(events.at(-1).type).toBe('done');+ const [, args] = spawn.mock.calls.at(-1);+ expect(args).not.toContain('--dangerously-skip-permissions');+ expect(args).not.toContain('Bash');+ expect(args.filter((a) => a === '--tools')).toHaveLength(1);+ expect(args[args.indexOf('--tools') + 1]).toBe('');+ // A project `.mcp.json` or `.claude/settings.json` cannot add servers or hooks.+ expect(args).toContain('--strict-mcp-config');+ expect(args[args.indexOf('--setting-sources') + 1]).toBe('user');+ });++ it('lets a caller without host control use an API provider', async () => {+ const api = { id: 'example-api', type: 'api', enabled: true, endpoint: 'http://127.0.0.1:1', defaultModel: 'm' };+ providers.getProviderById.mockResolvedValue(api);+ await expect(askService.resolveAskProvider('example-api', { hasHostControl: false })).resolves.toBe(api);+ });+});diff --git a/server/services/promptRunner.js b/server/services/promptRunner.jsindex dec9b523d1..1802aaf04a 100644--- a/server/services/promptRunner.js+++ b/server/services/promptRunner.js@@ -620,6 +620,13 @@ export function assertVisionRunUsedImages(result, requestedProvider) {* provider still benches it, so the Providers page and every unpinned caller* learn that this provider is sick. The one exception is a usage limit, whose* observed-block ledger a pinned caller records itself.+ * @param {boolean} [args.toolFree=false] — the prompt carries text this caller+ * does not control (AI app detection, #9008). A headless CLI run then gets no+ * approval-bypass flag and, where its vendor has one, its tool-disable switch+ * (`toolFreeOneShotArgs` in lib/providerVendors.js). Rides every fallback tier.+ * It does not reach a TUI run, whose interactive argv has no such posture —+ * a caller that must stay tool-free gates on `isToolFreeOneShotProvider`+ * and disables fallback.* @param {*} [args.responseSchema] — the caller's declared response schema* (issue #2350). A Zod-style schema (`.safeParse`/`.parse`) or a bare* predicate `(parsedValue) => boolean`. When set, the runner enables Tier-2@@ -1388,6 +1395,7 @@ async function executeProviderRunOnce({outputReserveTokens,callerPolicy = null,allowFallback = true,+ toolFree = false,}) {// Caller EXECUTION-MODE policy, enforced on the EXPLICIT provider before a run// record exists and carried into fallback selection below, so the pin and the@@ -1650,7 +1658,7 @@ async function executeProviderRunOnce({}if (effectiveProvider.type === PROVIDER_TYPES.CLI) {- executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, screenshots, onData, onComplete, timeout: effectiveTimeout }).catch(safeReject);+ executeCliRun({ runId, provider: providerForRun, prompt, workspacePath: effectiveCwd, screenshots, onData, onComplete, timeout: effectiveTimeout, toolFree }).catch(safeReject);} else if (effectiveProvider.type === PROVIDER_TYPES.API) {// API runs take model as a first-class arg — no clone needed. The// toolkit's executeApiRun now owns the primary wall-clock timeout (itdiff --git a/server/services/runner.js b/server/services/runner.jsindex ea7c68e10b..9a8fc90386 100644--- a/server/services/runner.js+++ b/server/services/runner.js@@ -322,7 +322,7 @@ const describeSpawnFailure = (spawnError, command) =>* `.cmd`/`.bat` spawn under `shell:false` fails outright post-CVE-2024-27980,* and why the `cmd.exe` wrapper avoids DEP0190's unescaped-join hazard).*/-export async function executeCliRun({ runId, provider, prompt, workspacePath, screenshots = [], onData, onComplete, timeout }) {+export async function executeCliRun({ runId, provider, prompt, workspacePath, screenshots = [], onData, onComplete, timeout, toolFree = false }) {const toolkit = requireToolkit();const runsPath = join(runnerConfig.dataDir, 'runs');@@ -380,7 +380,9 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, sc: null;const cleanupVisionFiles = vision?.cleanup || (() => Promise.resolve());// Build provider-specific args for prompt delivery- const builtArgs = vision?.invocation.args || buildCliArgs(provider);+ // `toolFree`: a one-shot over caller-supplied text gets no approval bypass+ // and no tools where the vendor can disable them (#9008).+ const builtArgs = vision?.invocation.args || buildCliArgs(provider, { toolFree });// Rewrite the argv for prompt delivery and learn whether to still write stdin:// - Antigravity (`agy`): prompt spliced in as the --print VALUE (agy doesn't// read stdin) → useStdin=false.diff --git a/server/services/voice/tools/ask.js b/server/services/voice/tools/ask.jsindex 96985f997b..213e036ef3 100644--- a/server/services/voice/tools/ask.js+++ b/server/services/voice/tools/ask.js@@ -50,7 +50,7 @@ export const ASK_TOOLS = [// runAsk yields { sources, delta, done, error }. Collect deltas into an array// (avoids O(n²) string reallocation on long answers); the terminal `done` event// delivers the canonical full answer + reranked sources and supersedes deltas.- for await (const evt of runAsk({ question: trimmed, mode: validMode, signal: ctx.signal })) {+ for await (const evt of runAsk({ question: trimmed, mode: validMode, signal: ctx.signal, hasHostControl: ctx.hasHostControl })) {if (evt.type === 'sources') sources = evt.sources;else if (evt.type === 'delta') deltas.push(evt.text);else if (evt.type === 'error') { errorMsg = evt.error; break; }