GeezerVison is showing github.com — feat: freeform workflow_script tool for raw-text inline scripts (X24) · rphang/opencode-workflows@c151e24
File treeExpand file treeCollapse file tree Open diff view settings Expand file treeCollapse file tree Open diff view settings Collapse file Copy file name to clipboardExpand all lines: README.md +6Lines changed: 6 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -79,6 +79,10 @@ run (6 agents, under a minute) is in [`demo/DEMO-OUTPUT.md`](demo/DEMO-OUTPUT.md | 79 | 79 |
| 80 | 80 | - **`workflow` tool** with the same script API as Claude Code's workflow tool: `agent()`, | 81 | 81 | `parallel()`, `pipeline()`, `phase()`, `log()`, `args`, `budget` and nested `workflow()`. | | 82 | +- **Raw-text scripts (extension).** On models whose capabilities list freeform text input (opencode | | 83 | + 2.3+), a `workflow_script` tool takes a new inline script as plain text instead of a JSON-escaped | | 84 | + string. It is the `workflow` tool with only `{script}`, under the same permission; the `workflow` | | 85 | + tool itself is unchanged. Turn it off with `freeformTool: false` or `OPENCODE_WORKFLOW_FREEFORM=0`. | 82 | 86 | - **Structured output.** `agent(prompt, { schema })` resolves to a JSON object validated against | 83 | 87 | your JSON Schema, and the agent retries when its output doesn't match. | 84 | 88 | - **Background runs.** The tool returns immediately. The result comes back as a task notification | @@ -469,6 +473,7 @@ Plugin options (config install only, see [Install](#other-options)): | 469 | 473 | | `disabled: true` | Registers no tools or commands. | | 470 | 474 | | `sizeGuideline` | `unrestricted`, `small`, `medium` (default) or `large`: tells the model to aim for fewer than ∞, 5, 10 or 50 agents. | | 471 | 475 | | `dataDir` | Where run transcripts are stored. Takes precedence over `OPENCODE_WORKFLOW_DATA_DIR`. | | | 476 | +| `freeformTool: false` | Registers no `workflow_script` tool: the model launches new inline scripts with the `workflow` tool only. | | 472 | 477 | | `rpcControl: false` | Makes the live tree's RPC read-only: the tree still shows runs, but its `x`, `p` and `m` keys (and any other RPC client) cannot stop, pause or message them. `/workflows msg` and `workflow_control` still work. See [Security model](#security-model). | | 473 | 478 |
| 474 | 479 | ## Environment variables | @@ -482,6 +487,7 @@ Set them in the environment of the opencode server. They work with every install | 482 | 487 | | `OPENCODE_WORKFLOW_SIZE_GUIDELINE` | `medium` | Same as the `sizeGuideline` option. The env var wins. | | 483 | 488 | | `OPENCODE_WORKFLOW_AGENT_TIMEOUT_MS` | unset (no timeout) | Per-agent timeout. An agent that exceeds it fails, and `agent()` returns `null`. | | 484 | 489 | | `MAX_STRUCTURED_OUTPUT_RETRIES` (or `OPENCODE_WORKFLOW_MAX_STRUCTURED_OUTPUT_RETRIES`) | `5` | Attempts a schema agent gets before `agent()` throws. | | | 490 | +| `OPENCODE_WORKFLOW_FREEFORM` | unset (on) | `0`, `false`, `no` or `off` registers no `workflow_script` tool, like the `freeformTool: false` option. | | 485 | 491 | | `OPENCODE_WORKFLOW_RPC_CONTROL` | unset (on) | `0`, `false`, `no` or `off` makes the live tree's RPC read-only, like the `rpcControl: false` option. | | 486 | 492 | | `OPENCODE_WORKFLOW_DATA_DIR` | `$XDG_DATA_HOME/opencode/workflows`, else `%LOCALAPPDATA%\opencode\workflows` (Windows) or `~/.local/share/opencode/workflows` | Run transcripts, stored as `<dir>/<sessionID>/<runId>/`. The `dataDir` plugin option wins over it. | | 487 | 493 |
| |
Collapse file Copy file name to clipboardExpand all lines: docs/PARITY.md +1Lines changed: 1 addition & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -141,6 +141,7 @@ Design: [`docs/design/steering-and-live-tree.md`](design/steering-and-live-tree. | 141 | 141 | | X19 | The agent's model is shown in `/workflows <runId>` and `workflow_control status` (a `model:` line per agent), in the RPC `list`/`status`/`delta` agent views (`model`) and on the TUI agent rows. A running agent whose live step (`session.step.started`) runs on another model than the recorded one shows the live one. A phase without a `meta.phases[].model` label shows the model its agents share (`PhaseSummary.agentModel` in run.json; the RPC phase view keeps listing up to two distinct models). TUI rows show the model in short form when narrow: the provider goes first, then the variant (`gpt-5.4-mini`), then the name is shortened and dropped after the activity; status, counts, tokens, cost and elapsed time always show. A phase label that is a `provider/model` ref is shortened the same way | EXT | `live-tree.test.ts` "X19 …" ×2<br>`tui.test.ts` "X19 …" ×2 | | 142 | 142 | | X20 | The task notification of a run that failed, or that has agents whose `agent()` call gave the script nothing, carries `<agent-failures>` (after `<warnings>`/`<steering>`, before `<script-path>`): `N of M agents returned no result (a failed, b stopped, c null[, d running]):`, then at most 10 lines `#<i> "<label>" <status>[ (agent() threw)][ in workflow "<name>"]: <first line of the error>` (labels and errors whitespace-folded, label ≤ 60, workflow name ≤ 40, error ≤ 160 characters; `returned null` for a completed/cached agent whose value was null; `stop_agent` shows as `failed: stopped by user`, P51; `(agent() threw)` for a schema agent whose output never validated, P21, `AgentRecord.threw`; `in workflow` for an agent a nested `workflow()` started, `AgentRecord.workflow`), then `… and K more: workflow_control {action:"result", runId:"<id>"} lists failed agents first.` The whole block is capped at 2,800 bytes of UTF-8 (`FAILURE_BLOCK_BYTES`): the per-line caps count characters, so lines that would overflow (3-digit index, `(agent() threw)`, nested workflow, multi-byte text) are folded into the `… and K more` count instead, and it stays under 3 KB with 1000 failing agents. A failed run with no such agent says "No agent failed: the error above was raised by the script itself (this includes agent() calls refused before an agent started: budget, agent cap, invalid options/schema)." Limit: a refused `agent()` call (budget, 1000-agent cap, schema preflight) leaves no agent record, so only that wording acknowledges it; inside `pipeline`/`parallel` it becomes a silent `null` that neither block names (an engine-side refusal counter is a follow-up) | EXT | `delivery.test.ts` "X20 …" ×7<br>unit `plugin.test.ts` "X20 …" ×1<br>e2e `results.test.ts` (live) | | 143 | 143 | | X21 | `workflow_control {action:"result", runId, agent?, offset?}` shows the parent model what each agent of a FINISHED run (completed, failed or stopped; also a resumed run, and a run read from disk after a plugin reload) returned, right away, before or after its notification arrives. Without `agent` (or with `""`): a header `Run <id> <status>: M agents: a completed, b cached, c failed, d stopped, e null`, then one row per agent, failed, stopped and null ones first, then the rest by index: `#i "label" status [phase] (workflow <name>) <tokens> tokens → <first line ≤ 100>` or `error: <first line ≤ 120>`; 50 rows per page with the footer `Rows X–Y of M. Next: {action:"result", runId:"<id>", offset:Y}`. `agent` is a string: `"9"` or `"#9"` is an index (when that index exists; a different agent labeled `"9"` is then named in a note), anything else an exact label; an ambiguous label lists up to 20 candidates, an unknown one is an error with the agent count. One agent: status, phase, nested workflow, `cached: replayed from run <id>; did not run again`, model, child session id, usage, duration, the first 500 characters of the prompt, the full error, warnings, its last 5 steering messages (each ≤ 500 characters), the kept worktree, then its return value (a string as is, anything else as indented JSON), 50 000 characters per page with `chars X–Y of Z; next offset Y`; a null agent says `agent() returned null to the script (<reason>)` (`agent() threw in the script (…)` for P21). While the run is running or paused it returns the P77 status note byte for byte, never an output. No other parameters: the fields models filled out of habit in the eval (`agentIndex`, `label`, `status`, `limit`, `maxChars`) are ignored, so a filled-in `status:"completed"` cannot hide failed agents. Scoped like every run action (P75); workflow agents cannot call it (P60) | EXT | `results.test.ts` "X21 …" ×15<br>e2e `results.test.ts` (live) | | | 144 | +| X24 | Freeform `workflow_script` tool (opencode 2.3.0 freeform tool input): a NEW inline script sent as raw text instead of JSON-escaped `{script}`. Input schema `{script: string}` (exactly one required string property, as opencode requires) with `freeform: {type: "text"}`; execute always receives `{script}` and takes the same launch path as `workflow {script}` (same output, P02; persisted script and `scriptPath`, P04; P03 errors). A single code fence wrapping the whole input is stripped. Any other key with a value (a JSON call from a model without freeform input) returns `status:"async_launched"` with the error `workflow_script takes only the script; use the workflow tool for args, name, scriptPath, resumeFromRunId or budget`, and nothing runs. `options.permission: "workflow"`: opencode hides a tool whose permission key (`options.permission ?? name`) is wholly denied, so every deny of `workflow` (workflow children P60, Plan mode, user and agent rules) hides it too; there is no separate rule. The session `context` hook drops it from requests whose model's `capabilities.freeform` (from `ctx.model.list()`, cached 5 min) does not list `text`; an unknown model keeps it (it still works as a JSON tool). The `workflow` tool's schema, options and description are unchanged (Claude Code parity, prompt caching). Opt out with the plugin option `freeformTool: false` or env `OPENCODE_WORKFLOW_FREEFORM=0` (`false`, `no`, `off`). The authoring reference tells the model to use it for new inline scripts when it is offered | EXT (the model-side raw-text encoding is opencode's and is not live-verified here) | `tool-surface.test.ts` "X24 …" ×11, "P01 …" (workflow tool unchanged) | | 144 | 145 |
| 145 | 146 | ## Test evidence | 146 | 147 |
| |
Collapse file Copy file name to clipboardExpand all lines: docs/SCRIPT-API.md +5Lines changed: 5 additions & 0 deletions - Display the source diff
- Display the rich diff
| Original file line number | Diff line number | Diff line change |
|---|
@@ -35,6 +35,11 @@ If the script fails its syntax or meta check, the result also has `error` set an | 35 | 35 | Every launch persists the script and returns its path as `scriptPath`, so an edited copy can be | 36 | 36 | relaunched with `{ scriptPath }`. | 37 | 37 |
| | 38 | +`workflow_script` (extension, [PARITY](PARITY.md) X24) is the same launch with only `script`, for | | 39 | +models that can send a tool's input as raw text: its whole input is the script source, with no JSON | | 40 | +escaping. It is dropped for models whose capabilities do not list freeform text, and is turned off | | 41 | +with the plugin option `freeformTool: false` or `OPENCODE_WORKFLOW_FREEFORM=0`. | | 42 | + | 38 | 43 | When the run finishes, stops or fails, its return value arrives in the parent session as a | 39 | 44 | `<task-notification>`, with the status and usage (agent count, tokens, duration). That is the only | 40 | 45 | way the result reaches the model. `workflow_control status` shows progress, never the result. | |
Collapse file Copy file name to clipboardExpand all lines: src/authoring.ts +3Lines changed: 3 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
@@ -36,6 +36,9 @@ deciding the next. | 36 | 36 | and objects as real JSON values — \`args: ["a.ts", "b.ts"]\`, NOT \`args: "[\\"a.ts\\"]"\` (a stringified | 37 | 37 | list reaches the script as one string and \`args.map\` throws). | 38 | 38 | - \`resumeFromRunId\`: relaunch a previous run, reusing its cached agent results (see Resume). | | 39 | +- If a \`workflow_script\` tool is offered, send a NEW inline script through it as raw text: its whole | | 40 | + input is the script source, starting with \`export const meta\`, with no code fence and no JSON wrapper. | | 41 | + Use the \`workflow\` tool for \`scriptPath\`, \`name\`, \`args\`, \`resumeFromRunId\` or a budget. | 39 | 42 |
| 40 | 43 | The tool returns immediately with \`{status: "async_launched", runId, taskId, scriptPath, transcriptDir}\`. | 41 | 44 | If the script fails its syntax/meta check the result carries \`error\` and nothing runs — fix and relaunch. | |
Collapse file Copy file name to clipboard +81Lines changed: 81 additions & 0 deletions | Original file line number | Diff line number | Diff line change |
|---|
| | 1 | +// X24: which models get the freeform `workflow_script` tool. | | 2 | +// | | 3 | +// opencode 2.3.0 sends a tool's freeform encoding only to models whose models.dev | | 4 | +// `capabilities.freeform` lists the format (core/src/session/model-request.ts); every other model | | 5 | +// would get `workflow_script` as a plain JSON tool, a duplicate of `workflow {script}`. The session | | 6 | +// "context" hook runs before each model request with the request's (resolved) model and a copy of | | 7 | +// its tool definitions; deleting a key there drops that tool from the request. | | 8 | + | | 9 | +import type { Plugin } from "@opencode/plugin" | | 10 | + | | 11 | +interface ListedModel { | | 12 | + id: string | | 13 | + modelID?: string | | 14 | + providerID: string | | 15 | + capabilities?: { freeform?: readonly string[] } | | 16 | +} | | 17 | + | | 18 | +/** The fields of the session "context" hook event this filter reads and edits. */ | | 19 | +export interface ContextHookEvent { | | 20 | + readonly model?: { readonly providerID?: string; readonly id?: string } | | 21 | + tools?: Record<string, unknown> | | 22 | +} | | 23 | + | | 24 | +export interface FreeformFilterOptions { | | 25 | + /** The freeform format the tool declares (default "text"). */ | | 26 | + format?: string | | 27 | + /** How long a `ctx.model.list()` result is reused (default 5 minutes). */ | | 28 | + ttlMs?: number | | 29 | + now?: () => number | | 30 | +} | | 31 | + | | 32 | +/** | | 33 | + * Returns a `session.hook("context")` callback that removes `toolName` from requests whose model is | | 34 | + * known not to list `format` in `capabilities.freeform`. A model the list does not know, or a list | | 35 | + * that fails, keeps the tool: it still works as a JSON tool. | | 36 | + */ | | 37 | +export function createFreeformToolFilter(ctx: Pick<Plugin.Context, "model">, toolName: string, opts: FreeformFilterOptions = {}) { | | 38 | + const format = opts.format ?? "text" | | 39 | + const ttlMs = opts.ttlMs ?? 5 * 60_000 | | 40 | + const now = opts.now ?? Date.now | | 41 | + let cache: { at: number; models: ListedModel[] } | undefined | | 42 | + let inflight: Promise<ListedModel[]> | undefined | | 43 | + | | 44 | + const models = (): Promise<ListedModel[]> => { | | 45 | + if (cache && now() - cache.at < ttlMs) return Promise.resolve(cache.models) | | 46 | + inflight ??= (async () => { | | 47 | + try { | | 48 | + const res = (await ctx.model.list()) as unknown as { data?: ListedModel[] } | ListedModel[] | | 49 | + const data = (Array.isArray(res) ? res : (res?.data ?? [])).filter((m) => m && typeof m === "object") | | 50 | + cache = { at: now(), models: data } | | 51 | + return data | | 52 | + } finally { | | 53 | + inflight = undefined | | 54 | + } | | 55 | + })() | | 56 | + return inflight | | 57 | + } | | 58 | + | | 59 | + const supports = async (ref: { providerID: string; id: string }): Promise<boolean | undefined> => { | | 60 | + let list: ListedModel[] | | 61 | + try { | | 62 | + list = await models() | | 63 | + } catch { | | 64 | + return undefined | | 65 | + } | | 66 | + const m = | | 67 | + list.find((x) => x.providerID === ref.providerID && x.id === ref.id) ?? | | 68 | + list.find((x) => x.providerID === ref.providerID && x.modelID === ref.id) | | 69 | + if (!m) return undefined | | 70 | + const formats = m.capabilities?.freeform | | 71 | + return Array.isArray(formats) && formats.includes(format) | | 72 | + } | | 73 | + | | 74 | + return async (event: ContextHookEvent): Promise<void> => { | | 75 | + const tools = event?.tools | | 76 | + if (!tools || !Object.prototype.hasOwnProperty.call(tools, toolName)) return | | 77 | + const ref = event.model | | 78 | + if (typeof ref?.providerID !== "string" || typeof ref.id !== "string") return | | 79 | + if ((await supports({ providerID: ref.providerID, id: ref.id })) === false) delete tools[toolName] | | 80 | + } | | 81 | +} |
Collapse file Copy file name to clipboardExpand all lines: src/plugin/setup.ts +26-1Lines changed: 26 additions & 1 deletion | Original file line number | Diff line number | Diff line change |
|---|
@@ -6,6 +6,7 @@ import { join } from "node:path" | 6 | 6 | import type { Plugin } from "@opencode/plugin" | 7 | 7 | import { listWorkflows, personalWorkflowsDir, projectWorkflowDirs, type RegistryOptions } from "../registry.ts" | 8 | 8 | import { createOpencodeRunner } from "../opencode/runner.ts" | | 9 | +import { createFreeformToolFilter } from "../opencode/freeform.ts" | 9 | 10 | import { createChildAskGuard, effectiveSessionRules } from "../opencode/permissions.ts" | 10 | 11 | import { createSubmitRegistry, createSubmitTool, type SubmitRegistry } from "../opencode/submit.ts" | 11 | 12 | import { RunStore } from "../store.ts" | @@ -14,12 +15,22 @@ import { addCommands } from "./commands.ts" | 14 | 15 | import { largeWorkflowThreshold, resolveSizeGuideline, sizeGuidelineAdvice } from "./guideline.ts" | 15 | 16 | import { WorkflowHost } from "./host.ts" | 16 | 17 | import { LiveRuntime } from "./rpc.ts" | 17 | | -import { CONTROL_TOOL_NAME, createControlTool, createWorkflowTool, WORKFLOW_TOOL_NAME, workflowToolDescription } from "./tools.ts" | | 18 | +import { | | 19 | + CONTROL_TOOL_NAME, | | 20 | + createControlTool, | | 21 | + createScriptTool, | | 22 | + createWorkflowTool, | | 23 | + SCRIPT_TOOL_NAME, | | 24 | + WORKFLOW_TOOL_NAME, | | 25 | + workflowToolDescription, | | 26 | +} from "./tools.ts" | 18 | 27 |
| 19 | 28 | export const PLUGIN_ID = "dynamic-workflows" | 20 | 29 | export const DISABLE_ENV = "OPENCODE_DISABLE_WORKFLOWS" | 21 | 30 | /** `0`/`false`/`no`/`off` makes the live tree's RPC read-only (X17). */ | 22 | 31 | export const RPC_CONTROL_ENV = "OPENCODE_WORKFLOW_RPC_CONTROL" | | 32 | +/** `0`/`false`/`no`/`off` registers no freeform `workflow_script` tool (X24). */ | | 33 | +export const FREEFORM_ENV = "OPENCODE_WORKFLOW_FREEFORM" | 23 | 34 |
| 24 | 35 | /** Injection seams (tests) and host overrides. Everything is optional. */ | 25 | 36 | export interface PluginDeps { | @@ -51,6 +62,14 @@ export function rpcControlEnabled(env: Record<string, string | undefined>, optio | 51 | 62 | return !(opt === false || (typeof opt === "string" && FALSY.test(opt.trim()))) | 52 | 63 | } | 53 | 64 |
| | 65 | +/** X24: `workflow_script` is registered unless env OPENCODE_WORKFLOW_FREEFORM is falsy or option `freeformTool` is false. */ | | 66 | +export function freeformToolEnabled(env: Record<string, string | undefined>, options: Record<string, unknown> | undefined): boolean { | | 67 | + const raw = env[FREEFORM_ENV] | | 68 | + if (raw !== undefined && FALSY.test(raw.trim())) return false | | 69 | + const opt = options?.freeformTool | | 70 | + return !(opt === false || (typeof opt === "string" && FALSY.test(opt.trim()))) | | 71 | +} | | 72 | + | 54 | 73 | /** P57: env OPENCODE_DISABLE_WORKFLOWS=1 (true/yes/on) or plugin option `disabled: true`. */ | 55 | 74 | export function isDisabled(env: Record<string, string | undefined>, options: Record<string, unknown> | undefined): boolean { | 56 | 75 | const raw = env[DISABLE_ENV] | @@ -82,6 +101,7 @@ export async function setupPlugin(ctx: Plugin.Context, deps: PluginDeps = {}): P | 82 | 101 | deniedTools: [WORKFLOW_TOOL_NAME, CONTROL_TOOL_NAME], | 83 | 102 | })) | 84 | 103 |
| | 104 | + const freeform = freeformToolEnabled(env, options) | 85 | 105 | const sizeGuideline = resolveSizeGuideline(env, options) | 86 | 106 | const sizeAdvice = sizeGuidelineAdvice(sizeGuideline) | 87 | 107 |
| @@ -153,10 +173,15 @@ export async function setupPlugin(ctx: Plugin.Context, deps: PluginDeps = {}): P | 153 | 173 | saved = listWorkflows(cwd, registryOptions) | 154 | 174 | } catch {} | 155 | 175 | editor.add(createWorkflowTool(host, workflowToolDescription({ saved, sizeAdvice }))) | | 176 | + if (freeform) editor.add(createScriptTool(host)) | 156 | 177 | editor.add(createControlTool(host)) | 157 | 178 | editor.add(createSubmitTool(submitRegistry)) | 158 | 179 | }), | 159 | 180 | ) | | 181 | + // X24: models that cannot send freeform text would only see a JSON duplicate of `workflow {script}`. | | 182 | + if (freeform && typeof (ctx.session as any).hook === "function") { | | 183 | + registrations.push(await ctx.session.hook("context", createFreeformToolFilter(ctx, SCRIPT_TOOL_NAME))) | | 184 | + } | 160 | 185 | registrations.push( | 161 | 186 | await ctx.command.transform((editor) => { | 162 | 187 | addCommands(editor, { | |
|