opencode icon indicating copy to clipboard operation
opencode copied to clipboard

Embedded SDK hosts (OpenCode.create, OpenCodeWorkerd.create) never run automations: only the server process starts Automation.run

Open heymaaz opened this issue 1 week ago • 4 comments

Summary

On OpenCode 2.4.1, an automation created on an embedded SDK host never runs. This is true for both OpenCode.create (@opencode/sdk) and OpenCodeWorkerd.create (@opencode/sdk/workerd). automation.create succeeds and the automation is active with a nextDueAt. But nextDueAt passes, runCount stays 0, and lastRunAt and lastOutcome stay empty.

opencode serve runs the same automation every 15 seconds.

The cause: only the server process starts the scheduler (Automation.Service.run). The embedded host boots the same application graph, but it does not start that fiber.

Impact

Automations are on by default in 2.4.x. On an embedded host, the model can call automation.create, and it gets back an active automation with a next run time. A plugin can also create one through ctx.experimental.automation (#65747). Nothing reports an error, and the automation never runs.

We embed OpenCodeWorkerd.create in Cloudflare-style Durable Objects. For us, an automation such as "check this PR again in 2 hours" would be accepted and then never run.

Environment

  • OpenCode 2.4.1 (6f0514052a), from npm: @opencode/[email protected], @opencode/[email protected], @opencode/[email protected]. dev (66d53a82d0) has the same code in the files below.
  • OpenCode.create: Node 24.22.3 in node:24-bookworm.
  • OpenCodeWorkerd.create: a SQLite-backed Durable Object in wrangler dev, Wrangler 4.152.0, in node:22-bookworm.
  • Control: opencode serve from @opencode/[email protected], in node:24-bookworm.
  • Docker 29.8.2 (OrbStack), Linux/arm64 on Apple Silicon.

Reproduction

For each runtime, repro.sh does these steps:

  1. It creates a session.
  2. It creates an automation with trigger: { type: "every", every: "15 seconds" } and the Code Mode action return { state: { runs: input.runs } }.
  3. It reads the automation again 50 s later.

The SDK hosts get permissions: [{ action: "*", resource: "*", effect: "allow" }], so that the Code Mode action is authorized without a prompt. opencode serve uses its default configuration.

It needs Docker, curl and jq, and no API keys. RUNTIMES=…, WAIT_S=…, VERSION=… and KEEP=1 select a subset, change the wait, change the version or leave the containers running.

repro.sh
#!/usr/bin/env bash
set -euo pipefail

VERSION=${VERSION:-2.4.1}
WRANGLER=${WRANGLER:-4.152.0}
WAIT_S=${WAIT_S:-50}
RUNTIMES=${RUNTIMES:-"sdk-node sdk-workerd serve"}

cleanup() {
  docker rm -f runtime >/dev/null 2>&1 || true
  docker volume rm probe-npm >/dev/null 2>&1 || true
}
[ "${KEEP:-0}" = 1 ] || trap cleanup EXIT
cleanup
for image in node:24-bookworm node:22-bookworm; do docker pull -q "$image" >/dev/null; done
docker volume create probe-npm >/dev/null
rm -rf work && mkdir -p work/node work/workerd && cd work

cat > node/package.json <<'EOF'
{ "name": "automation-probe", "private": true, "type": "module" }
EOF

cat > node/probe.mjs <<'EOF'
import { OpenCode as Sdk } from "@opencode/sdk";
import { OpenCode as Client } from "@opencode/client";

const config = { permissions: [{ action: "*", resource: "*", effect: "allow" }] };
const host =
  process.argv[2] === "sdk"
    ? await Sdk.create({ config: { content: JSON.stringify(config) } })
    : Client.make({
        baseUrl: "http://127.0.0.1:4096",
        headers: { authorization: `Basic ${btoa(`opencode:${process.env.SERVE_PASSWORD}`)}` },
      });
const show = ({ id, status, runCount, lastRunAt, lastOutcome, nextDueAt, state }) =>
  JSON.stringify({ id, status, runCount, lastRunAt, lastOutcome, nextDueAt, state });

if (process.argv[3] === "create" || process.argv[2] === "sdk") {
  const session = await (host.sessions ?? host.session).create({ location: { directory: process.cwd() } });
  const created = await host.experimental.automation.create({
    sessionID: session.id,
    name: "probe",
    trigger: { type: "every", every: "15 seconds" },
    action: { type: "code", code: "return { state: { runs: input.runs } }" },
  });
  console.log(show(created));
  if (process.argv[2] !== "sdk") process.exit(0);
  await new Promise((resolve) => setTimeout(resolve, Number(process.env.WAIT_S) * 1000));
  console.log(show(await host.experimental.automation.get({ automationID: created.id })));
} else {
  console.log(show(await host.experimental.automation.get({ automationID: process.argv[3] })));
}
process.exit(0);
EOF

cat > workerd/package.json <<'EOF'
{ "name": "automation-probe-workerd", "private": true, "type": "module" }
EOF

cat > workerd/wrangler.jsonc <<'EOF'
{
  "name": "automation-probe",
  "main": "index.js",
  "compatibility_date": "2026-08-30",
  "compatibility_flags": ["nodejs_compat"],
  "durable_objects": { "bindings": [{ "name": "PROBE", "class_name": "Probe" }] },
  "migrations": [{ "tag": "v1", "new_sqlite_classes": ["Probe"] }]
}
EOF

cat > workerd/index.js <<'EOF'
import { DurableObject } from "cloudflare:workers";
import { OpenCodeWorkerd } from "@opencode/sdk/workerd";

const config = { permissions: [{ action: "*", resource: "*", effect: "allow" }] };
const show = ({ id, status, runCount, lastRunAt, lastOutcome, nextDueAt, state }) => ({
  id, status, runCount, lastRunAt, lastOutcome, nextDueAt, state,
});

export class Probe extends DurableObject {
  constructor(ctx, env) {
    super(ctx, env);
    this.host = OpenCodeWorkerd.create({ storage: ctx.storage, config, models: { fetch: false } });
  }

  async fetch(request) {
    const url = new URL(request.url);
    const host = await this.host;
    if (url.pathname === "/create") {
      const session = await host.sessions.create({ location: { directory: "/workspace" } });
      const created = await host.experimental.automation.create({
        sessionID: session.id,
        name: "probe",
        trigger: { type: "every", every: "15 seconds" },
        action: { type: "code", code: "return { state: { runs: input.runs } }" },
      });
      return Response.json(show(created));
    }
    return Response.json(show(await host.experimental.automation.get({ automationID: url.searchParams.get("id") })));
  }
}

export default {
  fetch: (request, env) => env.PROBE.get(env.PROBE.idFromName("probe")).fetch(request),
};
EOF

install() {
  docker run --rm -v "$PWD/$1:/app" -v probe-npm:/root/.npm -w /app "$2" \
    sh -c "npm i --silent --no-audit --no-fund $3 >/dev/null 2>&1"
}
install node node:24-bookworm "@opencode/sdk@$VERSION @opencode/client@$VERSION"

wait_http() {
  for _ in $(seq 1 180); do
    code=$(docker exec runtime sh -c "curl -s -o /dev/null -w '%{http_code}' $1 || true" 2>/dev/null || true)
    [ -n "$code" ] && [ "$code" != 000 ] && return
    sleep 1
  done
  echo "runtime did not start" >&2
  docker logs runtime 2>&1 | tail -20 >&2
  exit 1
}

row() {
  printf '| %s | %s | %s | %s | %s | %s |\n' "$1" \
    "$(echo "$2" | jq -r .runCount)" "$(echo "$3" | jq -r .runCount)" \
    "$(echo "$3" | jq -r '.lastOutcome // "—"')" "$(echo "$3" | jq -r 'if .state then (.state | tojson) else "—" end')" \
    "$(echo "$3" | jq -r '.nextDueAt as $d | if $d < (now * 1000) then "yes, by \(((now * 1000 - $d) / 1000) | floor) s" else "no" end')"
}

echo "OpenCode $VERSION. Each row creates an automation with trigger { type: \"every\", every: \"15 seconds\" } and a Code Mode action, then reads it after ${WAIT_S} s."
echo
echo "| Runtime | runCount at create | runCount after ${WAIT_S} s | lastOutcome | state | nextDueAt in the past |"
echo "|---|---:|---:|---|---|---|"
for runtime in $RUNTIMES; do
  docker rm -f runtime >/dev/null 2>&1 || true
  case "$runtime" in
    sdk-node)
      out=$(docker run --rm --name runtime -v "$PWD/node:/app" -w /app -e WAIT_S="$WAIT_S" node:24-bookworm node probe.mjs sdk)
      row "\`OpenCode.create\` (\`@opencode/sdk\`, Node 24)" "$(echo "$out" | sed -n 1p)" "$(echo "$out" | sed -n 2p)" ;;
    sdk-workerd)
      install workerd node:22-bookworm "@opencode/sdk@$VERSION wrangler@$WRANGLER"
      docker run -d --name runtime -v "$PWD/workerd:/app" -w /app -e CI=1 -e WRANGLER_SEND_METRICS=false \
        node:22-bookworm npx wrangler dev --ip 127.0.0.1 --port 8787 >/dev/null
      wait_http http://127.0.0.1:8787/
      created=$(docker exec runtime curl -s -m 120 http://127.0.0.1:8787/create)
      sleep "$WAIT_S"
      after=$(docker exec runtime curl -s -m 60 "http://127.0.0.1:8787/get?id=$(echo "$created" | jq -r .id)")
      row "\`OpenCodeWorkerd.create\` in a Durable Object (\`wrangler dev\` $WRANGLER)" "$created" "$after" ;;
    serve)
      docker run -d --name runtime -v "$PWD/node:/app" -w /app node:24-bookworm \
        sh -c "npm i -g --silent --no-audit --no-fund @opencode/cli@$VERSION >/dev/null 2>&1 && opencode serve --hostname 127.0.0.1 --port 4096 2>&1" >/dev/null
      wait_http http://127.0.0.1:4096/
      password=$(docker logs runtime 2>&1 | awk '/server password/ {print $3}')
      created=$(docker exec -e SERVE_PASSWORD="$password" runtime node probe.mjs serve create)
      sleep "$WAIT_S"
      after=$(docker exec -e SERVE_PASSWORD="$password" runtime node probe.mjs serve "$(echo "$created" | jq -r .id)")
      row "\`opencode serve\` (\`@opencode/cli\`, control)" "$created" "$after" ;;
  esac
done

Actual behavior and opencode serve comparison

OpenCode 2.4.1. Each row creates an automation with trigger { type: "every", every: "15 seconds" } and a Code Mode action, then reads it after 50 s.

Runtime runCount at create runCount after 50 s lastOutcome state nextDueAt in the past
OpenCode.create (@opencode/sdk, Node 24) 0 0 — — yes, by 35 s
OpenCodeWorkerd.create in a Durable Object (wrangler dev 4.152.0) 0 0 — — yes, by 35 s
opencode serve (@opencode/cli, control) 0 3 fired {"runs":2} no
  • Embedded hosts: nextDueAt is 35 s in the past when the script reads the automation, and the automation has not run once.
  • opencode serve: the automation runs at 15 s, 30 s and 45 s. Its state comes from the Code Mode action.

Relevant source path

All at v2.4.1:

Expected behavior

  1. An embedded host runs automations, as opencode serve does: OpenCode.create starts Automation.Service.run (and SessionSearchBuild.Service.run) in the host runtime, as it starts resumeSuspendedSessions now.
  2. On workerd, an automation that falls due while the Durable Object has no requests still runs on time. Starting run there helps only while the object stays in memory. The host needs a way to drive the scheduler from the Durable Object alarm. For example, the SDK could expose tick() and the next due time, so the object's alarm() can call tick() and set the next alarm. Or OpenCodeWorkerd.create could set and handle the alarm itself.
  3. If a host does not run automations, automation.create (the tool, the HTTP route and the plugin API) fails with an error that says so. It does not accept an automation that will never run.

Acceptance

  1. With RUNTIMES=sdk-node, repro.sh shows a runCount of 3 and lastOutcome: fired after 50 s, the same as the opencode serve row.
  2. With RUNTIMES=sdk-workerd, the same result. An automation also runs when it falls due after the Durable Object is evicted, with no new request to the object.
  3. A test covers an automation that comes due on an embedded host.

Related reports checked

I searched the issues for "automation sdk", "automations embedded", "automation workerd", "automation durable object", "Automation.run" and "automations never run", and found no report of this.

  • #65747 (merged) added ctx.experimental.automation for plugins. That makes this bug easier to reach from an embedded host.
  • #65987 (merged) and #65988 (closed) fix automation.create calls that hang during plugin setup, including in the embedded SDK with instances. This report is about automations that are created correctly but never run.

heymaaz avatar Nov 24 '26 16:11 heymaaz

Thanks for the detailed report. I reproduced this on the released 2.4.1 packages, and it still happens on the latest dev (66d53a82d).

  • Embedded host (OpenCode.create, @opencode/[email protected], Node 24): an automation with every: "15 seconds" and the Code Mode action was still at runCount: 0 after 50 s, with no lastRunAt or lastOutcome. Its nextDueAt was about 36 s in the past.
  • Control (opencode serve, @opencode/[email protected]): the same automation ran 3 times in 50 s and ended with lastOutcome: "fired" and state: {"runs":2}.
  • Latest dev (66d53a82d) from source: the same embedded-host script gave the same result as the release, runCount: 0 with nextDueAt in the past.

The Code Mode action doesn't call a model, so nothing was simulated. I only tested the Node OpenCode.create host. I didn't run the OpenCodeWorkerd.create / Durable Object case, but it uses the same host code. The script below reproduces it.

Reproduction script (probe.mjs)
// Embedded SDK host: create an automation that should fire every 15 s, then read it after WAIT_S seconds.
import { OpenCode } from "@opencode/sdk";
const WAIT_S = Number(process.env.WAIT_S ?? 50);
const config = { permissions: [{ action: "*", resource: "*", effect: "allow" }] };
const host = await OpenCode.create({ config: { content: JSON.stringify(config) } });
const show = ({ id, status, runCount, lastRunAt, lastOutcome, nextDueAt, state }) =>
  JSON.stringify({ id, status, runCount, lastRunAt, lastOutcome, nextDueAt, state });
const session = await host.sessions.create({ location: { directory: process.cwd() } });
const created = await host.experimental.automation.create({
  sessionID: session.id,
  name: "probe",
  trigger: { type: "every", every: "15 seconds" },
  action: { type: "code", code: "return { state: { runs: input.runs } }" },
});
console.log("created:", show(created));
await new Promise((r) => setTimeout(r, WAIT_S * 1000));
const after = await host.experimental.automation.get({ automationID: created.id });
console.log(`after ${WAIT_S}s:`, show(after), "now:", Date.now());
process.exit(0);

Run it: bun probe.mjs

opencodejr[bot] avatar Nov 24 '26 16:11 opencodejr[bot]

The fix looks small: EmbeddedHost.create in packages/sdk/src/internal/host.ts already forks SessionRestart.Service.resumeSuspendedSessions with runtime.runFork(...). Forking Context.get(services, Automation.Service).run the same way would give embedded hosts the scheduler that packages/server/src/process.ts starts with Effect.forkIn(..., applicationScope). Per the existing comment there, the ManagedRuntime owns that fiber, so it would stop with the host the same way.

process.ts forks SessionSearchBuild.Service.run right after the automation loop, and the embedded host doesn't start that one either. So I think the session search index is never built on an embedded host, for the same reason.

I'm happy to send a PR for both. One question first: the shortest allowed interval is 15 s (MIN_CODE_INTERVAL), so an end-to-end test in packages/sdk/test/embedded.test.ts that waits for a real run would take about 15 s, over the 5 s the embedded tests aim for. Would a test with a raised timeout be OK, or would you rather have a narrower check, e.g. that a created automation's runCount moves past 0 under a shorter test-only interval?

(I use AI assistance for my contributions and check what I submit.)

miscos330 avatar Nov 24 '26 17:11 miscos330

Taking the host half of this. packages/server/src/process.ts:131-134 starts Automation.Service.run and SessionSearchBuild.Service.run; packages/sdk/src/internal/host.ts:54-56 starts only SessionRestart.resumeSuspendedSessions. I'll mirror the two fibers in the embedded host and add a test that an automation with an every trigger actually fires there. The workerd alarm half needs a Durable Object runtime, so it would be a separate PR if this lands.

Guembri01 avatar Nov 24 '26 20:11 Guembri01

Dropping my branch for this: @hearnadam's #66180 covers it (fix(sdk): start Automation.Service.run in embedded hosts), and I'd rather not race a PR that already exists — this session has already watched a duplicate get closed in six minutes.

For the record, the fix I had verified and was holding: start Automation.Service.run and SessionSearchBuild.Service.run in packages/sdk/src/internal/host.ts, mirroring packages/server/src/process.ts:131-134, with a test that creates an at: "in 2 seconds" code automation and polls runCount — fails without the change (automation never ran after ~12 s), 41 pass with it.

The workerd half of this issue (an automation that falls due while the Durable Object has no requests) is still open either way; that needs the alarm, not just the fiber.

Guembri01 avatar Nov 25 '26 19:11 Guembri01