Skip to content
Merged
Show file tree
Hide file tree
Changes from 16 commits
Commits
Show all changes
25 commits
Select commit Hold shift + click to select a range
1e76a35
feat(opencode): extend ToolStateError schema with optional reason
Astro-Han May 19, 2026
4947de3
feat(opencode): add ExternalResultError typed error class
Astro-Han May 19, 2026
5a70605
feat(opencode): add external-result registry with lifecycle state mac…
Astro-Han May 19, 2026
3c90f3b
refactor(opencode): narrow Tool wrapper catch for typed errors
Astro-Han May 19, 2026
f40c259
feat(opencode): add Tool.Def externalResult declaration
Astro-Han May 19, 2026
856bf35
feat(opencode): add ctx.externalResult primitive on Tool.Context
Astro-Han May 19, 2026
f95f850
refactor(opencode): writer wiring for typed reason persistence
Astro-Han May 19, 2026
5114013
feat(opencode): silent-timeout hasPending parallel guard at llm.ts:482
Astro-Han May 19, 2026
6fc2388
feat(opencode): add POST /session/:sessionID/tool/respond route
Astro-Han May 19, 2026
0aa9603
feat(opencode): add onSessionDestroyed registry teardown hook
Astro-Han May 19, 2026
1f287a9
feat(opencode): question tool flag-gated external-result branch
Astro-Han May 19, 2026
a7d17ef
feat(ui): question rendering branches + inline thin marker for D1=B
Astro-Han May 19, 2026
de72e52
docs(app): defer flag-on dock wire-up to PR B
Astro-Han May 19, 2026
9ee9ec0
fix(app): skip flag-on questions in recovery fallback detection
Astro-Han May 19, 2026
422e863
test(opencode): cover POST /:sessionID/tool/respond submit/dismiss/40…
Astro-Han May 19, 2026
e67819d
fix(question): coerce malformed submit payload + make completed-dismi…
Astro-Han May 19, 2026
851116b
fix(session): include ExternalResult in soft-cancel guard
Astro-Han May 19, 2026
e327368
fix(ui): move tool.tsx memos after partMetadage to avoid TDZ
Astro-Han May 19, 2026
679b31c
fix(session): run ExternalResult shutdown before instance-context guard
Astro-Han May 19, 2026
ad426ec
feat(question): tool-owned response decoder validates submit payloads
Astro-Han May 19, 2026
620c7a0
test(ui): lock declaration order in tool.tsx against TDZ regression
Astro-Han May 19, 2026
330d9d8
fix(question): trim option labels before membership check
Astro-Han May 19, 2026
5fb77b0
fix(session): mirror metadata helper when marking externalResultReady
Astro-Han May 19, 2026
b950fab
refactor(ui): collapse aborted+shutdown question interrupted branches
Astro-Han May 19, 2026
cf31735
chore: merge dev into question-tool-flagged
Astro-Han May 19, 2026
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
39 changes: 34 additions & 5 deletions packages/app/src/pages/session/blockers/question-fallback.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,16 +17,21 @@ const toolPart = (
id: string,
tool: string,
status: ToolState["status"] = "running",
attrs?: { messageID?: string; callID?: string },
): Part =>
({
attrs?: { messageID?: string; callID?: string; stateMetadata?: Record<string, unknown> },
): Part => {
const state = toolState(status)
if (attrs?.stateMetadata) {
;(state as { metadata?: Record<string, unknown> }).metadata = attrs.stateMetadata
}
return {
id,
type: "tool",
tool,
state: toolState(status),
state,
messageID: attrs?.messageID,
callID: attrs?.callID,
}) as Part
} as Part
}

const syncQ = (id: string, sessionID: string, tool?: { messageID: string; callID: string }): QuestionRequest =>
({
Expand Down Expand Up @@ -132,6 +137,30 @@ describe("findRunningQuestionFallbackSession", () => {
).toBe("s")
})

// New-path (PAWWORK_QUESTION_TOOL_EXTERNAL_RESULT) guard: a running
// question part with metadata.externalResultReady is self-managed by the
// external-result registry. Legacy fallback recovery must skip it,
// otherwise the auto-heal clock would arm on every flag-on session and
// halt good runs.
test("skips running question parts whose state metadata flags external-result", () => {
expect(
findRunningQuestionFallbackSession({
sessionID: "s",
syncQuestions: [],
messages: [message("m1")],
partsByMessageID: {
m1: [
toolPart("p1", "question", "running", {
messageID: "m1",
callID: "c1",
stateMetadata: { externalResultReady: true },
}),
],
},
}),
).toBeUndefined()
})

// Mixed-state guard for #419: when a sync entry lacks tool identity but a
// running part has identity, the legacy entry should still cover it. Pre-fix
// behavior would treat the running part as missing and trigger fallback,
Expand Down
8 changes: 8 additions & 0 deletions packages/app/src/pages/session/blockers/question-fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,14 @@ export function findRunningQuestionFallbackSession(input: {
if (!parts) continue
for (const part of parts) {
if (part.type !== "tool" || part.tool !== TOOL_QUESTION || part.state.status !== "running") continue
// New-path question (PAWWORK_QUESTION_TOOL_EXTERNAL_RESULT flag on):
// the tool part itself is the source of truth and the registry manages
// lifecycle. Legacy fallback recovery does not apply, so skip these
// parts so the recovery clock does not arm on every flag-on session.
const stateMeta = (part.state as { metadata?: Record<string, unknown> }).metadata
if (stateMeta && Object.prototype.hasOwnProperty.call(stateMeta, "externalResultReady")) {
continue
}
const callID = part.callID
const messageID = part.messageID
if (!callID || !messageID || !coveredKeys.has(`${messageID}:${callID}`)) {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,14 @@ export function createSessionBlockers(input: {
})

const questionRequest = createMemo(() => {
// Legacy paths (sync.data.blocker + sync.data.question). When the
// PAWWORK_QUESTION_TOOL_EXTERNAL_RESULT flag is on, neither is populated
// and the dock will be empty. Full dock wire-up (synthesise a
// QuestionRequest from running question tool parts in sync.data.message
// with metadata.externalResultReady, route submissions through
// POST /session/:sessionID/tool/respond) lands in PR B alongside SDK
// regeneration. Until then flag-on UX is API-only; PR A's E2E exercises
// the route via fetch.
return (
sessionQuestionBlockerRequest(sync.data.session, sync.data.blocker, activeSessionID()) ??
sessionQuestionRequest(sync.data.session, sync.data.question, activeSessionID())
Expand Down
15 changes: 15 additions & 0 deletions packages/core/src/flag/flag.ts
Original file line number Diff line number Diff line change
Expand Up @@ -48,6 +48,10 @@ export namespace Flag {
export const OPENCODE_SERVER_PASSWORD = process.env["OPENCODE_SERVER_PASSWORD"]
export const OPENCODE_SERVER_USERNAME = process.env["OPENCODE_SERVER_USERNAME"]
export const OPENCODE_ENABLE_QUESTION_TOOL = truthy("OPENCODE_ENABLE_QUESTION_TOOL")
// When true, the question tool uses the new external-result primitive
// (PR A flag-gated branch); when false (default), it uses the legacy
// Question.ask path. See docs/architecture/2026-05-19-question-as-tool-call.md.
export declare const PAWWORK_QUESTION_TOOL_EXTERNAL_RESULT: boolean

// Experimental
export const OPENCODE_EXPERIMENTAL = truthy("OPENCODE_EXPERIMENTAL")
Expand Down Expand Up @@ -158,6 +162,17 @@ Object.defineProperty(Flag, "OPENCODE_PLUGIN_META_FILE", {
configurable: false,
})

// Dynamic getter for PAWWORK_QUESTION_TOOL_EXTERNAL_RESULT
// Must be evaluated at access time, not module load time, so tests
// can toggle this without restarting the runtime.
Object.defineProperty(Flag, "PAWWORK_QUESTION_TOOL_EXTERNAL_RESULT", {
get() {
return truthy("PAWWORK_QUESTION_TOOL_EXTERNAL_RESULT")
},
enumerable: true,
configurable: false,
})

// Dynamic getter for OPENCODE_CLIENT
// This must be evaluated at access time, not module load time,
// because some commands override the client at runtime
Expand Down
52 changes: 52 additions & 0 deletions packages/opencode/src/server/instance/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { Command } from "../../command"
import { Log } from "@opencode-ai/core/util/log"
import { Permission } from "@/permission"
import { PermissionID } from "@/permission/schema"
import { ExternalResult } from "@/tool/external-result"
import { ModelID, ProviderID } from "@/provider/schema"
import { errors } from "../error"
import { lazy } from "../../util/lazy"
Expand Down Expand Up @@ -447,6 +448,57 @@ export const SessionRoutes = lazy(() =>
return c.json(result)
},
)
.post(
"/:sessionID/tool/respond",
describeRoute({
summary: "Respond to an external-result tool call",
description:
"Resolve a pending external-result Deferred (e.g. question tool) with the user's submitted payload or a dismiss action.",
operationId: "session.toolRespond",
responses: {
200: {
description: "Resolved",
content: { "application/json": { schema: resolver(z.object({ status: z.literal("ok") })) } },
},
...errors(400, 404, 409, 422),
},
}),
validator("param", z.object({ sessionID: SessionID.zod })),
validator(
"json",
z.discriminatedUnion("kind", [
z.object({
kind: z.literal("submit"),
messageID: MessageID.zod,
callID: z.string(),
payload: z.unknown(),
}),
z.object({
kind: z.literal("dismiss"),
messageID: MessageID.zod,
callID: z.string(),
}),
]),
),
async (c) => {
const { sessionID } = c.req.valid("param")
const body = c.req.valid("json")
const { messageID, callID } = body
const lookup = ExternalResult.lookup({ sessionID, messageID, callID })
if (lookup.state === "not_found") return c.json({ error: "no_pending_tool_call" }, 404)
if (lookup.state === "resolved") return c.json({ error: "already_resolved" }, 409)
const value =
body.kind === "dismiss"
? { kind: "dismissed" as const }
: { kind: "submitted" as const, value: body.payload }
const outcome = await AppRuntime.runPromise(
ExternalResult.resolveIfPending({ sessionID, messageID, callID, value }),
)
if (outcome === "resolved") return c.json({ status: "ok" })
if (outcome === "already_resolved") return c.json({ error: "already_resolved" }, 409)
return c.json({ error: "no_pending_tool_call" }, 404)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
},
)
.post(
"/:sessionID/abort",
describeRoute({
Expand Down
11 changes: 10 additions & 1 deletion packages/opencode/src/session/llm.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ import { EffectBridge } from "@/effect"
import * as Option from "effect/Option"
import { LLMTrace } from "./llm-trace"
import { SessionBlocker } from "./blocker"
import { ExternalResult } from "@/tool/external-result"

const log = Log.create({ service: "llm" })
export const OUTPUT_TOKEN_MAX = ProviderTransform.OUTPUT_TOKEN_MAX
Expand Down Expand Up @@ -478,11 +479,19 @@ const live: Layer.Layer<
const arm = () => {
const current = ++sequence
timeout = setTimeout(() => {
// Silent-timeout re-arm guard. We OR two sources:
// (1) the legacy `blockers.hasAwaitingQuestion` (used by
// the flag-off question path, deleted in PR B), and
// (2) `ExternalResult.hasPending` (used by the new
// flag-on path; PR B switches fully). Either path
// re-arms instead of aborting so user-answering-a-
// question sessions are never silently killed.
Effect.runPromise(
Effect.provide(blockers.hasAwaitingQuestion(SessionID.make(input.sessionID)), ctx),
)
.then((blocked) => {
.then((legacyBlocked) => {
if (disposed || current !== sequence) return
const blocked = legacyBlocked || ExternalResult.hasPending(input.sessionID)
if (blocked) {
arm()
return
Expand Down
1 change: 1 addition & 0 deletions packages/opencode/src/session/message-v2.ts
Original file line number Diff line number Diff line change
Expand Up @@ -381,6 +381,7 @@ export const ToolStateError = z
status: z.literal("error"),
input: z.record(z.string(), z.any()),
error: z.string(),
reason: z.enum(["aborted", "shutdown", "tool_failure"]).optional(),
metadata: z.record(z.string(), z.any()).optional(),
time: z.object({
start: z.number(),
Expand Down
8 changes: 8 additions & 0 deletions packages/opencode/src/session/processor.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@ import { classifyToolFailure } from "./tool-failure"
import type { Provider } from "@/provider"
import { ProviderTransform } from "@/provider"
import { Question } from "@/question"
import { ExternalResult } from "@/tool/external-result"
import { errorMessage } from "@/util/error"
import { Log } from "@opencode-ai/core/util/log"
import { isRecord } from "@/util/record"
Expand Down Expand Up @@ -566,12 +567,19 @@ export const layer: Layer.Layer<
// an explicit user dismissal — only the former is "interrupted". See #419.
const questionInterrupted =
match.part.tool === "question" && error instanceof Question.RejectedError && error.cancelled === true
// Narrow writer wiring (v10 P2 #4): only `ExternalResult.Error`
// carries a typed `reason` that survives to ToolStateError.reason.
// Legacy `Question.RejectedError` and every other thrown/defect
// intentionally leave `reason` undefined so the renderer's substring
// fallback for non-question tool errors continues to fire.
const reason = error instanceof ExternalResult.Error ? error.reason : undefined
yield* session.updatePart({
...match.part,
state: {
status: "error",
input: match.part.state.input,
error: errorMessage(error),
...(reason !== undefined ? { reason } : {}),
metadata: SessionDiagnostics.mergeMetadata(toolStateMetadata(match.part), {
diagnostics: {
...(diagnostics ?? {}),
Expand Down
57 changes: 57 additions & 0 deletions packages/opencode/src/session/prompt.ts
Original file line number Diff line number Diff line change
Expand Up @@ -40,6 +40,7 @@ import { SessionProcessor } from "./processor"
import { SessionDiagnostics } from "./diagnostics"
import { LoopRenderer } from "./loop-renderer"
import * as Tool from "@/tool/tool"
import { ExternalResult } from "@/tool/external-result"
import { Permission } from "@/permission"
import { SessionStatus } from "./status"
import { LLM } from "./llm"
Expand Down Expand Up @@ -732,6 +733,62 @@ NOTE: At any point in time through this workflow you should feel free to ask the
ruleset: Permission.merge(input.agent.permission, input.session.permission ?? []),
})
.pipe(Effect.orDie),
externalResult: ({ inputSnapshot }) =>
Effect.gen(function* () {
const sessionID = input.session.id
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
const messageID = input.processor.message.id
const callID = options.toolCallId
const deferred = yield* ExternalResult.register({
sessionID,
messageID,
callID,
inputSnapshot,
})
// Flip the running tool part's metadata flag so the renderer's
// "preparing..." placeholder transitions to active input controls.
// The dock / inline marker key on `metadata.externalResultReady`.
yield* input.processor.updateToolCall(callID, (match) => {
if (match.state.status !== "running") return match
const existing =
"metadata" in match.state && match.state.metadata && typeof match.state.metadata === "object"
? match.state.metadata
: {}
return {
...match,
state: {
...match.state,
metadata: { ...existing, externalResultReady: true },
},
}
})
Comment thread
Astro-Han marked this conversation as resolved.
Resolved
// Wire the AbortSignal: a turn abort flips the pending Deferred
// to ExternalResultError({reason: "aborted"}). Session destroy is
// handled separately by ExternalResult.onSessionDestroyed.
const abortHandler = () => {
run.promise(
ExternalResult.failIfPending({
sessionID,
messageID,
callID,
error: new ExternalResult.Error({ reason: "aborted" }),
}),
).catch(() => {})
}
const signal = options.abortSignal
if (signal) {
if (signal.aborted) {
abortHandler()
} else {
signal.addEventListener("abort", abortHandler, { once: true })
}
}
try {
const result = yield* Deferred.await(deferred)
return result as Tool.ExternalResultOutcome
} finally {
if (signal) signal.removeEventListener("abort", abortHandler)
}
}),
})

for (const item of yield* registry.tools({
Expand Down
8 changes: 8 additions & 0 deletions packages/opencode/src/session/session.ts
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ import { Runtime } from "@opencode-ai/core/runtime"
import type { Provider } from "@/provider"
import { Permission } from "@/permission"
import { Question } from "@/question"
import { ExternalResult } from "@/tool/external-result"
import { SessionBlocker } from "@/session/blocker"
import { Global } from "@/global"
import { Effect, Layer, Option, Context } from "effect"
Expand Down Expand Up @@ -585,6 +586,13 @@ export const layer: Layer.Layer<Service, never, Bus.Service | Storage.Service> =
yield* SessionBlocker.Service.use((svc) => svc.clearSession(sessionID, reason)).pipe(
Effect.provide(SessionBlocker.defaultLayer),
)
// Tear down external-result Deferreds held for this session. Pending
// entries' Deferreds are rejected with ExternalResultError({reason:
// "shutdown"}) so the running tool transitions to error state with the
// right durable reason. This hook fires on session delete / archive
// only — NOT on turn abort (that path runs through ctx.abort →
// failIfPending with reason: "aborted"). The two paths never overlap.
yield* ExternalResult.onSessionDestroyed(sessionID)
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
})

const createNext = Effect.fn("Session.createNext")(function* (input: {
Expand Down
Binary file added packages/opencode/src/tool/external-result.ts
Binary file not shown.
Loading