Skip to content

Durable coding-agent harnesses (Claude Code, Codex, OpenCode, Pi, fx) on a Workflow SDK World

67.3 KB
Raw Blame
// Generated by apps/cloudflare/scripts/vendor-world-cloudflare.mjs from
// vercel/workflow#4682 (packages/world-cloudflare) at a555966986af83b94cb77d1d427dfdb18a2732cc.
// Do not edit: refresh it with `pnpm --filter harness-cloudflare vendor:world`.
// src/quickjs.ts
var ASSETS_KEY = /* @__PURE__ */ Symbol.for("@workflow/core//quickjsCompiledAssets/v1");
function installQuickJSModules(modules) {
  globalThis[ASSETS_KEY] = {
    promise: Promise.resolve({
      wasm: modules.quickjs,
      extensions: [
        { name: "encoding", wasm: modules.encoding },
        { name: "headers", wasm: modules.headers },
        { name: "url", wasm: modules.url },
        {
          name: "structured-clone",
          wasm: modules.structuredClone,
          initFn: "qjs_ext_structured_clone_init"
        }
      ]
    })
  };
}

// src/runtime.ts
import { AsyncLocalStorage } from "node:async_hooks";
import { globalSingleton } from "@workflow/utils";
var DELIVERY_HEADER = "x-workflow-cloudflare-delivery";
var FLOW_URL = "http://workflow.internal/.well-known/workflow/v1/flow";
var state = globalSingleton("@workflow/world-cloudflare//runtime", 1, () => ({
  config: void 0,
  sharedFlow: void 0,
  pending: /* @__PURE__ */ new Map(),
  nextToken: 0
}));
function configureRuntime(config) {
  state.config = config;
}
function getRuntimeConfig() {
  if (!state.config) {
    throw new Error(
      "world-cloudflare: configureRuntime() was not called before the World was used"
    );
  }
  return state.config;
}
function createQueueHandler(_prefix, handler) {
  return async (req) => {
    const token = req.headers.get(DELIVERY_HEADER);
    const delivery = token ? state.pending.get(token) : void 0;
    if (!token || !delivery) {
      return new Response("Unknown workflow delivery", { status: 400 });
    }
    state.pending.delete(token);
    try {
      delivery.resolve(await handler(delivery.message, delivery.meta));
    } catch (error) {
      delivery.reject(error);
    }
    return new Response(null, { status: 204 });
  };
}
function sharedFlowRoute() {
  state.sharedFlow ??= getRuntimeConfig().createFlowRoute();
  return state.sharedFlow;
}
async function deliver(message, meta, flow = sharedFlowRoute()) {
  const token = `d${++state.nextToken}`;
  const result = new Promise((resolve, reject) => {
    state.pending.set(token, { message, meta, resolve, reject });
  });
  const response = await flow(
    new Request(FLOW_URL, {
      method: "POST",
      headers: { [DELIVERY_HEADER]: token }
    })
  );
  if (state.pending.delete(token)) {
    throw new Error(
      `world-cloudflare: workflow route did not run the delivery (HTTP ${response.status}: ${await response.text()})`
    );
  }
  return result;
}
var localRun = globalSingleton(
  "@workflow/world-cloudflare//localRun",
  1,
  () => ({ storage: new AsyncLocalStorage() })
);
function currentLocalRun() {
  return localRun.storage.getStore();
}
function runAsLocal(run, fn) {
  return localRun.storage.run(run, fn);
}

// src/world.ts
import { HookNotFoundError, WorkflowWorldError as WorkflowWorldError2 } from "@workflow/errors";
import { unwrapInvocationOutcome as unwrapInvocationOutcome2 } from "@workflow/errors/invocation";
import { SPEC_VERSION_CURRENT } from "@workflow/world";
import { ulid } from "ulid";

// src/encryption.ts
function secretBytes() {
  const raw = process.env.WORKFLOW_ENCRYPTION_SECRET;
  if (!raw) return void 0;
  const bytes = Uint8Array.from(atob(raw), (c) => c.charCodeAt(0));
  if (bytes.length !== 32) {
    throw new Error("WORKFLOW_ENCRYPTION_SECRET must be 32 bytes of base64");
  }
  return bytes;
}
async function getEncryptionKeyForRun(run) {
  const secret = secretBytes();
  if (!secret) return void 0;
  const runId = typeof run === "string" ? run : run.runId;
  const base = await crypto.subtle.importKey("raw", secret, "HKDF", false, [
    "deriveBits"
  ]);
  const bits = await crypto.subtle.deriveBits(
    {
      name: "HKDF",
      hash: "SHA-256",
      salt: new Uint8Array(32),
      info: new TextEncoder().encode(`workflow-cloudflare|${runId}`)
    },
    base,
    256
  );
  return new Uint8Array(bits);
}

// src/rpc.ts
import { env } from "cloudflare:workers";
import { WorkflowWorldError } from "@workflow/errors";
import {
  captureInvocationOutcome,
  unwrapInvocationOutcome
} from "@workflow/errors/invocation";
var RUNS_BINDING = "WORKFLOW_RUNS";
var TOKENS_BINDING = "WORKFLOW_TOKENS";
var STREAMS_BINDING = "WORKFLOW_STREAMS";
function namespace(binding) {
  const ns = env[binding];
  if (!ns) {
    throw new WorkflowWorldError(
      `world-cloudflare: missing Durable Object binding "${binding}"`,
      { status: 500 }
    );
  }
  return ns;
}
function stub(binding, name) {
  return namespace(binding).getByName(name);
}
function serve(fn) {
  return captureInvocationOutcome(async () => fn());
}
async function call(binding, name, method, ...args) {
  const outcome = await stub(binding, name)[method](...args);
  return unwrapInvocationOutcome(outcome);
}

// src/world.ts
function probeObjectName(correlationId) {
  return `probe:${correlationId}`;
}
async function onRun(runId, method, ...args) {
  const local = currentLocalRun();
  if (local && local.runId === runId) {
    const api = local.object.api;
    return api[method](
      ...args
    );
  }
  return call(RUNS_BINDING, runId, "call", method, args);
}
function unsupported(what) {
  throw new WorkflowWorldError2(
    `world-cloudflare: ${what} is not supported by this proof of concept`,
    { status: 501 }
  );
}
function streamObject(runId, name) {
  return `stream:${runId}:${name}`;
}
function streamIndexObject(runId) {
  return `streams:${runId}`;
}
var encoder = new TextEncoder();
var toBytes = (chunk) => typeof chunk === "string" ? encoder.encode(chunk) : chunk;
function createCloudflareWorld() {
  const streams = {
    async write(runId, name, chunk) {
      await call(STREAMS_BINDING, streamIndexObject(runId), "register", name);
      await call(STREAMS_BINDING, streamObject(runId, name), "append", [
        toBytes(chunk)
      ]);
    },
    async writeMulti(runId, name, chunks) {
      await call(STREAMS_BINDING, streamIndexObject(runId), "register", name);
      await call(
        STREAMS_BINDING,
        streamObject(runId, name),
        "append",
        chunks.map(toBytes)
      );
    },
    async close(runId, name) {
      await call(STREAMS_BINDING, streamIndexObject(runId), "register", name);
      await call(STREAMS_BINDING, streamObject(runId, name), "close");
    },
    async list(runId) {
      return call(STREAMS_BINDING, streamIndexObject(runId), "names");
    },
    async getChunks(runId, name, options) {
      return call(
        STREAMS_BINDING,
        streamObject(runId, name),
        "chunks",
        options ?? {}
      );
    },
    async getInfo(runId, name) {
      return call(
        STREAMS_BINDING,
        streamObject(runId, name),
        "info"
      );
    },
    async get(runId, name, startIndex = 0) {
      let next = startIndex;
      if (next < 0) {
        const info = await streams.getInfo(runId, name);
        next = Math.max(0, info.tailIndex + 1 + next);
      }
      let cancelled = false;
      return new ReadableStream({
        async pull(controller) {
          while (!cancelled) {
            const page = await streams.getChunks(runId, name, {
              cursor: String(next),
              limit: 100
            });
            if (page.data.length > 0) {
              for (const chunk of page.data) controller.enqueue(chunk.data);
              next += page.data.length;
              return;
            }
            if (page.done) {
              controller.close();
              return;
            }
            await new Promise((resolve) => setTimeout(resolve, 100));
          }
        },
        cancel() {
          cancelled = true;
        }
      });
    }
  };
  const world = {
    specVersion: SPEC_VERSION_CURRENT,
    capabilities: {
      // At most one runner per run: every ordinary delivery for a run is
      // executed by that run's Durable Object, one at a time. See run-object.ts.
      invoke: true
    },
    getEncryptionKeyForRun,
    // VM snapshots live in the run's object next to its event log, so a
    // snapshot and the log position it was taken at can never disagree.
    experimental_snapshots: {
      save: (runId, data, metadata) => onRun(runId, "snapshotSave", runId, data, metadata),
      load: (runId) => onRun(runId, "snapshotLoad", runId),
      delete: (runId) => onRun(runId, "snapshotDelete", runId)
    },
    async getDeploymentId() {
      return getRuntimeConfig().deploymentId;
    },
    createQueueHandler,
    async queue(queueName, message, opts) {
      const runId = message.runId;
      if (typeof runId === "string") {
        return onRun(runId, "enqueue", queueName, message, opts);
      }
      if ("__healthCheck" in message && message.__healthCheck) {
        return call(
          RUNS_BINDING,
          probeObjectName(message.correlationId),
          "call",
          "enqueue",
          [queueName, message, opts]
        );
      }
      return unsupported("a queue message without a runId");
    },
    async invoke(runId, payload, options) {
      const outcome = await onRun(runId, "invoke", runId, payload, options);
      return unwrapInvocationOutcome2(outcome);
    },
    runs: {
      get: ((runId, params) => onRun(runId, "runsGet", runId, params)),
      list: (() => unsupported("runs.list"))
    },
    steps: {
      get: ((runId, stepId, params) => onRun(
        runId,
        "stepsGet",
        runId,
        stepId,
        params
      )),
      list: ((params) => onRun(params.runId, "stepsList", params))
    },
    events: {
      create: (async (runId, data, params) => {
        const id = runId || `wrun_${ulid()}`;
        return onRun(id, "eventsCreate", id, data, params);
      }),
      get: (runId, eventId, params) => onRun(runId, "eventsGet", runId, eventId, params),
      list: (params) => onRun(params.runId, "eventsList", params),
      listByCorrelationId: (params) => onRun(params.runId, "eventsListByCorrelationId", params)
    },
    hooks: {
      async get(hookId, params) {
        const local = currentLocalRun();
        if (local) {
          try {
            return await onRun(local.runId, "hooksGet", hookId, params);
          } catch (error) {
            if (!HookNotFoundError.is(error)) throw error;
          }
        }
        const owner = await call(
          TOKENS_BINDING,
          `hook:${hookId}`,
          "lookup"
        );
        if (!owner) throw new HookNotFoundError(hookId);
        return onRun(owner.runId, "hooksGet", hookId, params);
      },
      async getByToken(token, params) {
        const owner = await call(
          TOKENS_BINDING,
          `token:${token}`,
          "lookup"
        );
        if (!owner) throw new HookNotFoundError(token);
        try {
          return await onRun(owner.runId, "hooksGet", owner.hookId, params);
        } catch (error) {
          if (HookNotFoundError.is(error)) throw new HookNotFoundError(token);
          throw error;
        }
      },
      async list(params) {
        if (!params.runId) return unsupported("hooks.list without a runId");
        return onRun(params.runId, "hooksList", params);
      }
    },
    streams
  };
  return world;
}

// src/run-object.ts
import { DurableObject } from "cloudflare:workers";
import {
  EntityConflictError as EntityConflictError2,
  WorkflowRunNotFoundError as WorkflowRunNotFoundError2,
  WorkflowWorldError as WorkflowWorldError4
} from "@workflow/errors";
import {
  captureInvocationOutcome as captureInvocationOutcome2,
  isTerminalInvocationError,
  unwrapInvocationOutcome as unwrapInvocationOutcome3
} from "@workflow/errors/invocation";
import {
  decodeSnapshotEnvelope,
  encodeSnapshotEnvelope,
  getQueueTopicPrefix,
  isTerminalWorkflowRunStatus as isTerminalWorkflowRunStatus2,
  requireEventSlot as requireEventSlot2,
  SPEC_VERSION_CURRENT as SPEC_VERSION_CURRENT3
} from "@workflow/world";

// ../world-sim/dist/store.js
import { EntityConflictError, HookNotFoundError as HookNotFoundError2, PreconditionFailedError, RunExpiredError, TooEarlyError, WorkflowRunNotFoundError, WorkflowWorldError as WorkflowWorldError3 } from "@workflow/errors";
import { entityResolveData, isChildEntityCreationEvent, isHookEventRequiringExistence, isStepEventType, isTerminalRunEventType, isTerminalStepEventType, isTerminalStepStatus, isTerminalWorkflowRunStatus, requireEventSlot, SPEC_VERSION_CURRENT as SPEC_VERSION_CURRENT2, slotToEventId, stripEventDataRefs } from "@workflow/world";
var MAX_EVENTS_PER_RUN = 25e3;
var DEFAULT_PAGE_LIMIT = 20;
var RUN_EVENT_INDEX_WINDOW = 16;
function countRecordedAtOrBelow(index, maxSlot) {
  const above = index.recentEventIds.filter((id) => requireEventSlot(id) > maxSlot).length;
  const pruned = index.total > index.recentEventIds.length;
  if (pruned && above === index.recentEventIds.length)
    return null;
  return index.total - above;
}
function isDate(value) {
  return Object.prototype.toString.call(value) === "[object Date]";
}
function clone(value) {
  if (Array.isArray(value))
    return value.map(clone);
  if (isDate(value))
    return new Date(value.getTime());
  if (value instanceof Uint8Array)
    return value;
  if (value && typeof value === "object") {
    const out = {};
    for (const [k, v] of Object.entries(value))
      out[k] = clone(v);
    return out;
  }
  return value;
}
function encodeCursor(createdAt, id) {
  return `${createdAt.toISOString()}|${id}`;
}
function decodeCursor(cursor) {
  if (!cursor)
    return null;
  const [time, id] = cursor.split("|");
  return { timeMs: new Date(time).getTime(), id: id || null };
}
function paginate(items, opts) {
  const sortOrder = opts.pagination?.sortOrder ?? opts.defaultSortOrder ?? "desc";
  const limit = opts.pagination?.limit ?? DEFAULT_PAGE_LIMIT;
  const cursor = decodeCursor(opts.pagination?.cursor);
  const sorted = [...items].sort((a, b) => {
    const at = opts.getCreatedAt(a).getTime();
    const bt = opts.getCreatedAt(b).getTime();
    if (at !== bt)
      return sortOrder === "asc" ? at - bt : bt - at;
    const ai = opts.getId(a);
    const bi = opts.getId(b);
    return sortOrder === "asc" ? ai.localeCompare(bi) : bi.localeCompare(ai);
  });
  const afterCursor = cursor ? sorted.filter((item) => {
    const t = opts.getCreatedAt(item).getTime();
    if (sortOrder === "asc") {
      if (t < cursor.timeMs)
        return false;
      if (t === cursor.timeMs && cursor.id) {
        return opts.getId(item).localeCompare(cursor.id) > 0;
      }
      return t > cursor.timeMs;
    }
    if (t > cursor.timeMs)
      return false;
    if (t === cursor.timeMs && cursor.id) {
      return opts.getId(item).localeCompare(cursor.id) < 0;
    }
    return t < cursor.timeMs;
  }) : sorted;
  const hasMore = afterCursor.length > limit;
  const page = hasMore ? afterCursor.slice(0, limit) : afterCursor;
  const last = page[page.length - 1];
  return {
    data: page.map(clone),
    cursor: last ? encodeCursor(opts.getCreatedAt(last), opts.getId(last)) : null,
    hasMore
  };
}
function createSimStore(options) {
  const { ids, now: nowMs } = options;
  const events = [];
  const runs = /* @__PURE__ */ new Map();
  const steps = /* @__PURE__ */ new Map();
  const hooks = /* @__PURE__ */ new Map();
  const tokenOwners = /* @__PURE__ */ new Map();
  const waits = /* @__PURE__ */ new Map();
  const disposedHooks = /* @__PURE__ */ new Set();
  const externalWriteMarker = /* @__PURE__ */ new Map();
  const runEventIndex = /* @__PURE__ */ new Map();
  let armedWithhold;
  let withheld;
  function applyWithhold(source) {
    if (!withheld || withheld.remaining <= 0)
      return source;
    const { eventId } = withheld;
    withheld.remaining--;
    if (withheld.remaining <= 0)
      withheld = void 0;
    const visible = source.filter((e) => e.eventId < eventId);
    const hidden = source.length - visible.length;
    if (hidden > 0) {
      options.onStaleRead?.({ eventId, hidden, truncated: true });
    }
    return visible;
  }
  const stepKey = (runId, stepId) => `${runId}:${stepId}`;
  const waitKey = (runId, correlationId) => `${runId}:${correlationId}`;
  function eventPosition(runId) {
    return {
      eventId: slotToEventId(committedSlot(runId) + 1),
      createdAt: new Date(nowMs())
    };
  }
  function committedSlot(runId) {
    return events.filter((event) => event.runId === runId).reduce((max, event) => Math.max(max, requireEventSlot(event.eventId)), 0);
  }
  function recordInIndex(event) {
    const index = runEventIndex.get(event.runId) ?? {
      recentEventIds: [],
      total: 0
    };
    index.recentEventIds.push(event.eventId);
    index.recentEventIds.sort((a, b) => a.localeCompare(b));
    if (index.recentEventIds.length > RUN_EVENT_INDEX_WINDOW) {
      index.recentEventIds.shift();
    }
    index.total++;
    runEventIndex.set(event.runId, index);
  }
  function append(event) {
    events.push(event);
    recordInIndex(event);
    if (armedWithhold !== void 0) {
      withheld = { eventId: event.eventId, remaining: armedWithhold };
      armedWithhold = void 0;
    }
    options.onEvent?.(event);
    return event;
  }
  function requireRun(runId) {
    const run = runs.get(runId);
    if (!run)
      throw new WorkflowRunNotFoundError(runId);
    return run;
  }
  function resumeContextFor(run) {
    const ctx = run.executionContext ?? {};
    return {
      deploymentId: run.deploymentId,
      workflowName: run.workflowName,
      runSpecVersion: run.specVersion,
      ...typeof ctx.workflowCoreVersion === "string" ? { workflowCoreVersion: ctx.workflowCoreVersion } : {},
      ...typeof ctx.nodeVersion === "string" ? { nodeVersion: ctx.nodeVersion } : {},
      ...ctx.traceCarrier && typeof ctx.traceCarrier === "object" ? {
        traceCarrier: ctx.traceCarrier
      } : {},
      ...run.encryptionPublicKey ? { encryptionPublicKey: run.encryptionPublicKey } : {}
    };
  }
  function releaseRunResources(runId) {
    for (const [hookId, hook] of hooks) {
      if (hook.runId !== runId)
        continue;
      if (tokenOwners.get(hook.token) === hookId)
        tokenOwners.delete(hook.token);
      hooks.delete(hookId);
    }
    for (const [key, wait] of waits) {
      if (wait.runId === runId)
        waits.delete(key);
    }
  }
  function eventsForRun(runId) {
    return events.filter((e) => e.runId === runId);
  }
  function applyEvent(event, at) {
    const runId = event.runId;
    const data = event.eventData;
    const correlationId = event.correlationId;
    switch (event.eventType) {
      case "run_created": {
        const run = {
          runId,
          deploymentId: data?.deploymentId,
          workflowName: data?.workflowName,
          status: "pending",
          specVersion: event.specVersion,
          executionContext: data?.executionContext,
          input: data?.input,
          attributes: data?.attributes ?? {},
          encryptionPublicKey: data?.encryptionPublicKey,
          createdAt: at,
          updatedAt: at
        };
        runs.set(runId, run);
        return { run };
      }
      case "run_started": {
        const existing = runs.get(runId);
        if (!existing)
          return {};
        const run = {
          ...existing,
          status: "running",
          output: void 0,
          error: void 0,
          completedAt: void 0,
          startedAt: existing.startedAt ?? at,
          updatedAt: at
        };
        runs.set(runId, run);
        return { run };
      }
      case "run_completed":
      case "run_failed":
      case "run_cancelled": {
        const existing = runs.get(runId);
        if (!existing)
          return {};
        const run = {
          ...existing,
          status: event.eventType === "run_completed" ? "completed" : event.eventType === "run_failed" ? "failed" : "cancelled",
          output: data?.output,
          error: data?.error,
          errorCode: data?.errorCode,
          completedAt: at,
          updatedAt: at
        };
        runs.set(runId, run);
        releaseRunResources(runId);
        return { run };
      }
      case "attr_set": {
        const existing = runs.get(runId);
        if (!existing)
          return {};
        const attributes = { ...existing.attributes };
        for (const change of data?.changes ?? []) {
          if (change.value === null)
            delete attributes[change.key];
          else
            attributes[change.key] = change.value;
        }
        const run = { ...existing, attributes, updatedAt: at };
        runs.set(runId, run);
        return { run };
      }
      case "step_created": {
        if (!correlationId)
          return {};
        const step = {
          runId,
          stepId: correlationId,
          stepName: data?.stepName,
          status: "pending",
          input: data?.input,
          attempt: 0,
          createdAt: at,
          updatedAt: at,
          specVersion: event.specVersion
        };
        steps.set(stepKey(runId, correlationId), step);
        return { step };
      }
      case "step_started":
      case "step_completed":
      case "step_failed":
      case "step_retrying": {
        if (!correlationId)
          return {};
        const key = stepKey(runId, correlationId);
        const existing = steps.get(key);
        if (!existing)
          return {};
        const step = event.eventType === "step_started" ? {
          ...existing,
          status: "running",
          startedAt: existing.startedAt ?? at,
          attempt: existing.attempt + 1,
          retryAfter: void 0,
          updatedAt: at
        } : event.eventType === "step_completed" ? {
          ...existing,
          status: "completed",
          output: data?.result,
          completedAt: at,
          updatedAt: at
        } : event.eventType === "step_failed" ? {
          ...existing,
          status: "failed",
          error: data?.error,
          completedAt: at,
          updatedAt: at
        } : {
          ...existing,
          status: "pending",
          error: data?.error,
          retryAfter: data?.retryAfter,
          updatedAt: at
        };
        steps.set(key, step);
        return { step };
      }
      case "hook_created": {
        if (!correlationId)
          return {};
        const token = data?.token;
        const owningRun = runs.get(runId);
        const hook = {
          runId,
          hookId: correlationId,
          token,
          metadata: data?.metadata,
          ownerId: "sim-owner",
          projectId: "sim-project",
          environment: "sim",
          createdAt: at,
          specVersion: event.specVersion,
          isWebhook: data?.isWebhook ?? false,
          isSystem: data?.isSystem ?? false,
          ...owningRun ? { resumeContext: resumeContextFor(owningRun) } : {}
        };
        hooks.set(correlationId, hook);
        tokenOwners.set(token, correlationId);
        return { hook };
      }
      // A delivered payload changes no row of its own; the hook is reported
      // back so the caller can return it.
      case "hook_received":
        return correlationId ? { hook: hooks.get(correlationId) } : {};
      case "hook_disposed": {
        if (!correlationId)
          return {};
        disposedHooks.add(correlationId);
        const existing = hooks.get(correlationId);
        if (existing && tokenOwners.get(existing.token) === correlationId) {
          tokenOwners.delete(existing.token);
        }
        hooks.delete(correlationId);
        return {};
      }
      case "wait_created": {
        if (!correlationId)
          return {};
        const key = waitKey(runId, correlationId);
        const wait = {
          waitId: key,
          runId,
          status: "waiting",
          resumeAt: data?.resumeAt,
          createdAt: at,
          updatedAt: at,
          specVersion: event.specVersion
        };
        waits.set(key, wait);
        return { wait };
      }
      case "wait_completed": {
        if (!correlationId)
          return {};
        const key = waitKey(runId, correlationId);
        const existing = waits.get(key);
        if (!existing)
          return {};
        const wait = {
          ...existing,
          status: "completed",
          completedAt: at,
          updatedAt: at
        };
        waits.set(key, wait);
        return { wait };
      }
      default:
        return {};
    }
  }
  async function create(runIdArg, data, params) {
    const now = new Date(nowMs());
    const internal = params;
    const resolveData = entityResolveData(params?.resolveData ?? "all");
    const specVersion = data.specVersion ?? SPEC_VERSION_CURRENT2;
    let runId;
    if (data.eventType === "run_created" && !runIdArg) {
      runId = ids.runId();
    } else if (!runIdArg) {
      throw new Error("runId is required for non-run_created events");
    } else {
      runId = runIdArg;
    }
    let position = eventPosition(runId);
    let currentRun = runs.get(runId);
    if (data.eventType === "run_started" && !currentRun && data.eventData) {
      const seed = data.eventData;
      if (seed.deploymentId && seed.workflowName && seed.input !== void 0) {
        const synthetic = {
          eventType: "run_created",
          runId,
          ...position,
          specVersion,
          eventData: {
            deploymentId: seed.deploymentId,
            workflowName: seed.workflowName,
            input: seed.input,
            executionContext: seed.executionContext,
            attributes: seed.attributes,
            encryptionPublicKey: seed.encryptionPublicKey
          }
        };
        currentRun = applyEvent(synthetic, now).run;
        append(synthetic);
        position = eventPosition(runId);
      }
    }
    if ((data.eventType === "run_failed" || data.eventType === "attr_set") && !currentRun) {
      throw new WorkflowRunNotFoundError(runId);
    }
    const snapshot = internal?.snapshot;
    if (options.preconditionGuard && snapshot) {
      const marker = externalWriteMarker.get(runId);
      if (marker !== void 0 && snapshot.maxSlot < marker) {
        throw new PreconditionFailedError(`Run "${runId}" changed out of band since the caller's snapshot`);
      }
      if (options.countGuard) {
        const index = runEventIndex.get(runId);
        const recorded = index ? countRecordedAtOrBelow(index, snapshot.maxSlot) : null;
        if (recorded !== null && recorded > snapshot.count) {
          throw new PreconditionFailedError(`Run "${runId}" holds ${recorded} events at or below the caller's watermark, but the caller loaded ${snapshot.count}`);
        }
      }
    }
    const createsChildEntity = isChildEntityCreationEvent(data);
    const lazyStepStart = createsChildEntity && data.eventType === "step_started";
    if (currentRun && isTerminalWorkflowRunStatus(currentRun.status)) {
      if (data.eventType === "run_cancelled" && currentRun.status === "cancelled") {
        const event2 = append({
          ...data,
          runId,
          ...position,
          specVersion
        });
        return {
          event: stripEventDataRefs(clone(event2), resolveData),
          run: clone(currentRun),
          maxEvents: MAX_EVENTS_PER_RUN
        };
      }
      if (data.eventType === "run_started") {
        throw new RunExpiredError(`Workflow run "${runId}" is already in terminal state "${currentRun.status}"`);
      }
      if (isTerminalRunEventType(data.eventType)) {
        throw new EntityConflictError(`Cannot transition run from terminal state "${currentRun.status}"`);
      }
      if (createsChildEntity) {
        throw new EntityConflictError(`Cannot create new entities on run in terminal state "${currentRun.status}"`);
      }
      if (data.eventType === "attr_set") {
        throw new EntityConflictError(`Cannot set attributes on run in terminal state "${currentRun.status}"`);
      }
    }
    let validatedStep;
    if (isStepEventType(data.eventType) && data.eventType !== "step_created" && data.correlationId) {
      validatedStep = steps.get(stepKey(runId, data.correlationId));
      if (!validatedStep && !lazyStepStart) {
        throw new WorkflowWorldError3(`Step "${data.correlationId}" not found`);
      }
      if (lazyStepStart && validatedStep) {
        throw new EntityConflictError(`Step "${data.correlationId}" already created`);
      }
      if (validatedStep) {
        if (isTerminalStepStatus(validatedStep.status)) {
          throw new EntityConflictError(`Cannot modify step in terminal state "${validatedStep.status}"`);
        }
        if (data.eventType === "step_started" && validatedStep.retryAfter && validatedStep.retryAfter.getTime() > nowMs()) {
          throw new TooEarlyError(`Cannot start step "${data.correlationId}": retryAfter timestamp has not been reached yet`, {
            retryAfter: Math.ceil((validatedStep.retryAfter.getTime() - nowMs()) / 1e3)
          });
        }
        if (currentRun && isTerminalWorkflowRunStatus(currentRun.status)) {
          if (validatedStep.status !== "running") {
            throw new RunExpiredError(`Cannot modify non-running step on run in terminal state "${currentRun.status}"`);
          }
        }
      }
    }
    if (isHookEventRequiringExistence(data.eventType) && data.correlationId) {
      if (disposedHooks.has(data.correlationId)) {
        throw new HookNotFoundError2(data.correlationId);
      }
      if (!hooks.has(data.correlationId)) {
        throw new HookNotFoundError2(data.correlationId);
      }
    }
    let event = {
      ...data,
      runId,
      ...position,
      specVersion
    };
    if (data.eventType === "run_started" && "eventData" in event) {
      delete event.eventData;
    }
    function sinceCursorDelta() {
      if (typeof params?.sinceCursor !== "string")
        return void 0;
      if (!isTerminalStepEventType(data.eventType) && data.eventType !== "hook_created") {
        return void 0;
      }
      const page = paginate(applyWithhold(eventsForRun(runId)), {
        pagination: { cursor: params.sinceCursor, sortOrder: "asc" },
        getCreatedAt: (e) => e.createdAt,
        getId: (e) => e.eventId
      });
      return {
        events: page.data.map((e) => stripEventDataRefs(e, resolveData)),
        cursor: page.cursor,
        hasMore: page.hasMore
      };
    }
    switch (data.eventType) {
      case "run_created": {
        if (runs.has(runId)) {
          throw new EntityConflictError(`Workflow run "${runId}" already exists`);
        }
        break;
      }
      case "run_started": {
        if (currentRun?.status === "running") {
          return { run: clone(currentRun), maxEvents: MAX_EVENTS_PER_RUN };
        }
        break;
      }
      case "step_created": {
        if (steps.has(stepKey(runId, data.correlationId))) {
          throw new EntityConflictError(`Step "${data.correlationId}" already created`);
        }
        break;
      }
      case "hook_created": {
        const { token } = data.eventData;
        const owner = tokenOwners.get(token);
        const externalOwner = internal?.externalTokenOwner;
        if (owner && owner !== data.correlationId || externalOwner) {
          const conflict = append({
            eventType: "hook_conflict",
            runId,
            eventId: event.eventId,
            createdAt: now,
            specVersion,
            correlationId: data.correlationId,
            eventData: {
              token,
              conflictingRunId: externalOwner ?? (owner ? hooks.get(owner)?.runId : void 0)
            }
          });
          const delta = sinceCursorDelta();
          const conflictResult = {
            event: stripEventDataRefs(clone(conflict), resolveData),
            run: currentRun ? clone(currentRun) : void 0
          };
          return delta ? { ...conflictResult, ...delta } : conflictResult;
        }
        if (hooks.has(data.correlationId)) {
          throw new EntityConflictError(`Hook "${data.correlationId}" already created`);
        }
        requireRun(runId);
        break;
      }
      case "hook_disposed": {
        if (disposedHooks.has(data.correlationId)) {
          throw new EntityConflictError(`Hook "${data.correlationId}" already disposed`);
        }
        break;
      }
      case "wait_created": {
        if (waits.has(waitKey(runId, data.correlationId))) {
          throw new EntityConflictError(`Wait "${data.correlationId}" already exists`);
        }
        break;
      }
      case "wait_completed": {
        const existing = waits.get(waitKey(runId, data.correlationId));
        if (!existing) {
          throw new WorkflowWorldError3(`Wait "${data.correlationId}" not found`);
        }
        if (existing.status === "completed") {
          throw new EntityConflictError(`Wait "${data.correlationId}" already completed`);
        }
        break;
      }
    }
    let stepCreatedLazily = false;
    if (data.eventType === "step_started" && lazyStepStart && !validatedStep && data.eventData) {
      const created = {
        eventType: "step_created",
        runId,
        ...position,
        specVersion,
        correlationId: data.correlationId,
        eventData: {
          stepName: data.eventData.stepName,
          input: data.eventData.input
        }
      };
      applyEvent(created, now);
      append(created);
      stepCreatedLazily = true;
      const { input: _dropped, ...rest } = data.eventData;
      position = eventPosition(runId);
      event = { ...event, ...position, eventData: rest };
    }
    const { run, step, hook, wait } = applyEvent(event, now);
    event = append(event);
    if (options.preconditionGuard && snapshot === void 0 && (data.eventType === "hook_received" || data.eventType === "step_completed" || data.eventType === "step_failed")) {
      const previous = externalWriteMarker.get(runId) ?? 0;
      externalWriteMarker.set(runId, Math.max(previous, requireEventSlot(event.eventId)));
    }
    let deltaPage;
    if (data.eventType === "run_started" && run && !params?.skipPreload) {
      const page = paginate(eventsForRun(runId), {
        pagination: { limit: 1e3, sortOrder: "asc" },
        getCreatedAt: (e) => e.createdAt,
        getId: (e) => e.eventId
      });
      deltaPage = {
        events: page.data,
        cursor: page.cursor,
        hasMore: page.hasMore
      };
    } else {
      deltaPage = sinceCursorDelta();
    }
    const result = {
      event: stripEventDataRefs(clone(event), resolveData),
      run: run ? clone(run) : void 0,
      step: step ? clone(step) : void 0,
      hook: hook ? clone(hook) : void 0,
      wait: wait ? clone(wait) : void 0,
      // `as const`: outside a returned literal there is no contextual type to
      // keep this from widening to `boolean`, and the field is `true | undefined`.
      ...stepCreatedLazily ? { stepCreated: true } : {},
      ...run ? { maxEvents: MAX_EVENTS_PER_RUN } : {}
    };
    return deltaPage ? { ...result, ...deltaPage } : result;
  }
  const storage = {
    runs: {
      async get(id, params) {
        const run = runs.get(id);
        if (!run)
          throw new WorkflowRunNotFoundError(id);
        const copy = clone(run);
        if (params?.resolveData === "none") {
          return { ...copy, input: void 0, output: void 0 };
        }
        return copy;
      },
      async getMany(idList, params) {
        return Promise.all(idList.map(async (id) => runs.has(id) ? await storage.runs.get(id, params) : null));
      },
      async list(params) {
        let items = [...runs.values()];
        if (params?.workflowName) {
          items = items.filter((r) => r.workflowName === params.workflowName);
        }
        if (params?.status !== void 0) {
          const statuses = Array.isArray(params.status) ? params.status : [params.status];
          items = items.filter((r) => statuses.includes(r.status));
        }
        const page = paginate(items, {
          pagination: params?.pagination,
          getCreatedAt: (r) => r.createdAt,
          getId: (r) => r.runId
        });
        if (params?.resolveData === "none") {
          return {
            ...page,
            data: page.data.map((r) => ({
              ...r,
              input: void 0,
              output: void 0
            }))
          };
        }
        return page;
      }
    },
    steps: {
      async get(runId, stepId, params) {
        const found = steps.get(stepKey(runId, stepId));
        if (!found)
          throw new WorkflowWorldError3(`Step "${stepId}" not found`);
        const copy = clone(found);
        if (params?.resolveData === "none") {
          return { ...copy, input: void 0, output: void 0 };
        }
        return copy;
      },
      async list(params) {
        const items = [...steps.values()].filter((s) => s.runId === params.runId);
        const page = paginate(items, {
          pagination: params.pagination,
          getCreatedAt: (s) => s.createdAt,
          getId: (s) => s.stepId
        });
        if (params.resolveData === "none") {
          return {
            ...page,
            data: page.data.map((s) => ({
              ...s,
              input: void 0,
              output: void 0
            }))
          };
        }
        return page;
      }
    },
    events: {
      create,
      async get(runId, eventId, params) {
        const found = events.find((e) => e.runId === runId && e.eventId === eventId);
        if (!found)
          throw new Error(`Event ${eventId} in run ${runId} not found`);
        return stripEventDataRefs(clone(found), params?.resolveData ?? "all");
      },
      async list(params) {
        const page = paginate(applyWithhold(eventsForRun(params.runId)), {
          pagination: params.pagination,
          defaultSortOrder: "asc",
          getCreatedAt: (e) => e.createdAt,
          getId: (e) => e.eventId
        });
        const resolve = params.resolveData ?? "all";
        return {
          ...page,
          data: page.data.map((e) => stripEventDataRefs(e, resolve))
        };
      },
      async listByCorrelationId(params) {
        const page = paginate(events.filter((e) => e.correlationId === params.correlationId), {
          pagination: params.pagination,
          defaultSortOrder: "asc",
          getCreatedAt: (e) => e.createdAt,
          getId: (e) => e.eventId
        });
        const resolve = params.resolveData ?? "all";
        return {
          ...page,
          data: page.data.map((e) => stripEventDataRefs(e, resolve))
        };
      }
    },
    hooks: {
      async get(hookId) {
        const found = hooks.get(hookId);
        if (!found)
          throw new HookNotFoundError2(hookId);
        return clone(found);
      },
      async getByToken(token) {
        const hookId = tokenOwners.get(token);
        const found = hookId ? hooks.get(hookId) : void 0;
        if (!found)
          throw new HookNotFoundError2(token);
        return clone(found);
      },
      async list(params) {
        const items = [...hooks.values()].filter((h) => !params.runId || h.runId === params.runId);
        return paginate(items, {
          pagination: params.pagination,
          getCreatedAt: (h) => h.createdAt,
          getId: (h) => h.hookId
        });
      }
    },
    withholdNextEvent(reads = 1) {
      armedWithhold = reads;
    },
    seedFromLog(log) {
      for (const event of log) {
        const seeded = clone(event);
        events.push(seeded);
        recordInIndex(seeded);
        applyEvent(seeded, seeded.createdAt);
      }
    },
    // Log order and commit order are the same: positions are assigned at commit.
    allEvents: (runId) => (runId ? eventsForRun(runId) : events).map(clone).sort((a, b) => a.createdAt.getTime() - b.createdAt.getTime() || a.eventId.localeCompare(b.eventId)),
    allEventsInCommitOrder: (runId) => (runId ? eventsForRun(runId) : events).map(clone),
    allRuns: () => [...runs.values()].map(clone),
    allSteps: (runId) => [...steps.values()].filter((s) => !runId || s.runId === runId).map(clone),
    allHooks: (runId) => [...hooks.values()].filter((h) => !runId || h.runId === runId).map(clone),
    allWaits: (runId) => [...waits.values()].filter((w) => !runId || w.runId === runId).map(clone),
    hookByToken: (token) => {
      const hookId = tokenOwners.get(token);
      const found = hookId ? hooks.get(hookId) : void 0;
      return found ? clone(found) : void 0;
    }
  };
  return storage;
}

// src/run-object.ts
import { monotonicFactory } from "ulid";
var EVENT_PREFIX = "ev:";
var SIGNAL_PREFIX = "sig:";
var KEY_PREFIX = "key:";
var INVOKE_PREFIX = "inv:";
var FENCE_PREFIX = "fence:";
var SNAPSHOT_PREFIX = "snap:";
var SNAPSHOT_CHUNK_BYTES = 19e5;
var BACKSTOP_MS = 1e4;
var PINNED_RECHECK_MS = 60 * 6e4;
var MAX_STEP_DELIVERIES = 6;
var MAX_ATTEMPTS = 100;
var debugEnabled = () => process.env.WORKFLOW_CLOUDFLARE_DEBUG === "1";
function debug(...args) {
  if (debugEnabled()) console.log("[world-cloudflare]", ...args);
}
var eventKey = (slot) => `${EVENT_PREFIX}${String(slot).padStart(12, "0")}`;
function isPlainWake(message) {
  return Object.keys(message).every(
    (key) => key === "runId" || key === "traceCarrier" || key === "requestedAt"
  );
}
var Mutex = class {
  #tail = Promise.resolve();
  run(fn) {
    const next = this.#tail.then(fn);
    this.#tail = next.catch(() => {
    });
    return next;
  }
};
var RunObject = class extends DurableObject {
  api;
  #runId;
  #store;
  /** The committed log, in slot order. */
  #log = [];
  /** Events the store appended during the create in progress. */
  #appended = [];
  #lastCreatedAtMs = 0;
  #writes = new Mutex();
  #signals = /* @__PURE__ */ new Map();
  #inflight = /* @__PURE__ */ new Set();
  #flowBusy = false;
  #stepDeliveries = 0;
  #completingWaits = /* @__PURE__ */ new Set();
  #alarmAt;
  #messageIds = monotonicFactory();
  #flowRoute;
  /**
   * Signals held back because the run belongs to another build. Not
   * persisted: the next instance (possibly running that build, after a
   * rollback) decides afresh.
   */
  #pinned = /* @__PURE__ */ new Set();
  /** This instance's own workflow route (see `RuntimeConfig.createFlowRoute`). */
  #flow() {
    this.#flowRoute ??= getRuntimeConfig().createFlowRoute();
    return this.#flowRoute;
  }
  constructor(ctx, env2) {
    super(ctx, env2);
    this.api = {
      eventsCreate: (runId, data, params) => this.#eventsCreate(runId, data, params),
      eventsGet: (runId, eventId, params) => this.#withRun(
        runId,
        () => this.#store.events.get(runId, eventId, params)
      ),
      eventsList: (params) => this.#withRun(params.runId, () => this.#store.events.list(params)),
      eventsListByCorrelationId: (params) => this.#withRun(
        params.runId,
        () => this.#store.events.listByCorrelationId(params)
      ),
      runsGet: (runId, params) => this.#withRun(
        runId,
        () => this.#store.runs.get(runId, params)
      ),
      stepsGet: (runId, stepId, params) => this.#withRun(
        runId,
        () => this.#store.steps.get(runId, stepId, params)
      ),
      stepsList: (params) => this.#withRun(
        params.runId,
        () => this.#store.steps.list(params)
      ),
      hooksGet: async (hookId, params) => this.#store.hooks.get(hookId, params),
      hooksList: async (params) => this.#store.hooks.list(params),
      enqueue: (queueName, message, opts) => this.#enqueue(queueName, message, opts),
      invoke: (runId, payload, options) => this.#invoke(runId, payload, options),
      snapshotSave: async (runId, data, metadata) => this.#withRun(runId, async () => this.#saveSnapshot(data, metadata)),
      snapshotLoad: async (runId) => this.#withRun(runId, async () => this.#loadSnapshot()),
      snapshotDelete: async (runId) => this.#withRun(runId, async () => this.#deleteSnapshot())
    };
    ctx.blockConcurrencyWhile(async () => this.#load());
  }
  // ---------------------------------------------------------------------------
  // RPC surface
  /** Generic entry point for the World client (see world.ts `onRun`). */
  async call(method, args) {
    return serve(
      () => this.api[method](...args)
    );
  }
  /**
   * Is `hookId` a live hook of this run? Asked by a token object before it
   * hands this hook's token to another claimant. A hook this run has never
   * created is fenced first: its `hook_created` can no longer commit, so a
   * "dead" answer stays true. Deliberately outside the write mutex: the
   * claimer may be this run, waiting on that very token object.
   */
  async hookLiveness(hookId) {
    return serve(() => {
      const run = this.#currentRun();
      const live = run !== void 0 && !isTerminalWorkflowRunStatus2(run.status) && this.#hasLiveHook(hookId);
      if (live) return "live";
      const created = this.#log.some(
        (e) => e.eventType === "hook_created" && e.correlationId === hookId
      );
      if (!created) this.ctx.storage.kv.put(`${FENCE_PREFIX}${hookId}`, true);
      return "dead";
    });
  }
  async alarm() {
    debug("alarm", this.#runId);
    this.#alarmAt = void 0;
    this.#drive();
  }
  /** Test hook: what this object holds. */
  async inspect() {
    return serve(() => {
      const meta = this.ctx.storage.kv.get(
        `${SNAPSHOT_PREFIX}meta`
      );
      const snapshot = meta ? this.#loadSnapshot() : null;
      return {
        runId: this.#runId,
        events: this.#log.length,
        signals: [...this.#signals.values()].map((s) => ({
          kind: s.kind,
          runAt: s.runAt,
          attempt: s.attempt
        })),
        snapshot: snapshot ? {
          bytes: meta?.bytes,
          parts: meta?.parts,
          eventCount: snapshot.metadata.eventCount,
          eventsCursor: snapshot.metadata.eventsCursor
        } : null
      };
    });
  }
  /** Test hook: drop this instance, as a deploy or eviction would. */
  async reset() {
    this.ctx.abort("reset requested");
  }
  // ---------------------------------------------------------------------------
  // Storage
  async #load() {
    const kv = this.ctx.storage.kv;
    this.#runId = kv.get("runId");
    const log = [...kv.list({ prefix: EVENT_PREFIX })].map(
      ([, event]) => event
    );
    this.#store = createSimStore({
      now: () => Math.max(Date.now(), this.#lastCreatedAtMs),
      ids: {
        ulid: () => this.#messageIds(),
        runId: () => `wrun_${this.#messageIds()}`,
        messageId: () => `msg_${this.#messageIds()}`,
        count: () => 0
      },
      onEvent: (event) => this.#appended.push(event)
    });
    this.#store.seedFromLog(log);
    this.#log = log;
    for (const event of log) this.#noteCreatedAt(event);
    for (const [, signal] of kv.list({ prefix: SIGNAL_PREFIX })) {
      if (signal.delivering) {
        signal.delivering = false;
        signal.attempt++;
        this.#store_(signal);
      }
      this.#signals.set(signal.messageId, signal);
    }
    debug(
      "loaded",
      this.#runId,
      `${log.length} events`,
      `${this.#signals.size} signals`
    );
    await this.#scheduleAlarm();
  }
  #noteCreatedAt(event) {
    const ms = new Date(event.createdAt).getTime();
    if (ms > this.#lastCreatedAtMs) this.#lastCreatedAtMs = ms;
  }
  #bindRun(runId) {
    if (this.#runId === runId) return;
    if (this.#runId !== void 0) {
      throw new WorkflowWorldError4(
        `world-cloudflare: object for run ${this.#runId} asked about run ${runId}`,
        { status: 500 }
      );
    }
    this.#runId = runId;
    this.ctx.storage.kv.put("runId", runId);
  }
  async #withRun(runId, fn) {
    if (this.#runId !== void 0 && this.#runId !== runId) {
      throw new WorkflowRunNotFoundError2(runId);
    }
    return fn();
  }
  #currentRun() {
    return this.#runId ? this.#store.allRuns()[0] : void 0;
  }
  #hasLiveHook(hookId) {
    return this.#store.allHooks().some((hook) => hook.hookId === hookId);
  }
  #eventsCreate(runId, data, params) {
    debug("events.create", data.eventType, data.correlationId ?? "");
    return this.#writes.run(async () => {
      this.#bindRun(runId);
      const internal = {};
      if (data.eventType === "hook_created") {
        const owner = await this.#claimToken(
          runId,
          data.correlationId,
          data.eventData.token
        );
        if (owner) internal.externalTokenOwner = owner;
      }
      this.#appended = [];
      let result;
      try {
        result = await this.#store.events.create(runId, data, {
          ...params,
          ...internal
        });
      } finally {
        this.#persistAppended();
      }
      await this.#afterCommit();
      return this.#withSkippedReport(runId, result, params);
    });
  }
  /**
   * Make every event the store just appended durable. A failure here leaves
   * the in-memory store ahead of storage, so the instance is dropped and the
   * next request rebuilds from what was persisted.
   */
  #persistAppended() {
    const appended = this.#appended;
    this.#appended = [];
    if (appended.length === 0) return;
    try {
      for (const event of appended) {
        this.ctx.storage.kv.put(
          eventKey(requireEventSlot2(event.eventId)),
          event
        );
        this.#log.push(event);
        this.#noteCreatedAt(event);
      }
    } catch (error) {
      this.ctx.abort("event persistence failed");
      throw error;
    }
  }
  /**
   * Bump-and-report (see `CreateEventParams.eventCount`): a writer whose view
   * was behind gets the events it skipped over. Writes here are serialized, so
   * the committed slot is always the next free one; the report is what keeps
   * a writer's view a prefix of the log.
   */
  async #withSkippedReport(runId, result, params) {
    const known = params?.eventCount;
    if (known === void 0 || !result.event || "events" in result) {
      return result;
    }
    const slot = requireEventSlot2(result.event.eventId);
    if (slot <= known + 1) return result;
    debug("reporting skipped slots", known + 1, "to", slot - 1);
    const before = known > 0 ? this.#log[known - 1] : void 0;
    const page = await this.#store.events.list({
      runId,
      pagination: {
        sortOrder: "asc",
        limit: slot - 1 - known,
        ...before ? {
          cursor: `${new Date(before.createdAt).toISOString()}|${before.eventId}`
        } : {}
      },
      resolveData: params?.resolveData ?? "all"
    });
    return {
      ...result,
      events: page.data,
      cursor: page.cursor,
      hasMore: false
    };
  }
  /**
   * Claim `token` for `hookId` in the cross-run registry before the
   * `hook_created` commits. Returns the run that holds it, if another does.
   */
  async #claimToken(runId, hookId, token) {
    const kv = this.ctx.storage.kv;
    for (let attempt = 0; attempt < 5; attempt++) {
      kv.delete(`${FENCE_PREFIX}${hookId}`);
      const claim = await call(
        TOKENS_BINDING,
        `token:${token}`,
        "claim",
        runId,
        hookId
      );
      if (!claim.granted) return claim.ownerRunId;
      await call(TOKENS_BINDING, `hook:${hookId}`, "record", runId);
      if (!kv.get(`${FENCE_PREFIX}${hookId}`)) return void 0;
    }
    throw new WorkflowWorldError4(
      `world-cloudflare: could not settle ownership of hook token for ${hookId}`,
      { status: 503 }
    );
  }
  /** Housekeeping after any commit: schedule new wait deadlines, etc. */
  async #afterCommit() {
    const run = this.#currentRun();
    if (run && isTerminalWorkflowRunStatus2(run.status)) {
      for (const signal of [...this.#signals.values()]) {
        if (!this.#inflight.has(signal.messageId)) this.#remove(signal);
      }
    }
    await this.#scheduleAlarm();
  }
  // ---------------------------------------------------------------------------
  // Execution signals
  async #enqueue(queueName, message, opts) {
    const runId = message.runId;
    debug(
      "enqueue",
      Object.keys(message),
      opts?.idempotencyKey ?? "",
      opts?.delaySeconds ?? 0
    );
    const isHealthCheck = "__healthCheck" in message;
    if (runId && !isHealthCheck) this.#bindRun(runId);
    const kv = this.ctx.storage.kv;
    const key = opts?.idempotencyKey;
    if (key) {
      const existing = kv.get(`${KEY_PREFIX}${key}`);
      if (existing && this.#signals.has(existing)) {
        return { messageId: existing };
      }
    }
    const signal = {
      messageId: `msg_${this.#messageIds()}`,
      queueName,
      message,
      kind: "stepId" in message && typeof message.stepId === "string" ? "step" : "flow",
      runAt: Date.now() + Math.max(0, opts?.delaySeconds ?? 0) * 1e3,
      attempt: 1,
      ...key ? { idempotencyKey: key } : {}
    };
    kv.put(`${SIGNAL_PREFIX}${signal.messageId}`, signal);
    if (key) kv.put(`${KEY_PREFIX}${key}`, signal.messageId);
    this.#signals.set(signal.messageId, signal);
    await this.#scheduleAlarm();
    queueMicrotask(() => this.#drive());
    return { messageId: signal.messageId };
  }
  #store_(signal) {
    this.ctx.storage.kv.put(`${SIGNAL_PREFIX}${signal.messageId}`, signal);
  }
  #remove(signal) {
    const kv = this.ctx.storage.kv;
    kv.delete(`${SIGNAL_PREFIX}${signal.messageId}`);
    if (signal.idempotencyKey && kv.get(`${KEY_PREFIX}${signal.idempotencyKey}`) === signal.messageId) {
      kv.delete(`${KEY_PREFIX}${signal.idempotencyKey}`);
    }
    this.#signals.delete(signal.messageId);
  }
  #reschedule(signal, delayMs, failed) {
    if (!this.#signals.has(signal.messageId)) return;
    signal.delivering = false;
    signal.runAt = Date.now() + delayMs;
    if (failed) {
      signal.attempt++;
      if (signal.attempt > MAX_ATTEMPTS) {
        signal.parked = `gave up after ${MAX_ATTEMPTS} attempts`;
        console.error(
          `[world-cloudflare] ${signal.messageId}: ${signal.parked}`
        );
      }
    }
    this.#store_(signal);
  }
  /** Start whatever is due. Never awaits: deliveries run in the background. */
  #drive() {
    const now = Date.now();
    this.#completeDueWaits(now);
    const due = [...this.#signals.values()].filter(
      (s) => !s.parked && !this.#pinned.has(s.messageId) && s.runAt <= now && !this.#inflight.has(s.messageId)
    ).sort(
      (a, b) => a.runAt - b.runAt || (a.messageId < b.messageId ? -1 : 1)
    );
    for (const signal of due) {
      if (signal.kind !== "step") continue;
      if (this.#stepDeliveries >= MAX_STEP_DELIVERIES) break;
      this.#background(this.#deliverStep(signal));
    }
    if (!this.#flowBusy) {
      const next = due.find((s) => s.kind === "flow");
      if (next) this.#background(this.#deliverFlow(next, due));
    }
    void this.#scheduleAlarm();
  }
  #background(task) {
    this.ctx.waitUntil(
      task.catch(
        (error) => console.error("[world-cloudflare] delivery task failed", error)
      ).finally(() => this.#drive())
    );
  }
  /** Is this signal's run pinned to a different build than this isolate? */
  #pinnedDeployment(signal) {
    if ("__healthCheck" in signal.message) return void 0;
    const message = signal.message;
    const runDeployment = this.#currentRun()?.deploymentId ?? message.runInput?.deploymentId;
    const ours = getRuntimeConfig().deploymentId;
    return runDeployment && runDeployment !== ours ? runDeployment : void 0;
  }
  /** Hold a signal back for the life of this instance; nothing runs it here. */
  #holdForOtherBuild(signal, reason) {
    signal.delivering = false;
    this.#store_(signal);
    this.#pinned.add(signal.messageId);
    console.error(`[world-cloudflare] holding ${signal.messageId}: ${reason}`);
  }
  #meta(signal) {
    signal.delivering = true;
    this.#store_(signal);
    return {
      attempt: signal.attempt,
      queueName: signal.queueName,
      messageId: signal.messageId
    };
  }
  /** Apply a delivery's outcome to its signal. */
  #settle(signal, result, error) {
    if (error !== void 0) {
      const backoff = Math.min(6e4, 1e3 * 2 ** (signal.attempt - 1));
      console.error(
        `[world-cloudflare] delivery ${signal.messageId} attempt ${signal.attempt} failed`,
        error
      );
      this.#reschedule(signal, backoff, true);
      return;
    }
    const timeout = result?.timeoutSeconds;
    if (typeof timeout === "number") {
      this.#reschedule(signal, Math.max(0, timeout) * 1e3, false);
      return;
    }
    this.#remove(signal);
  }
  async #deliverFlow(signal, due) {
    this.#flowBusy = true;
    this.#inflight.add(signal.messageId);
    const absorbed = isPlainWake(signal.message) ? due.filter(
      (s) => s !== signal && s.kind === "flow" && isPlainWake(s.message) && !this.#inflight.has(s.messageId)
    ) : [];
    for (const s of absorbed) this.#inflight.add(s.messageId);
    try {
      const pinned = this.#pinnedDeployment(signal);
      if (pinned) {
        this.#holdForOtherBuild(
          signal,
          `run is pinned to deployment ${pinned}; this isolate runs ${getRuntimeConfig().deploymentId}`
        );
        return;
      }
      let result;
      let error;
      debug(
        "flow delivery start",
        signal.messageId,
        `attempt ${signal.attempt}`,
        Object.keys(signal.message),
        `absorbed ${absorbed.length}`
      );
      try {
        result = await runAsLocal(
          { runId: this.#runId ?? "", object: this },
          () => deliver(signal.message, this.#meta(signal), this.#flow())
        );
      } catch (e) {
        error = e ?? new Error("delivery failed");
      }
      debug(
        "flow delivery end",
        signal.messageId,
        error ? `error ${String(error)}` : JSON.stringify(result)
      );
      for (const s of absorbed) this.#remove(s);
      this.#settle(signal, result, error);
    } finally {
      this.#inflight.delete(signal.messageId);
      for (const s of absorbed) this.#inflight.delete(s.messageId);
      this.#flowBusy = false;
    }
  }
  async #deliverStep(signal) {
    this.#stepDeliveries++;
    this.#inflight.add(signal.messageId);
    try {
      const pinned = this.#pinnedDeployment(signal);
      if (pinned) {
        this.#holdForOtherBuild(
          signal,
          `run is pinned to deployment ${pinned}`
        );
        return;
      }
      let result;
      let error;
      try {
        debug(
          "step delivery start",
          signal.messageId,
          signal.message.stepName
        );
        const runner = this.ctx.exports.StepRunner;
        result = unwrapInvocationOutcome3(
          await runner.run(signal.message, this.#meta(signal))
        );
      } catch (e) {
        error = e ?? new Error("step delivery failed");
      }
      this.#settle(signal, result, error);
    } finally {
      this.#inflight.delete(signal.messageId);
      this.#stepDeliveries--;
    }
  }
  // ---------------------------------------------------------------------------
  // Timers
  /**
   * Complete waits whose deadline has passed. The workflow would do this
   * itself on its next replay; doing it here, at the deadline, puts the
   * `wait_completed` in the log at the right time even while the workflow is
   * busy running a step inline (`Promise.race([step(), sleep()])`).
   */
  #completeDueWaits(now) {
    const run = this.#currentRun();
    if (!run || isTerminalWorkflowRunStatus2(run.status)) return;
    for (const wait of this.#store.allWaits()) {
      if (wait.status === "completed" || !wait.resumeAt) continue;
      if (new Date(wait.resumeAt).getTime() > now) continue;
      const correlationId = wait.waitId.slice(run.runId.length + 1);
      if (this.#completingWaits.has(correlationId)) continue;
      this.#completingWaits.add(correlationId);
      this.ctx.waitUntil(
        (async () => {
          try {
            await this.#eventsCreate(run.runId, {
              eventType: "wait_completed",
              specVersion: run.specVersion ?? SPEC_VERSION_CURRENT3,
              correlationId,
              eventData: { resumeAt: wait.resumeAt }
            });
            await this.#enqueue(this.#queueName(run), { runId: run.runId });
          } catch (error) {
            if (!EntityConflictError2.is(error)) {
              console.error("[world-cloudflare] completing wait failed", error);
            }
          } finally {
            this.#completingWaits.delete(correlationId);
          }
        })()
      );
    }
  }
  async #scheduleAlarm() {
    let next;
    const consider = (ms) => {
      if (next === void 0 || ms < next) next = ms;
    };
    for (const signal of this.#signals.values()) {
      if (signal.parked || this.#inflight.has(signal.messageId)) continue;
      consider(
        this.#pinned.has(signal.messageId) ? Date.now() + PINNED_RECHECK_MS : signal.runAt
      );
    }
    const run = this.#currentRun();
    if (run && !isTerminalWorkflowRunStatus2(run.status)) {
      for (const wait of this.#store.allWaits()) {
        if (wait.status !== "completed" && wait.resumeAt) {
          consider(new Date(wait.resumeAt).getTime());
        }
      }
    }
    if (this.#inflight.size > 0) consider(Date.now() + BACKSTOP_MS);
    const target = next ?? null;
    if (target === this.#alarmAt) return;
    this.#alarmAt = target;
    debug(
      "alarm at",
      target === null ? "none" : new Date(target).toISOString()
    );
    if (target === null) await this.ctx.storage.deleteAlarm();
    else await this.ctx.storage.setAlarm(target);
  }
  #queueName(run) {
    return `${getQueueTopicPrefix("workflow")}${run.workflowName}`;
  }
  // ---------------------------------------------------------------------------
  // VM snapshots
  /**
   * One envelope (metadata + bytes), split across storage values and
   * written in one synchronous transaction, so a snapshot can never be read
   * with another suspension's metadata.
   */
  #saveSnapshot(data, metadata) {
    const envelope = encodeSnapshotEnvelope(metadata, data);
    const parts = Math.max(
      1,
      Math.ceil(envelope.length / SNAPSHOT_CHUNK_BYTES)
    );
    this.ctx.storage.transactionSync(() => {
      this.#deleteSnapshotSync();
      for (let i = 0; i < parts; i++) {
        this.ctx.storage.kv.put(
          `${SNAPSHOT_PREFIX}${i}`,
          envelope.slice(
            i * SNAPSHOT_CHUNK_BYTES,
            (i + 1) * SNAPSHOT_CHUNK_BYTES
          )
        );
      }
      this.ctx.storage.kv.put(`${SNAPSHOT_PREFIX}meta`, {
        parts,
        bytes: envelope.length
      });
    });
    debug(
      "snapshot saved",
      `${envelope.length} bytes`,
      `eventCount ${metadata.eventCount}`
    );
  }
  #loadSnapshot() {
    const kv = this.ctx.storage.kv;
    const meta = kv.get(
      `${SNAPSHOT_PREFIX}meta`
    );
    if (!meta) return null;
    const envelope = new Uint8Array(meta.bytes);
    let offset = 0;
    for (let i = 0; i < meta.parts; i++) {
      const part = kv.get(`${SNAPSHOT_PREFIX}${i}`);
      if (!part) return null;
      envelope.set(part, offset);
      offset += part.length;
    }
    if (offset !== meta.bytes) return null;
    const decoded = decodeSnapshotEnvelope(envelope);
    if (decoded)
      debug("snapshot loaded", `eventCount ${decoded.metadata.eventCount}`);
    return decoded;
  }
  #deleteSnapshot() {
    this.ctx.storage.transactionSync(() => this.#deleteSnapshotSync());
  }
  #deleteSnapshotSync() {
    const kv = this.ctx.storage.kv;
    const meta = kv.get(`${SNAPSHOT_PREFIX}meta`);
    if (!meta) return;
    for (let i = 0; i < meta.parts; i++) kv.delete(`${SNAPSHOT_PREFIX}${i}`);
    kv.delete(`${SNAPSHOT_PREFIX}meta`);
  }
  // ---------------------------------------------------------------------------
  // invoke(): inputs for the running workflow
  async #invoke(runId, payload, options) {
    this.#bindRun(runId);
    const kv = this.ctx.storage.kv;
    const requestId = options?.idempotencyKey ?? `inv_${this.#messageIds()}`;
    const stored = kv.get(`${INVOKE_PREFIX}${requestId}`);
    if (stored) return stored;
    const run = this.#currentRun();
    if (!run) throw new WorkflowRunNotFoundError2(runId);
    const queueName = this.#queueName(run);
    const outcome = await captureInvocationOutcome2(
      () => runAsLocal(
        { runId, object: this },
        () => deliver(
          { runId, invoke: true, requestId, input: payload },
          {
            attempt: 1,
            queueName,
            messageId: `msg_${this.#messageIds()}`
          },
          this.#flow()
        )
      ),
      isTerminalInvocationError
    );
    kv.put(`${INVOKE_PREFIX}${requestId}`, outcome);
    if (outcome.ok && outcome.value?.status === "accepted") {
      await this.#enqueue(queueName, { runId });
    }
    return outcome;
  }
};

// src/step-runner.ts
import { WorkerEntrypoint } from "cloudflare:workers";
var StepRunner = class extends WorkerEntrypoint {
  async run(message, meta) {
    return serve(() => deliver(message, meta));
  }
};

// src/stream-object.ts
import { DurableObject as DurableObject2 } from "cloudflare:workers";
var chunkKey = (index) => `c:${String(index).padStart(12, "0")}`;
var StreamObject = class extends DurableObject2 {
  #meta() {
    return this.ctx.storage.kv.get("meta") ?? { count: 0, closed: false };
  }
  async append(chunks) {
    return serve(() => {
      const meta = this.#meta();
      if (meta.closed) throw new Error("Cannot write to a closed stream");
      for (const chunk of chunks) {
        this.ctx.storage.kv.put(chunkKey(meta.count++), chunk);
      }
      this.ctx.storage.kv.put("meta", meta);
    });
  }
  async close() {
    return serve(() => {
      this.ctx.storage.kv.put("meta", { ...this.#meta(), closed: true });
    });
  }
  async chunks(options) {
    return serve(() => {
      const meta = this.#meta();
      const start = options.cursor ? Number.parseInt(options.cursor, 10) : 0;
      const limit = Math.min(options.limit ?? 100, 1e3);
      const data = [];
      for (const [key, value] of this.ctx.storage.kv.list({
        start: chunkKey(start),
        end: chunkKey(start + limit),
        prefix: "c:"
      })) {
        data.push({ index: Number.parseInt(key.slice(2), 10), data: value });
      }
      const end = start + data.length;
      const hasMore = end < meta.count;
      return {
        data,
        cursor: hasMore ? String(end) : null,
        hasMore,
        done: meta.closed && !hasMore
      };
    });
  }
  async info() {
    return serve(() => {
      const meta = this.#meta();
      return { tailIndex: meta.count - 1, done: meta.closed };
    });
  }
  async register(name) {
    return serve(() => {
      this.ctx.storage.kv.put(`n:${name}`, true);
    });
  }
  async names() {
    return serve(
      () => [...this.ctx.storage.kv.list({ prefix: "n:" })].map(
        ([key]) => key.slice(2)
      )
    );
  }
};

// src/token-object.ts
import { DurableObject as DurableObject3 } from "cloudflare:workers";
var TokenObject = class extends DurableObject3 {
  /** Serializes claims: the liveness check below awaits another object. */
  #claims = Promise.resolve();
  async claim(runId, hookId) {
    return serve(() => {
      const next = this.#claims.then(() => this.#claim(runId, hookId));
      this.#claims = next.catch(() => {
      });
      return next;
    });
  }
  async #claim(runId, hookId) {
    const kv = this.ctx.storage.kv;
    const owner = kv.get("owner");
    if (!owner || owner.runId === runId && owner.hookId === hookId) {
      kv.put("owner", { runId, hookId });
      return { granted: true };
    }
    const liveness = await call(
      RUNS_BINDING,
      owner.runId,
      "hookLiveness",
      owner.hookId
    );
    if (liveness === "live") {
      return { granted: false, ownerRunId: owner.runId };
    }
    kv.put("owner", { runId, hookId });
    return { granted: true };
  }
  /** The recorded owner, live or not. Readers confirm with the owning run. */
  async lookup() {
    return serve(() => this.ctx.storage.kv.get("owner") ?? null);
  }
  /** Record `hook:<hookId>` → run. Idempotent; hook ids are unique. */
  async record(runId) {
    return serve(() => {
      this.ctx.storage.kv.put("owner", { runId, hookId: "" });
    });
  }
};

// src/index.ts
function setupCloudflareWorld(options) {
  installQuickJSModules(options.quickjs);
  configureRuntime({
    deploymentId: options.deploymentId,
    createFlowRoute: options.createFlowRoute
  });
  const world = createCloudflareWorld();
  options.setWorld(world);
  return world;
}
export {
  RunObject,
  StepRunner,
  StreamObject,
  TokenObject,
  createCloudflareWorld,
  setupCloudflareWorld
};