Agents as activities

Time: ~10 minutes. Tangible win: you can wrap a Claude Code or Devin agent call as a Cadence activity so each of your 7 research stages is run by an agent — retried, timed out, and replay-safe — without poisoning workflow determinism.

Ian — until now the "work" inside each stage was a hand-wave. This lesson makes it concrete: the work is an AI agent you invoke from the command line. Claude Code and Devin become the engines that actually execute a stage. The whole point of Lessons 1–2 pays off here, because an agent call is the textbook example of what must live in an activity, never in the workflow.

Primary sources Claude Code — Run programmatically (headless claude -p) and Devin API — Common Flows (create session, then poll). Read the "Basic usage" and "Getting started: API key to first session" sections respectively.

Why an agent call is an activity, always

Workflow code must be deterministic — replay has to produce the same decisions every time (Lesson 1). An LLM is the opposite of deterministic: the same prompt yields different text, at a different latency, with a non-zero chance of failure. It also reaches the network and spends money. Every property that bans code from a workflow is present here.

Never call an agent from workflow code Not exec.Command("claude", ...), not an HTTP call to Devin, not reading the result. All of it goes inside an activity. The workflow only decides which agent to run, in what order, and what to do with the result. The non-determinism is sealed inside the activity, where Cadence records only the final output into history — so replay reuses that recorded output and never re-runs the model.

The two agents have two shapes

This is the one distinction that changes your code. Claude headless is a synchronous subprocess: one command runs, blocks, and exits. Devin is an asynchronous job: you create a session, get an ID, and poll until it finishes.

Claude Code (headless)Devin
Invocationclaude -p "…" subprocessPOST /v1/sessions (HTTP)
ModelSynchronous — blocks till exitAsync — returns a session_id
Get resultRead stdout, check exit codePoll GET /sessions/{id}
Cadence patternOne activity, blockingCreate activity + poll (timer loop or heartbeat)

Claude as a blocking activity

Headless mode is claude -p "<prompt>" --output-format json: single prompt to stdout, then exit code 0 on success, non-zero on failure (docs). That maps cleanly onto a normal activity — the kind you already know how to time out and retry.

// ACTIVITY — side effects live here, non-determinism is fine.
func ClaudeStage(ctx context.Context, prompt string) (string, error) {
    cmd := exec.CommandContext(ctx, "claude", "-p", prompt,
        "--output-format", "json",
        "--allowedTools", "Read,Edit,Bash") // scope the blast radius
    out, err := cmd.Output()
    if err != nil {
        // non-zero exit → return err so Cadence can retry
        return "", fmt.Errorf("claude failed: %w", err)
    }
    var res struct{ Result string `json:"result"` }
    json.Unmarshal(out, &res)
    return res.Result, nil
}

In the workflow you call it like any activity, with the timeouts and retry policy from Lesson 2. An agent run is slow, so StartToClose is minutes, not seconds:

ao := workflow.ActivityOptions{
    StartToCloseTimeout: 10 * time.Minute,   // one agent run's ceiling
    RetryPolicy: &cadence.RetryPolicy{
        InitialInterval: 5 * time.Second,
        BackoffCoefficient: 2.0,
        MaximumAttempts: 3,
        NonRetryableErrorReasons: []string{"BadRequestError"},
    },
}
ctx = workflow.WithActivityOptions(ctx, ao)
var draft string
err := workflow.ExecuteActivity(ctx, ClaudeStage, prompt).Get(ctx, &draft)
Use --bare for reproducible runs Plain claude -p auto-loads hooks, skills, MCP servers, and CLAUDE.md from the working directory and ~/.claude — so the same activity behaves differently on a teammate's worker. claude --bare -p "…" skips all of that for a deterministic environment (you then set ANTHROPIC_API_KEY explicitly). For a Cadence worker you want the --bare behaviour. (docs: "Start faster with bare mode")

Devin as a create-then-poll pair

Devin's API is async: POST /v1/sessions with a prompt returns {session_id, url, status}, then you GET the session until status is terminal — the docs' Python loop breaks on exit, error, or suspended (Common Flows). You have two Cadence-idiomatic ways to model the wait.

Option 1 — poll inside one activity with heartbeats. The activity creates the session then loops, calling activity.RecordHeartbeat each cycle. If the worker dies, Cadence restarts the activity; the heartbeat payload carries the session_id so the retry rejoins the existing session instead of starting a new one.

func DevinStage(ctx context.Context, prompt string) (string, error) {
    id := createSession(prompt)             // POST /v1/sessions
    for {
        activity.RecordHeartbeat(ctx, id)   // checkpoint the session id
        s := getSession(id)                 // GET /sessions/{id}
        switch s.Status {
        case "blocked", "finished":         // terminal → done
            return s.Output, nil
        case "expired":
            return "", fmt.Errorf("devin session failed")
        }
        time.Sleep(10 * time.Second)        // fine: this is activity code
    }
}

Option 2 — split into "start" and "wait" with a durable timer. One activity creates the session; the workflow then workflow.Sleeps (Lesson 5) and a second activity checks status, looping in deterministic workflow code. This frees the worker between polls — right when a Devin task runs for hours.

Which option? Short agent runs (minutes): Option 1 — simpler, one activity. Long runs (hours/days) or many parallel sessions: Option 2 — the worker isn't pinned waiting, and the sleep is durable across restarts. This is the same activity-vs-child decision discipline from Lesson 5: reach for the lighter tool first.

Idempotency bites harder with agents

Lesson 2's at-least-once rule is sharper here because agent runs cost money and mutate repos. A retried ClaudeStage runs the model again — a second charge, and possibly a second commit. Two defenses, both your responsibility:

Mapping onto your 7 stages

Each stage becomes an activity that invokes an agent; the workflow is the durable coordinator that was previously your ICM folder structure. Intent and evaluation are cheap, fast Claude calls (blocking activities). Execution — the heavy "go build/research this" stage — is the natural Devin candidate (async, long-running, Option 2). The human-review boundary between stages is the signal gate from Lesson 4. Nothing about the agent lives in the workflow; the workflow just sequences the activities and decides what each result means.

Retrieval check

Where does the exec.Command("claude", ...) call belong, and why?

Correct. An LLM call is non-deterministic, slow, networked, and costs money — every reason code is banned from a workflow. It goes in an activity; Cadence records only the output for replay.

No. The agent call is non-deterministic, so it must be an activity. The workflow only sequences activities and interprets results — it never runs the model.

Why does Devin need a different Cadence pattern than Claude headless?

Correct. Claude headless blocks until the subprocess exits; Devin returns a session_id immediately and you poll until the status is terminal. The async shape forces a create-then-poll pattern.

No. Devin is async: POST returns a session_id and you poll GET until terminal. That create-then-poll shape differs from Claude's single blocking subprocess.

A Devin poll activity dies mid-session and Cadence retries it. How do you avoid starting a second paid session?

Correct. Recording the session_id as a heartbeat payload lets the retried activity read it back and resume polling the existing session rather than creating a new one.

No. The fix is heartbeating the session_id so a retry re-attaches to the same session. Timeouts don't prevent the duplicate, and polling can't move into a workflow (it's a network call).

New terms — headless mode, bare mode, create-then-poll, session polling, agent activity — are in the glossary.

Ask me anything. Good follow-ups: "Show me the full Go worker that registers both ClaudeStage and DevinStage" or "How do I pass the deterministic run ID into the agent so retries overwrite?" You've now got the model-call half of the mission — next we can pair-build the real 2-stage slice (one Claude activity, one Devin activity) against your research-assistant-workflow, or jump to the Lesson 8 synthesis: map all 7 stages and make the Cadence-vs-ICM call with evidence.