Skip to content

fix(runtime): refuse an agent-prompt write into a live credential prompt - #19978

Draft
nwparker wants to merge 8 commits into
mainfrom
nwparker/credential-prompt-write-guard
Draft

nwparker wants to merge 8 commits into
mainfrom
nwparker/credential-prompt-write-guard

Conversation

@nwparker

@nwparker nwparker commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor
Files Added Deleted Net
Test 6 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​992 $\color{#cf222e}{\Huge{\mathbf{−}}}$​10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​982
Prod 10 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​456 $\color{#cf222e}{\Huge{\mathbf{−}}}$​79 $\color{#1a7f37}{\Huge{\mathbf{+}}}$​377

Scope — one write path, not all of them

Read this before the rest. The fence lives at exactly one place, orca-runtime-write-terminal-agent-prompt.ts, and terminal-send-method.ts:192 only routes there when all of agentPrompt === true && hasText && enter === true && interrupt !== true && client.type === 'desktop' hold (and the pane runs a settled-prompt agent). Everything else falls through to runtime.sendTerminal, which is unchanged by this PR.

write path can carry user text fenced by this PR
sendTerminalAgentPrompt → writeTerminalAgentPrompt (CLI --text --enter, worker start, dispatch --inject, coordinator auto-dispatch, federated preamble) yes yes
runtime.sendTerminal (runtime-terminal-writer.ts) — ownership lease only yes no
mobile RPC terminal.send — fails the client.type === 'desktop' check outright yes no
orca terminal send --text X without --enter yes no (see below)
window.api.pty.write from the renderer (agent-paste-draft.ts) yes no — closed by #20004
plugin terminal.sendText yes no
mailbox-pointer-pty-write.ts:26 no (fixed pointer text) no

Mobile is entirely unfenced. A phone sending terminal.send with text and enter takes the sendTerminal path and meets no credential check. Do not read this PR as "Orca now refuses credential-prompt writes."

None of these six were fenced before this PR either — it adds a fence to one path rather than removing one from the others. That makes the uncovered surface incompleteness, not regression. It is called out here so nobody infers otherwise from the title.

The --enter asymmetry is a decision, not an omission

src/cli/handlers/terminal-send.ts:18 sets agentPrompt only when !!text && enter && !interrupt, so the same text with and without --enter gets different treatment, and a two-phase send (--text X, then a bare Enter) bypasses the fence entirely.

That is deliberate and should stay: --text without --enter is how you legitimately answer a credential prompt. Fencing it would make it impossible to type a password into the very dialog this detector exists to recognise. Please do not "fix" this without replacing the escape hatch.

What

When Orca decides an agent is ready, it types the user's task prompt into that pane. If the readiness verdict is wrong and a credential surface is on screen instead, the prompt is submitted to an auth provider as a credential attempt — and if that surface echoes, it also lands verbatim in the session transcript.

This is vocabulary added to a fence that already exists, not a new enforcement layer. That framing matters for review. writeTerminalAgentPrompt already throws agent_prompt_blocked whenever getAgentPromptActivity reads permission, and that status already comes from detectTerminalWaitBlockedReason over the terminal tail. The fence knew about trust dialogs, update banners, hooks review and approval menus — and nothing about passwords, API keys, passphrases, OTPs, 2FA codes, sign-in menus or OAuth device codes. So the change is one new agent-neutral reason, agent-credential-prompt, plus a shape-based detector that produces it. No new call sites, no new gate.

Two properties are deliberate:

  • It defers, it does not drop. The caller gets agent_prompt_blocked with a named reason, and terminal.wait --tui-idle reports blockedReason: 'agent-credential-prompt' instead of resolving. The idle poll re-reads the tail, so the refusal clears by itself once the dialog is answered. There is a test for exactly that: refuse, sign in, then the same pane admits the send.
  • It is unconditional. Unlike every other blocked reason, a live idle OSC title and a ready caret elsewhere on the screen cannot clear it. That asymmetry is the whole point: a wrong readiness verdict is the thing being guarded against, so it must not be the thing that overrides the guard. isKnownReadyPromptPreview also stops calling such a screen ready.

Because the reason is unconditional, a false positive is not free. It does not merely defer a prompt: it also publishes an idle agent as status: 'permission' into the one agent-status store, so the sidebar, worktree ps, mobile and the dashboard all show it as waiting on the user until new output arrives. That cost is what drives the position discipline described below.

ELI5

When Orca starts an agent for you, it watches the terminal, waits until the agent looks ready, and then types your task into it. If that judgement is wrong and what's really on screen is a sign-in box asking for a password, an API key or a 2FA code, Orca types your task into that box and presses enter — handing it to an auth provider as a credential attempt, and, if the box echoes, writing it into the saved session transcript too.

Orca already had a "don't type yet" check; it just didn't know what credential prompts look like. It knew about trust dialogs, update banners and approval menus, and nothing about passwords. This PR teaches it that vocabulary. When it sees a credential prompt it refuses to send and says why, and because the check re-reads the screen, the refusal clears by itself once you've signed in.

The rule that keeps it from over-firing is shape, not wording: a credential prompt is a request for input. It sits at the bottom of the screen and ends in a colon or an input caret. An agent talking about authentication is prose, and it leaves its own composer caret on the last row. Enter the verification code we sent to your phone: is blocked; • I implemented two-factor authentication for the login flow. above a › Ask Codex to do anything caret is not.

This covers the orchestration and CLI route into a terminal. #20004 does the same for the other route.

Why now

The Antigravity readiness detector motivating this has been reverted to merge-base on #19749, but the premise survives the revert. #19749's own loop-3 finding documented a residual it explicitly chose not to fix:

a silent startup modal — one whose wording falls entirely outside the blocked-signal vocabulary — drawn over a complete ready chrome can still read as ready. Ordering cannot help, because there is no signal to order against. Documented rather than papered over.

That residual is now a permanent documented property of shipping code. Adding credential wording to the vocabulary is the only thing that gives ordering something to order against. The exposure is also not confined to worker-start: dispatch-methods.ts:159 and coordinator-task-dispatch.ts:139 have no pre-write tui-idle wait at all and rely entirely on this in-write fence.

The 18 false positives this PR's earlier detector produced

An earlier revision of this branch paired an auth verb with an auth flow phrase anywhere in the live window, with no terminator requirement and no position requirement. That is the shape of an agent reporting auth work, not the shape of a credential prompt. A readiness review found 18 real screens that refused a prompt and pinned the agent to permission. All of them carry the agent's own live composer caret, which — because the reason is unconditional — does not clear the block.

Verbatim, as they appear on screen:

• I implemented two-factor authentication for the login flow.
  The authenticator app now generates a 6-digit code.
› Ask Codex to do anything
· Added two-factor authentication. Tests for the authenticator app pass.
✳ Claude Code
>
  └ src/Login.tsx:31:  <button>Sign in with GitHub</button>
  └ src/Login.tsx:44:  // authorization code exchange
› Ask Codex to do anything
Error: authentication required
    at signInWithToken (auth.ts:22)
› Ask Codex to do anything

The remaining fourteen are the same failure mode across Codex, Claude Code, Gemini and OpenCode: completion summaries about SSO/MFA/OAuth work, rg hits on auth documentation and login components, a shell deploy failure, and an agent asking the user whether MFA should be required.

The earlier corpus missed an entire category. The "0 false positives on 31 legitimate screens" claim this body previously carried was true of those 31 screens and false in the field: not one of them paired an auth verb with an auth-flow phrase, which is precisely the combination that produced all 18. The category it lacked is the most common thing an agent does after working on a login flow — narrate what it just built. All 18 are now in the suite as must-allow cases.

The rule as it now stands

The pair rule is replaced by two rules, both of which demand prompt shape:

  1. Bottom-anchored request. The auth-flow marker must sit on the last non-blank row; that row must not be a finished sentence (a lone . / ! / ? — ... and … are progress wording, not sentences, so Press Enter to open github.com in your browser... still qualifies); and the window must also carry an auth verb or a credential noun.
  2. Interactive auth question. A row shaped ? … carrying an auth verb or flow phrase. Prose never starts with a bare ?, so this is unambiguously a dialog header even when its options wrap below it.

Rule 2 exists for a specific true positive. A plain "flow marker must be the last row" rule loses the antigravity auth-method menu, where the flow marker is on the second-to-last row:

? How would you like to authenticate?
❯ Sign in with Google
  Use an API key

Rule 2 recovers it without loosening rule 1. It is the only true positive in the corpus that the last-row rule alone would have dropped.

AUTH_FLOW_RE is split into action wording and topic wording. Action wording (sign in with, authentication required, press enter to open, waiting for authentication, paste code here, enter the code, open this url) is what a dialog addressing the user says. Topic wording (2fa, two-factor, authenticator app, device code, verification code, N-digit code) is equally at home in narration, so it only carries the bottom row when that row is also terminated. The concrete reason: without the split, a bottom row reading sms verification code blocks.

The bare-label rule is also position-gated now. password: with no ask verb is how a printed k8s manifest and a form template read, so it only counts on the bottom row. That closes the reported kind: Secret / stringData: / password: / › Ask Codex to do anything false positive. Enter your API key: keeps its ask-verb path and is unaffected by position.

The lane divergence this PR shipped with, now fixed

The detector had a cheap prefilter, TERMINAL_CREDENTIAL_PROMPT_SENTINEL_RE, run per retained tail line so that only candidate-bearing tails parse in full. Its doc comment says it "must stay a superset" of the index. It was not a superset, and the consequence was that the two lanes disagreed about the dialog this whole guard was written for.

terminal-wait-detection.test.ts:427 already held the fixture — the live Antigravity sign-in menu from F19749-1:

Antigravity CLI 1.0.3
[email protected] (Antigravity Business)
Sign in to continue
~/orca/workspaces/orca/agy-dispatch-issue
1. Open browser
2. Paste an API key
>

2. Paste an API key is a prompt to findCredentialPromptIndex, because PURE_TERMINATOR_RE treats end-of-row as a terminator. But the sentinel only accepted a credential noun followed by punctuation, and this menu has no punctuation anywhere. So the renderer lane (which has no prefilter) refused the screen while the main lane returned clean.

Why the corpus never caught it: the test asserting the superset property ran only over LIVE_CREDENTIAL_SURFACES — the screens we already believed block. A prefilter bug on a screen we had wrongly classified as clean is invisible to that test by construction. The invariant is about the index's own verdict, so it now runs over both corpora:

for (const [name, lines] of [...LIVE_CREDENTIAL_SURFACES, ...LEGITIMATE_AGENT_SCREENS]) {
  if (findCredentialPromptIndex(screen(lines).toLowerCase()) === null) continue
  expect(lines.some((line) => TERMINAL_CREDENTIAL_PROMPT_SENTINEL_RE.test(line)), name).toBe(true)
}

The sentinel now also accepts a row-final noun and tolerates a trailing box rule (a framed dialog ends … API key here: │, which it had been counting as "not a terminator" — every full-box TUI was invisible to it). The sign-in menu's sibling dialogs — the model picker and the privacy notice, same chrome, same bare > caret — are pinned as must-allow so this cannot be widened into them.

A near-miss worth reading: the sentinel is quadratic if you spell it the obvious way

The common api-key ask names the env var it fills (Enter your OPENAI_API_KEY:), which api[ -]?key misses. The natural fix is a vendor slot in the noun alternation:

(?:[a-z0-9]+_)?api[ _-]?keys?

That is 30 ms on a single 5.5k-character line, in a regex that runs per retained tail line at streaming rate. [a-z0-9]+ scans forward at every start offset and backtracks looking for _, which is O(n²) per line. It hung the tail-index suite outright.

The vendor slot belongs in the prefix rules instead — CREDENTIAL_ASK_PREFIX_RE tolerating a trailing _, and CREDENTIAL_LABEL_PREFIX_RE accepting a bounded, anchored [a-z][a-z0-9]{0,20}_ segment. Same coverage, 0.03 ms, ~1000x. A budget test now pins it, and reinstating the quadratic form fails that test.

Named limitation: the detector is English-only

10 of 15 non-English credential prompts are not detected, including localized git credential prompts ('https://github.com' 的用户名:) and zh/ja/ko/ru/pt/fr api-key, password and verification-code asks. The originating user report on #19749 was in Traditional Chinese, so this population is real, not hypothetical.

This is named scope, not oversight. Adding CJK/European credential nouns imports a new false-positive population in the same move: 密碼: and パスワード: appear constantly in agent narration about password work, and the position discipline that separates a prompt from a mention in English has no equivalent tuned for those languages. Doing it properly is a feature, and doing it hastily would undo the false-positive work this PR just did. A follow-up should build a non-English corpus first.

Two things that are fixed here, because they are locale-independent:

  • sudo on any locale. sudo translates its prompt but never its [sudo] tag ([sudo] Passwort für neil:, [sudo] neil 的密碼:), and the only thing it ever asks for at that tag is a password. The rule now keys on the tag.
  • Env-var api-key asks (Enter your OPENAI_API_KEY:), per above.

Two false negatives, now fixed

The same review found two flows this PR named as targets and did not actually catch. Both are real credential surfaces and both are now blocked:

! First copy your one-time code: 1A2B-3C4D
Press Enter to open github.com in your browser...
Browser didn't open? Use the url below to sign in:
https://claude.ai/oauth/authorize?code=true
Paste code here if prompted >

The first is gh auth login's device code; the second is Claude Code's own /login paste-code screen. Bottom-anchoring plus widening paste (the|your)? code (here|below) closes both.

Two screens still block, deliberately

SYNOPSIS
     ssh [-l login_name] ...
     Enter passphrase for key:
npm notice Log in on https://registry.npmjs.org/
Username:
Password:

The npm one is a real credential prompt — blocking it is correct, not a false positive. The ssh man page is byte-ambiguous with the genuine Enter passphrase for key: prompt; no amount of shape discipline separates them, and the asymmetric bias says refuse. Both clear on the next repaint. Stating them rather than quietly counting them as passes.

False positives — measured, not estimated

Corpus Result
91 must-allow screens (31 original + the 18 false positives above + 21 found by adversarial probing) 91/91 pass
35 must-refuse screens (23 original + 2 earlier false negatives + 10 found by adversarial probing) 35/35 refuse
TERMINAL_TITLE_CLASSIFICATION_CORPUS (67 titles) 0 fire
991,869 string literals extracted from all 21,276 source files under src/, each read as a screen 171 hits before → 157 after; 0 newly blocked, 10 freed

The 10 literals freed are all genuine Orca UI strings that had no business blocking anything — Sign in required., Sign in with the account you want to add (e.g. use a private/incognito browser window for a second account)., Claude is not signed in for the selected account. Sign in with the Claude CLI for this CLAUDE_CONFIG_DIR, then retry., the Gemini CLI OAuth extraction description, and similar. Zero literals started blocking that did not block before.

The must-allow corpus is the one that matters: agents narrating credential work, agents summarising completed auth work (the category the earlier corpus lacked), agents asking the user credential-adjacent questions, the user's own task prompt echoed above the composer, rg output quoting prompt wording, diffs that add credential prompt strings, and printed config whose bare password: label is not the bottom row.

Detection stays bounded to the last 4 non-blank lines, because an answered prompt stays in scrollback and agents print credential wording constantly while working on auth code.

Bias is toward refusing on purpose: a false negative types secrets-adjacent text into a credential field, a false positive delays a prompt until a dialog is answered — but, per the note in What, it also mislabels an idle agent, so "refuse when unsure" is not a licence to match on wording alone.

Mutation evidence

Not verified by reading.

  • Reverting the detector rule while keeping the corpus turns 23 tests red (and more now that the corpus has grown) in terminal-credential-prompt-detection.test.ts: all 18 new must-allow screens, both new must-refuse screens at both their assertion sites, and the sentinel-superset test. Every new case dies under the mutation that should kill it.
  • Disabling the credential candidate in findBlockedSignalInLiveWindow turns 29 tests red, and two of the write-site regressions then time out at 30s because the prompt actually reaches the PTY — which is the harm, reproduced.

The regression fixture is the #19749 screen itself: full Antigravity ready chrome that the reverted merge-base detector accepts (header, a gemini model row, a lone > caret), an idle OSC title, and a device-code sign-in dialog drawn over it. The test asserts the send is refused and that zero bytes reach the PTY.

Wire compatibility

Additive union member, no capability negotiation needed. docs/reference/remote-wire-compatibility.md:179-180 names this enum as an explicit Rule 1 exception: "New members added to RuntimeTerminalWaitBlockedReason are also Rule 1: no consumer switches exhaustively on it, and both the CLI and worker-start interpolate it as an opaque string."

This PR adds exactly one member: agent-credential-prompt. To be unambiguous, because a review of the combined stack read them as belonging here: the five codex-* → agent-* renames (codex-update-prompt, codex-cwd-prompt, codex-hooks-review-prompt, codex-trust-workspace, codex-interactive-prompt) are #19749's, this PR's base branch, and appear in a diff against main only because of the stacking. They are not part of this change.

agent-credential-prompt is deliberately NOT in the legacy alias map. It was born neutral — no host ever published a codex-credential-prompt, so there is no older spelling to alias. An alias entry would invent one and render agent-credential-prompt (…) at all four sites that use describeTerminalWaitBlockedReason. Two tests in terminal-wait-blocked-reason-legacy-alias.test.ts pin that it renders unannotated and resolves to no alias, so this does not get "fixed" later.

False positives found after review, and how they were found

Counts and suite sizes in this body are at time of writing; they have gone stale twice already
as the corpus grew.

Five false-positive classes reached this PR past a two-sided corpus that read 100% clean. Every one
was a term the corpus already contained, sitting in a position nobody had written down — which
is the failure mode of a curated corpus, not an accident.

The one that matters most: formatted source code

Replaying 16,206 credential-vocabulary lines mined from this repo's own tracked files, each placed
one row above a real agent composer caret, produced 100 refusals across 25 distinct lines on
Codex, Claude Code and OpenCode. The corpus had rg hits and diffs, which carry their own chrome,
but no plain formatted source.

24 of the 25 are one shape:

      ? 'Update desktop Orca and sign in to connect from anywhere'
› Ask Codex to do anything

AUTH_QUESTION_ROW_RE rests on the comment "Prose never starts with a bare ?". That is true of
prose and irrelevant: oxfmt puts a ternary's consequent on its own row exactly that way, and
5,666 tracked files in this repo contain such a line. sawAuthQuestion then returned
unconditionally, with no position requirement, so a composer caret directly below could not clear
it. Any agent printing Orca's own source tripped it. Nine of the 25 matched only because
\b(?:log[ -]?in)\b reads user.login as the auth verb.

The 25th is a different rule and a real wrapped comment in this repo:

    // Why: a merely missing or expired bundle must not enter the credential

CREDENTIAL_ASK_PREFIX_RE was unanchored, so an ask verb anywhere in a row made a row-final
credential noun a prompt. Terminal wrapping makes ending on a noun routine.

Why isLastRow is NOT the gate on the ask-prefix path

The obvious simplification is to require the ask-prefix path to be the last row, matching the
bare-label rule. Do not do this — it silently deletes the dialog this guard exists for. In the
Antigravity sign-in menu the credential row is not the last row:

1. Open browser
2. Paste an API key      <- the only row that makes this a credential surface
>                        <- the last row

2. Paste an API key is a prompt because end-of-row counts as a terminator. Gate it on isLastRow
and the #19749 dialog stops being detected. The rule used instead is position of a different kind:
the ask verb must lead its row, modulo decoration and a menu number. 2. Paste an API key
leads; sixty characters of prose before enter the does not.

Two more, found by the generative suite this PR adds

candidate.credential set the credential-noun flag, because only the auth-verb regex had been
taught that a dot means a property access. That flag corroborates an otherwise-inert bottom row, so
an identifier alone could refuse a screen that was only printing source. Excluded . and . only:
\w would break the env-var ask (OPENAI_API_KEY), which is a real prompt.

// Sign in with the provider console to continue read as a dialog leading its row, because the
decoration run accepted a comment marker. A dialog decorates with box rules, bullets, carets and
menu numbers, never with // or *.

The mechanism, not just the fixes

terminal-credential-vocabulary-shapes.test.ts expands the detector's own vocabulary sources
into plain phrases and crosses every term against the shapes a term takes when it is output rather
than a prompt, above each agent's composer caret. It grows by itself: add a noun to
CREDENTIAL_NOUN_SOURCE and it is checked in every shape on the next run.

It is deterministic (depends only on the detector, not on repo contents), bounded (~1,400
evaluations, 12ms), and it carries a positive control asserting every noun still refuses in a real
ask, so the negative cases cannot pass by the detector having quietly stopped working. All seven
mutations — the five fixes above, the earlier flow-rule position discipline, and a fully disabled
detector — turn it red.

Validation against real recorded output

The detector now runs clean over all 11 captured PTY transcripts in the repo — the eight real
agy transcripts added by #19983 (including antigravity-ready-api-key-gemini-model, whose ready
chrome names an API key) and the three cursor-agent captures. Zero false positives on real recorded
agent output.

Agents with no evidence behind them

Coverage rests on recorded or reconstructed output for Codex, Claude Code, Gemini, OpenCode,
cursor-agent, Antigravity and Command Code. 25 agents have no transcript. Five are title-only —
pi, omp, hermes, copilot, devin — and twenty have nothing at all. Their chrome is
unverified against this detector in either direction.

Shapes this detector does not catch, measured

Independent verification compared this detector against the previous revision and found 12 shapes
that stopped being refused. All 12 behave exactly as origin/main does, which has no credential
detection at all
, so they are incompleteness against an intermediate commit on this branch rather
than a regression against the merge target. Naming them instead of quietly re-tuning:

  • One was worth fixing and is fixed: ? Authenticate with the CLI? [Y/n]. A bracketed confirm
    default is a mainstream convention (apt, readline, enquirer), and [/] have been dropped from
    the code-shape class. (y/N) with parentheses always worked.
  • The rest hinge on a dot inside a host name (github.com, [email protected]) reading as a
    property access. Real git credential prompts are unaffected — they route through
    GIT_CREDENTIAL_RE (Username for 'https://github.com':) and stay refused — so the residue is
    auth-adjacent prose that mentions a hostname, which was never a live prompt.

A complexity hazard that the budget test could not see

Worth reading before touching any rule here. The noun lookbehind was briefly written as
(?<!\.[a-z0-9_$]*), which is quadratic: the engine retries it from every position in an
identifier run, so doubling the run quadruples the cost — measured 79µs / 286µs / 4572µs at
512 / 1024 / 4096 characters.

The budget test did not catch it, for two compounding reasons:

  1. it drove TERMINAL_CREDENTIAL_PROMPT_SENTINEL_RE, which is built from the raw noun source
    and carries no lookbehind, so it is structurally blind to the rule that has one;
  2. driving findCredentialPromptIndex instead does not help either, because
    MAX_CREDENTIAL_LINE_LENGTH caps every row at 512 characters, and at that length a quadratic
    lookbehind is only ~1.7× a linear one. A test above the cap measures the cap; a test below it
    cannot discriminate.

The bound is {0,64} — it must exceed the longest realistic dot-to-noun distance (39 in this repo today) while staying bounded. The durable part is that the budget now drives the noun regex directly and
asserts the complexity class at 1024 vs 4096, so the 512 cap is a safety margin rather than the
only thing holding — and that cap is documented where it is defined as load-bearing for complexity,
not merely for throughput.

What this detector does in a plain shell pane, by design

Mined into a shell pane — no agent composer anywhere on screen — rather than above a composer,
20,350 rows produce 25 refusals from 18 distinct rows, a bottom-row rate of 0.12%, stable
across verification passes. Every one is either the deliberate bottom-row bare-label rule
(credentialIds: Set<string>, apiKey, credentialError:) or one of this detector's own corpus
strings quoted in source.

This is intended, not a defect, and a reader should know it: a shell pane whose bottom row is
credential-shaped source will occasionally be refused.
The bare-label rule exists because
Password: on the bottom row is exactly what docker login, sudo and git print, and nothing
on screen distinguishes that from a printed manifest. The refusal is transient — it clears as soon
as the shell repaints a new bottom row — and it surfaces synchronously with a named reason rather
than hanging.

One known constructible case is deliberately not fixed: a ? row carrying only brackets
(? [signIn, signOut], ? credentials[index]) can refuse in a shell pane with no composer below,
because [/] were removed from the code-shape class so that bracketed confirm defaults
(? Authenticate with the CLI? [Y/n]) keep working. All eight real instances in this repo also
carry a dot access and stay code-shaped, and a sweep of 20,350 shell-pane rows found zero
occurrences of the bare shape. Adding another shape rule to catch something that does not occur is
how the previous rounds of surface area got added.

Coverage is explicitly PARTIAL

See the inventory table at the top for the write-path breakdown. Beyond that, three detector-level gaps are measured and deliberately left open:

  • Wrapped prompts. At 80 columns, Enter the personal access token for https://github.com/…(scopes: r / epo, workflow, read:org): puts the noun on one row and the terminator on the next, and does not match. Same for a long ssh passphrase path. Fixing it means joining adjacent rows, which fabricates text that was never on screen and breaks the byte-identity equivalence proof fix(renderer): refuse an agent paste into a live credential prompt #20004 adds.
  • Chatter printed after the prompt. CREDENTIAL_TAIL_LINES = 4, so the fix(runtime): agent-neutral wait-blocked reasons #19749 screen plus a Press Ctrl+C to cancel footer is clean, as is Claude /login plus its footer, and docker login whose password ask is pushed up by its own multi-line warning. Widening the window strictly increases false positives.
  • Three remaining false positives, all pre-existing tuning debt rather than new: a bare password: label owning the bottom row (a printed k8s manifest or form template), and an inquirer-style ? Should the app use sign in with Google or its own login.

Not covered by this PR:

  • src/renderer/src/lib/agent-paste-draft.ts (sendBracketedPasteToAgent) — writes through window.api.pty.write and can never reach agent_prompt_blocked. Its gate is waitForAgentDraftInputReady (DECSET 2004 + render-quiet), which a TUI showing its own sign-in dialog satisfies. This backs quick launch, submit-after-ready, work-item launch, folder-workspace startup and fix-checks, so it is the more commonly hit lane. Closed by fix(renderer): refuse an agent paste into a live credential prompt #20004, which stacks directly on this branch.
  • src/main/runtime/orchestration/mailbox-pointer-pty-write.ts:26 — the mailbox pointer lane gates on an idle edge only, with no blocked-reason check. Verified at source and left open deliberately: the bytes are fixed orchestration pointer text, not a user task prompt, so neither the secret-typing nor the transcript-echo harm applies. Worth a follow-up, not a blocker.

Residual risk — read this before merging

  • Do not merge this PR alone. It guards only runtime-routed writes (CLI, orchestration, federation). The renderer paste lane backs quick launch, submit-after-ready, work-item launch and folder-workspace startup — i.e. most user-initiated prompt delivery — and is closed by fix(renderer): refuse an agent paste into a live credential prompt #20004. Shipping this one on its own would close the rarer hole while reading, from the changelog, as fixed. The stack merges together or not at all.
  • The mailbox pointer lane (above) and fix(renderer): refuse an agent paste into a live credential prompt #20004's fail-open when no pane is registered leave the guard incomplete by design. Both are reasoned, both are documented, neither should be implied closed in a release note.

Separate fix in this PR: a latent main-process hang

Flagging this on its own so it is not missed inside a guard PR. startOfLastNonBlankLines (src/main/runtime/terminal-wait-tail-window.ts) infinite-loops on any tail whose first character is a newline. String.lastIndexOf clamps a negative position argument up to 0, so a leading newline makes the walk answer lineStart = 1 with lineEnd = 0 forever. It sits on the main-process PTY data path, so it is a hard hang rather than a slow scan.

It is latent, not live: all three current producers filter blank lines (buildPreview drops empties, buildTerminalWaitText joins trimmed non-empty lines, visibleNonBlankTerminalLines filters the visible-screen probe). Found while building the false-positive corpus, which fed it raw fixture strings. One-line condition plus a regression test.

Pre-existing gap found, not fixed here

src/cli/handlers/orchestration/worker-observation-handlers.ts:43 interpolates raw wait.reason with no formatter — the one render site describeTerminalWaitBlockedReason does not reach. Harmless for this reason specifically (born neutral, renders identically either way), but it means an older host's codex-* token still reaches a non-Codex user on that surface.

Verification

command result
pnpm test src/main/runtime/terminal-credential-prompt-detection.test.ts all green — the must-refuse corpus now also pins the Antigravity sign-in menu, the vendor-qualified indented ask, localized sudo, the env-var api-key ask and a boxed dialog; the must-allow corpus pins the new false positives below plus the sign-in menu's sibling dialogs
pnpm test over the four credential suites + terminal-wait-detection + terminal-tail-sentinel-index 202 passed
mutation check, 11 mutations all 11 caught. One initially survived — the sentinel's box-rule tolerance was not pinned by any corpus screen — and the corpus case was tightened until it was
pnpm tc:node, pnpm tc:web, pnpm tc:cli (one at a time) clean
oxlint src clean

No max-lines disable was added anywhere in this change.

False positives found by adversarial probing, now pinned

The previous corpus read 49/49 must-allow clean. Probing it with screens it did not contain — records rather than requests, and non-English narration — found seven more, every one of which pinned an idle agent to permission:

$ git log --oneline -3
a1b2c3d fix(auth): drop the stale authorization header
d4e5f6a feat(auth): sign in with GitHub
• Updated the login page copy
⏳ Waiting for you to review the diff
• Fixed the deploy step
• Root cause: authentication required from the vercel CLI
$ pnpm deploy
錯誤:authentication required,請先執行 gh auth login

plus a changelog bullet (- feat(auth): sign in with Apple support), a checklist item, and German narration. A single commit subject on its own was enough: sign in with contains the auth verb, so it self-corroborated.

The common cause is position, not vocabulary. The rule required the flow phrase to own the bottom row and not be narration, but NARRATION_ROW_RE only knew ASCII sentence punctuation — so anything ending a row without a period, and all CJK prose, escaped it. Now: an action phrase must lead its row (modulo dialog decoration and the lead-ins a dialog actually uses, and enter the code: / Please sign in with…), waiting for you to carries an auth continuation instead of matching every agent waiting on a human, and narration includes CJK sentence punctuation.

Stacking

Based on fix/agent-neutral-wait-blocked-reason (#19749) rather than main, because it depends on that branch's RuntimeTerminalWaitBlockedReason union and its single describeTerminalWaitBlockedReason formatter. Rebasing produced two conflicts, both pure formatter-reflow against that branch's codex-* → agent-* rename; both resolved to the rename.

@greptile-apps

greptile-apps Bot commented Sep 11, 2026 •

Copy link
Copy Markdown

Too many files changed for review (293 files, 100 file limit).

Bypass the limit by tagging @greptile-apps to review.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Important

The credential detector's sawAuthVerb && sawAuthFlow fallback blocks common agent narration that has no dialog to answer, and the block does not self-clear — an idle agent's next prompt is refused indefinitely. Tighten the fallback before merging.

Reviewed changes

  • agent-credential-prompt blocked reason — additive member of RuntimeTerminalWaitBlockedReason, produced by a new shape-based detector (findCredentialPromptIndex) keyed on credential nouns plus prompt terminators, wired into the existing write-site fence (writeTerminalAgentPrompt → getAgentPromptActivity).
  • Unconditional semantics — isUnconditionalTerminalWaitBlockedReason prevents a ready caret or idle title from clearing the new reason (and, now, agent-approval-prompt) in isKnownReadyPromptPreview, findActionableTerminalWaitBlockedSignal, and both status-query sites.
  • Sentinel gating — TERMINAL_CREDENTIAL_PROMPT_SENTINEL_RE added to the cheap negative scan so only candidate-bearing tails parse in full.
  • Latent hang fix — startOfLastNonBlankLines no longer spins on a leading-newline tail.
  • Cursor-approval detector moved to terminal-cursor-approval-detection.ts (no behavior change).

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the false-positive tightening is well done and verified; one minor recall observation inline.

Reviewed changes

  • Prompt-shape fallback — replaced the loose sawAuthVerb && sawAuthFlow pair rule with a fallback that only refuses when an auth-action phrase owns the bottom row as an unfinished clause, or an inquirer ? question row drew the screen.
  • Action/topic flow split — AUTH_FLOW is now dialog-only AUTH_ACTION_FLOW plus narration-safe AUTH_TOPIC_FLOW, and the bare-label password: form is gated to the bottom row.
  • Corpus widening — 18 confirmed false positives and 2 formerly-missed device-code flows (gh auth login, Claude /login) added to the two-sided corpus.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

bottomRow.length <= MAX_CREDENTIAL_LINE_LENGTH &&
bottomRowAsks &&
!NARRATION_ROW_RE.test(bottomRow) &&
(sawAuthVerb || sawCredentialNoun)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The (sawAuthVerb || sawCredentialNoun) guard means the topic-flow bottom-row branch can never fire on its own: authenticator app and 6-digit code are neither an AUTH_VERB nor a CREDENTIAL_NOUN, so the canonical standalone Enter the 6-digit code from your authenticator app: is not blocked (verified against the shipped regexes). It is pre-existing rather than a regression, and is usually masked by a Two-factor authentication header within the 4-line window — but it is also why the oauth device-code flow corpus case only passes because its URL contains login.

Technical details
# Topic-flow vocabulary should count as a credential signal on its own

## Affected sites
- src/main/runtime/terminal-credential-prompt-detection.ts:179 — `(sawAuthVerb || sawCredentialNoun)` gates `authFlowOwnsBottom`, but the topic-flow vocabulary is neither an `AUTH_VERB` nor a `CREDENTIAL_NOUN`.

## Reproducers (validated against the shipped regexes)
- "Enter the 6-digit code from your authenticator app:" → not blocked
- "Enter the code:" → not blocked
- oauth device-code flow whose URL lacks `login` (e.g. `https://example.com/device`) → not blocked

## Required outcome
- Decide whether the topic-flow-plus-terminator bottom row (already gated by `!NARRATION_ROW_RE` and the `:›❯»>_` terminator) is specific enough to count on its own, or whether the co-occurrence guard should stay.

## Suggested approach (optional)
- Drop `(sawAuthVerb || sawCredentialNoun)` for the `AUTH_FLOW_RE.test(bottomRow) && CLAUSE_TERMINATED_RE.test(bottomRow)` branch, or fold the topic-flow vocabulary into a `sawCredentialSignal` that includes it.

A readiness verdict is what decides whether Orca types the user's task
prompt into a pane, and any readiness detector can be wrong. The
Antigravity one has been rewritten five times and has repeatedly read
ready with a sign-in dialog on screen, at which point the prompt is
typed into that dialog: submitted to the auth provider as a credential
attempt, and — because the daemon records raw PTY output with no
redaction (terminal-history-session-writer.ts) — written into the
session transcript and published over terminal.read / worktree.ps if the
surface echoes.

The write site already has the guard machinery: writeTerminalAgentPrompt
throws agent_prompt_blocked whenever getAgentPromptActivity reads
`permission`, and that comes from detectTerminalWaitBlockedReason over
the tail. What was missing is vocabulary — the blocked-signal set knew
about trust, update, hooks and approval dialogs, and nothing about
passwords, API keys, OTPs, 2FA or OAuth device codes.

So this adds an agent-neutral `agent-credential-prompt` reason and a
shape-based detector for it, and makes it unconditional: unlike every
other reason, a live idle title and a ready caret must not clear it,
because a wrong readiness verdict is exactly the failure being guarded.
isKnownReadyPromptPreview stops calling such a screen ready, so
terminal.wait reports the reason rather than resolving. The refusal is a
defer, not a drop: the wait poll re-reads the tail, so it clears once the
dialog is answered.

Bias is deliberately toward refusing. Measured on a corpus of 47,581
string literals from the repo's own runtime/shared/cli fixtures, the
detector fires on 7 (0.015%), all of which are genuine credential-prompt
shapes when read as a screen-bottom line. On a two-sided corpus in the
new suite it blocks 23/23 live credential surfaces and fires on 0/31
legitimate agent screens, including agents narrating credential work,
agents asking the user credential-adjacent questions, rg output quoting
prompt wording, and diffs adding prompt strings. Verified by mutation:
disabling the candidate turns 29 tests red, and the two write-site
regressions then let the prompt through.

Also fixes a latent main-process hang found while building the corpus:
startOfLastNonBlankLines spun forever on any tail whose first character
is a newline, because lastIndexOf clamps a negative position up to 0.
Every producer filters blank lines today, so it is unreachable rather
than live, but it sits on the PTY data path.

Wire compatibility: `agent-credential-prompt` is an additive union
member, per docs/reference/remote-wire-compatibility.md rule 1. No zod
schema validates the value and the only equality comparisons are on
locally-computed reasons; the CLI interpolates it as a string.
The auth-verb x auth-flow pair rule fired on any two auth-ish lines in the
live window with no terminator and no position requirement, so an agent
summarising auth work ("Added two-factor authentication, the authenticator
app tests pass") refused the next prompt and, because the reason is
unconditional, published an idle agent as `permission` to every status reader.

The pair rule now demands the shape of a request for input: an action-flow
marker owning the bottom row as an unfinished clause, or an inquirer-style
`? ...authenticate?` dialog header. Topic wording (2fa, authenticator app,
device code) no longer carries the bottom row on its own. The bare-label rule
(`password:`) is likewise restricted to the bottom row, so printed k8s
manifests and form templates pass.

Widening `paste code here` and anchoring on the bottom row also closes the two
device-code flows the guard was missing: `gh auth login` and Claude `/login`.

Corpus: 25 must-refuse (23 existing + the 2 former false negatives), 50
must-allow (32 existing + the 18 confirmed false positives).
@nwparker
nwparker force-pushed the nwparker/credential-prompt-write-guard branch from 5274745 to 833d9f0 Compare September 11, 2026 06:52
@nwparker
nwparker changed the base branch from fix/agent-neutral-wait-blocked-reason to main September 11, 2026 06:52
…prefilter honest

Adversarial probing against screens the corpus does not contain -- non-English
output, agents with unusual chrome, records rather than requests -- found both
directions wrong.

False positives, all with the auth phrase mid-row in a line whose subject is
something else: a `git log --oneline` ending on `feat(auth): sign in with
GitHub`, a changelog bullet, a checklist item, `Root cause: authentication
required from the vercel CLI`, and any `Waiting for you to ...` row once anything
above it mentioned login. Localized narration was worse: NARRATION_ROW_RE knew
only ASCII sentence punctuation, so a Chinese or German summary of auth work had
no way to read as prose while still embedding English auth wording. An action
phrase now has to LEAD its row, `waiting for you to` carries an auth
continuation, and narration includes CJK sentence punctuation.

False negative, and the one that matters: the live Antigravity sign-in menu
already fixtured in terminal-wait-detection.test.ts -- the dialog #19749 was
filed for -- was NOT detected. `2. Paste an API key` is a prompt to the index
because end-of-row is a terminator, but the cheap sentinel only accepted a noun
followed by punctuation, so the tail was dropped before it was ever parsed. The
sentinel's doc comment calls itself a superset of the index; it was not, and the
test asserting so only ran over screens we already expected to block. It now runs
over both corpora against the index's own verdict, which is what found this.

Also: sudo translates its prompt but not its `[sudo]` tag, the common api-key ask
names the env var it fills, and a boxed dialog ends its rows with a frame glyph
the sentinel counted as "not a terminator".

The env-var vendor slot belongs in the prefix rules, not the noun alternation:
spelled `(?:[a-z0-9]+_)?api[ _-]?key` it is quadratic, 30ms on one 5.5k-char
line, in a regex that runs per retained tail line at streaming rate. Pinned with
a budget.
@coderabbitai

coderabbitai Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Review Change StackReview Change Stack

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 42ffe485-fa2e-4898-aa7b-3634ef7a8956

📥 Commits

Reviewing files that changed from the base of the PR and between 9cf3b96 and 07d1328.

📒 Files selected for processing (1)
  • src/main/runtime/terminal-credential-prompt-detection.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.


📝 Walkthrough

Walkthrough

The runtime detects live terminal credential prompts and reports agent-credential-prompt. Credential prompts remain authoritative when ready-terminal chrome is present. Shared sentinel and Cursor approval detection moved into dedicated modules. Runtime permission and status checks use unconditional blocker handling. Tail scanning now avoids a leading-newline infinite loop. New tests cover prompt corpora, write guards, wait states, and blocked-reason rendering.

Priority: ➖ Normal

Merge Risk: 🟡 Moderate · up to 07d13

Some authentication prompts may not be recognized as blocked waits, allowing task writes while credentials are requested. Resolve these detection gaps before merge.

🚥 Pre-merge checks | ✅ 3 | ❌ 2

❌ Failed checks (2 warnings)

Check name Status Explanation Resolution
Docstring Coverage ⚠️ Warning Docstring coverage is 27.78% which is insufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 18 functions across 16 files. Write docstrings for the functions missing them to satisfy the coverage threshold.
Description check ⚠️ Warning The description provides extensive technical context and verification details, but it omits or renames several required template sections. It lacks a Fixes # issue entry, visual proof or the require… Add the required template sections and complete them. Include a Linked Issue section with Fixes #<issue>, a Visual Proof section with before/after evidence or exactly N/A plus a reason, a Testing section with the required checklis…
✅ Passed checks (3 passed)
Check name Status Explanation
Linked Issues check ✅ Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check ✅ Passed Check skipped because no linked issues were found for this pull request.
Title check ✅ Passed The title clearly describes the primary change: blocking agent-prompt writes when a live credential prompt is detected.
Full details: Description check

Explanation

The description provides extensive technical context and verification details, but it omits or renames several required template sections. It lacks a Fixes # issue entry, visual proof or the required N/A statement, testing checkboxes, and the remaining checklist sections.

Resolution

Add the required template sections and complete them. Include a Linked Issue section with Fixes #&lt;issue&gt;, a Visual Proof section with before/after evidence or exactly N/A plus a reason, a Testing section with the required checklist and platform coverage, and the missing AI Disclosure, Review, Agent skill upstream boundary, Notes, and Checklist sections.

  • Fix all pre-merge checks with AI
✨ Finishing Touches 💡 1
📝 Generate docstrings 💡
  • Create stacked PR
  • Commit on current branch

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@nwparker nwparker changed the title fix(runtime): refuse a task prompt into a live credential prompt fix(runtime): refuse an agent-prompt write into a live credential prompt Sep 11, 2026
Mining 16,206 distinct credential-vocabulary lines out of this repo's own tracked
files and placing each one row above a real agent composer caret produced **100
refusals across 25 distinct lines**, on Codex, Claude Code and OpenCode. The
corpus had `rg` hits and diffs, which carry their own chrome, but no plain
formatted source -- and that is the category that leaked.

24 of the 25 are one shape. `AUTH_QUESTION_ROW_RE` rests on "prose never starts
with a bare `?`", which is true and irrelevant: oxfmt puts a ternary's consequent
on its own row as `? someValue`, and **5,666 tracked files have one**.
`sawAuthQuestion` then returns unconditionally, with no position requirement, so a
composer caret directly below could not clear it. Nine matched only because
`\b(?:log[ -]?in)\b` reads `user.login` as the auth verb.

The 25th is the other rule: `CREDENTIAL_ASK_PREFIX_RE` was unanchored, so an ask
verb anywhere in a row made a row-final credential noun a prompt -- `// Why: a
merely missing or expired bundle must not enter the credential` is a real wrapped
comment in this repo, and terminal wrapping makes ending on a noun routine.

Three fixes, the same position discipline the flow rule already uses:

- the ask verb must LEAD its row, modulo decoration and a menu number, so
  `2. Paste an API key` still reads as a prompt and 60 characters of prose before
  `enter the` does not;
- `.login` is a property access, not an auth verb;
- a known composer caret on the bottom row suppresses the question-row rule,
  because an agent sitting at its own prompt is not asking anyone anything.

The caret set deliberately includes a bare `>`. It suppresses only the
question-row rule, and the #19749 sign-in dialog -- whose own bottom row is `>` --
matches through `isCredentialPromptLine`, which returns first. Verified: that
dialog and the auth-method menu both still refuse.

Mined-corpus refusals 100 -> 0, with the mined lines added as a corpus category so
the next widening has to refuse them. Sentinel budget unchanged.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the position-discipline rewrite is careful, well-reasoned, and thoroughly pinned; one minor recall gap inline.

Reviewed changes

  • Position-disciplined the auth-action fallback — added AUTH_ACTION_FLOW_LEADS_ROW_RE, which requires the dialog-only action phrase to lead its row, and gave waiting for you to an explicit auth continuation, so commit subjects, changelog bullets, and localized narration no longer read as prompts.
  • Widened locale-independent coverage — sudo now keys on its untranslated [sudo] tag, and env-var api-key asks (Enter your OPENAI_API_KEY:) are caught via a _ noun separator plus vendor prefix slots, with a linearity budget test guarding the sentinel against the quadratic spelling.
  • Made the prefilter an honest superset — the sentinel now accepts box-glyph runs and a bare row-final noun, and the superset test runs over both corpora, closing the lane divergence that let the main path silently pass the Antigravity sign-in menu.
  • Extended the two-sided corpus — must-refuse gains the sign-in menu, localized sudo, env-var and boxed asks; must-allow gains records, changelog/checklist items, and the sibling model-picker/privacy dialogs.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

// Why `waiting for you to` carries an auth continuation: bare "waiting for you to …" is how
// every agent narrates waiting on a review, a branch choice or an approval.
const AUTH_ACTION_FLOW_SOURCE =
'sign[ -]?in with|log[ -]?in with|authenticate with|authentication required|authorization required|sign[ -]?in required|login required|enter (?:the )?code|waiting for (?:authentication|authorization|you to (?:sign|log|authenticate|authoriz|finish|enter (?:the |your )?code))|open (?:this|the following) url|press enter to (?:open|sign)|paste (?:it|(?:the |your )?code) (?:here|below)'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The authoriz continuation is dead — it never matches authorize or authorization. Both AUTH_ACTION_FLOW_LEADS_ROW_RE and AUTH_FLOW_RE append \b right after the flow source, and both real words continue with a word character (e/ation) after the truncated token, so \b always fails. Waiting for you to authorize (a genuine OAuth/browser-auth prompt shape) is silently missed even though the continuation list plainly intends to catch it.

Technical details
# Fix the dead `authoriz` continuation

## Affected sites
- src/main/runtime/terminal-credential-prompt-detection.ts:82 — `authoriz` inside the `waiting for you to (...)` alternation of `AUTH_ACTION_FLOW_SOURCE`.

## Repro (verified via node against the shipped regex)
- "Waiting for you to authorize" → not matched (expected match)
- "Waiting for you to authorize in your browser" → not matched
- "Waiting for you to sign in…" → matched (control)

## Required outcome
- `waiting for you to authorize...` should read as an auth-action flow phrase.

## Suggested approach
- Spell it `authoriz(?:e|ation)` (or simply `authorize`) in `AUTH_ACTION_FLOW_SOURCE`. It is single-sourced, so the detector and the sentinel both pick up the fix with no superset-invariant change.

… decoration

Two more false positives of the same family as the ternary one, found by crossing
the detector's own vocabulary against the shapes a term takes when it is output
rather than a prompt.

`candidate.credential` set the credential-noun flag: only the auth-verb regex had
been taught that a dot means a property access. That flag corroborates an
otherwise-inert bottom row, so an identifier alone could refuse a screen that was
only printing source. Excluded `.` and `.` only -- `\w` would break the env-var
ask (`OPENAI_API_KEY`), which is a real prompt.

`    // Sign in with the provider console to continue` read as a dialog leading
its row, because the decoration run before the action phrase accepted a comment
marker. A dialog decorates its instruction with box rules, bullets, carets and
menu numbers, never with `//` or `*`.

Both pinned, and the #19749 sign-in dialog and auth-method menu still refuse.

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 3bd5b06a-c361-4955-99fc-dd1d4e982a31

📥 Commits

Reviewing files that changed from the base of the PR and between b3e0a33 and fa0af56.

📒 Files selected for processing (16)
  • src/main/runtime/orca-runtime-resolve-authoritative-terminal-wait-permission.ts
  • src/main/runtime/runtime-terminal-agent-status-query.ts
  • src/main/runtime/terminal-credential-prompt-detection.test.ts
  • src/main/runtime/terminal-credential-prompt-detection.ts
  • src/main/runtime/terminal-credential-prompt-write-guard.test.ts
  • src/main/runtime/terminal-cursor-approval-detection.ts
  • src/main/runtime/terminal-tail-sentinel-index.test.ts
  • src/main/runtime/terminal-tail-sentinel-index.ts
  • src/main/runtime/terminal-wait-blocked-sentinel.ts
  • src/main/runtime/terminal-wait-detection.test.ts
  • src/main/runtime/terminal-wait-detection.ts
  • src/main/runtime/terminal-wait-tail-state.ts
  • src/main/runtime/terminal-wait-tail-window.test.ts
  • src/main/runtime/terminal-wait-tail-window.ts
  • src/shared/runtime-terminal-contracts.ts
  • src/shared/terminal-wait-blocked-reason-legacy-alias.test.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 6 remain after this review.

// Why `waiting for you to` carries an auth continuation: bare "waiting for you to …" is how
// every agent narrates waiting on a review, a branch choice or an approval.
export const AUTH_ACTION_FLOW_SOURCE =
'sign[ -]?in with|log[ -]?in with|authenticate with|authentication required|authorization required|sign[ -]?in required|login required|enter (?:the )?code|waiting for (?:authentication|authorization|you to (?:sign|log|authenticate|authoriz|finish|enter (?:the |your )?code))|open (?:this|the following) url|press enter to (?:open|sign)|paste (?:it|(?:the |your )?code) (?:here|below)'

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🔒 Security & Privacy | 🛡️ Analyzed with Security Review | 🟡 Minor | ⚡ Quick win

🧩 Analysis chain

🤖 get_repo_knowledge executed:

get_repo_knowledge stablyai/orca /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/architecture /tmp/coderabbit-repo-knowledge/stablyai-orca-89dc44e4/learnings

Length of output: 47225


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- relevant source symbols ---'
rg -n -A35 -B12 'AUTH_ACTION_FLOW_SOURCE|AUTH_FLOW_RE|findCredentialPromptIndex|assertTerminalAgentSendable|sendTerminalAgentPrompt' \
  src/main/runtime/terminal-credential-prompt-detection.ts \
  src/main/runtime/terminal-wait-detection.ts \
  src/main/runtime/terminal-agent* 2>/dev/null || true
printf '%s\n' '--- focused tests ---'
sed -n '600,720p' src/main/runtime/terminal-credential-prompt-detection.test.ts

Repository: stablyai/orca

Length of output: 32240


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- matching files ---'
git ls-files 'src/main/runtime/*terminal*' | sort
printf '%s\n' '--- exact detector definitions and callers ---'
rg -n -A45 -B15 'AUTH_ACTION_FLOW_SOURCE|AUTH_FLOW_RE|findCredentialPromptIndex|assertTerminalAgentSendable|sendTerminalAgentPrompt' src/main/runtime

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
file='src/main/runtime/terminal-credential-prompt-detection.ts'
printf '%s\n' '--- detector source ---'
sed -n '1,280p' "$file"
printf '%s\n' '--- wait propagation ---'
sed -n '170,330p' src/main/runtime/terminal-wait-detection.ts
printf '%s\n' '--- sendability references ---'
rg -n -A30 -B20 'assertTerminalAgentSendable|sendTerminalAgentPrompt' src/main

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
sed -n '1,280p' src/main/runtime/terminal-credential-prompt-detection.ts
printf '\n--- wait detector ---\n'
sed -n '170,330p' src/main/runtime/terminal-wait-detection.ts
printf '\n--- sendability references ---\n'
rg -n -A30 -B20 'assertTerminalAgentSendable|sendTerminalAgentPrompt' src/main

Repository: stablyai/orca

Length of output: 50370


🏁 Script executed:

#!/bin/bash
set -eu
printf '%s\n' '--- source ---'
cat -n src/main/runtime/terminal-credential-prompt-detection.ts | sed -n '1,115p'
printf '%s\n' '--- test cases around authorization wording ---'
rg -n -A8 -B8 'authorize|authorization|authoriz|Waiting for you' src/main/runtime/terminal-credential-prompt-detection.test.ts

Repository: stablyai/orca

Length of output: 13540


Sensitive Data Exposure

Reachability: External
Exploitability: Moderate
CWE: CWE-200 — Exposure of Sensitive Information to an Unauthorized Actor

Match complete authorization words in AUTH_ACTION_FLOW_SOURCE. The surrounding regex requires a word boundary after this branch, so authoriz cannot match authorize or authorization. A bottom-row Waiting for you to authorize prompt can therefore bypass agent-credential-prompt detection and allow sendTerminalAgentPrompt to write into the authorization prompt. Replace authoriz with authorize|authorization, and add regression coverage for both forms.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta — the source-code false-positive tightening is clean and well-pinned. Two prior non-blocking recall observations remain open on the PR and are unchanged by these commits.

Reviewed changes

  • AUTH_VERB_RE / CREDENTIAL_NOUN_RE lookbehinds — property accesses (user.login, candidate.credential) no longer read as auth wording or credential nouns, so source printed into the pane stops corroborating an otherwise-inert bottom row.
  • Anchored the ask verb — CREDENTIAL_ASK_PREFIX_RE now requires the ask verb to lead its row, so prose that merely ends on a credential noun (must not enter the credential) reads as narration.
  • Comment markers are not decoration — / and * were removed from the decoration run in AUTH_ACTION_FLOW_LEADS_ROW_RE, so // Sign in with … and JSDoc rows no longer read as dialogs.
  • Composer-caret suppression — a new COMPOSER_CARET_ROW_RE suppresses the inquirer-? rule when the bottom row is the agent's own composer, so ternary consequents (? someValue) above a live caret no longer read as a question dialog.
  • Corpus widened — ~30 new must-allow screens (ternary consequents, wrapped comments/JSDoc, property-access rows) mined from tracked source.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

… questions

Re-verification found the previous fix incomplete: 18 refusals survived, one root
cause. The composer suppression fired only when the caret was the literal bottom
row, and no agent draws it there -- Codex puts a model footer under it, OpenCode a
status bar, droid a key-hint row. So the ternary false positive survived for Codex
and OpenCode, both gating agents, and cursor-agent and antigravity passed only
because four chrome rows pushed the trigger outside the window.

Position alone cannot separate these: `? How would you like to authenticate?`
above its option rows and `? prevAssignees.filter(...)` above a caret and a status
bar sit at the same offset from the bottom. So two rules:

- suppression scans the last three non-blank rows for a caret, not the bottom row;
- a `?` row that is code-shaped (quotes, braces, brackets, `=>`, `!==`, a `foo.bar`
  access) is not a question. Parentheses stay legal, since real prompts write
  `(Use arrow keys)`.

Also: the noun lookbehind now spans an identifier to its opening dot, because
`candidate.personal_access_token` still corroborated when only one character was
checked -- the dot precedes `personal`, not `access_token`.

Mined-corpus refusals: 16,297 lines x 13 real agent tails = 0. Controls hold.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta — the composer-region suppression and the code-vs-question separation are both clean and well-pinned. The two prior non-blocking recall observations remain open on the PR and are unchanged by this commit.

Reviewed changes

  • Variable-length credential-noun lookbehind — (?<!\.) became (?<!\.[a-z0-9_$]*), so the dot anchored at the start of an identifier now excludes the whole family (candidate.personal_access_token) instead of only a noun with a dot immediately before it.
  • Composer region, not bottom row — COMPOSER_CARET_ROW_RE now suppresses the inquirer-? rule when any of the last 3 non-blank rows is a composer caret, because Codex, OpenCode and droid draw a model footer or status bar under their caret.
  • Code-shaped rows are not questions — a new CODE_SHAPED_ROW_RE separates a ternary consequent (quotes, braces, =>, ;, or a .property access) from an inquirer header, so a ? row that is formatted source stops reading as a dialog even without a caret to vouch for it.
  • Corpus widened — five new must-allow screens pin the bare-identifier ternary, the login-access ternary, and the personal_access_token identifier above real composer footers.

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 1


ℹ️ Review info
⚙️ Run configuration

Configuration used: Repository UI

Review profile: CHILL

Plan: Advanced

Run ID: 50939a7a-f960-46be-a4e0-89b9666080bb

📥 Commits

Reviewing files that changed from the base of the PR and between fa0af56 and 4023adb.

📒 Files selected for processing (2)
  • src/main/runtime/terminal-credential-prompt-detection.test.ts
  • src/main/runtime/terminal-credential-prompt-detection.ts

Included review availability: Your plan provides up to 10 included reviews per hour; 5 remain after this review.

sawAuthQuestion =
sawAuthQuestion ||
(AUTH_QUESTION_ROW_RE.test(line) &&
!CODE_SHAPED_ROW_RE.test(line) &&

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🎯 Functional Correctness | 🟠 Major | ⚡ Quick win

Do not classify quoted authentication questions as source code.

Line 257 rejects any ? authentication question that contains ' or ". For example, a live screen with ? How would you like to authenticate with "GitHub"? followed by option rows sets no sawAuthQuestion. The option row does not satisfy bottomRowAsks, so findCredentialPromptIndex returns null.

Refine CODE_SHAPED_ROW_RE so a quote embedded in prompt prose does not classify the row as source code. Preserve detection for quoted ternary consequents. Add this screen to LIVE_CREDENTIAL_SURFACES.

… see it

`(?<!\.[a-z0-9_$]*)` is quadratic — the engine retries the lookbehind from every
position in an identifier run, so doubling the run quadruples the cost. Measured
at 512/1024/4096 characters: 79us / 286us / 4572us, against 47 / 88 / 354 bounded.
`{0,40}` restores linearity and reproduces the unbounded verdict on every
correctness case, `candidate.personal_access_token` and `OPENAI_API_KEY` included.

Why the existing budget could not see it: it drives the sentinel, which is built
from the RAW noun source and carries no lookbehind. Driving the detector instead
does not help either, because MAX_CREDENTIAL_LINE_LENGTH caps every row at 512 and
the gap between linear and quadratic is only ~1.7x there. So the budget now drives
the noun regex directly and asserts the complexity class at 1024 vs 4096.

The 512 cap is documented as load-bearing for complexity, not just throughput.

Also dropped `[`/`]` from the code-shape class: a bracketed confirm default
(`? Authenticate with the CLI? [Y/n]`) is a mainstream convention and was reading
as source. Both confirm shapes are pinned as must-refuse; no code row regressed.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No new issues in this delta — the lookbehind bound and the bracketed-confirm fix are clean and well-pinned. The two prior non-blocking recall observations (authoriz continuation, topic-flow co-occurrence guard) remain open on the PR and are unchanged by this commit.

Reviewed changes

  • Bounded the credential-noun lookbehind — CREDENTIAL_NOUN_LOOKBEHIND went from (?<!\.[a-z0-9_$]*) to (?<!\.[a-z0-9_$]{0,40}), making the rule linear in an identifier run instead of quadratic while still excluding candidate.personal_access_token and the env-var ask.
  • Added a complexity-class budget test — a new CREDENTIAL_NOUN_RE_FOR_BUDGET export drives the lookbehind-bearing regex directly (the sentinel is structurally blind to it, and the 512-char cap hides the growth curve), asserting the 4096/1024 ratio stays under 8×.
  • Recognized bracketed confirm defaults — dropped [/] from CODE_SHAPED_ROW_RE so ? Authenticate with the CLI? [Y/n] reads as a dialog rather than formatted code, with two new must-refuse corpus cases pinning it.
  • Documented the line cap as load-bearing for complexity, not just throughput.

Verified the budget test actually discriminates: driving the shipped bounded form on its own test line gives a 3.9× 4096/1024 ratio (passes < 8×), while the quadratic spelling gives 16.9× (fails), so the assertion would catch a regression rather than passing over it. Full terminal-credential-prompt-detection.test.ts suite is green (170 tests).

Pullfrog  | Fix it ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

…nd exists

`{0,40}` was one character from wrong. The divergence boundary is exactly 41
characters between the opening dot and the noun, and
`settings.defaultOrganizationServiceAccountClientApiKey` sits at 39 — a real
identifier shape in this codebase, clearing the bound by one.

The quadratic behaviour comes from `*`, not from the size of the bound, so the
headroom is free: 1024 -> 4096 grows 4.20x at 64 against 14.21x unbounded, and all
eight correctness cases are unchanged. The reasoning is now in the comment,
because `{0,64}` reads as arbitrary otherwise and the obvious "simplification" is
back to `*`.

@pullfrog pullfrog Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

ℹ️ No critical issues — the headroom widen is correct and the budget test still discriminates; one documentation-accuracy nit inline.

Reviewed changes

  • Widened the noun lookbehind bound — CREDENTIAL_NOUN_LOOKBEHIND moved from {0,40} to {0,64}, with the reasoning (unbounded * is quadratic, larger bounds are free, headroom for identifier growth) now documented in the comment.
  • No detector or corpus behavior change — the commit is a comment rewrite plus the bound widen; all 170 detection tests pass and the complexity-class budget test still discriminates the linear form.

Pullfrog  | Fix all ➔ | Fix 👍s ➔ | View workflow run | Using DeepSeek Pro (free via Pullfrog for OSS) | 𝕏

* Why 64 specifically, and not smaller: the bound has to exceed the longest realistic distance
* between the opening dot and the noun, or a long property chain stops being recognised as a
* property access and starts corroborating a prompt. The longest in this repo today is 39
* (`settings.defaultOrganizationServiceAccountClientApiKey`), which clears a bound of 40 by one

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The cited example settings.defaultOrganizationServiceAccountClientApiKey appears nowhere in this tree — git grep OrganizationServiceAccount matches only this comment itself. It reads like a Google Cloud auth identifier lifted from a dependency rather than Orca source, so either reword the claim or cite a real identifier from the repo (the bound itself is fine regardless).

@nwparker
nwparker marked this pull request as draft September 13, 2026 05:49
@nwparker

Copy link
Copy Markdown
Contributor Author

⏸️ Paused — draft pending a design decision, not a fix

This PR is correct as far as it was verified, and is being paused anyway. The reason is design shape, not a defect.

What is actually verified

Four rounds of review, each with an independent verifier re-deriving its own inputs rather than reusing the author's:

  • False positives: 0. 162,800 mined screens across two contexts (agent composer and shell pane), 468 agent-template screens across all 36 agents, 13 real recorded PTY captures, four corpora, 1,046 tests. Codex, Claude Code, OpenCode and Gemini clean on every probe.
  • Performance: linear. Streaming sentinel ~2% of a normal onPtyData chunk; worst reachable row 17.2 µs; budget test turns red under mutation.
  • Failure mode: loud and fast. A refusal resolves synchronously in <50 ms with a named reason; no path waits.

Why it is paused anyway

The detector accreted rather than converged. It now carries roughly eight interacting rules — bottom-anchored request, interactive-question, action/topic split, code-shape rejection, composer-region scan, caret suppression, bracket handling, a bounded lookbehind, plus a 512-char cap that turned out to be load-bearing for complexity and was undocumented until round four. Every one was added to patch a specific hole found by the previous round.

Across four rounds, an independent verifier found a live false-positive class in each of the first three that the author's own tests had cleared:

  1. Curated corpus read 49/49 clean → mining found 108 refusals (formatted TypeScript ternaries read as sign-in dialogs; 5,666 tracked files contain such a line).
  2. Fix verified 100 → 0 → but the permanent test hand-wrote idealised composer tails ending on the caret.
  3. Real chrome sourced from the repo's own corpora → 120 refusals the permanent test could not generate (footer-under-caret, affecting Codex and OpenCode).

Every failure was idealised test input, never wrong reasoning. That pattern is the concern: the tests pass because someone adversarial kept looking, not because the design makes the class impossible.

The question that was never asked

The task was always framed as "fix the detector." Nobody asked whether a text detector is the right instrument.

A genuine password prompt disables echo at the termios layer. That is ground truth, not inference — and Orca has no echo detection anywhere (confirmed by audit). It would not cover echoing surfaces (API-key asks, OAuth device codes), but those are exactly the cases where a wrong guess is least catastrophic, and a much thinner text rule could cover them.

That is a different design: one hard signal plus a small heuristic, instead of eight heuristics. If it is feasible, most of the rules here disappear.

What to keep regardless of the decision

  • The write-path inventory — the fence covers 1 of 7 paths that can carry arbitrary user text; mobile is entirely unfenced.
  • The corpora (live credential surfaces, legitimate agent screens, auth-summary, auth-mention).
  • The generative suite, and the block comment on AGENT_COMPOSER_TAILS recording why its rows must come from captured chrome and never be hand-written.
  • The finding that the guard originally did not detect the live Antigravity sign-in menu — the dialog fix(runtime): agent-neutral wait-blocked reasons #19749 was filed for — and that the two lanes disagreed about it, because a prefilter documenting itself as "a superset" was not one.

To un-draft

Either (a) an echo/termios investigation concludes the hard signal is not available, in which case this is the best available instrument and should merge with #20004; or (b) it is available, and this is rebuilt around it.

Do not merge this alone — #20004 covers the paste lane, which is the most-used path. Merging one without the other reads as protection it does not provide.

@nwparker

Copy link
Copy Markdown
Contributor Author

Scoping correction: what echo detection can and cannot replace

The comment above proposes PTY echo state as a ground-truth alternative to text inference. That is right, but the scope is narrower than it first appears, and getting this wrong would rebuild the exact hole this guard was filed for.

Where echo is authoritative

sudo, ssh passphrase, git credential, docker login — all clear ECHO at the termios layer. That is a hard signal, not a guess.

Critically, termios does not care what language the prompt is in. That eliminates the entire English-only false-negative class documented here — 10 of 15 non-English credential prompts currently pass — which was explicitly declined as a vocabulary fix because adding CJK/European nouns would import a new false-positive population (密碼: appears constantly in Chinese narration about password work). Echo detection removes that trade-off entirely. Given the originating user report on #19749 was written in Traditional Chinese, this matters more than it looks.

Where echo carries no information

A full-screen TUI runs in raw mode with ECHO already off for the entire session. For Codex, Antigravity, Claude Code and every other TUI agent, the signal is constant and says nothing about whether a sign-in dialog currently owns the screen.

That is precisely where #19749's Antigravity sign-in dialog lives — the dialog this guard exists for, and the one the original detector missed entirely (see the lane-divergence finding above).

Device-code flows are the second gap. gh auth login and Claude Code's /login echo the code you paste, so no echo transition occurs at all.

The honest shape of a redesign

  • Echo detection owns the shell-prompt class outright — authoritative, language-independent, no corpus required.
  • The text detector shrinks to the TUI-dialog and device-code cases it cannot cover. Much less surface than the ~8 rules here, but it does not disappear.
  • Anyone assuming echo replaces everything will leave the TUI dialog unguarded, which is where this started.

Before committing to it

Confirm node-pty can expose the slave's termios on macOS, Linux and Windows. Windows has no termios — ConPTY would need a different mechanism or an explicitly stated gap. Per AGENTS.md, a Windows-shaped answer is required before this is a design rather than a POSIX-only idea.

Two findings that survive any instrument

Both are about the system, not the detector, and a replacement inherits them:

  1. The lane divergence. The main process and renderer disagreed about the fix(runtime): agent-neutral wait-blocked reasons #19749 dialog, because TERMINAL_CREDENTIAL_PROMPT_SENTINEL_RE documented itself as "a superset of everything findCredentialPromptIndex can match" and was not one — and the test asserting that property only ran over screens already believed to block. Any replacement detector sitting behind that same prefilter inherits the bug.
  2. MAX_CREDENTIAL_LINE_LENGTH = 512 is load-bearing for complexity, not throughput — and no test could observe that through the pipeline in either direction (above the cap, rows are skipped; below it, the quadratic/linear gap is only ~1.7×). The budget test had to assert the growth curve of the rule directly. A redesign that changes or removes that cap needs to know this.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant