Skip to content
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
81 changes: 75 additions & 6 deletions packages/opencode/src/tool/question.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,78 @@ import { Tool } from "./tool"
import { Question } from "../question"
import DESCRIPTION from "./question.txt"

// altimate_change start — non-interactive auto-answer support.
// When running under `claude --print`, CI, or any other context without a TTY,
// there is nobody to click an option in the TUI. The default Question.ask()
// behaviour is to await a Deferred indefinitely, which causes the parent
// process to TaskStop the subprocess after a long wait — looking exactly like
// a hang. See deliverable 02 (Run F first sub-session) for the trace.
//
// Resolution policy: in non-interactive mode, pick the option whose label
// contains a "safe" keyword (skip / cancel / profile only / no / abort).
// If no such option exists, pick the LAST option (UX convention: safer/cancel
// usually sits at the end). The agent then sees a concrete answer in the
// tool result and can continue without blocking. Override via env var:
// ALTIMATE_AUTO_ANSWER=first — always pick first option
// ALTIMATE_AUTO_ANSWER=last — always pick last option (default)
// ALTIMATE_AUTO_ANSWER=skip — return Unanswered for all questions
const SAFE_KEYWORDS = [
"skip",
"cancel",
"no",
"abort",
"profile only",
"profile-only",
"decline",
"deny",
"stop",
]

function isNonInteractive(): boolean {
if (process.env["ALTIMATE_FORCE_INTERACTIVE"] === "1") return false
if (process.env["ALTIMATE_NON_INTERACTIVE"] === "1") return true
return !process.stdin.isTTY

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.

Likely regression for server / IDE (headless-but-interactive) mode — !process.stdin.isTTY is the wrong signal for "no human is listening."

Question.ask() does not only resolve on a TUI keypress. Answers also arrive over HTTP: Question.reply({ requestID, answers }) is exposed at POST /question/:requestID/reply (packages/opencode/src/server/routes/question.ts), with GET /question to list pending ones. So when altimate-code runs as a server with a frontend/IDE client (VS Code / JetBrains / web), process.stdin.isTTY is false, yet a real human can answer via the route.

With this guard, that existing interactive flow is misclassified as non-interactive: execute() short-circuits to autoAnswer() → returns Unanswered immediately and never publishes the question for the client to reply to. The UI user loses the ability to answer, out of the box — ALTIMATE_FORCE_INTERACTIVE=1 exists but server deployments won't have it set.

Suggestion: gate on whether an answer channel actually exists, not on TTY. E.g. treat it as interactive when the server/question clients are connected (a pending-question listener is registered), and reserve the auto-answer path for true headless runs (run subprocess / CI). At minimum, default server mode to interactive and require explicit ALTIMATE_NON_INTERACTIVE=1 to opt into auto-answer, so the altimate-code run-as-subprocess fix doesn't also silently disable the HTTP reply path.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

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

Thanks for catching this — your point was the core insight that drove the entire redesign of this PR. Addressed across f981199, d2a85165, and 764291c0.

Specifically:

  • tool/question.ts no longer touches process.stdin.isTTY at all. Detection is now opt-in via ALTIMATE_NON_INTERACTIVE, and run is the only entrypoint that sets it. serve, web, acp, and workspace-serve deliberately leave it unset, so their POST /question/:requestID/reply path stays live for connected IDE/web clients exactly as you described.
  • cli/cmd/run.ts sets the env var only when args.attach is not set — attach-mode runs the agent on the remote server, so the local env var would just be noise and could mislead other host-local tools.
  • tool/bash.ts strips ALTIMATE_NON_INTERACTIVE from mergedEnv before spawning children, so a nested altimate-code serve (or any server entrypoint) spawned from a run session doesn't inherit the flag and silently disable its own HTTP reply path. This was a latent regression of the same class you flagged — it would have hit the same IDE/web users.

The block comment at tool/question.ts:6-38 captures the rationale and explicitly mentions PR #937 review for future maintainers. Tests at test/tool/question.test.ts lock in the default-interactive contract (the suryaiyer95-named regression class) plus FORCE_INTERACTIVE precedence and NON_INTERACTIVE=0 opt-out.

There's one remaining architectural item your review surfaced indirectly: session/llm.ts:299 only consults agent.permission, not the merged session.permission, so the question: deny rule in run.ts is intent-marker only. Tracked as a follow-up — out of scope here because the env-var path now handles the actual behavior correctly.

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.

[🟠 MEDIUM] There's a potential null pointer exception here. Depending on the runtime environment (e.g., embedded environments or child processes without standard streams), process.stdin could be undefined. Using optional chaining process.stdin?.isTTY is a safer approach and adheres to the null checks guideline.

Suggested change:

Suggested change
return !process.stdin.isTTY
return !process.stdin?.isTTY

}

function autoAnswer(questions: Question.Info[]): Question.Answer[] {
const mode = (process.env["ALTIMATE_AUTO_ANSWER"] ?? "last").toLowerCase()
return questions.map((q) => {
if (mode === "skip") return []
if (mode === "first") return q.options[0] ? [q.options[0].label] : []
if (mode === "last") {
const safe = q.options.find((o) => {
const text = `${o.label} ${o.description}`.toLowerCase()
return SAFE_KEYWORDS.some((k) => text.includes(k))
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Outdated
})
if (safe) return [safe.label]
const last = q.options[q.options.length - 1]
return last ? [last.label] : []
}
// exact label match for explicit answers, e.g. ALTIMATE_AUTO_ANSWER="Profile only"
const match = q.options.find((o) => o.label.toLowerCase() === mode)
return match ? [match.label] : []
})
}
// altimate_change end

export const QuestionTool = Tool.define("question", {
description: DESCRIPTION,
parameters: z.object({
questions: z.array(Question.Info.omit({ custom: true })).describe("Questions to ask"),
}),
async execute(params, ctx) {
const answers = await Question.ask({
sessionID: ctx.sessionID,
questions: params.questions,
tool: ctx.callID ? { messageID: ctx.messageID, callID: ctx.callID } : undefined,
})
// altimate_change start — short-circuit when no human is listening.
let answers: Question.Answer[]
if (isNonInteractive()) {
answers = autoAnswer(params.questions)
} else {
answers = await Question.ask({
sessionID: ctx.sessionID,
questions: params.questions,
tool: ctx.callID ? { messageID: ctx.messageID, callID: ctx.callID } : undefined,
})
}
// altimate_change end

function format(answer: Question.Answer | undefined) {
if (!answer?.length) return "Unanswered"
Expand All @@ -22,9 +83,17 @@ export const QuestionTool = Tool.define("question", {

const formatted = params.questions.map((q, i) => `"${q.question}"="${format(answers[i])}"`).join(", ")

// altimate_change start — flag auto-answers explicitly so the agent
// knows the user didn't actually answer and can decide whether to
// proceed with that choice or fail back gracefully.
const prefix = isNonInteractive()
Comment thread
cubic-dev-ai[bot] marked this conversation as resolved.
Outdated
? `Running in non-interactive mode (no TTY). Auto-answered with safe defaults: `
: `User has answered your questions: `
// altimate_change end

return {
title: `Asked ${params.questions.length} question${params.questions.length > 1 ? "s" : ""}`,
output: `User has answered your questions: ${formatted}. You can now continue with the user's answers in mind.`,
output: `${prefix}${formatted}. You can now continue with the user's answers in mind.`,
metadata: {
answers,
},
Expand Down
123 changes: 123 additions & 0 deletions packages/opencode/test/tool/question.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,12 +19,18 @@ describe("tool.question", () => {
let askSpy: any

beforeEach(() => {
// Force the original interactive path for the legacy tests below — the
// test environment is non-TTY (bun:test runs without a terminal), so
// without this override the non-interactive auto-answer branch would
// short-circuit `Question.ask` and the existing spies would never fire.
process.env["ALTIMATE_FORCE_INTERACTIVE"] = "1"
askSpy = spyOn(QuestionModule.Question, "ask").mockImplementation(async () => {
return []
})
})

afterEach(() => {
delete process.env["ALTIMATE_FORCE_INTERACTIVE"]
askSpy.mockRestore()
})

Expand Down Expand Up @@ -106,3 +112,120 @@ describe("tool.question", () => {
// }
// })
})

describe("tool.question non-interactive auto-answer", () => {
let askSpy: any

beforeEach(() => {
process.env["ALTIMATE_NON_INTERACTIVE"] = "1"
askSpy = spyOn(QuestionModule.Question, "ask").mockImplementation(async () => [])
})

afterEach(() => {
delete process.env["ALTIMATE_NON_INTERACTIVE"]
delete process.env["ALTIMATE_AUTO_ANSWER"]
askSpy.mockRestore()
})

test("picks safe-keyword option when present and does not invoke Question.ask", async () => {
const tool = await QuestionTool.init()
const questions = [
{
question: "May I run row-level hashdiff comparisons?",
header: "PII consent",
options: [
{ label: "Approve row diff", description: "Sample rows may appear" },
{ label: "Profile only", description: "Safer; no row content surfaced" },
],
},
]

const result = await tool.execute({ questions }, ctx)
expect(askSpy).not.toHaveBeenCalled()
expect(result.output).toContain("Profile only")
expect(result.output).toContain("non-interactive mode")
})

test("falls back to last option when no safe keyword matches", async () => {
const tool = await QuestionTool.init()
const questions = [
{
question: "Pick a color",
header: "Color",
options: [
{ label: "Red", description: "The color of passion" },
{ label: "Blue", description: "The color of sky" },
],
},
]

const result = await tool.execute({ questions }, ctx)
expect(askSpy).not.toHaveBeenCalled()
expect(result.output).toContain("Blue")
})

test("ALTIMATE_AUTO_ANSWER=first picks first option", async () => {
process.env["ALTIMATE_AUTO_ANSWER"] = "first"
const tool = await QuestionTool.init()
const questions = [
{
question: "Pick a color",
header: "Color",
options: [
{ label: "Red", description: "" },
{ label: "Blue", description: "" },
],
},
]

const result = await tool.execute({ questions }, ctx)
expect(result.output).toContain("Red")
})

test("ALTIMATE_AUTO_ANSWER=skip returns Unanswered for each question", async () => {
process.env["ALTIMATE_AUTO_ANSWER"] = "skip"
const tool = await QuestionTool.init()
const questions = [
{
question: "Pick a color",
header: "Color",
options: [{ label: "Red", description: "" }],
},
]

const result = await tool.execute({ questions }, ctx)
expect(result.output).toContain("Unanswered")
})

test("ALTIMATE_AUTO_ANSWER=<exact label> picks matching option", async () => {
process.env["ALTIMATE_AUTO_ANSWER"] = "blue"
const tool = await QuestionTool.init()
const questions = [
{
question: "Pick a color",
header: "Color",
options: [
{ label: "Red", description: "" },
{ label: "Blue", description: "" },
],
},
]

const result = await tool.execute({ questions }, ctx)
expect(result.output).toContain("Blue")
})

test("non-interactive prefix is set when Question.ask is bypassed", async () => {
const tool = await QuestionTool.init()
const questions = [
{
question: "OK to proceed?",
header: "Proceed",
options: [{ label: "Cancel", description: "Stop" }],
},
]

const result = await tool.execute({ questions }, ctx)
expect(result.output.startsWith("Running in non-interactive mode")).toBe(true)
})
})
Loading