GV

GeezerVison

The World Wide Web, restored to 800 pixels of glory.

Home|About|Gaming cabinet|Archives|How it works|Starter sites

On this site

  • Sign in
  • ActionsCI/CD and automation
  • CodespacesCloud development environments
  • All Features
  • Documentation
  • Training
  • Certifications
  • Build with Copilot
  • Customize Copilot
  • Integrations
  • Trending repos
  • GitHub Sponsors
  • Developer articles
  • Enterprises

This view

  • Original page
  • New address

GeezerVison is showing github.com — fix: P76 approval prompts never outlive their caller; a deny on any s… · rphang/opencode-workflows@4c81591

File tree

Expand file treeCollapse file tree
Open diff view settings
Filter options
  • docs
    • OPENCODE-API-NOTES.md
    • PARITY.md
  • src
    • opencode
      • permission-assert.ts
    • plugin
      • host.ts
      • setup.ts
      • tools.ts
  • tests
    • helpers
      • fake-opencode-ctx.ts
    • parity
      • cc-extras.test.ts
    • unit
      • permission-assert.test.ts
Expand file treeCollapse file tree
Open diff view settings
Collapse file

‎docs/OPENCODE-API-NOTES.md‎

Copy file name to clipboardExpand all lines: docs/OPENCODE-API-NOTES.md
+6-1Lines changed: 6 additions & 1 deletion
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -54,7 +54,12 @@ the 2.3.0 packages and `tsc` is clean against their types.
5454
rejection with feedback rejects with a `Tool.Error` (`_tag: "Tool.Error"`, `message`); a plain
5555
rejection rejects with the `Permission.DeclinedError` defect (`_tag: "Permission.DeclinedError"`),
5656
which a tool must rethrow so the step ends. `source: {type:"tool", messageID, id}` ties the prompt
57-
to a tool call. There is no abort signal: a pending prompt stays until answered. P76 uses it.
57+
to a tool call. There is no abort signal: the adapter runs it in its own fiber, and core drops a
58+
pending prompt only when that fiber ends, so a prompt stays until answered even after the tool call
59+
is cancelled. `permission.list({sessionID})` lists the session's pending requests (`{id, action,
60+
resources, source?, metadata?, …}`) and `permission.reply({sessionID, requestID, decision:
61+
"once"|"always"|"reject", message?})` answers one; a `reject` also rejects every other pending
62+
request of that session. P76 uses assert, and list + reply to withdraw a prompt nobody waits on.
5863
- **Session `context` hook** (`ctx.session.hook("context", cb)`): runs before each primary model
5964
request with `{sessionID, agent, model: {providerID, id, variant?}, system, messages, options,
6065
tools: {[name]: {description, input}}}` (a copy); deleting a `tools` key drops that tool from the
Collapse file

‎docs/PARITY.md‎

Copy file name to clipboardExpand all lines: docs/PARITY.md
+2-2Lines changed: 2 additions & 2 deletions
  • Display the source diff
  • Display the rich diff
Original file line numberDiff line numberDiff line change
@@ -107,7 +107,7 @@ Install methods, env vars and the user-facing summary of DEGRADED/N/A items: `RE
107107
| P73 | Restart one running agent (`r` in `/workflows`) | DEGRADED (no restart action. Use `stop_agent` (the agent counts as failed and `agent()` returns `null`), or stop the run and relaunch with `resumeFromRunId`: that agent and every later one run again) | `cc-extras.test.ts` "P73 …" ×1 |
108108
| P74 | Each agent's full transcript can be opened from the run view | DEGRADED (the transcript is the agent's opencode child session, tagged `[wf:<runId>]` (P62); `agents/<i>.json` in the transcript dir holds its prompt, result, usage and that `sessionID`, and `/workflows <runId>` shows prompt and result as one clipped line) | `cc-extras.test.ts` "P74 …" ×1 |
109109
| P75 | Run management (status, stop, stop one agent, pause/resume, save, `/workflows <runId>`) only acts on the current session's own runs | FULL (another session's run, live or on disk, answers "not found in this session", the same as an unknown id, so ids cannot be probed) | `cc-extras.test.ts` "P75 …" ×2 |
110-
| P76 | `scriptPath` (tool input and `workflow({scriptPath})`) only reads files the session may read | DEGRADED (a file whose real path (links resolved) is outside the project dir, this session's run store and the personal workflows dir needs `external_directory` for its directory, then every file needs `read`; UNC/device paths are refused before any file access; nothing is copied into the run dir when refused. The plugin first evaluates the caller's agent and session rules itself: a deny (on any spelling of the path) refuses without asking, and the spelling a rule allows is the one checked next. On opencode 2.3.0 the rest goes through `ctx.permission.assert` with the read tool's resources (`<dir>/*` saved as `<dir>/*`; the file, saved as `*`), so saved "always" approvals and evaluate hooks apply. For a `workflow` tool call it shows opencode's prompt in the calling (root) session, tied to that call; a rejection with feedback or a deny is the tool's `error`, a plain rejection is rethrown so opencode ends the step as for its own tools. `workflow({scriptPath})` inside a running script never prompts (no one may be there, and a prompt cannot be withdrawn when the run stops): its asserts carry a marker that the plugin's `permission.evaluate` hook turns from "ask" into deny. Without `assert` (or without the evaluate hook) an `external_directory` "ask" counts as refused and `read` refuses only on deny) | `cc-extras.test.ts` "P76 …" ×14 |
110+
| P76 | `scriptPath` (tool input and `workflow({scriptPath})`) only reads files the session may read | DEGRADED (a file whose real path (links resolved) is outside the project dir, this session's run store and the personal workflows dir needs `external_directory` for its directory, then every file needs `read`; UNC/device paths are refused before any file access; nothing is copied into the run dir when refused. The plugin first evaluates the caller's agent and session rules itself: a deny (on any spelling of the path) refuses without asking, and the spelling a rule allows is the one checked next. On opencode 2.3.0 the rest goes through `ctx.permission.assert` with the read tool's resources (`<dir>/*` saved as `<dir>/*`; the file, saved as `*`), so saved "always" approvals and evaluate hooks apply. For a `workflow` tool call it shows opencode's prompt in the calling (root) session, tied to that call; a rejection with feedback or a deny is the tool's `error`, a plain rejection is rethrown so opencode ends the step as for its own tools. `assert` takes no abort signal, so when the call is cancelled (its `signal`, read only for a scriptPath launch) the plugin stops waiting, withdraws the prompt by replying `reject` to the pending request whose `source` is that call (opencode rejects every prompt then open in that session), and starts no run, also when the approval lands just then. `workflow({scriptPath})` inside a running script never prompts (no one may be there, and a prompt cannot be withdrawn when the run stops): its asserts carry a marker that the plugin's `permission.evaluate` hook turns from "ask" into deny. It fails closed even when a later plugin's evaluate hook turns that back into an ask: such a check counts as refused after 3 s and the prompt it raised (found by a per-assert id in its `metadata`) is withdrawn the same way. Without `assert` (or without the evaluate hook) an `external_directory` "ask" counts as refused and `read` refuses only on deny) | `cc-extras.test.ts` "P76 …" ×18<br>unit `permission-assert.test.ts` "P76 …" ×6 |
111111
| P77 | Single delivery path: a run's result reaches the parent model only as the task notification (Claude Code has no model-facing status tool that returns it). After launching, the model ends its turn and does not poll, sleep or shell-wait | FULL (`workflow_control` status/list exist for when the user asks about progress, but they never include the run's result or per-agent result previews, nor what a running agent is writing or thinking (they show `writing…` / `thinking…`). For a running/paused run they tell the model to end its turn; for a finished run they say the result is delivered as the task notification (end the turn if not received yet). That note names no file and no other action (it used to point to `run.json`, which sent a model to read files and raised `external_directory` asks), so before the notification a status call offers nothing new. From the 2nd status/`result` call on the same run by the same session since the run last changed state, the note adds "Repeating this call does not wait or speed anything up." The run's per-agent values reach the model through `workflow_control` `result` (X21) once the run has FINISHED; while it runs or is paused, `result` returns the same note byte for byte. Residual (model behavior, wording only): some models still poll status while a run is going (seen with nemotron), and a model may read a finished run's agents before its notification arrives and then report twice; both were accepted over a notification gate, note 12. The user-facing `/workflows <runId>` always shows the result. The `workflow` tool description, its launch `summary`, the `workflow_control` description and the authoring reference all say to end the turn after launching; note 10) | `delivery.test.ts` "P77 …" ×7, "P79 P77 …" ×1<br>`live-tree.test.ts` "P77 X11 …" ×1<br>`results.test.ts` "X21 P77 …" ×2<br>unit `plugin.test.ts` "P77 …" ×2 |
112112
| P78 | Workflow subagents know they run non-interactively inside a script: nobody answers questions, and their final message is returned verbatim to the script as data | FULL (every plain child prompt starts with `SUBAGENT_PREAMBLE` (`src/opencode/runner.ts`): no human, no questions or confirmations (assume and continue), final message = only the requested content in the requested format, assumptions only if that format has room, no workflows. Schema agents get `STRUCTURED_SUBAGENT_PREAMBLE` (the `workflow_submit` call is the answer; no "final text answer" wording) and the `workflow_submit` instructions after the task. The resume key (P41) hashes the script's own prompt, so adding the preamble does not change it; the resume-key test is a regression guard, it passed before P78 too) | `subagents.test.ts` "P78 …" ×4 |
113113
| P79 | The task notification tells the model where each agent's own result is and to check it BEFORE diagnosing an empty or unexpected result ("do not assume agents returned non-empty results"). Claude Code names `<transcriptDir>/journal.jsonl` (one `{type:'result',...}` line per completed agent) | ADAPTED (every notification of a run that started an agent ends with `<diagnostics>`, after `<transcript-dir>`: "Per-agent results: workflow_control {action:"result", runId:"<runId>"} lists every agent (failed ones first) with a preview of its return value or error; add agent:"<index or label>" for one agent's full return value. If the result above is empty or unexpected, check this BEFORE diagnosing — do not assume agents returned non-empty results. If you cannot use it, tell the user to open /workflows <runId>; do not read the transcript files with shell commands." It points at the action (X21), not the file: the transcript dir is outside the project, so each read raises an `external_directory` ask (in a headless `opencode serve` turn with no client attached the turn blocks on it), and opencode's `read` cuts lines at 2000 characters, so a journal line with a long value cannot be read whole. The `workflow` tool description has a PER-AGENT OUTPUTS paragraph for after the notification; the launch output, status and list never point at it (P77). Bake-off: `docs/design/agent-output-access.md`) | `delivery.test.ts` "P79 …" ×3<br>e2e `results.test.ts` (live) |
@@ -150,7 +150,7 @@ Design: [`docs/design/steering-and-live-tree.md`](design/steering-and-live-tree.
150150

151151
## Test evidence
152152

153-
`npm run test:parity` (`bun test tests/parity`) runs 359 tests in 15 files, and all pass. They
153+
`npm run test:parity` (`bun test tests/parity`) runs 363 tests in 15 files, and all pass. They
154154
enter at the highest level possible: the plugin's `setup()` over a fake opencode v2 Context
155155
(`tests/helpers/plugin-harness.ts`), then the `workflow` and `workflow_control` tools
156156
(`execute`), the slash commands, and the `<task-notification>` delivered through
Collapse file

‎src/opencode/permission-assert.ts‎

Copy file name to clipboardExpand all lines: src/opencode/permission-assert.ts
+122-11Lines changed: 122 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,20 @@
55
// the reason; a plain rejection rejects with a Permission.DeclinedError defect, which a tool must
66
// rethrow so opencode ends the step as it does for its own tools (core/src/plugin/host.ts).
77
//
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.
1322

1423
import type { Plugin } from "@opencode/plugin"
1524

@@ -24,8 +33,25 @@ export interface AssertRequest {
2433
source?: { type: "tool"; messageID: string; id: string }
2534
}
2635

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"
2955

3056
/** Metadata key that marks an assert nobody can answer (a workflow() call inside a running script). */
3157
export const UNATTENDED_METADATA_KEY = "workflowUnattended"
@@ -34,6 +60,17 @@ export const UNATTENDED_ASK_MESSAGE =
3460
"workflow() inside a running workflow cannot ask for approval, so the request was refused. Add an allow " +
3561
'rule, or approve it with "always" when a workflow tool call asks for it'
3662

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+
3774
/** A user's plain rejection of the prompt (core Permission.DeclinedError, tunnelled as a defect). */
3875
export function isPermissionDecline(e: unknown): boolean {
3976
return !!e && typeof e === "object" && (e as { _tag?: unknown })._tag === "Permission.DeclinedError"
@@ -53,20 +90,94 @@ export function createUnattendedAskGuard() {
5390
* before 2.3.0) or no evaluate hook (an unattended assert could then prompt): callers then evaluate the
5491
* rules themselves. The caller registers createUnattendedAskGuard() when this returns a function.
5592
*/
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 {
57105
const permission = (ctx as any).permission as Partial<Plugin.Context["permission"]> | undefined
58106
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)}`
60113
const input: Record<string, unknown> = {
61114
sessionID: request.sessionID,
62115
action: request.action,
63116
resources: request.resources,
64117
}
65118
if (request.agent) input.agent = request.agent
66119
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 }
68123
if (metadata) input.metadata = metadata
69124
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+
})
71182
}
72183
}

0 commit comments

Comments
0 (0)
You are visitor 01402792 — GeezerVison does not store the pages you look up.
Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required.