|
5 | 5 | // the reason; a plain rejection rejects with a Permission.DeclinedError defect, which a tool must |
6 | 6 | // rethrow so opencode ends the step as it does for its own tools (core/src/plugin/host.ts). |
7 | 7 | // |
8 | | -// The `workflow` tool call is the only interactive path: a workflow() call inside a running script |
9 | | -// happens in the background, where a prompt would hold the run on a user who may not be there (and |
10 | | -// could outlive the run, since assert takes no abort signal). Those asserts carry a metadata marker, |
11 | | -// and this plugin's evaluate hook turns their "ask" into a deny: saved approvals and allow rules |
12 | | -// still admit the file, nothing prompts. |
| 8 | +// assert takes no abort signal (the plugin adapter runs it in its own fiber) and core drops a pending |
| 9 | +// prompt only when that fiber ends, so a prompt would outlive whoever waits on it. Every assert made |
| 10 | +// here is therefore bounded, and when its caller gives up the prompt it raised is withdrawn by |
| 11 | +// replying "reject" to it (permission.list → the request with our tool call as `source`, or our |
| 12 | +// nonce in `metadata`). Core applies a reject to every pending prompt of that session (a batch), so |
| 13 | +// a withdrawal also rejects any other prompt open in the parent session at that moment. |
| 14 | +// |
| 15 | +// The `workflow` tool call is the only interactive path, bounded by the call's abort signal (the |
| 16 | +// user cancelling the call). A workflow() call inside a running script happens in the background, |
| 17 | +// where a prompt would hold the run on a user who may not be there. Those asserts carry a metadata |
| 18 | +// marker that this plugin's evaluate hook turns from "ask" into a deny, so saved approvals and allow |
| 19 | +// rules still admit the file and nothing prompts. Another plugin's evaluate hook runs after ours and |
| 20 | +// could turn it back into an ask: such an assert also has a short timeout, after which it counts as |
| 21 | +// refused (fail closed) and its prompt is withdrawn. |
13 | 22 |
|
14 | 23 | import type { Plugin } from "@opencode/plugin" |
15 | 24 |
|
@@ -24,8 +33,25 @@ export interface AssertRequest { |
24 | 33 | source?: { type: "tool"; messageID: string; id: string } |
25 | 34 | } |
26 | 35 |
|
27 | | -/** Resolves when allowed; rejects as `ctx.permission.assert` does (see the header). */ |
28 | | -export type AssertPermission = (request: AssertRequest, mode: { interactive: boolean }) => Promise<void> |
| 36 | +export interface AssertMode { |
| 37 | + /** A tool call the user is watching: a prompt may be shown. */ |
| 38 | + interactive: boolean |
| 39 | + /** Gives up (and withdraws the prompt) when aborted: the tool call's signal. */ |
| 40 | + signal?: AbortSignal |
| 41 | +} |
| 42 | + |
| 43 | +/** |
| 44 | + * Resolves when allowed; rejects as `ctx.permission.assert` does (see the header), with an |
| 45 | + * AbortError when `mode.signal` aborts first, and with UNATTENDED_ASK_MESSAGE when an unattended |
| 46 | + * check is still waiting after its timeout. |
| 47 | + */ |
| 48 | +export type AssertPermission = (request: AssertRequest, mode: AssertMode) => Promise<void> |
| 49 | + |
| 50 | +/** How long an unattended check may wait (it should never wait: our evaluate hook denies its ask). */ |
| 51 | +export const UNATTENDED_ASSERT_TIMEOUT_MS = 3000 |
| 52 | + |
| 53 | +/** metadata key holding a per-assert id, to find (and withdraw) the prompt an unattended assert raised. */ |
| 54 | +export const ASSERT_ID_METADATA_KEY = "workflowAssertId" |
29 | 55 |
|
30 | 56 | /** Metadata key that marks an assert nobody can answer (a workflow() call inside a running script). */ |
31 | 57 | export const UNATTENDED_METADATA_KEY = "workflowUnattended" |
@@ -34,6 +60,17 @@ export const UNATTENDED_ASK_MESSAGE = |
34 | 60 | "workflow() inside a running workflow cannot ask for approval, so the request was refused. Add an allow " + |
35 | 61 | 'rule, or approve it with "always" when a workflow tool call asks for it' |
36 | 62 |
|
| 63 | +/** The caller gave up (its signal aborted) before the check finished; any prompt was withdrawn. */ |
| 64 | +export function isPermissionCancelled(e: unknown): boolean { |
| 65 | + return e instanceof Error && e.name === "AbortError" |
| 66 | +} |
| 67 | + |
| 68 | +function cancelled(): Error { |
| 69 | + const e = new Error("the workflow tool call was cancelled while waiting for approval; no run was started") |
| 70 | + e.name = "AbortError" |
| 71 | + return e |
| 72 | +} |
| 73 | + |
37 | 74 | /** A user's plain rejection of the prompt (core Permission.DeclinedError, tunnelled as a defect). */ |
38 | 75 | export function isPermissionDecline(e: unknown): boolean { |
39 | 76 | return !!e && typeof e === "object" && (e as { _tag?: unknown })._tag === "Permission.DeclinedError" |
@@ -53,20 +90,94 @@ export function createUnattendedAskGuard() { |
53 | 90 | * before 2.3.0) or no evaluate hook (an unattended assert could then prompt): callers then evaluate the |
54 | 91 | * rules themselves. The caller registers createUnattendedAskGuard() when this returns a function. |
55 | 92 | */ |
56 | | -export function createPermissionAsserter(ctx: Pick<Plugin.Context, "permission">): AssertPermission | undefined { |
| 93 | +export interface PermissionAsserterOptions { |
| 94 | + /** Default UNATTENDED_ASSERT_TIMEOUT_MS. */ |
| 95 | + unattendedTimeoutMs?: number |
| 96 | + /** Withdrawal polls permission.list until the assert settles: this often, at most this many times. */ |
| 97 | + withdrawIntervalMs?: number |
| 98 | + withdrawTries?: number |
| 99 | +} |
| 100 | + |
| 101 | +export function createPermissionAsserter( |
| 102 | + ctx: Pick<Plugin.Context, "permission">, |
| 103 | + opts: PermissionAsserterOptions = {}, |
| 104 | +): AssertPermission | undefined { |
57 | 105 | const permission = (ctx as any).permission as Partial<Plugin.Context["permission"]> | undefined |
58 | 106 | if (typeof permission?.assert !== "function" || typeof permission.hook !== "function") return undefined |
59 | | - return async (request, mode) => { |
| 107 | + const intervalMs = opts.withdrawIntervalMs ?? 50 |
| 108 | + const tries = opts.withdrawTries ?? 100 |
| 109 | + let seq = 0 |
| 110 | + return (request, mode) => { |
| 111 | + if (mode.signal?.aborted) return Promise.reject(cancelled()) |
| 112 | + const assertId = `${Date.now().toString(36)}-${++seq}-${Math.random().toString(36).slice(2, 8)}` |
60 | 113 | const input: Record<string, unknown> = { |
61 | 114 | sessionID: request.sessionID, |
62 | 115 | action: request.action, |
63 | 116 | resources: request.resources, |
64 | 117 | } |
65 | 118 | if (request.agent) input.agent = request.agent |
66 | 119 | if (request.save?.length) input.save = request.save |
67 | | - const metadata = mode.interactive ? request.metadata : { ...request.metadata, [UNATTENDED_METADATA_KEY]: true } |
| 120 | + const metadata = mode.interactive |
| 121 | + ? request.metadata |
| 122 | + : { ...request.metadata, [UNATTENDED_METADATA_KEY]: true, [ASSERT_ID_METADATA_KEY]: assertId } |
68 | 123 | if (metadata) input.metadata = metadata |
69 | 124 | if (mode.interactive && request.source) input.source = request.source |
70 | | - await permission.assert!(input as any) |
| 125 | + const ours = (r: any): boolean => |
| 126 | + mode.interactive |
| 127 | + ? !!request.source && r?.source?.type === "tool" && r.source.id === request.source.id && r.source.messageID === request.source.messageID |
| 128 | + : r?.metadata?.[ASSERT_ID_METADATA_KEY] === assertId |
| 129 | + |
| 130 | + let settled = false |
| 131 | + const asserted = Promise.resolve().then(() => permission.assert!(input as any)) |
| 132 | + asserted.then( |
| 133 | + () => void (settled = true), |
| 134 | + () => void (settled = true), |
| 135 | + ) |
| 136 | + // The prompt may not exist yet when the caller gives up: keep looking until the assert settles. |
| 137 | + const withdraw = async () => { |
| 138 | + for (let i = 0; i < tries && !settled; i++) { |
| 139 | + try { |
| 140 | + const res = (await permission.list!({ sessionID: request.sessionID } as any)) as any |
| 141 | + const list: any[] = Array.isArray(res) ? res : Array.isArray(res?.data) ? res.data : [] |
| 142 | + for (const r of list) { |
| 143 | + if (!ours(r) || typeof r.id !== "string") continue |
| 144 | + await permission.reply!({ sessionID: request.sessionID, requestID: r.id, decision: "reject" } as any).catch(() => {}) |
| 145 | + } |
| 146 | + } catch {} |
| 147 | + if (!settled) await new Promise((r) => setTimeout(r, intervalMs)) |
| 148 | + } |
| 149 | + } |
| 150 | + const timeoutMs = mode.interactive ? undefined : (opts.unattendedTimeoutMs ?? UNATTENDED_ASSERT_TIMEOUT_MS) |
| 151 | + |
| 152 | + return new Promise<void>((resolve, reject) => { |
| 153 | + let timer: ReturnType<typeof setTimeout> | undefined |
| 154 | + const done = () => { |
| 155 | + if (timer) clearTimeout(timer) |
| 156 | + mode.signal?.removeEventListener("abort", onAbort) |
| 157 | + } |
| 158 | + const giveUp = (error: Error) => { |
| 159 | + done() |
| 160 | + reject(error) |
| 161 | + void withdraw() |
| 162 | + } |
| 163 | + const onAbort = () => giveUp(cancelled()) |
| 164 | + mode.signal?.addEventListener("abort", onAbort, { once: true }) |
| 165 | + if (timeoutMs !== undefined) { |
| 166 | + timer = setTimeout(() => giveUp(new Error(UNATTENDED_ASK_MESSAGE)), timeoutMs) |
| 167 | + ;(timer as any).unref?.() |
| 168 | + } |
| 169 | + asserted.then( |
| 170 | + () => { |
| 171 | + done() |
| 172 | + // Allowed just as the caller gave up: still not allowed to start anything. |
| 173 | + if (mode.signal?.aborted) reject(cancelled()) |
| 174 | + else resolve() |
| 175 | + }, |
| 176 | + (e) => { |
| 177 | + done() |
| 178 | + reject(e) |
| 179 | + }, |
| 180 | + ) |
| 181 | + }) |
71 | 182 | } |
72 | 183 | } |