Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
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
25 changes: 24 additions & 1 deletion packages/opencode/src/cli/cmd/run.ts
Original file line number Diff line number Diff line change
Expand Up @@ -718,6 +718,27 @@ export const RunCommand = effectCmd({
// exit, killing the in-process server and every job with it, before
// all of their results are surfaced.
const background = BackgroundTasks.make(sessionID)
// Sessions already known to descend from this run's root, so a request is checked once.
const ownedSessions = new Set<string>([sessionID])
const ownsPermissionSession = async (id: string) => {
if (ownedSessions.has(id)) return true
if (background.owns(id)) return true
const chain: string[] = []
let current: string | undefined = id
for (let depth = 0; current && depth < 16; depth++) {
if (ownedSessions.has(current)) {
for (const item of chain) ownedSessions.add(item)
return true
}
chain.push(current)
const next: string | undefined = await client.session
.get({ sessionID: current })
.then((info) => info.data?.parentID)
.catch(() => undefined)
current = next
}
return false
}
let rootIdle = false
let lastText = ""
let error: string | undefined
Expand Down Expand Up @@ -885,7 +906,9 @@ export const RunCommand = effectCmd({

if (event.type === "permission.asked") {
const permission = event.properties
if (permission.sessionID !== sessionID) continue
// A delegated child (foreground or background) waits for the same answer the root would
// get; nobody else answers a headless run's requests, so ignoring it hangs the child.
if (!(await ownsPermissionSession(permission.sessionID))) continue

if (auto) {
await client.permission.reply({
Expand Down
85 changes: 85 additions & 0 deletions packages/opencode/test/cli/run/child-permission.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,85 @@
import { describe, expect } from "bun:test"
import { Duration, Effect, Option } from "effect"
import { writeFile } from "node:fs/promises"
import path from "node:path"
import { cliIt } from "../../lib/cli-process"
import { reply } from "../../lib/llm-server"
import { testProviderConfig } from "../../lib/test-provider"

// A permission request raised by a delegated child session must be answered by the headless run the same
// way as the root's, or the child waits forever.
// A permission request raised by a delegated child session must be answered by the headless run the same
// way as the root's, or the child waits forever.
// Responses are keyed on the session (its first user message) and on how many tool results it has seen, so
// each session gets its own script whatever the interleaving.
const first = (body: any): string => JSON.stringify((body.messages ?? []).find((m: any) => m.role === "user") ?? "")
const tools = (body: any): number => (body.messages ?? []).filter((m: any) => m.role === "tool").length
const flow = (llm: any, envFile: string) =>
Effect.gen(function* () {
const session = (text: string, seen: number) => (hit: any) => first(hit.body).includes(text) && tools(hit.body) === seen
yield* llm.pushMatch((hit: any) => JSON.stringify(hit.body).includes("Generate a title"), reply().text("Update calc").stop())
yield* llm.pushMatch(
session("Implement validation in src/calc.ts", 0),
reply().tool("task", { description: "plan", prompt: "Plan the edit", subagent_type: "think", background: false }),
)
yield* llm.pushMatch(
session("Plan the edit", 0),
reply().text("<silvercode-result>1. Edit calc.ts</silvercode-result>").tool("finish", { reason: "success", result: "planned" }).stop(),
)
yield* llm.pushMatch(
session("Implement validation in src/calc.ts", 1),
reply().tool("task", { description: "implement", prompt: "Implement the edit", subagent_type: "code", background: false }),
)
yield* llm.pushMatch(session("Implement the edit", 0), reply().tool("read", { filePath: envFile }))
yield* llm.pushMatch(
session("Implement the edit", 1),
reply().text("<silvercode-result>Done</silvercode-result>").tool("finish", { reason: "success", result: "implemented" }).stop(),
)
yield* llm.pushMatch(
session("Implement validation in src/calc.ts", 2),
reply().text("ROOT_DONE").tool("finish", { reason: "success", result: "done" }).stop(),
)
})

type Outcome = { exited: boolean; seen: boolean; rejected: boolean }
const SECRET = "APP_MODE=demo_child_perm_marker"

describe("headless run child permission requests", () => {
const exec = (extraArgs: string[]) => ({ llm, home, opencode }: any): Effect.Effect<Outcome, unknown, any> =>
Effect.gen(function* () {
const envFile = path.join(home, ".env")
yield* Effect.promise(() => writeFile(envFile, SECRET + "\n"))
yield* flow(llm, envFile)
const config = JSON.stringify({
...testProviderConfig(llm.url),
agent: { work: { finishTool: true }, think: { finishTool: true }, code: { finishTool: true } },
})
const run = yield* opencode.startRun("Implement validation in src/calc.ts", { extraArgs, env: { OPENCODE_CONFIG_CONTENT: config } })
const exited = yield* run.result.pipe(Effect.timeoutOption(Duration.seconds(20)))
const hits = (yield* llm.hits) as any[]
if (Option.isNone(exited)) {
run.interrupt()
const killed = yield* run.result
// Evidence for a timeout: which scripted turns the model server saw, and what the process printed.
const turns = hits.map((hit: any) => `${first(hit.body).slice(0, 40)}|tools=${tools(hit.body)}`)
console.log("child-permission timeout evidence", JSON.stringify({ turns, stderr: String((killed as { stderr?: string }).stderr ?? "").slice(-1500) }))
}
const stderr = Option.isSome(exited) ? String((exited.value as { stderr?: string }).stderr ?? "") : ""
return {
exited: Option.isSome(exited),
rejected: stderr.includes("permission requested: external_directory") && stderr.includes("auto-rejecting"),
seen: hits.some((hit) => JSON.stringify(hit.body).includes(SECRET)) }
})

cliIt.live("under --yolo a foreground child's read is allowed once and its content is delivered", (ctx) =>
Effect.gen(function* () {
const out = yield* exec(["--yolo"])(ctx)
expect(out).toEqual({ exited: true, seen: true, rejected: false })
}), 60_000)

cliIt.live("without --yolo a foreground child's request is rejected, its content is absent and the run exits", (ctx) =>
Effect.gen(function* () {
const out = yield* exec([])(ctx)
expect(out).toEqual({ exited: true, seen: false, rejected: true })
}), 60_000)
})
Loading