diff --git a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts index 32fcdb0097..b8ee9e2591 100644 --- a/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts +++ b/apps/server/src/orchestration-v2/Adapters/ClaudeAdapterV2.ts @@ -1340,6 +1340,10 @@ const CLAUDE_KNOWN_TOOL_CLASSIFICATIONS: Record< toolsearch: { itemType: "dynamic_tool", requestKind: "command" }, webfetch: { itemType: "web_search", requestKind: "command" }, websearch: { itemType: "web_search", requestKind: "command" }, + // Workflow tool_uses project as coordinator subagent rows, not tool calls; + // the classification only applies on the degraded path where a result + // arrives without its task_started. + workflow: { itemType: "dynamic_tool", requestKind: "command" }, write: { itemType: "file_change", requestKind: "file-change" }, }; @@ -1548,6 +1552,49 @@ const claudeWorkflowAgentStatus = (entry: unknown) => { } }; +type ClaudeWorkflowRunHandles = Partial< + Omit, "phases"> +>; + +// Clients render `sessionUrl` into an anchor href — restrict to web URLs so a +// hostile tool result cannot smuggle a javascript:/file: scheme through. +const claudeWorkflowHttpUrl = (value: unknown): string | undefined => { + if (typeof value !== "string" || value.trim().length === 0) return undefined; + try { + const parsed = new URL(value); + return parsed.protocol === "https:" || parsed.protocol === "http:" ? value : undefined; + } catch { + return undefined; + } +}; + +const trimmedRecordField = (value: unknown, keys: ReadonlyArray): string | undefined => { + const field = firstRecordField(value, keys); + return typeof field === "string" && field.trim().length > 0 ? field.trim() : undefined; +}; + +// Run handles from the Workflow tool result (script path, transcript dir, +// run id; `sessionUrl` replaces them for remote runs). The result shape is +// undocumented SDK surface, so every field is optional and absent fields +// degrade to less detail, never a failure. +const claudeWorkflowRunHandles = (value: unknown): ClaudeWorkflowRunHandles | undefined => { + const name = trimmedRecordField(value, ["workflowName", "workflow_name"]); + const runId = trimmedRecordField(value, ["runId", "run_id"]); + const scriptPath = trimmedRecordField(value, ["scriptPath", "script_path"]); + const transcriptDir = trimmedRecordField(value, ["transcriptDir", "transcript_dir"]); + const sessionUrl = claudeWorkflowHttpUrl(firstRecordField(value, ["sessionUrl", "session_url"])); + const warning = trimmedRecordField(value, ["warning"]); + const handles = { + ...(name === undefined ? {} : { name }), + ...(runId === undefined ? {} : { runId }), + ...(scriptPath === undefined ? {} : { scriptPath }), + ...(transcriptDir === undefined ? {} : { transcriptDir }), + ...(sessionUrl === undefined ? {} : { sessionUrl }), + ...(warning === undefined ? {} : { warning }), + } satisfies ClaudeWorkflowRunHandles; + return Object.keys(handles).length > 0 ? handles : undefined; +}; + function isClaudeNonSubagentTask(message: SDKMessage): boolean { return isClaudeOpaqueBackgroundTaskType(claudeTaskTypeFromSdkMessage(message)); } @@ -2839,7 +2886,10 @@ export function makeClaudeAdapterV2( readonly roleFallback?: string; readonly model?: string; readonly kind?: OrchestrationV2Subagent["kind"]; - readonly workflow?: OrchestrationV2Subagent["workflow"]; + // Merged over the prior workflow value: phases arrive on progress + // snapshots while run handles arrive on the tool result, so neither + // side may clobber the other. + readonly workflow?: Partial>; readonly workflowMembership?: OrchestrationV2Subagent["workflowMembership"]; readonly parentNodeId?: OrchestrationV2ExecutionNode["id"]; readonly allowCreateSettled?: boolean; @@ -2992,7 +3042,9 @@ export function makeClaudeAdapterV2( ...(input.agentType === undefined ? {} : { role: providerSubagentRole(input.agentType, input.roleFallback) }), - ...(input.workflow === undefined ? {} : { workflow: input.workflow }), + ...(input.workflow === undefined + ? {} + : { workflow: { phases: [], ...(priorTask?.workflow ?? {}), ...input.workflow } }), ...(input.workflowMembership === undefined ? {} : { workflowMembership: input.workflowMembership }), @@ -4103,6 +4155,7 @@ export function makeClaudeAdapterV2( } else { const agentType = recordField(message, "subagent_type"); const isWorkflow = message.task_type === "local_workflow"; + const workflowName = trimmedRecordField(message, ["workflow_name", "workflowName"]); yield* updateClaudeSubagentNode({ context, taskId: message.task_id, @@ -4110,7 +4163,13 @@ export function makeClaudeAdapterV2( ...(message.prompt === undefined ? {} : { prompt: message.prompt }), title: message.description, ...(typeof agentType === "string" ? { agentType } : {}), - ...(isWorkflow ? { kind: "workflow", roleFallback: "workflow-coordinator" } : {}), + ...(isWorkflow + ? { + kind: "workflow" as const, + roleFallback: "workflow-coordinator", + ...(workflowName === undefined ? {} : { workflow: { name: workflowName } }), + } + : {}), status: "running", reopen: true, }); @@ -4298,7 +4357,10 @@ export function makeClaudeAdapterV2( } for (const toolUse of claudeToolUseBlocksFromAssistantMessage(message)) { - if (toolUse.name === "Agent") { + // Agent and Workflow tool_uses never enter toolCalls: both + // project as subagent rows (task_started arrives under the same + // tool_use_id), and registering them too would double-render. + if (toolUse.name === "Agent" || toolUse.name === "Workflow") { continue; } yield* ensureToolCallStarted({ @@ -4324,6 +4386,24 @@ export function makeClaudeAdapterV2( if (isClaudeSubagentAsyncLaunchAck(output)) { continue; } + // The Workflow tool resolves immediately with a launch ACK + // carrying the run's handles (script path, transcript dir, run + // id) while the workflow keeps running; attach the handles and + // leave settling to task_notification. + if (subagent.task.kind === "workflow" && !isClaudeToolResultError(toolResult)) { + const handles = claudeWorkflowRunHandles(claudeNativeToolOutputValue(output)); + const status = subagent.task.status; + if (handles !== undefined && status !== "idle" && status !== "interrupted") { + yield* updateClaudeSubagentNode({ + context, + taskId: subagent.task.nativeTaskRef?.nativeId ?? String(subagent.task.id), + toolUseId: toolResult.tool_use_id, + workflow: handles, + status, + }); + } + continue; + } const result = claudeSubagentResultText(output); yield* updateClaudeSubagentNode({ context, diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/claude_transcript.ndjson b/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/claude_transcript.ndjson index 0778d13261..cad6213320 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/claude_transcript.ndjson +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/claude_transcript.ndjson @@ -3,7 +3,9 @@ {"type": "expect_outbound", "label": "prompt.offer:1", "frame": {"type": "prompt.offer", "message": {"type": "user", "message": {"role": "user", "content": "Run a two-phase workflow, then answer exactly: claude workflow fixture complete"}, "parent_tool_use_id": null}}} {"type": "emit_inbound", "label": "system", "frame": {"type": "system", "subtype": "init", "agents": [], "apiKeySource": "none", "claude_code_version": "2.1.183", "cwd": "/tmp/claude-replay-claude_workflow", "tools": [], "mcp_servers": [], "model": "claude-sonnet-4-6", "permissionMode": "bypassPermissions", "slash_commands": [], "output_style": "default", "skills": [], "plugins": [], "fast_mode_state": "off", "uuid": "af3bf4cc-1385-4e19-a5fa-fcbe2a0ca201", "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201"}} {"type": "emit_inbound", "label": "assistant:commentary", "frame": {"type": "assistant", "message": {"model": "claude-sonnet-4-6", "id": "msg_01claudeworkflow1", "type": "message", "role": "assistant", "content": [{"type": "text", "text": "Starting the two-phase workflow."}], "stop_reason": null, "stop_sequence": null, "stop_details": null, "usage": {"input_tokens": 1, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 1, "service_tier": "standard", "inference_geo": "not_available"}, "context_management": null}, "parent_tool_use_id": null, "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201", "uuid": "97898e28-ee4e-4fcf-80c3-5c790c502201"}} -{"type": "emit_inbound", "label": "task_started:local_workflow", "frame": {"type": "system", "subtype": "task_started", "task_id": "wf7ka2mq1", "tool_use_id": "toolu_01ClaudeWorkflowFixture01", "description": "Research and implement", "task_type": "local_workflow", "prompt": "Research the parser, then implement the fix.", "uuid": "4873c95b-1aa9-44a5-9783-dc56dac73201", "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201"}} +{"type": "emit_inbound", "label": "assistant:workflow_tool_use", "frame": {"type": "assistant", "message": {"model": "claude-sonnet-4-6", "id": "msg_01claudeworkflow3", "type": "message", "role": "assistant", "content": [{"type": "tool_use", "id": "toolu_01ClaudeWorkflowFixture01", "name": "Workflow", "input": {"script": "export const meta = { name: 'research-implement', description: 'Research the parser, then implement the fix.', phases: [{ title: 'Research' }, { title: 'Implement' }] }"}}], "stop_reason": null, "stop_sequence": null, "stop_details": null, "usage": {"input_tokens": 1, "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "output_tokens": 1, "service_tier": "standard", "inference_geo": "not_available"}, "context_management": null}, "parent_tool_use_id": null, "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201", "uuid": "97898e28-ee4e-4fcf-80c3-5c790c502202"}} +{"type": "emit_inbound", "label": "task_started:local_workflow", "frame": {"type": "system", "subtype": "task_started", "task_id": "wf7ka2mq1", "tool_use_id": "toolu_01ClaudeWorkflowFixture01", "description": "Research and implement", "task_type": "local_workflow", "workflow_name": "research-implement", "prompt": "Research the parser, then implement the fix.", "uuid": "4873c95b-1aa9-44a5-9783-dc56dac73201", "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201"}} +{"type": "emit_inbound", "label": "user:workflow_launch_ack", "frame": {"type": "user", "message": {"role": "user", "content": [{"tool_use_id": "toolu_01ClaudeWorkflowFixture01", "type": "tool_result", "content": [{"type": "text", "text": "Workflow started in the background (runId: wf_run_fixture01). A task notification will arrive when it completes."}], "is_error": false}]}, "parent_tool_use_id": null, "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201", "uuid": "526e0d3c-7688-4b39-8b54-4aa438b93201", "tool_use_result": {"taskId": "wf7ka2mq1", "runId": "wf_run_fixture01", "workflowName": "research-implement", "taskType": "local_workflow", "scriptPath": "/tmp/claude-replay-claude_workflow/.claude/workflows/research-implement.mjs", "transcriptDir": "/tmp/claude-replay-claude_workflow/.claude/projects/-tmp-claude-replay/wf_run_fixture01", "sessionUrl": "javascript:alert(1)"}}} {"type": "emit_inbound", "label": "task_progress:phase-1", "frame": {"type": "system", "subtype": "task_progress", "task_id": "wf7ka2mq1", "tool_use_id": "toolu_01ClaudeWorkflowFixture01", "description": "Research phase running", "usage": {"input_tokens": 300, "output_tokens": 200, "total_tokens": 500, "tool_uses": 4}, "workflow_progress": [{"type": "workflow_phase", "index": 0, "title": "Research"}, {"type": "workflow_phase", "index": 1, "title": "Implement"}, {"type": "workflow_agent", "index": 0, "label": "Researcher", "state": "waiting", "phaseIndex": 0, "attempt": 0, "model": "claude-sonnet-4-6", "lastToolName": "Read", "tokens": 200, "toolCalls": 2}], "uuid": "4873c95b-1aa9-44a5-9783-dc56dac73202", "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201"}} {"type": "emit_inbound", "label": "task_progress:phase-2", "frame": {"type": "system", "subtype": "task_progress", "task_id": "wf7ka2mq1", "tool_use_id": "toolu_01ClaudeWorkflowFixture01", "description": "Implement phase running", "usage": {"input_tokens": 700, "output_tokens": 500, "total_tokens": 1200, "tool_uses": 9}, "workflow_progress": [{"type": "workflow_phase", "index": 0, "title": "Research"}, {"type": "workflow_phase", "index": 1, "title": "Implement"}, {"type": "workflow_agent", "index": 0, "label": "Researcher", "state": "done", "phaseIndex": 0, "attempt": 0, "model": "claude-sonnet-4-6", "lastToolName": "Read", "tokens": 400, "toolCalls": 3}, {"type": "workflow_agent", "index": 1, "label": "Implementer", "state": "active", "phase_index": 1, "attempt": 0, "model": "claude-opus-4-1", "last_tool_name": "Edit", "tokens": 500, "tool_calls": 4}], "uuid": "4873c95b-1aa9-44a5-9783-dc56dac73203", "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201"}} {"type": "emit_inbound", "label": "task_notification:local_workflow", "frame": {"type": "system", "subtype": "task_notification", "task_id": "wf7ka2mq1", "tool_use_id": "toolu_01ClaudeWorkflowFixture01", "status": "completed", "output_file": "", "summary": "Workflow finished both phases.", "usage": {"input_tokens": 900, "output_tokens": 600, "total_tokens": 1500, "tool_uses": 11}, "uuid": "4873c95b-1aa9-44a5-9783-dc56dac73204", "session_id": "3c7f21a0-9d4e-4b21-8f60-000000000201"}} diff --git a/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/output.ts b/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/output.ts index 885fa83796..98e7a71adf 100644 --- a/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/output.ts +++ b/apps/server/src/orchestration-v2/testkit/fixtures/claude_workflow/output.ts @@ -23,10 +23,31 @@ export function assertClaudeWorkflowOutput( const coordinator = projection.subagents.find((subagent) => subagent.kind === "workflow"); assert.isDefined(coordinator, "the workflow must reach the projection as a coordinator"); assert.deepEqual(coordinator?.role, { name: "workflow-coordinator", source: "app_default" }); - assert.deepEqual(coordinator?.workflow?.phases, [ - { index: 0, title: "Research" }, - { index: 1, title: "Implement" }, - ]); + // Phases arrive on progress snapshots; run handles arrive on the launch + // ACK; the name arrives on task_started. All three must merge rather than + // the later write clobbering the earlier ones. The fixture's hostile + // `javascript:` sessionUrl must be dropped by the scheme filter, not + // carried into the projection. + assert.deepEqual(coordinator?.workflow, { + phases: [ + { index: 0, title: "Research" }, + { index: 1, title: "Implement" }, + ], + name: "research-implement", + runId: "wf_run_fixture01", + scriptPath: "/tmp/claude-replay-claude_workflow/.claude/workflows/research-implement.mjs", + transcriptDir: + "/tmp/claude-replay-claude_workflow/.claude/projects/-tmp-claude-replay/wf_run_fixture01", + }); + // The Workflow tool_use projects as the coordinator row only; registering + // it as a tool call too would render the run twice in the timeline. + assert.lengthOf( + projection.turnItems.filter( + (item) => item.type === "dynamic_tool" && item.toolName === "Workflow", + ), + 0, + "the Workflow tool_use must not double-render as a tool call", + ); const members = projection.subagents .filter((subagent) => subagent.kind === "workflow_agent") diff --git a/packages/contracts/src/orchestrationV2.test.ts b/packages/contracts/src/orchestrationV2.test.ts index a3e3133ff8..731f657152 100644 --- a/packages/contracts/src/orchestrationV2.test.ts +++ b/packages/contracts/src/orchestrationV2.test.ts @@ -611,6 +611,65 @@ describe("orchestration V2 contracts", () => { expect(decoded.recentActivity).toEqual([]); }); + it("keeps run handles optional on the workflow struct", () => { + const coordinatorRow = { + id: "node-workflow-1", + threadId: "thread-1", + runId: "run-1", + parentNodeId: "node-root-1", + origin: "provider_native", + createdBy: "agent", + driver: "claudeAgent", + providerInstanceId: "claudeAgent", + providerThreadId: null, + childThreadId: null, + nativeTaskRef: null, + prompt: "Research the parser, then implement the fix.", + title: "Research and implement", + model: null, + kind: "workflow", + status: "running", + result: null, + startedAt: DateTime.formatIso(now), + completedAt: null, + updatedAt: DateTime.formatIso(now), + }; + + // Coordinator rows stored before run handles existed carry phases only + // and must decode unchanged — no migration rewrites them. + const phasesOnly = decodeStoredOrchestrationV2Subagent( + JSON.stringify({ + ...coordinatorRow, + workflow: { phases: [{ index: 0, title: "Research" }] }, + }), + ); + expect(phasesOnly.workflow).toEqual({ phases: [{ index: 0, title: "Research" }] }); + + const withHandles = decodeStoredOrchestrationV2Subagent( + JSON.stringify({ + ...coordinatorRow, + workflow: { + phases: [{ index: 0, title: "Research" }], + name: "research-implement", + runId: "wf_run_1", + scriptPath: "/tmp/workflows/research-implement.mjs", + transcriptDir: "/tmp/projects/wf_run_1", + sessionUrl: "https://claude.ai/session/1", + warning: "workflow exceeded the size guideline", + }, + }), + ); + expect(withHandles.workflow).toEqual({ + phases: [{ index: 0, title: "Research" }], + name: "research-implement", + runId: "wf_run_1", + scriptPath: "/tmp/workflows/research-implement.mjs", + transcriptDir: "/tmp/projects/wf_run_1", + sessionUrl: "https://claude.ai/session/1", + warning: "workflow exceeded the size guideline", + }); + }); + it("decodes app-owned subagent parent-wake policies", () => { const appOwnedSubagent = { id: "node-subagent-2", diff --git a/packages/contracts/src/orchestrationV2.ts b/packages/contracts/src/orchestrationV2.ts index 6933b0dc76..d41c1dbc67 100644 --- a/packages/contracts/src/orchestrationV2.ts +++ b/packages/contracts/src/orchestrationV2.ts @@ -566,6 +566,17 @@ export const OrchestrationV2Subagent = Schema.Struct({ workflow: Schema.NullOr( Schema.Struct({ phases: Schema.Array(OrchestrationV2WorkflowPhase), + // Run handles from the Workflow tool result. `scriptPath` and + // `transcriptDir` are server-local paths clients echo back to + // inspection RPCs, which re-validate them before touching disk. + // `sessionUrl` replaces the local handles for remote runs and is + // scheme-restricted to http(s) at the adapter. + name: Schema.optional(TrimmedNonEmptyString), + runId: Schema.optional(TrimmedNonEmptyString), + scriptPath: Schema.optional(TrimmedNonEmptyString), + transcriptDir: Schema.optional(TrimmedNonEmptyString), + sessionUrl: Schema.optional(TrimmedNonEmptyString), + warning: Schema.optional(TrimmedNonEmptyString), }), ).pipe(Schema.withDecodingDefault(Effect.succeed(null))), workflowMembership: Schema.NullOr(