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

fix(agents): deliver agy prompts as the --print value, not via stdin

Adam Eivy9ac6be6ea4ec
diff --git a/.changelog/NEXT.md b/.changelog/NEXT.md
index 454d101c08..15fc0cb74e 100644
--- a/.changelog/NEXT.md
+++ b/.changelog/NEXT.md
@@ -2,6 +2,8 @@
## Creative Director
+- **Antigravity (`agy`) agents now actually receive their task** — CD plan/treatment agents (and every other headless `agy` run) were launched as `agy --print --dangerously-skip-permissions` with the prompt piped to stdin. But unlike the old Gemini CLI, `agy --print` takes the prompt as the flag's *value* and does not read stdin — so the flag parser consumed `--dangerously-skip-permissions` as the "prompt," the real 23KB brief was ignored, and the agent dutifully researched the flag name and asked for clarification (while permission auto-approval silently never took effect). The prompt is now delivered as the `--print` value (`agy --dangerously-skip-permissions --print "<prompt>"`) across all six spawn paths (runner, direct, "Run Prompt", ask, vision, cos-runner). The interactive TUI path was never affected (it pastes the prompt, no `--print` to swallow the flag).
+
- **Commissioned videos now honor the project's locked aspect ratio** — a scheduled Creative Commission (e.g. a daily 9:16 clip) whose plan renders through `media_enqueueVideoJob` was rendering at the video worker's default 768×512 landscape box: the planner authored an `aspectRatio` string the worker doesn't read, and the project's locked preset was never resolved into the `width`/`height` the renderer actually consumes. The server now deterministically forces every directive-plan video render onto the project's locked aspect/quality/duration preset (the planner keeps ownership of prompt/style), and the `cd-plan` prompt documents the locked settings so the plan preview stays honest.
- **A completed video commission no longer looks like it "did nothing"** — the directive-plan flow marked the project `complete` but never promoted the rendered clip to `finalVideoId`, so the Creative Director overview showed "Final video: not yet rendered" even though the render had landed in the media library. Plan completion now promotes the last rendered video to the project's final video (and backfills it on re-entry for already-complete projects).
diff --git a/PLAN.md b/PLAN.md
index f6344a7cdd..2533fa32ea 100644
--- a/PLAN.md
+++ b/PLAN.md
@@ -83,3 +83,11 @@ by `/do:replan --issues`:
### PortOS-update / CoS-agent mutual-exclusion follow-up
- [ ] **Gate every CoS spawn engine on `updateInProgress` so a scheduled/autopilot spawn can't start during a PortOS self-update.** The update flow now blocks `POST /api/update/execute` when a CoS agent is live or mid-spawn (`server/routes/update.js` `countActiveCosAgents`, fast-fail + post-lock re-check via `getActiveAgentIds()` + `spawningTasks`), and the Update tab suppresses restart buttons while agents run. Residual: an agent that begins spawning *after* the route's post-lock re-check but before `update.sh` reaches its `pm2 delete` (a multi-second window covering git pull / submodules / npm install) is still severed. Fully closing it means having the spawn side consult the update lock: add a synchronous in-memory `isUpdateInProgress()` mirror to `server/services/updateChecker.js` (kept in lockstep with the persisted flag in `setUpdateInProgress`) and have the CoS spawn engines skip-and-requeue (return the existing `SPAWN_DEDUP_SKIP`-style no-op, leaving the task queued for after the restart) when it's set. **This must cover ALL spawn engines, not just `spawnAgentForTask`** — per the CoS autonomous-spawn precedent, gating one chokepoint gives false confidence; audit `dequeueNextTask` / `evaluateTasks` / `executeScheduledJob` and the Creative Director / on-demand bridges (grep the spawn call sites in `server/services/agentLifecycle.js` + `subAgentSpawner.js` + `cos*.js`). Deferred from the codex review of this PR (r2 P1) because it's a CoS-subsystem change spanning multiple spawn paths that deserves its own focused PR + tests; the 409 guard, post-lock re-check, and the orphan reaper bound the residual exposure in the meantime.
+
+### Antigravity CLI prompt-delivery follow-up
+
+- [ ] **Handle `agy` + non-empty `extraArgs` so the prompt stays the LAST argv token.** `agy --print` takes the prompt as its VALUE, so `ensureAntigravityPrintArgs` puts `--print` last and `prepareAntigravityPrompt` (via `prepareCliPrompt`, `server/lib/antigravity.js` / `server/lib/cliProviderArgs.js`) splices the prompt right after it. But `cliProviderRun.js` builds `[...buildCliArgs(provider), ...extraArgs]`, so for an antigravity provider with a non-empty `extraArgs` the delivered argv becomes `… --print "<PROMPT>" <extraArg…>` — the prompt is still `--print`'s value (correct), but any trailing extraArgs become positional args agy may reject. Low risk today (no caller passes `extraArgs` for an antigravity provider), but if one is added, either strip/relocate the trailing `--print` marker so extraArgs precede it, or have `prepareAntigravityPrompt` move `--print <prompt>` to the very end after splicing. Deferred from the agy prompt-delivery fix — the shipped paths (CD plan via runner/direct, Run Prompt, ask, vision) pass no extraArgs and are validated end-to-end.
+
+### Creative Director agents should not push code (deferred — needs a distinct completion contract)
+
+- [ ] **Suppress `/simplify` + `/do:push` + PR in CD agent completions WITHOUT breaking their API output contract.** CD plan/treatment/evaluation agents persist their real output via an HTTP call in the task BODY (e.g. `PATCH http://localhost:5555/api/creative-director/{id}/plan` — see the plan prompt), and use the `.agent-done` sentinel only as a *done-signal* (a short markdown summary that PortOS's 2s poll consumes to finalize the run). They run on `main` (`useWorktree:false`, `configCodingOnMain:true`) and make no repo changes, so the trailing `/simplify` → `/do:push` completion is both pointless and dangerous (a `/do:push` on main could commit stray working-tree files). The fix must remove `/simplify`+`/do:push`+PR from the CD completion while KEEPING (a) the sentinel done-signal handshake and (b) the task-body PATCH as the output channel. **Do NOT reuse `discardWorktree`** — codex review (2026-07-16) correctly flagged that it routes to `buildProgrammaticOutputCompletionSection`, whose wording ("your *only* output channel is the `.agent-done` sentinel; write your result there in the payload format from your instructions") directly contradicts the PATCH and could make the agent write the plan to the sentinel instead of PATCHing → plan never persists → project stalls/re-enqueues. `readOnly:true` is also wrong ("read data and report findings only" contradicts the PATCH, and the CLI read-only path emits no sentinel). The correct fix is a NEW completion contract (e.g. a `apiOutput`/`noRepoOutput` metadata flag) that emits: "This task persists its output via the API/tool calls described above and makes no repo changes — do NOT run `/simplify`, `/do:push`, `/do:pr`, `git commit/push`, or open a PR; when done write a short summary to the sentinel to signal completion." Thread the flag through the completion selection in `server/services/agentPromptBuilder.js` (lines ~1137-1160 light path + the full-context path ~790, and whichever of `buildTuiCompletionSection`/`buildCliCompletionSection` CD actually reaches — confirm via a regenerated CD prompt fixture) and add a test asserting the CD prompt contains the sentinel step but NO `/do:push`/`/do:pr`/`/simplify`. Deferred from this PR because it needs a carefully-designed prompt-contract change + fixture test, not a rushed flag reuse.
diff --git a/server/cos-runner/index.js b/server/cos-runner/index.js
index f6ea2639e7..0b54f6ede4 100644
--- a/server/cos-runner/index.js
+++ b/server/cos-runner/index.js
@@ -17,6 +17,7 @@ import http from 'http';
import { Server as SocketServer } from 'socket.io';
import { ensureDir, PATHS } from '../lib/fileUtils.js';
import { prepareCliSpawn, killProcessTree } from '../lib/bufferedSpawn.js';
+import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { createStreamJsonParser } from './streamJsonParser.js';
import { loadState, saveState, withState } from './runnerState.js';
@@ -195,7 +196,14 @@ app.post('/spawn', async (req, res) => {
// output → startup-failure. Mirrors the working "Run Prompt" path
// (server/services/runner.js); resolved against childEnv so a provider PATH
// override is honored. See issue #2243.
- const { command: spawnCommand, args: finalSpawnArgs } = prepareCliSpawn(command, spawnArgs, childEnv);
+ // Deliver the prompt per provider convention BEFORE resolving the spawn shim:
+ // - Antigravity (`agy`): spliced in as the --print VALUE (agy does not read
+ // stdin) → useStdin=false. Without this the prompt never reaches the model
+ // and the trailing --print marker swallows the next flag as its "prompt".
+ // - Grok on Windows: `/dev/stdin` rewritten to a temp file → useStdin=false.
+ // - Every other provider: unchanged, prompt over stdin → useStdin=true.
+ const { args: deliveredArgs, useStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(command, spawnArgs, prompt);
+ const { command: spawnCommand, args: finalSpawnArgs } = prepareCliSpawn(command, deliveredArgs, childEnv);
// Spawn the CLI process
const claudeProcess = spawn(spawnCommand, finalSpawnArgs, {
@@ -225,8 +233,9 @@ app.post('/spawn', async (req, res) => {
workspacePath: cwd
});
- // Send prompt via stdin
- claudeProcess.stdin.write(prompt);
+ // Send prompt via stdin (skipped when the prompt was delivered via argv —
+ // antigravity's --print value, or grok's Windows temp file).
+ if (useStdin) claudeProcess.stdin.write(prompt);
claudeProcess.stdin.end();
// Handle stdout
@@ -273,6 +282,7 @@ app.post('/spawn', async (req, res) => {
// Handle errors
claudeProcess.on('error', (err) => {
+ cleanupPromptFile();
console.error(`❌ Agent ${agentId} spawn error: ${err.message}`);
emitToServer('agent:error', { agentId, error: err.message });
activeAgents.delete(agentId);
@@ -280,6 +290,7 @@ app.post('/spawn', async (req, res) => {
// Handle process exit
claudeProcess.on('close', async (code) => {
+ cleanupPromptFile();
try {
const agent = activeAgents.get(agentId);
// Cancel any pending SIGKILL timer — process already exited.
diff --git a/server/cos-runner/index.test.js b/server/cos-runner/index.test.js
index b59c37dc39..01b1e22abe 100644
--- a/server/cos-runner/index.test.js
+++ b/server/cos-runner/index.test.js
@@ -22,10 +22,13 @@ describe('cos-runner spawn — Windows CLI shim resolve+wrap (#2243)', () => {
it('resolves+wraps the agent CLI command before spawning it', () => {
// The agent spawn (the /spawn handler) must feed its command/args through
// prepareCliSpawn and spawn WHATEVER it returns — never the bare `command`.
+ // deliveredArgs is spawnArgs after prepareCliPrompt (antigravity --print
+ // value / grok Windows temp-file rewrite); every provider still resolves
+ // through prepareCliSpawn before spawning.
const call = RUNNER_SRC.match(
- /const\s*\{\s*command:\s*spawnCommand,\s*args:\s*finalSpawnArgs\s*\}\s*=\s*prepareCliSpawn\(\s*command,\s*spawnArgs,\s*childEnv\s*\)/
+ /const\s*\{\s*command:\s*spawnCommand,\s*args:\s*finalSpawnArgs\s*\}\s*=\s*prepareCliSpawn\(\s*command,\s*deliveredArgs,\s*childEnv\s*\)/
);
- expect(call, 'agent spawn must call prepareCliSpawn(command, spawnArgs, childEnv)').not.toBeNull();
+ expect(call, 'agent spawn must call prepareCliSpawn(command, deliveredArgs, childEnv)').not.toBeNull();
// The resolved pair must be what spawn() actually receives.
expect(RUNNER_SRC).toMatch(/spawn\(\s*spawnCommand,\s*finalSpawnArgs,/);
});
@@ -35,13 +38,38 @@ describe('cos-runner spawn — Windows CLI shim resolve+wrap (#2243)', () => {
// BEFORE the resolve so PATH resolution sees the child's PATH, and is reused
// as the spawn env — matching the working server/services/runner.js path.
const childEnvIdx = RUNNER_SRC.indexOf('const childEnv = (() =>');
- const prepareIdx = RUNNER_SRC.indexOf('prepareCliSpawn(command, spawnArgs, childEnv)');
+ const prepareIdx = RUNNER_SRC.indexOf('prepareCliSpawn(command, deliveredArgs, childEnv)');
expect(childEnvIdx, 'childEnv must be defined').toBeGreaterThan(-1);
expect(prepareIdx, 'prepareCliSpawn must run against childEnv').toBeGreaterThan(-1);
expect(childEnvIdx, 'childEnv must be built before the resolve').toBeLessThan(prepareIdx);
});
});
+describe('cos-runner spawn — per-provider prompt delivery (antigravity --print value)', () => {
+ it('imports prepareCliPrompt from the shared cliProviderArgs helper', () => {
+ expect(RUNNER_SRC).toMatch(
+ /import\s*\{[^}]*\bprepareCliPrompt\b[^}]*\}\s*from\s*'\.\.\/lib\/cliProviderArgs\.js';/
+ );
+ });
+
+ it('runs the built argv through prepareCliPrompt before resolving the spawn', () => {
+ // Antigravity (`agy`) takes the prompt as the --print VALUE and does NOT read
+ // stdin; without this the prompt never reaches the model. prepareCliPrompt
+ // rewrites the argv (and returns useStdin=false for agy) before the resolve.
+ const prepareIdx = RUNNER_SRC.indexOf('prepareCliPrompt(command, spawnArgs, prompt)');
+ const resolveIdx = RUNNER_SRC.indexOf('prepareCliSpawn(command, deliveredArgs, childEnv)');
+ expect(prepareIdx, 'must call prepareCliPrompt(command, spawnArgs, prompt)').toBeGreaterThan(-1);
+ expect(resolveIdx, 'must resolve the delivered argv').toBeGreaterThan(-1);
+ expect(prepareIdx, 'prompt delivery runs before the spawn resolve').toBeLessThan(resolveIdx);
+ });
+
+ it('gates the stdin write on useStdin so an argv-delivered prompt is not also piped', () => {
+ // For antigravity (--print value) / grok-on-Windows (temp file) useStdin is
+ // false — writing the prompt to stdin too would be redundant/incorrect.
+ expect(RUNNER_SRC).toMatch(/if\s*\(\s*useStdin\s*\)\s*claudeProcess\.stdin\.write\(prompt\)/);
+ });
+});
+
describe('cos-runner termination — Windows tree-kill for cmd.exe-wrapped shims (#2243)', () => {
it('imports killProcessTree from the shared bufferedSpawn helper', () => {
expect(RUNNER_SRC).toMatch(
diff --git a/server/lib/aiToolkit/internal/antigravity.js b/server/lib/aiToolkit/internal/antigravity.js
index cd1b9aa2c6..a40072cc4d 100644
--- a/server/lib/aiToolkit/internal/antigravity.js
+++ b/server/lib/aiToolkit/internal/antigravity.js
@@ -39,14 +39,19 @@ export function stripAntigravityUnsupportedArgs(args = []) {
return out;
}
+// `agy --print`/`-p`/`--prompt` takes the prompt as the flag's VALUE and does
+// NOT read stdin. So the print flag must be the FINAL token (a marker); the host
+// runner splices the prompt in right after it at spawn time. Keep in sync with
+// server/lib/antigravity.js#ensureAntigravityPrintArgs — the host overrides the
+// runner (setCliRunner), so the prompt injection itself lives host-side.
+const ANTIGRAVITY_PRINT_FLAGS = ['--print', '-p', '--prompt'];
+
export function ensureAntigravityPrintArgs(args = []) {
- const out = stripAntigravityUnsupportedArgs(args);
- if (!out.some((arg) => arg === '--print' || arg === '-p' || arg === '--prompt')) {
- out.unshift('--print');
- }
+ const out = stripAntigravityUnsupportedArgs(args).filter((arg) => !ANTIGRAVITY_PRINT_FLAGS.includes(arg));
if (!out.includes('--dangerously-skip-permissions') && !out.includes('--sandbox')) {
out.push('--dangerously-skip-permissions');
}
+ out.push('--print');
return out;
}
diff --git a/server/lib/aiToolkit/providers.test.js b/server/lib/aiToolkit/providers.test.js
index ec41923a7d..d1643090c0 100644
--- a/server/lib/aiToolkit/providers.test.js
+++ b/server/lib/aiToolkit/providers.test.js
@@ -548,7 +548,7 @@ describe('Provider Service', () => {
expect(active.id).toBe('antigravity-cli');
expect(legacy).toBeNull();
expect(antigravity.command).toBe('agy');
- expect(antigravity.args).toEqual(['--print', '--dangerously-skip-permissions']);
+ expect(antigravity.args).toEqual(['--dangerously-skip-permissions', '--print']);
expect(antigravity.defaultModel).toBe('antigravity-configured-default');
expect(antigravity.contextWindow).toBe(1048576);
expect(antigravity.envVars).toEqual({ KEEP_ME: '1' });
diff --git a/server/lib/antigravity.js b/server/lib/antigravity.js
index 5ced8b3be0..a5f7f9534e 100644
--- a/server/lib/antigravity.js
+++ b/server/lib/antigravity.js
@@ -12,17 +12,63 @@ export function isAntigravityCliProvider(provider) {
return provider?.id === ANTIGRAVITY_CLI_ID || isAntigravityCommand(provider?.command);
}
+// agy print flags. Unlike the old Gemini CLI (which read the prompt from stdin),
+// `agy --print`/`-p`/`--prompt` takes the prompt as the flag's VALUE and does
+// NOT read stdin at all. So the print flag must be the FINAL token, with the
+// prompt spliced in right after it at spawn time by prepareAntigravityPrompt.
+export const ANTIGRAVITY_PRINT_FLAGS = ['--print', '-p', '--prompt'];
+
export function ensureAntigravityPrintArgs(args = []) {
- const out = stripAntigravityUnsupportedArgs(args);
- if (!out.some((arg) => arg === '--print' || arg === '-p' || arg === '--prompt')) {
- out.unshift('--print');
- }
+ // Drop any bare print flag the caller baked in — we re-add exactly one as the
+ // trailing marker. (PortOS always supplies the prompt itself, so a
+ // user-configured print flag never carries a prompt value to preserve.)
+ const out = stripAntigravityUnsupportedArgs(args).filter((arg) => !ANTIGRAVITY_PRINT_FLAGS.includes(arg));
if (!out.includes('--dangerously-skip-permissions') && !out.includes('--sandbox')) {
out.push('--dangerously-skip-permissions');
}
+ // Print flag LAST: it is a marker with no value here. A bare trailing --print
+ // is NOT a runnable invocation on its own — prepareAntigravityPrompt injects
+ // the prompt as its value before the process is spawned. Leaving another flag
+ // (e.g. --dangerously-skip-permissions) after --print would make agy consume
+ // THAT flag as the prompt text (the bug that shipped the flag name to the
+ // model instead of the task — see server/lib/antigravity.js history).
+ out.push('--print');
return out;
}
+const NOOP_CLEANUP = () => {};
+
+/**
+ * Spawn-time prompt delivery for the antigravity CLI: splice the prompt in as
+ * the VALUE of the trailing print flag (agy does not read stdin). Mirrors the
+ * `{ args, useStdin, cleanup }` shape of grok.js#prepareGrokPromptFile so the
+ * spawn sites can dispatch through a single helper (see prepareCliPrompt).
+ *
+ * @param {string[]} args - argv as built by ensureAntigravityPrintArgs
+ * @param {string} prompt - the full prompt text
+ * @returns {{ args: string[], useStdin: false, cleanup: () => void }}
+ */
+export function prepareAntigravityPrompt(args = [], prompt = '') {
+ const out = [...args];
+ // Find the LAST print flag so the prompt lands as its value even if the argv
+ // carries stray tokens (it shouldn't, post-ensureAntigravityPrintArgs).
+ let idx = -1;
+ for (let i = out.length - 1; i >= 0; i--) {
+ if (ANTIGRAVITY_PRINT_FLAGS.includes(out[i])) { idx = i; break; }
+ }
+ if (idx === -1) {
+ out.push('--print', prompt);
+ } else {
+ out.splice(idx + 1, 0, prompt);
+ }
+ return { args: out, useStdin: false, cleanup: NOOP_CLEANUP };
+}
+
+// TUI mode launches the interactive bubbletea REPL (NO --print) and the prompt
+// is delivered by bracketed-paste after the input-ready handshake — never as an
+// argv value. So, unlike the CLI path, there is no print flag to accidentally
+// swallow --dangerously-skip-permissions: the flag stays a real boolean and the
+// permission auto-approval actually takes effect. Do NOT add --print here.
export function ensureAntigravityTuiArgs(args = []) {
const out = stripAntigravityUnsupportedArgs(args);
if (!out.includes('--dangerously-skip-permissions') && !out.includes('--sandbox')) {
diff --git a/server/lib/antigravity.test.js b/server/lib/antigravity.test.js
index 38e476e850..a57b7e4cef 100644
--- a/server/lib/antigravity.test.js
+++ b/server/lib/antigravity.test.js
@@ -7,6 +7,7 @@ import {
ensureAntigravityPrintArgs,
ensureAntigravityTuiArgs,
stripAntigravityUnsupportedArgs,
+ prepareAntigravityPrompt,
} from './antigravity.js';
describe('antigravity command/provider predicates', () => {
@@ -54,28 +55,66 @@ describe('stripAntigravityUnsupportedArgs', () => {
});
describe('ensureAntigravityPrintArgs', () => {
- it('injects --print and --dangerously-skip-permissions for empty args', () => {
- expect(ensureAntigravityPrintArgs([])).toEqual(['--print', '--dangerously-skip-permissions']);
+ // agy takes the prompt as the VALUE of --print (it does NOT read stdin), so
+ // --print must be the FINAL token and --dangerously-skip-permissions must come
+ // BEFORE it — otherwise agy consumes the flag as the prompt text. That was the
+ // shipped bug: the model received "--dangerously-skip-permissions" as its task.
+ it('puts --print LAST with --dangerously-skip-permissions before it', () => {
+ expect(ensureAntigravityPrintArgs([])).toEqual(['--dangerously-skip-permissions', '--print']);
});
- it('strips legacy Gemini flags then injects print/skip-permissions', () => {
+ it('never leaves a flag AFTER --print (regression: flag-swallowing)', () => {
+ const args = ensureAntigravityPrintArgs([]);
+ expect(args[args.length - 1]).toBe('--print');
+ expect(args).not.toContain('--print --dangerously-skip-permissions');
+ });
+
+ it('strips legacy Gemini flags then emits skip-permissions + trailing --print', () => {
expect(ensureAntigravityPrintArgs(['--yolo', '-m', 'gemini-2.5-pro', '--output-format', 'text']))
- .toEqual(['--print', '--dangerously-skip-permissions']);
+ .toEqual(['--dangerously-skip-permissions', '--print']);
});
- it('does not duplicate --print when already present (incl. -p / --prompt)', () => {
- expect(ensureAntigravityPrintArgs(['--print'])).toEqual(['--print', '--dangerously-skip-permissions']);
- expect(ensureAntigravityPrintArgs(['-p'])).toEqual(['-p', '--dangerously-skip-permissions']);
- expect(ensureAntigravityPrintArgs(['--prompt'])).toEqual(['--prompt', '--dangerously-skip-permissions']);
+ it('normalizes any pre-baked print flag (--print / -p / --prompt) to a single trailing --print', () => {
+ expect(ensureAntigravityPrintArgs(['--print'])).toEqual(['--dangerously-skip-permissions', '--print']);
+ expect(ensureAntigravityPrintArgs(['-p'])).toEqual(['--dangerously-skip-permissions', '--print']);
+ expect(ensureAntigravityPrintArgs(['--prompt'])).toEqual(['--dangerously-skip-permissions', '--print']);
});
it('does not add --dangerously-skip-permissions when --sandbox is present', () => {
- expect(ensureAntigravityPrintArgs(['--sandbox'])).toEqual(['--print', '--sandbox']);
+ expect(ensureAntigravityPrintArgs(['--sandbox'])).toEqual(['--sandbox', '--print']);
});
it('does not duplicate --dangerously-skip-permissions', () => {
expect(ensureAntigravityPrintArgs(['--dangerously-skip-permissions']))
- .toEqual(['--print', '--dangerously-skip-permissions']);
+ .toEqual(['--dangerously-skip-permissions', '--print']);
+ });
+});
+
+describe('prepareAntigravityPrompt', () => {
+ it('splices the prompt in as the VALUE of the trailing --print (no stdin)', () => {
+ const built = ensureAntigravityPrintArgs([]);
+ const { args, useStdin } = prepareAntigravityPrompt(built, 'do the creative work');
+ expect(args).toEqual(['--dangerously-skip-permissions', '--print', 'do the creative work']);
+ expect(useStdin).toBe(false);
+ });
+
+ it('keeps --dangerously-skip-permissions as a real flag, not the prompt', () => {
+ const built = ensureAntigravityPrintArgs([]);
+ const { args } = prepareAntigravityPrompt(built, 'PROMPT');
+ // the flag stays before --print; only PROMPT follows --print
+ expect(args.indexOf('--dangerously-skip-permissions')).toBeLessThan(args.indexOf('--print'));
+ expect(args[args.indexOf('--print') + 1]).toBe('PROMPT');
+ });
+
+ it('appends --print + prompt when no print flag is present', () => {
+ const { args, useStdin } = prepareAntigravityPrompt(['--sandbox'], 'hi');
+ expect(args).toEqual(['--sandbox', '--print', 'hi']);
+ expect(useStdin).toBe(false);
+ });
+
+ it('returns a callable no-op cleanup', () => {
+ const { cleanup } = prepareAntigravityPrompt(['--print'], 'x');
+ expect(() => cleanup()).not.toThrow();
});
});
diff --git a/server/lib/cliProviderArgs.js b/server/lib/cliProviderArgs.js
index a8ae34affb..2429377b63 100644
--- a/server/lib/cliProviderArgs.js
+++ b/server/lib/cliProviderArgs.js
@@ -18,8 +18,8 @@
*/
import { resolveCliModel, hasModelFlag, resolveBedrockCliModel, prefixOpencodeModel, isOpencodeCommand, buildCodexStartupArgs } from './providerModels.js';
-import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from './antigravity.js';
-import { isGrokCommand, ensureGrokHeadlessArgs } from './grok.js';
+import { ensureAntigravityPrintArgs, isAntigravityCliProvider, isAntigravityCommand, prepareAntigravityPrompt } from './antigravity.js';
+import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from './grok.js';
/**
* Build CLI args based on provider type. Each CLI provider has different
@@ -125,6 +125,31 @@ export function buildCliArgs(provider) {
return args;
}
+/**
+ * Spawn-time prompt delivery dispatcher. Every CLI spawn site runs the built
+ * argv + prompt through this right before spawning, then honors the returned
+ * `useStdin` flag (write the prompt to stdin only when true) and calls
+ * `cleanup()` after the run. Returns `{ args, useStdin, cleanup }`.
+ *
+ * - Antigravity (`agy`): the prompt is spliced in as the VALUE of --print
+ * (agy does NOT read stdin) → `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`.
+ *
+ * @param {string} command - provider.command (e.g. 'agy', 'claude', 'grok')
+ * @param {string[]} args - argv as built by buildCliArgs
+ * @param {string} prompt - the full prompt text
+ * @returns {{ args: string[], useStdin: boolean, cleanup: () => void }}
+ */
+export function prepareCliPrompt(command, args, prompt) {
+ if (isAntigravityCommand(command)) {
+ return prepareAntigravityPrompt(args, prompt);
+ }
+ return prepareGrokPromptFile(args, prompt);
+}
+
// Strip dangling/empty `--model` / `-m` tokens (no value follows, or the
// joined form has an empty value). Those would survive into the spawned
// argv unchanged and cause the CLI to reject the invocation — see the
diff --git a/server/lib/cliProviderRun.js b/server/lib/cliProviderRun.js
index 162e63e860..05e4d4218b 100644
--- a/server/lib/cliProviderRun.js
+++ b/server/lib/cliProviderRun.js
@@ -17,8 +17,7 @@
*/
import { spawn } from 'child_process';
-import { buildCliArgs } from './cliProviderArgs.js';
-import { prepareGrokPromptFile } from './grok.js';
+import { buildCliArgs, prepareCliPrompt } from './cliProviderArgs.js';
import { buildOpencodeEnvVars } from './opencodeConfig.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from './bufferedSpawn.js';
@@ -92,9 +91,10 @@ export function runCliProviderPrompt(args = {}) {
// right --model/-m flag for this provider's CLI convention.
const effectiveProvider = { ...provider, defaultModel: model ?? provider.defaultModel };
const builtArgs = [...buildCliArgs(effectiveProvider), ...(Array.isArray(extraArgs) ? extraArgs : [])];
- // Grok's `--prompt-file /dev/stdin` sentinel is fed via stdin on POSIX; on
- // Windows it's rewritten to a temp file (useStdin=false). No-op otherwise.
- const { args: spawnArgs, useStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(builtArgs, prompt);
+ // Deliver the prompt per provider convention: antigravity gets it as the
+ // --print VALUE (no stdin); grok's `--prompt-file /dev/stdin` is fed via stdin
+ // on POSIX / a temp file on Windows (useStdin=false); everyone else via stdin.
+ const { args: spawnArgs, useStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(provider.command, builtArgs, prompt);
return new Promise((resolve) => {
let stdout = '';
diff --git a/server/services/agentCliSpawning.js b/server/services/agentCliSpawning.js
index 8e270cfd4e..04ab210fb9 100644
--- a/server/services/agentCliSpawning.js
+++ b/server/services/agentCliSpawning.js
@@ -26,7 +26,8 @@ import { createCodexStderrFormatter } from '../lib/codexCliOutput.js';
import { PROVIDER_TYPES } from '../lib/aiToolkit/constants.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
-import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../lib/grok.js';
+import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
+import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';
import { resolveCliModel, buildEffortArgs, buildCodexStartupArgs, resolveBedrockCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand, applyLeanClaudeArgs, providerSuppliesGithubToken } from '../lib/providerModels.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { resolveForgeTokenEnv } from './git.js';
@@ -320,7 +321,7 @@ export function buildCliSpawnConfig(provider, model, settingsEnv = {}, { systemP
// Grok Build CLI (`grok`): headless one-shot agent. Reads the combined
// contract+task prompt from `--prompt-file /dev/stdin` (rewritten to a temp
- // file on Windows at the spawn site — prepareGrokPromptFile), bypasses approval
+ // file on Windows at the spawn site — via prepareCliPrompt), bypasses approval
// prompts, and emits plain text (the live-output handler falls through to its
// default text path, like OpenCode). grok is a non-Claude command, so
// agentLifecycle keeps the operating contract in the stdin prompt (no
@@ -478,9 +479,10 @@ export async function spawnDirectly({
// bare name → spawn ENOENT (errno -4058) → startup-failure. Mirrors the
// working "Run Prompt" path (server/services/runner.js); resolved against
// childEnv so a provider PATH override is honored. See issue #2243.
- // Grok's `--prompt-file /dev/stdin` is fed via stdin on POSIX; on Windows it's
- // rewritten to a temp file (useStdin=false). No-op for every other provider.
- const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(cliConfig.args, prompt);
+ // Deliver the prompt per provider convention: antigravity as the --print
+ // VALUE (no stdin); grok's `--prompt-file /dev/stdin` via stdin (POSIX) / temp
+ // file (Windows); every other provider via stdin (writePromptToStdin=true).
+ const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(cliConfig.command, cliConfig.args, prompt);
const { command: spawnCommand, args: spawnArgs } = prepareCliSpawn(cliConfig.command, deliveredArgs, childEnv);
const claudeProcess = spawn(spawnCommand, spawnArgs, {
diff --git a/server/services/agentCliSpawning.test.js b/server/services/agentCliSpawning.test.js
index 03122bf0b1..890aa7cd15 100644
--- a/server/services/agentCliSpawning.test.js
+++ b/server/services/agentCliSpawning.test.js
@@ -209,7 +209,7 @@ describe('buildCliSpawnConfig', () => {
const config = buildCliSpawnConfig({ id: 'antigravity-cli', command: 'agy', args: [] }, 'antigravity-configured-default');
expect(config.command).toBe('agy');
- expect(config.args).toEqual(['--print', '--dangerously-skip-permissions']);
+ expect(config.args).toEqual(['--dangerously-skip-permissions', '--print']);
});
it('runs `opencode run -m ollama/<model>` for a headless OpenCode Ollama agent', () => {
diff --git a/server/services/askService.js b/server/services/askService.js
index 08237485f8..a2ef2b3f4d 100644
--- a/server/services/askService.js
+++ b/server/services/askService.js
@@ -33,7 +33,8 @@ import { tokenize as bm25Tokenize, STOP_WORDS } from '../lib/bm25.js';
import { VALID_MODES as STORAGE_VALID_MODES } from './askConversations.js';
import { resolveCliModel, prefixOpencodeModel, hasModelFlag, isOpencodeCommand } from '../lib/providerModels.js';
import { ensureAntigravityPrintArgs, isAntigravityCliProvider } from '../lib/antigravity.js';
-import { isGrokCommand, ensureGrokHeadlessArgs, prepareGrokPromptFile } from '../lib/grok.js';
+import { isGrokCommand, ensureGrokHeadlessArgs } from '../lib/grok.js';
+import { prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { prepareCliSpawn } from '../lib/bufferedSpawn.js';
import { ensureProviderReady as ensureOllamaProviderReady } from './ollamaManager.js';
@@ -583,9 +584,10 @@ async function* streamCompletion(provider, model, prompt, signal) {
} else if (cliModel) {
args.push('--model', cliModel);
}
- // Grok's /dev/stdin sentinel is fed via stdin on POSIX; on Windows it's
- // rewritten to a temp file (writePromptToStdin=false). No-op otherwise.
- const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(args, prompt);
+ // 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);
const childEnv = (() => { const e = { ...process.env, ...provider.envVars }; delete e.CLAUDECODE; return e; })();
// Resolve a bare npm-installed CLI (a .cmd/.bat shim on Windows) to its real
// path and wrap it as `cmd.exe /c <path>` so spawn() under shell:false can
diff --git a/server/services/runner.js b/server/services/runner.js
index 6a68ab00ca..f58da650e2 100644
--- a/server/services/runner.js
+++ b/server/services/runner.js
@@ -8,8 +8,7 @@ import { join } from 'path';
import { atomicWrite, ensureDir, tryReadFile } from '../lib/fileUtils.js';
import { hasModelFlag, extractBakedModel } from '../lib/providerModels.js';
import { buildOpencodeEnvVars } from '../lib/opencodeConfig.js';
-import { buildCliArgs } from '../lib/cliProviderArgs.js';
-import { prepareGrokPromptFile } from '../lib/grok.js';
+import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { agentGuardEnv } from '../lib/agentGuard/index.js';
import { createImmediateFallbackSignalDetector } from '../lib/aiToolkit/errorDetection.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';
@@ -200,14 +199,17 @@ export async function executeCliRun({ runId, provider, prompt, workspacePath, on
killProcessTree(childProcess);
};
- // Build provider-specific args for stdin-based prompt delivery
+ // Build provider-specific args for prompt delivery
const builtArgs = buildCliArgs(provider);
- // Grok reads its prompt from `--prompt-file`; on POSIX that's /dev/stdin (fed
- // by the stdin write below), on Windows a real temp file (no /dev/stdin). This
- // rewrites the argv + tells us whether to still write stdin. No-op for every
- // other provider. cleanupPromptFile removes any temp file after the run.
- const { args, useStdin, cleanup: cleanupPromptFile } = prepareGrokPromptFile(builtArgs, prompt);
- console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via ${useStdin ? 'stdin' : 'prompt-file'})`);
+ // 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.
+ // - Grok: `--prompt-file /dev/stdin` on POSIX (fed by the stdin write below),
+ // rewritten to a temp file on Windows → useStdin=false.
+ // - Every other provider: unchanged, prompt over stdin → useStdin=true.
+ // cleanupPromptFile removes any temp file after the run (no-op otherwise).
+ const { args, useStdin, cleanup: cleanupPromptFile } = prepareCliPrompt(provider.command, builtArgs, prompt);
+ console.log(`🚀 Executing CLI: ${provider.command} (${prompt.length} chars via ${useStdin ? 'stdin' : 'argv'})`);
// Prepend the pm2 shim (agentGuardEnv) onto the final PATH so an unrestricted
// agent can't `pm2 kill` the shared daemon. See server/lib/agentGuard.
diff --git a/server/services/runner.test.js b/server/services/runner.test.js
index edc1039b3b..fb7f30bd51 100644
--- a/server/services/runner.test.js
+++ b/server/services/runner.test.js
@@ -495,13 +495,13 @@ describe('buildCliArgs — antigravity-cli headless mode', () => {
it('uses agy print mode and does not pass model flags', () => {
const provider = { id: 'antigravity-cli', command: 'agy', args: [], defaultModel: 'antigravity-configured-default' };
const args = buildCliArgs(provider);
- expect(args).toEqual(['--print', '--dangerously-skip-permissions']);
+ expect(args).toEqual(['--dangerously-skip-permissions', '--print']);
});
it('strips legacy Gemini flags during invocation', () => {
const provider = { id: 'antigravity-cli', command: 'agy', args: ['--yolo', '-m', 'gemini-2.5-pro', '--output-format', 'text'], defaultModel: 'antigravity-configured-default' };
const args = buildCliArgs(provider);
- expect(args).toEqual(['--print', '--dangerously-skip-permissions']);
+ expect(args).toEqual(['--dangerously-skip-permissions', '--print']);
});
});
diff --git a/server/services/visionCli.js b/server/services/visionCli.js
index 8b6dfcc1ff..08a6886a8d 100644
--- a/server/services/visionCli.js
+++ b/server/services/visionCli.js
@@ -27,8 +27,7 @@ import { spawn } from 'child_process';
import { writeFile, rm, mkdtemp } from 'fs/promises';
import { tmpdir } from 'os';
import { join } from 'path';
-import { buildCliArgs } from '../lib/cliProviderArgs.js';
-import { prepareGrokPromptFile } from '../lib/grok.js';
+import { buildCliArgs, prepareCliPrompt } from '../lib/cliProviderArgs.js';
import { resolveCliModel, isCodexProvider, buildCodexStartupArgs } from '../lib/providerModels.js';
import { extractCodexAssistant, extractCodexAssistantTail } from '../lib/codexAssistantExtract.js';
import { killProcessTree, resolveWindowsExecutable, prepareWindowsSafeSpawn } from '../lib/bufferedSpawn.js';
@@ -122,10 +121,10 @@ export async function describeImageViaCli({
try {
await writeFile(join(dir, IMAGE_BASENAME), bytes);
const { command, args, stdin, cwd } = buildCliVisionInvocation(provider, visionModel, dir, prompt);
- // Grok reads its prompt from --prompt-file /dev/stdin (fed via stdin on
- // POSIX); on Windows it's rewritten to a temp file (writePromptToStdin=false).
- // No-op for every other provider.
- const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup } = prepareGrokPromptFile(args, stdin);
+ // Deliver the prompt per provider convention: antigravity as the --print
+ // VALUE (agy doesn't read stdin); grok's --prompt-file /dev/stdin via stdin
+ // (POSIX) / temp file (Windows); every other provider via stdin.
+ const { args: deliveredArgs, useStdin: writePromptToStdin, cleanup } = prepareCliPrompt(command, args, stdin);
cleanupPromptFile = cleanup;
const childEnv = { ...process.env, ...provider?.envVars };