Skip to content

Commit ed91f93

Browse files
于晓彤claude
authored andcommitted
feat(workflow): P0-P3 runtime discipline — retention, commands, needs, usage
- Event retention: 500-row hard cap per workflow with protected-kind allowlist so forensic / terminal events never prune (P3 anomalyco#11). - Pending-commands queue with stable-fingerprint dedup, ACK path for runtime command_ids, and 1h TTL on timed_out_at entries (P1/P3). - Legal state-machine transitions for node status, with runtime-source bypass for stall / limit-reach forced moves (P0/P2). - Structured open_need / fulfill_need lifecycle replacing free-form blocker text; auto-waits the node and wakes master on fulfill (P2). - Workflow.Summary zod schema (.loose + .meta ref) plus matching WorkflowSummary type on the sql layer — legacy rows still parse (P3 anomalyco#13). - Per-node usage accumulation from assistant message tokens/cost with message-id dedup; workflow Runtime.usage rolls up across nodes; advisory limits from workflow.config.limits emit one-shot node.budget_exceeded (P3 anomalyco#15). - workflow_need_fulfill registered in ToolRegistry; control HTTP route returns { ok, deduped, command_id } so the master sees dedup signal. Co-Authored-By: Claude Opus 4.7 <[email protected]>
1 parent ddccc3b commit ed91f93

5 files changed

Lines changed: 1095 additions & 33 deletions

File tree

‎packages/opencode/src/server/instance/workflow.ts‎

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -292,7 +292,13 @@ export function WorkflowRoutes() {
292292
description: "Control accepted",
293293
content: {
294294
"application/json": {
295-
schema: resolver(z.boolean()),
295+
schema: resolver(
296+
z.object({
297+
ok: z.literal(true),
298+
deduped: z.boolean(),
299+
command_id: z.string().optional(),
300+
}),
301+
),
296302
},
297303
},
298304
},

‎packages/opencode/src/tool/registry.ts‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -39,6 +39,7 @@ import {
3939
WorkflowControlTool,
4040
WorkflowCreateTool,
4141
WorkflowEdgeCreateTool,
42+
WorkflowNeedFulfillTool,
4243
WorkflowNodeAbortTool,
4344
WorkflowNodeCreateTool,
4445
WorkflowNodePauseTool,
@@ -164,6 +165,7 @@ export namespace ToolRegistry {
164165
const workflowControl = yield* WorkflowControlTool
165166
const workflowUpdate = yield* WorkflowUpdateTool
166167
const workflowPull = yield* WorkflowPullTool
168+
const workflowNeedFulfill = yield* WorkflowNeedFulfillTool
167169

168170
const state = yield* InstanceState.make<State>(
169171
Effect.fn("ToolRegistry.state")(function* (ctx) {
@@ -261,6 +263,7 @@ export namespace ToolRegistry {
261263
workflowControl: Tool.init(workflowControl),
262264
workflowUpdate: Tool.init(workflowUpdate),
263265
workflowPull: Tool.init(workflowPull),
266+
workflowNeedFulfill: Tool.init(workflowNeedFulfill),
264267
})
265268

266269
return {
@@ -301,6 +304,7 @@ export namespace ToolRegistry {
301304
tool.workflowControl,
302305
tool.workflowUpdate,
303306
tool.workflowPull,
307+
tool.workflowNeedFulfill,
304308
...(Flag.OPENCODE_EXPERIMENTAL_LSP_TOOL ? [tool.lsp] : []),
305309
...(Flag.OPENCODE_EXPERIMENTAL_PLAN_MODE && Flag.OPENCODE_CLIENT === "cli" ? [tool.plan] : []),
306310
],

‎packages/opencode/src/tool/workflow.ts‎

Lines changed: 112 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -121,7 +121,7 @@ export const WorkflowCreateTool = Tool.define("workflow_create", {
121121
title: z.string(),
122122
session_id: z.string().optional(),
123123
config: z.record(z.string(), z.any()).optional(),
124-
summary: z.record(z.string(), z.any()).optional(),
124+
summary: Workflow.Summary.optional(),
125125
nodes: Workflow.create.schema.shape.nodes,
126126
edges: Workflow.create.schema.shape.edges,
127127
checkpoints: Workflow.create.schema.shape.checkpoints,
@@ -202,7 +202,7 @@ export const WorkflowNodeCreateTool = Tool.define("workflow_node_create", {
202202
})
203203

204204
export const WorkflowNodeStartTool = Tool.define("workflow_node_start", {
205-
description: "Start an existing workflow node by creating and attaching its child session, then optionally send the initial prompt.",
205+
description: "Start an existing workflow node by creating and attaching its child session, then optionally send the initial prompt. Idempotent — calling on an already-running node returns the current state without re-prompting.",
206206
parameters: z.object({
207207
node_id: z.string(),
208208
title: z.string().optional(),
@@ -215,6 +215,33 @@ export const WorkflowNodeStartTool = Tool.define("workflow_node_start", {
215215
if (current.status === "cancelled") {
216216
throw new Error(`Workflow node ${current.id} is cancelled and cannot be started again.`)
217217
}
218+
if (current.status === "completed") {
219+
throw new Error(`Workflow node ${current.id} is already completed; use workflow_control with retry to re-run.`)
220+
}
221+
222+
// P0.3 idempotent start: if the node is already running / waiting with an
223+
// attached session, skip session creation and re-prompting. This keeps
224+
// accidental double-calls from spawning another LLM round mid-execution.
225+
if (
226+
current.session_id &&
227+
(current.status === "running" || current.status === "waiting")
228+
) {
229+
return {
230+
title: current.title,
231+
metadata: {
232+
workflowID: current.workflow_id,
233+
nodeID: current.id,
234+
sessionID: current.session_id,
235+
},
236+
output: format({
237+
node: current,
238+
session_id: current.session_id,
239+
idempotent: true,
240+
reason: `node already ${current.status}; skipped re-prompt`,
241+
}),
242+
}
243+
}
244+
218245
const picked = input.model ?? current.model
219246
if (!configured(picked)) {
220247
throw new Error(
@@ -407,33 +434,35 @@ export const WorkflowReadTool = Tool.define("workflow_read", {
407434
})
408435

409436
export const WorkflowControlTool = Tool.define("workflow_control", {
410-
description: "Send a soft control command to a workflow node, such as continue, resume, retry, or context injection.",
437+
description: "Send a soft control command to a workflow node, such as continue, resume, retry, or context injection. Duplicates within a 5s window are silently absorbed.",
411438
parameters: z.object({
412439
workflow_id: z.string(),
413440
node_id: z.string(),
414441
command: z.enum(["continue", "resume", "retry", "inject_context"]),
415442
payload: z.record(z.string(), z.any()).optional(),
416443
}),
417444
async execute(input) {
418-
await Workflow.control({
445+
const result = await Workflow.control({
419446
workflowID: input.workflow_id,
420447
nodeID: input.node_id,
421448
source: "orchestrator",
422449
command: input.command,
423450
payload: input.payload,
424451
})
425452
const node = await Workflow.getNode(input.node_id)
426-
if (node.session_id) {
453+
// Only re-prompt the slave if we actually enqueued a new command.
454+
// Deduped commands already have an in-flight slave round.
455+
if (!result.deduped && node.session_id) {
427456
void prompt({
428457
workflowID: input.workflow_id,
429458
nodeID: input.node_id,
430459
agent: node.agent,
431460
sessionID: node.session_id,
432461
model: node.model,
433462
text: [
434-
`Runtime command: ${input.command}`,
463+
`Runtime command: ${input.command} (command_id: ${result.command_id})`,
435464
input.payload ? JSON.stringify(input.payload, null, 2) : "",
436-
"Call workflow_pull now, apply the command, and continue execution in this node session.",
465+
"Call workflow_pull now, apply the command, ack it via workflow_update.patch.ack, and continue execution.",
437466
]
438467
.filter(Boolean)
439468
.join("\n\n"),
@@ -444,22 +473,41 @@ export const WorkflowControlTool = Tool.define("workflow_control", {
444473
metadata: {
445474
workflowID: input.workflow_id,
446475
nodeID: input.node_id,
476+
commandID: result.command_id,
477+
deduped: result.deduped,
447478
},
448479
output: format({
449480
ok: true,
450481
command: input.command,
482+
command_id: result.command_id,
483+
deduped: result.deduped,
451484
}),
452485
}
453486
},
454487
})
455488

456489
export const WorkflowUpdateTool = Tool.define("workflow_update", {
457-
description: "Update the current workflow node state from inside a subagent session. Only changed fields need to be sent.",
490+
description: "Update the current workflow node state from inside a subagent session. Only changed fields need to be sent. Pass `ack` to acknowledge runtime command_ids surfaced by workflow_pull. Pass `open_need` to structurally raise a blocker that the orchestrator must fulfill.",
458491
parameters: z.object({
459492
node_id: z.string().optional(),
460493
patch: nodePatch,
461494
event_kind: z.string().optional(),
462495
event_payload: z.record(z.string(), z.any()).optional(),
496+
/** List of runtime command_ids this update acknowledges. Removes them
497+
* from pending_commands and emits node.command_acked. */
498+
ack: z.array(z.string()).optional(),
499+
ack_note: z.string().optional(),
500+
/** Optional structured need. When set, the node auto-transitions to
501+
* waiting (unless already terminal) and pushes an entry into
502+
* state_json.open_needs for the orchestrator to fulfill. */
503+
open_need: z
504+
.object({
505+
title: z.string(),
506+
prompt: z.string().optional(),
507+
kind: z.enum(["context", "approval", "tool", "other"]).optional(),
508+
required_by: z.string().optional(),
509+
})
510+
.optional(),
463511
}),
464512
async execute(input, ctx) {
465513
const node = input.node_id ? await Workflow.getNode(input.node_id) : await Workflow.nodeBySession(ctx.sessionID)
@@ -475,13 +523,68 @@ export const WorkflowUpdateTool = Tool.define("workflow_update", {
475523
}
476524
: undefined,
477525
})
526+
let acked: string[] = []
527+
if (input.ack && input.ack.length > 0) {
528+
const result = await Workflow.ackCommand({
529+
nodeID: node.id,
530+
source: "node",
531+
command_ids: input.ack as [string, ...string[]],
532+
note: input.ack_note,
533+
})
534+
acked = result.acked
535+
}
536+
let opened_need_id: string | undefined
537+
if (input.open_need) {
538+
const result = await Workflow.openNeed({
539+
nodeID: node.id,
540+
source: "node",
541+
title: input.open_need.title,
542+
prompt: input.open_need.prompt,
543+
kind: input.open_need.kind,
544+
required_by: input.open_need.required_by,
545+
})
546+
opened_need_id = result.need_id
547+
}
478548
return {
479549
title: updated.title,
480550
metadata: {
481551
workflowID: updated.workflow_id,
482552
nodeID: updated.id,
553+
acked,
554+
opened_need_id,
555+
},
556+
output: format({ ...updated, acked, opened_need_id }),
557+
}
558+
},
559+
})
560+
561+
export const WorkflowNeedFulfillTool = Tool.define("workflow_need_fulfill", {
562+
description: "Orchestrator fulfills a structured need raised by a slave. Moves the need from open to resolved, injects the supplied context, and wakes the slave.",
563+
parameters: z.object({
564+
node_id: z.string(),
565+
need_id: z.string(),
566+
context: z.string(),
567+
resolution_note: z.string().optional(),
568+
}),
569+
async execute(input) {
570+
const node = await Workflow.getNode(input.node_id)
571+
const result = await Workflow.fulfillNeed({
572+
nodeID: node.id,
573+
source: "orchestrator",
574+
need_id: input.need_id,
575+
context: input.context,
576+
resolution_note: input.resolution_note,
577+
})
578+
return {
579+
title: `need ${input.need_id} fulfilled`,
580+
metadata: {
581+
workflowID: node.workflow_id,
582+
nodeID: node.id,
583+
needID: input.need_id,
584+
commandID: result.command_id,
585+
remainingOpen: result.remaining_open,
483586
},
484-
output: format(updated),
587+
output: format(result),
485588
}
486589
},
487590
})

0 commit comments

Comments
 (0)