eve 0.29.4 → 0.30.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +28 -0
- package/dist/src/channel/clear-session.d.ts +4 -0
- package/dist/src/channel/clear-session.js +1 -0
- package/dist/src/channel/compact-session.d.ts +4 -0
- package/dist/src/channel/compact-session.js +1 -0
- package/dist/src/channel/routes.d.ts +34 -6
- package/dist/src/channel/types.d.ts +61 -9
- package/dist/src/chunks/{use-eve-agent-8mofdZcO.js → use-eve-agent-BXMIf5fR.js} +85 -1
- package/dist/src/chunks/{use-eve-agent-bKJbH0k4.js → use-eve-agent-k-XHfrJT.js} +85 -1
- package/dist/src/cli/dev/tui/message-queue.d.ts +12 -16
- package/dist/src/cli/dev/tui/message-queue.js +1 -1
- package/dist/src/cli/dev/tui/prompt-commands.d.ts +13 -5
- package/dist/src/cli/dev/tui/prompt-commands.js +1 -1
- package/dist/src/cli/dev/tui/runner.d.ts +7 -7
- package/dist/src/cli/dev/tui/runner.js +1 -1
- package/dist/src/cli/dev/tui/setup-panel.js +4 -1
- package/dist/src/cli/dev/tui/subagent-pump.d.ts +5 -5
- package/dist/src/cli/dev/tui/terminal-renderer.js +12 -12
- package/dist/src/client/agent-info-schema.d.ts +2 -2
- package/dist/src/client/agent-info-schema.js +1 -1
- package/dist/src/client/index.d.ts +1 -1
- package/dist/src/client/session.d.ts +15 -1
- package/dist/src/client/session.js +1 -1
- package/dist/src/client/types.d.ts +20 -0
- package/dist/src/compiled/.vendor-stamp.json +6 -6
- package/dist/src/compiled/@workflow/core/_devalue.d.ts +8 -0
- package/dist/src/compiled/@workflow/core/capabilities.d.ts +5 -0
- package/dist/src/compiled/@workflow/core/index.js +2 -2
- package/dist/src/compiled/@workflow/core/replay-payload-cache.d.ts +11 -0
- package/dist/src/compiled/@workflow/core/runtime/compute-instance.d.ts +12 -0
- package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +18 -0
- package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +103 -31
- package/dist/src/compiled/@workflow/core/runtime/replay-recovery-reporter.d.ts +36 -0
- package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +22 -2
- package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +17 -13
- package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +13 -8
- package/dist/src/compiled/@workflow/core/runtime.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/runtime.js +3 -3
- package/dist/src/compiled/@workflow/core/serialization/codec.d.ts +17 -0
- package/dist/src/compiled/@workflow/core/serialization/hardened.d.ts +155 -0
- package/dist/src/compiled/@workflow/core/serialization/index.d.ts +2 -1
- package/dist/src/compiled/@workflow/core/serialization/reducers/common.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/serialization.d.ts +13 -9
- package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +41 -0
- package/dist/src/compiled/@workflow/core/version.d.ts +1 -1
- package/dist/src/compiled/@workflow/core/workflow.js +1 -1
- package/dist/src/compiled/@workflow/errors/index.d.ts +16 -8
- package/dist/src/compiled/@workflow/errors/index.js +1 -1
- package/dist/src/compiled/@workflow/world/analytics.d.ts +2 -0
- package/dist/src/compiled/@workflow/world/events.d.ts +87 -0
- package/dist/src/compiled/@workflow/world/hooks.d.ts +39 -0
- package/dist/src/compiled/@workflow/world/index.d.ts +1 -1
- package/dist/src/compiled/@workflow/world/interfaces.d.ts +61 -0
- package/dist/src/compiled/@workflow/world/queue.d.ts +40 -0
- package/dist/src/compiled/@workflow/world-local/index.js +3 -3
- package/dist/src/compiled/@workflow/world-vercel/index.js +14 -14
- package/dist/src/compiled/_chunks/workflow/{attribute-changes-1LmTKuTT.js → attribute-changes-DROfGk6l.js} +3 -3
- package/dist/src/compiled/_chunks/workflow/{dist-WjtNsOyf.js → dist-D5bR13zs.js} +1 -1
- package/dist/src/compiled/_chunks/workflow/{dist-BeQ_csYA.js → dist-dNxTT6nO.js} +2 -2
- package/dist/src/compiled/_chunks/workflow/resume-hook-bc-OQVI0.js +1 -0
- package/dist/src/compiled/_chunks/workflow/run-DM3ouA3U.js +1 -0
- package/dist/src/compiled/_chunks/workflow/sleep-D5iWly6-.js +1 -0
- package/dist/src/compiled/_chunks/workflow/wait-until-DoW76jdb.js +15 -0
- package/dist/src/compiler/extension-compatibility.d.ts +8 -8
- package/dist/src/compiler/extension-compatibility.js +1 -1
- package/dist/src/compiler/manifest.d.ts +11 -22
- package/dist/src/compiler/manifest.js +1 -1
- package/dist/src/compiler/normalize-agent-config.d.ts +3 -1
- package/dist/src/compiler/normalize-agent-config.js +1 -1
- package/dist/src/compiler/normalize-manifest.js +1 -1
- package/dist/src/compiler/normalize-subagent.d.ts +1 -0
- package/dist/src/compiler/normalize-subagent.js +1 -1
- package/dist/src/compiler/remote-agent-node.d.ts +3 -0
- package/dist/src/context/dynamic-subagent-lifecycle.d.ts +22 -0
- package/dist/src/context/dynamic-subagent-lifecycle.js +1 -0
- package/dist/src/context/dynamic-tool-lifecycle.js +1 -1
- package/dist/src/context/keys.d.ts +21 -2
- package/dist/src/context/keys.js +1 -1
- package/dist/src/context/run-step.js +1 -1
- package/dist/src/execution/cancel-descendant-turns-step.js +1 -1
- package/dist/src/execution/create-session-step.d.ts +2 -0
- package/dist/src/execution/create-session-step.js +1 -1
- package/dist/src/execution/delegation-tool.d.ts +3 -0
- package/dist/src/execution/delegation-tool.js +1 -0
- package/dist/src/execution/dispatch-runtime-actions-step.js +1 -1
- package/dist/src/execution/dispatch-workflow-runtime-actions-step.js +1 -1
- package/dist/src/execution/effective-agent-config.d.ts +12 -0
- package/dist/src/execution/effective-agent-config.js +1 -0
- package/dist/src/execution/node-step.d.ts +4 -0
- package/dist/src/execution/node-step.js +1 -1
- package/dist/src/execution/remote-agent-dispatch.d.ts +3 -1
- package/dist/src/execution/remote-agent-dispatch.js +1 -1
- package/dist/src/execution/runtime-context.d.ts +2 -0
- package/dist/src/execution/runtime-context.js +1 -1
- package/dist/src/execution/session-callback-request.d.ts +5 -0
- package/dist/src/execution/session-callback-request.js +1 -0
- package/dist/src/execution/session-delivery-hook.d.ts +1 -0
- package/dist/src/execution/session-delivery-hook.js +1 -1
- package/dist/src/execution/settle-cancelled-turn-step.js +1 -1
- package/dist/src/execution/subagent-event-proxy-step.js +1 -1
- package/dist/src/execution/workflow-entry.js +1 -1
- package/dist/src/execution/workflow-runtime.d.ts +2 -0
- package/dist/src/execution/workflow-runtime.js +1 -1
- package/dist/src/execution/workflow-steps.js +1 -1
- package/dist/src/harness/agent-handles.d.ts +238 -0
- package/dist/src/harness/agent-handles.js +2 -0
- package/dist/src/harness/compaction.d.ts +1 -1
- package/dist/src/harness/compaction.js +1 -1
- package/dist/src/harness/tool-loop.js +2 -2
- package/dist/src/harness/types.d.ts +16 -0
- package/dist/src/internal/application/package.js +1 -1
- package/dist/src/internal/authored-definition/core.js +1 -1
- package/dist/src/internal/authored-module-loader.js +1 -1
- package/dist/src/internal/nitro/host/create-application-nitro.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response-from-manifest.js +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.d.ts +1 -1
- package/dist/src/internal/nitro/routes/agent-info/build-agent-info-response.js +1 -1
- package/dist/src/internal/nitro/routes/channel-dispatch.js +1 -1
- package/dist/src/internal/vercel-agent-summary.d.ts +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.d.ts +10 -0
- package/dist/src/internal/workflow-bundle/dynamic-capability-transform-plugin.js +1 -0
- package/dist/src/internal/workflow-bundle/dynamic-remote-agent-transform.d.ts +7 -0
- package/dist/src/internal/workflow-bundle/dynamic-remote-agent-transform.js +3 -0
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.d.ts +2 -0
- package/dist/src/internal/workflow-bundle/dynamic-tool-ast-references.js +1 -1
- package/dist/src/internal/workflow-bundle/dynamic-tool-transform.js +2 -2
- package/dist/src/protocol/clear-session.d.ts +14 -0
- package/dist/src/protocol/clear-session.js +1 -0
- package/dist/src/protocol/compact-session.d.ts +14 -0
- package/dist/src/protocol/compact-session.js +1 -0
- package/dist/src/protocol/message.d.ts +19 -1
- package/dist/src/protocol/message.js +1 -1
- package/dist/src/protocol/routes.d.ts +10 -0
- package/dist/src/protocol/routes.js +1 -1
- package/dist/src/public/channels/auth.d.ts +11 -25
- package/dist/src/public/channels/auth.js +1 -1
- package/dist/src/public/channels/eve.js +1 -1
- package/dist/src/public/channels/index.d.ts +1 -1
- package/dist/src/public/definitions/agent.d.ts +35 -1
- package/dist/src/public/definitions/agent.js +1 -1
- package/dist/src/public/definitions/channel.d.ts +5 -2
- package/dist/src/public/definitions/channel.js +1 -1
- package/dist/src/public/definitions/hook.d.ts +1 -0
- package/dist/src/public/definitions/tool.d.ts +4 -1
- package/dist/src/public/index.d.ts +1 -2
- package/dist/src/public/index.js +1 -1
- package/dist/src/runtime/framework-channels/index.js +1 -1
- package/dist/src/runtime/framework-tools/connection-search-dynamic.d.ts +2 -18
- package/dist/src/runtime/framework-tools/connection-search-dynamic.js +2 -2
- package/dist/src/runtime/framework-tools/index.d.ts +7 -2
- package/dist/src/runtime/framework-tools/index.js +1 -1
- package/dist/src/runtime/resolve-agent-graph.js +1 -1
- package/dist/src/runtime/resolve-agent.js +1 -1
- package/dist/src/runtime/resolve-dynamic-subagent.d.ts +12 -0
- package/dist/src/runtime/resolve-dynamic-subagent.js +1 -0
- package/dist/src/runtime/resolve-dynamic-tool.d.ts +15 -0
- package/dist/src/runtime/resolve-dynamic-tool.js +1 -1
- package/dist/src/runtime/subagents/dynamic-agent-config.d.ts +22 -0
- package/dist/src/runtime/subagents/dynamic-agent-config.js +1 -0
- package/dist/src/runtime/subagents/dynamic-remote-agent-config.d.ts +13 -0
- package/dist/src/runtime/subagents/dynamic-remote-agent-config.js +1 -0
- package/dist/src/runtime/subagents/registry.d.ts +10 -2
- package/dist/src/runtime/subagents/registry.js +1 -1
- package/dist/src/runtime/types.d.ts +11 -2
- package/dist/src/setup/flows/registry.js +1 -1
- package/dist/src/setup/scaffold/channels-catalog.d.ts +2 -2
- package/dist/src/setup/scaffold/channels-catalog.js +1 -1
- package/dist/src/setup/scaffold/connections/catalog.d.ts +2 -2
- package/dist/src/setup/scaffold/create/project.js +1 -1
- package/dist/src/shared/agent-definition.d.ts +7 -0
- package/dist/src/shared/agent-turn-outcome.d.ts +47 -0
- package/dist/src/shared/agent-turn-outcome.js +1 -0
- package/dist/src/shared/dynamic-tool-definition.d.ts +1 -5
- package/dist/src/shared/dynamic-tool-definition.js +1 -1
- package/dist/src/svelte/index.js +1 -1
- package/dist/src/svelte/use-eve-agent.js +1 -1
- package/dist/src/vue/index.js +1 -1
- package/dist/src/vue/use-eve-agent.js +1 -1
- package/docs/channels/custom.mdx +41 -1
- package/docs/channels/eve.mdx +27 -2
- package/docs/concepts/default-harness.md +4 -0
- package/docs/concepts/sessions-runs-and-streaming.md +1 -1
- package/docs/guides/auth-and-route-protection.md +13 -13
- package/docs/guides/client/streaming.mdx +14 -0
- package/docs/guides/dev-tui.md +12 -9
- package/docs/guides/dynamic-capabilities.md +74 -6
- package/docs/guides/frontend/nextjs.mdx +1 -1
- package/docs/guides/frontend/nuxt.mdx +1 -1
- package/docs/guides/frontend/sveltekit.mdx +1 -1
- package/docs/guides/remote-agents.md +33 -0
- package/docs/reference/project-layout.md +1 -1
- package/docs/reference/typescript-api.md +48 -48
- package/docs/subagents.mdx +32 -2
- package/package.json +8 -8
- package/dist/src/compiled/_chunks/workflow/resume-hook-D1_5NCZ6.js +0 -1
- package/dist/src/compiled/_chunks/workflow/run-C240Ctf4.js +0 -1
- package/dist/src/compiled/_chunks/workflow/sleep-De802yfX.js +0 -1
- package/dist/src/compiled/_chunks/workflow/wait-until-z48sPUjU.js +0 -15
|
@@ -227,6 +227,15 @@ export interface WorldCapabilities {
|
|
|
227
227
|
* ignore `stateUpdatedAt` must leave this unset so runtime optimizations
|
|
228
228
|
* that rely on the 412 fence (see `WORKFLOW_PRECONDITION_GUARD`) are not
|
|
229
229
|
* enabled without an actual fence behind them.
|
|
230
|
+
*
|
|
231
|
+
* A World declaring this should honour the whole snapshot the runtime sends,
|
|
232
|
+
* not just the watermark: `stateUpdatedAt`, `stateEventCount` (the count
|
|
233
|
+
* fence, which catches an event missing at or below the watermark — the case
|
|
234
|
+
* the watermark provably cannot see) and, optionally, `stateCursor` (return
|
|
235
|
+
* the missing events on the 412 to save the client a reload). See
|
|
236
|
+
* `CreateEventParams` for each field's contract. The runtime does not branch
|
|
237
|
+
* on which halves are implemented; a World that ignores the count simply
|
|
238
|
+
* fences less.
|
|
230
239
|
*/
|
|
231
240
|
preconditionGuard?: boolean;
|
|
232
241
|
/**
|
|
@@ -244,6 +253,36 @@ export interface WorldCapabilities {
|
|
|
244
253
|
* combined with it (and so Worlds document the contract explicitly).
|
|
245
254
|
*/
|
|
246
255
|
maxConcurrency?: boolean;
|
|
256
|
+
/**
|
|
257
|
+
* The World's `events.create` deduplicates concurrent `hook_received` writes
|
|
258
|
+
* that carry the same `(runId, resumeId)` — collapsing them onto a single
|
|
259
|
+
* committed event and returning the canonical one to every caller. This is
|
|
260
|
+
* the backend half of `resumeHook()`'s parallel fast path: the producer's
|
|
261
|
+
* direct write and the queue consumer's re-ensure both write the same
|
|
262
|
+
* `resumeId`, and exactly one event must survive or the run replays a
|
|
263
|
+
* duplicated `hook_received`.
|
|
264
|
+
*
|
|
265
|
+
* The core runtime fails closed on this: the parallel path is taken ONLY
|
|
266
|
+
* when the World declares `hookResumeDedup === true` AND the target run's
|
|
267
|
+
* deployment can re-ensure from `hookInput` (see the execution-context
|
|
268
|
+
* marker `hookResumeInputVersion`). A World that accepts a `resumeId` but
|
|
269
|
+
* does not enforce the `(runId, resumeId)` constraint must leave this unset
|
|
270
|
+
* so the runtime keeps the sequential single-writer path.
|
|
271
|
+
*
|
|
272
|
+
* Enabled statically for `world-local` (filesystem sidecar claim keyed on
|
|
273
|
+
* `(runId, resumeId)`; the adapter and its backend ship together, so a static
|
|
274
|
+
* capability can never drift from the backend). `world-vercel` deliberately
|
|
275
|
+
* leaves this UNSET and instead attests support per-lookup via the
|
|
276
|
+
* server-computed, response-only `Hook.resumeCapabilities.hookResumeDedupVersion`
|
|
277
|
+
* (see `HookResumeCapabilitiesSchema`), so a server rollback or kill switch
|
|
278
|
+
* degrades new resumes to the sequential path immediately without redeploying
|
|
279
|
+
* the adapter. `world-postgres` leaves it unset for now and stays sequential.
|
|
280
|
+
*
|
|
281
|
+
* The resume gate treats EITHER signal as backend support (see
|
|
282
|
+
* `resume-hook.ts`): this static capability OR a current
|
|
283
|
+
* `resumeCapabilities.hookResumeDedupVersion` on the by-token hook.
|
|
284
|
+
*/
|
|
285
|
+
hookResumeDedup?: boolean;
|
|
247
286
|
}
|
|
248
287
|
/**
|
|
249
288
|
* The "World" interface represents how Workflows are able to communicate with the outside world.
|
|
@@ -364,6 +403,28 @@ export interface World extends Queue, Streamer, Storage {
|
|
|
364
403
|
* tolerate `undefined` for direct callers.
|
|
365
404
|
*/
|
|
366
405
|
createRunId?(options?: Readonly<Record<string, unknown>>): string;
|
|
406
|
+
/**
|
|
407
|
+
* The environment this World's writes are attributed to by the backend
|
|
408
|
+
* (`@workflow/world-vercel`: `'production' | 'preview' | 'development'`).
|
|
409
|
+
*
|
|
410
|
+
* Synchronous and side-effect free: implementations derive this from
|
|
411
|
+
* configuration or environment variables they already hold, never from a
|
|
412
|
+
* network call. Return `undefined` when the environment can't be determined.
|
|
413
|
+
*
|
|
414
|
+
* The value MUST match the attribution the backend will actually apply to
|
|
415
|
+
* this client's writes — for `world-vercel` that means keeping it in lockstep
|
|
416
|
+
* with the `x-vercel-environment` header (proxy path) and the OIDC token's
|
|
417
|
+
* `environment` claim (in-deployment path). A value that merely looks
|
|
418
|
+
* plausible is worse than `undefined`, because callers use it to detect
|
|
419
|
+
* cross-tenant mismatches and a wrong answer manufactures a false one.
|
|
420
|
+
*
|
|
421
|
+
* `start()` stamps this into the queue message's `runInput` so the consuming
|
|
422
|
+
* deployment can tell that a message it was handed was created against a
|
|
423
|
+
* different environment than its own. Not all Worlds have an environment
|
|
424
|
+
* dimension — local dev and Postgres have exactly one tenant, so they omit
|
|
425
|
+
* this and the check is skipped.
|
|
426
|
+
*/
|
|
427
|
+
getEnvironment?(): string | undefined;
|
|
367
428
|
/**
|
|
368
429
|
* World-specific display fields for a run.
|
|
369
430
|
*
|
|
@@ -51,8 +51,30 @@ export declare const RunInputSchema: z.ZodObject<{
|
|
|
51
51
|
executionContext: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
52
52
|
attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
53
53
|
allowReservedAttributes: z.ZodOptional<z.ZodLiteral<true>>;
|
|
54
|
+
environment: z.ZodOptional<z.ZodString>;
|
|
54
55
|
}, z.core.$strip>;
|
|
55
56
|
export type RunInput = z.infer<typeof RunInputSchema>;
|
|
57
|
+
/**
|
|
58
|
+
* Lazy hook resume data carried through the queue alongside a workflow
|
|
59
|
+
* invocation. Present only when `resumeHook()` takes the parallel fast path:
|
|
60
|
+
* the producer persists the `hook_received` event and publishes this invocation
|
|
61
|
+
* concurrently. On receipt, a consumer that understands `hookInput` idempotently
|
|
62
|
+
* ensures the `hook_received` event exists — keyed by `resumeId` — before
|
|
63
|
+
* replaying, so the two concurrent writes converge on exactly one event.
|
|
64
|
+
*
|
|
65
|
+
* The `payload` is the already-serialized (and possibly encrypted) resume
|
|
66
|
+
* payload — the identical bytes the producer also sent on the direct
|
|
67
|
+
* `events.create`, so both server receipts hash to the same digest under the
|
|
68
|
+
* `(runId, resumeId)` constraint.
|
|
69
|
+
*/
|
|
70
|
+
export declare const HookResumeInputSchema: z.ZodObject<{
|
|
71
|
+
resumeId: z.ZodString;
|
|
72
|
+
hookId: z.ZodString;
|
|
73
|
+
token: z.ZodString;
|
|
74
|
+
payload: z.ZodUnknown;
|
|
75
|
+
payloadDigest: z.ZodString;
|
|
76
|
+
}, z.core.$strip>;
|
|
77
|
+
export type HookResumeInput = z.infer<typeof HookResumeInputSchema>;
|
|
56
78
|
export declare const WorkflowInvokePayloadSchema: z.ZodObject<{
|
|
57
79
|
runId: z.ZodString;
|
|
58
80
|
traceCarrier: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
@@ -61,6 +83,7 @@ export declare const WorkflowInvokePayloadSchema: z.ZodObject<{
|
|
|
61
83
|
eventId: z.ZodString;
|
|
62
84
|
count: z.ZodNumber;
|
|
63
85
|
}, z.core.$strip>>;
|
|
86
|
+
preconditionReinvocations: z.ZodOptional<z.ZodNumber>;
|
|
64
87
|
serverErrorRetryCount: z.ZodOptional<z.ZodNumber>;
|
|
65
88
|
stepId: z.ZodOptional<z.ZodString>;
|
|
66
89
|
stepName: z.ZodOptional<z.ZodString>;
|
|
@@ -72,6 +95,14 @@ export declare const WorkflowInvokePayloadSchema: z.ZodObject<{
|
|
|
72
95
|
executionContext: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
73
96
|
attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
74
97
|
allowReservedAttributes: z.ZodOptional<z.ZodLiteral<true>>;
|
|
98
|
+
environment: z.ZodOptional<z.ZodString>;
|
|
99
|
+
}, z.core.$strip>>;
|
|
100
|
+
hookInput: z.ZodOptional<z.ZodObject<{
|
|
101
|
+
resumeId: z.ZodString;
|
|
102
|
+
hookId: z.ZodString;
|
|
103
|
+
token: z.ZodString;
|
|
104
|
+
payload: z.ZodUnknown;
|
|
105
|
+
payloadDigest: z.ZodString;
|
|
75
106
|
}, z.core.$strip>>;
|
|
76
107
|
}, z.core.$strip>;
|
|
77
108
|
export type WorkflowInvokePayload = z.infer<typeof WorkflowInvokePayloadSchema>;
|
|
@@ -114,6 +145,7 @@ export declare const QueuePayloadSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
114
145
|
eventId: z.ZodString;
|
|
115
146
|
count: z.ZodNumber;
|
|
116
147
|
}, z.core.$strip>>;
|
|
148
|
+
preconditionReinvocations: z.ZodOptional<z.ZodNumber>;
|
|
117
149
|
serverErrorRetryCount: z.ZodOptional<z.ZodNumber>;
|
|
118
150
|
stepId: z.ZodOptional<z.ZodString>;
|
|
119
151
|
stepName: z.ZodOptional<z.ZodString>;
|
|
@@ -125,6 +157,14 @@ export declare const QueuePayloadSchema: z.ZodUnion<readonly [z.ZodObject<{
|
|
|
125
157
|
executionContext: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodAny>>;
|
|
126
158
|
attributes: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>;
|
|
127
159
|
allowReservedAttributes: z.ZodOptional<z.ZodLiteral<true>>;
|
|
160
|
+
environment: z.ZodOptional<z.ZodString>;
|
|
161
|
+
}, z.core.$strip>>;
|
|
162
|
+
hookInput: z.ZodOptional<z.ZodObject<{
|
|
163
|
+
resumeId: z.ZodString;
|
|
164
|
+
hookId: z.ZodString;
|
|
165
|
+
token: z.ZodString;
|
|
166
|
+
payload: z.ZodUnknown;
|
|
167
|
+
payloadDigest: z.ZodString;
|
|
128
168
|
}, z.core.$strip>>;
|
|
129
169
|
}, z.core.$strip>]>;
|
|
130
170
|
export type QueuePayload = z.infer<typeof QueuePayloadSchema>;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import{i as e,o as t,t as n}from"../../_chunks/workflow/rolldown-runtime-DaDcL9Zw.js";import"../../_chunks/workflow/dist-B-vbuNqP.js";import{i as r,n as i,r as a,t as o}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{D as s,T as c,_ as l,d as u,f as d,o as f,r as p}from"../../_chunks/workflow/dist-
|
|
2
|
-
`);for(let e of r){let r=e.trim().split(/\s+/);if(r.length<5||r[0]?.toUpperCase()!==`TCP`)continue;let[,i,,a,o]=r;if(a?.toUpperCase()!==`LISTENING`||o!==t.toString())continue;let s=i.lastIndexOf(`:`);if(s===-1)continue;let c=Ne(i.slice(s+1));c!==void 0&&n.push(c)}return n}const Fe=
|
|
1
|
+
import{i as e,o as t,t as n}from"../../_chunks/workflow/rolldown-runtime-DaDcL9Zw.js";import"../../_chunks/workflow/dist-B-vbuNqP.js";import{i as r,n as i,r as a,t as o}from"../../_chunks/workflow/workflow-routes-CwqB063q.js";import{D as s,T as c,_ as l,d as u,f as d,o as f,r as p}from"../../_chunks/workflow/dist-dNxTT6nO.js";import{A as m,B as h,D as g,E as _,H as v,I as ee,J as y,L as te,M as b,Mr as x,O as ne,R as S,V as re,W as C,X as w,a as ie,d as T,di as E,h as ae,j as oe,n as se,o as D,p as O,q as ce,r as le,u as k,v as A,xn as j,yr as M,z as ue}from"../../_chunks/workflow/dist-D5bR13zs.js";import{n as de,t as fe}from"../../_chunks/workflow/spec-version-C0hBsfu-.js";import{t as N}from"../../_chunks/workflow/undici-DWL_MYmT.js";import{createHash as pe}from"node:crypto";import{promisify as me}from"node:util";import{fileURLToPath as he}from"node:url";import{promises as P}from"node:fs";import F,{access as ge,constants as _e,mkdir as ve,readFile as I,readdir as ye,readlink as be,rm as xe,unlink as Se,writeFile as Ce}from"node:fs/promises";import L from"node:path";import{tmpdir as we}from"node:os";import{execFile as Te}from"node:child_process";import{setTimeout as Ee}from"node:timers/promises";import{EventEmitter as De}from"node:events";var Oe=class extends s{dataDir;constructor(e,t){super(`[workflow] The local (filesystem) world cannot create its data directory "${e}" (${t}). Workflow runs cannot be stored, so every run will fail before its first step. If this is a Vercel deployment, its filesystem is read-only and the local world cannot work there. The world is selected from the environment when the process starts: the Vercel world is used when VERCEL_DEPLOYMENT_ID is set, unless WORKFLOW_TARGET_WORLD says otherwise. Unset WORKFLOW_TARGET_WORLD in this deployment, or set WORKFLOW_TARGET_WORLD=vercel, to use the Vercel world. Otherwise point WORKFLOW_LOCAL_DATA_DIR at a writable directory.`,{code:t}),this.name=`UnwritableDataDirError`,this.dataDir=e}static is(e){return e instanceof Error&&e.name===`UnwritableDataDirError`}};const ke=new Set([`EROFS`,`EACCES`,`EPERM`]);function Ae(e){return e!==void 0&&ke.has(e)}let je=!1;function Me(e){if(je||!process.env.VERCEL_DEPLOYMENT_ID)return;let t=L.resolve(e),n=we();t===n||t.startsWith(`${n}${L.sep}`)||(je=!0,console.warn(`[workflow] Warning: the local (filesystem) world is running inside a Vercel deployment, writing to ${t}. That filesystem is read-only, so workflow runs will fail before their first step. The world is selected from the environment when the process starts: the Vercel world is used when VERCEL_DEPLOYMENT_ID is set, unless WORKFLOW_TARGET_WORLD says otherwise. Unset WORKFLOW_TARGET_WORLD in this deployment, or set WORKFLOW_TARGET_WORLD=vercel, to use the Vercel world.`))}function Ne(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}function Pe(e,t){let n=[],r=e.trim().split(`
|
|
2
|
+
`);for(let e of r){let r=e.trim().split(/\s+/);if(r.length<5||r[0]?.toUpperCase()!==`TCP`)continue;let[,i,,a,o]=r;if(a?.toUpperCase()!==`LISTENING`||o!==t.toString())continue;let s=i.lastIndexOf(`:`);if(s===-1)continue;let c=Ne(i.slice(s+1));c!==void 0&&n.push(c)}return n}const Fe=me(Te);function Ie(e,t=10){let n=parseInt(e,t);if(!Number.isNaN(n)&&n>=0&&n<=65535)return n}const Le=((e,t)=>e.join(t))([``,`proc`],`/`);async function Re(e){let t=[`${Le}/net/tcp`,`${Le}/net/tcp6`],n=[],r=new Set,i=`${Le}/${e}/fd`;try{let e=(await ye(i)).sort((e,t)=>Number.parseInt(e,10)-Number.parseInt(t,10)),t=await Promise.allSettled(e.map(async e=>(await be(`${i}/${e}`)).match(/^socket:\[(\d+)\]$/)?.[1]??null));for(let e of t)e.status===`fulfilled`&&e.value&&(n.push(e.value),r.add(e.value))}catch{return[]}if(n.length===0)return[];let a=new Map;for(let e of t)try{let t=(await I(e,`utf8`)).split(`
|
|
3
3
|
`).slice(1);for(let e of t){if(!e.trim())continue;let t=e.trim().split(/\s+/);if(t.length<10)continue;let n=t[1],i=t[3],o=t[9];if(!n||i!==`0A`||!o||!r.has(o))continue;let s=n.indexOf(`:`);if(s===-1)continue;let c=n.slice(s+1);if(!c)continue;let l=Ie(c,16);l!==void 0&&a.set(o,l)}}catch{}let o=[];for(let e of n){let t=a.get(e);t!==void 0&&o.push(t)}return o}async function ze(e){try{let{stdout:t}=await Fe(`lsof`,[`-a`,`-i`,`-P`,`-n`,`-p`,e.toString()]),n=[],r=t.split(`
|
|
4
|
-
`);for(let e of r)if(e.includes(`LISTEN`)){let t=e.trim().split(/\s+/)[8];if(t){let e=t.lastIndexOf(`:`);if(e!==-1){let r=Ie(t.slice(e+1));r!==void 0&&n.push(r)}}}return n}catch{return[]}}async function Be(e){try{let{stdout:t}=await Fe(`cmd`,[`/c`,`netstat -ano -p tcp | findstr LISTENING`]);return Pe(t,e)}catch{return[]}}async function Ve(){let{pid:e,platform:t}=process;try{switch(t){case`linux`:return await Re(e);case`darwin`:return await ze(e);case`win32`:return await Be(e);default:return[]}}catch(e){return process.env.NODE_ENV===`development`&&console.debug(`[getAllPorts] Detection failed:`,e),[]}}const He=`${o}/flow?__health`;async function Ue(e,t={}){let{endpoint:n=He,timeout:r=500}=t,i=new AbortController,a=setTimeout(()=>i.abort(),r);try{return(await fetch(`http://localhost:${e}${n}`,{method:`HEAD`,signal:i.signal})).status===200}catch{return!1}finally{clearTimeout(a)}}async function We(e){let t=await Ve();if(t.length===0)return;if(t.length===1)return t[0];let n=(await Promise.all(t.map(async t=>({port:t,isWorkflow:await Ue(t,e)})))).find(e=>e.isWorkflow);return n?n.port:(process.env.NODE_ENV===`development`&&console.debug(`[getWorkflowPort] Probing failed, falling back to first port:`,t[0]),t[0])}function Ge(e){let t={get value(){let n=e();return Object.defineProperty(t,"value",{value:n}),n}};return t}const Ke=()=>process.env.WORKFLOW_LOCAL_DATA_DIR||`.workflow-data`,qe=()=>process.env.WORKFLOW_LOCAL_BASE_URL,Je=Ge(()=>({dataDir:Ke(),baseUrl:qe()}));function Ye(e){if(e.recoverActiveRuns!==void 0)return e.recoverActiveRuns;let t=process.env.WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS?.toLowerCase();return!(t===`0`||t===`false`)}function Xe(e){return e.baseUrl??process.env.WORKFLOW_LOCAL_BASE_URL??i(`http://localhost`)}async function Ze(e){if(e.baseUrl)return e.baseUrl;if(process.env.WORKFLOW_LOCAL_BASE_URL)return process.env.WORKFLOW_LOCAL_BASE_URL;if(typeof e.port==`number`)return i(`http://localhost:${e.port}`);if(process.env.PORT)return i(`http://localhost:${process.env.PORT}`);let t=await We({endpoint:a()});if(t)return i(`http://localhost:${t}`);throw Error(`Unable to resolve base URL for workflow queue.`)}const Qe=A(()=>Math.random());function $e(e){let t=typeof e==`string`?e:String(e);return t.length>48?`${t.slice(0,48)}…`:t}var et=class extends s{constructor(e,t){super(`Unsafe ${e} "${$e(t)}": must not be empty, contain ".", "/", "\\", or null bytes`),this.name=`UnsafeEntityIdError`}static is(e){return e instanceof Error&&e.name===`UnsafeEntityIdError`}};function R(e,t){if(t.length===0||t.startsWith(`.`)||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`)||t.includes(`.`))throw new et(e,t)}function z(e,...t){let n=L.resolve(e),r=L.resolve(e,...t);if(r!==n&&!r.startsWith(n+L.sep))throw new et(`path`,t.join(`/`));return r}const tt=process.platform===`win32`;async function B(e,t=5){if(!tt)return e();let n=[`EPERM`,`EBUSY`,`EACCES`];for(let r=0;r<=t;r++)try{return await e()}catch(e){if(!(r<t&&n.includes(e.code)))throw e;let i=10*2**r+Math.random()*10;await new Promise(e=>setTimeout(e,i))}throw Error(`Retry loop exited unexpectedly`)}const nt=new Set,rt=new Set;function it(){nt.clear(),rt.clear()}const at=/\.[a-zA-Z][a-zA-Z0-9-]*$/;function V(e){return e.replace(at,``)}function ot(e,t){return e.endsWith(`.${t}`)}function st(e){return!at.test(e)}function H(e,t,n,r){return R(`fileId`,n),r!==void 0&&R(`tag`,r),z(e,t,r?`${n}.${r}.json`:`${n}.json`)}async function U(e,t,n,r,i){if(R(`fileId`,n),i!==void 0&&R(`tag`,i),i){let a=await K(z(e,t,`${n}.${i}.json`),r);if(a!==null)return a}return K(z(e,t,`${n}.json`),r)}async function ct(e,t){let n=`.${t}.json`;try{return(await F.readdir(e)).filter(e=>e.endsWith(n))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function lt(e,t,n){let r=`.${t}${n}`;try{return(await F.readdir(e)).filter(e=>e.endsWith(r))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function ut(e){let t=L.resolve(e);if(!rt.has(t))try{await F.mkdir(t,{recursive:!0}),rt.add(t)}catch(e){let n=e.code;if(Ae(n)&&!await dt(t))throw new Oe(t,n)}}async function dt(e){try{return(await F.stat(e)).isDirectory()}catch{return!1}}async function ft(e,t){await ut(e);try{return await t()}catch(n){if(n.code!==`ENOENT`)throw n;return rt.delete(L.resolve(e)),await ut(e),t()}}function W(e,t){return t instanceof Uint8Array?{__type:`Uint8Array`,data:Buffer.from(t).toString(`base64`)}:t}function pt(e,t){return typeof t==`object`&&t&&t.__type===`Uint8Array`&&typeof t.data==`string`?new Uint8Array(Buffer.from(t.data,`base64`)):t}async function G(e,t,n){return mt(e,JSON.stringify(t,W,2),n)}async function mt(e,t,n){if(!n?.overwrite){if(nt.has(e))throw new p(`File ${e} already exists and 'overwrite' is false`);try{throw await F.access(e),nt.add(e),new p(`File ${e} already exists and 'overwrite' is false`)}catch(e){if(e.code!==`ENOENT`)throw e}}let r=`${e}.tmp.${Qe()}`,i=!1;try{await ft(L.dirname(e),async()=>{await F.writeFile(r,t),i=!0,await B(()=>F.rename(r,e))}),nt.add(e)}catch(e){throw i&&await B(()=>F.unlink(r),3).catch(()=>{}),e}}async function K(e,t){try{let n=await F.readFile(e,`utf-8`);return t.parse(JSON.parse(n,pt))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ht(e){return await F.readFile(e)}async function gt(e){let t=await F.open(e,`r`);try{let e=Buffer.allocUnsafe(1),{bytesRead:n}=await t.read(e,0,1,0);return n===0?void 0:e[0]}finally{await t.close()}}async function q(e){try{await F.unlink(e)}catch(e){if(e.code!==`ENOENT`)throw e}}async function J(e,t){let n=`${e}.tmp.${Qe()}`,r=!1;try{return await ft(L.dirname(e),async()=>{await F.writeFile(n,t,{flag:`wx`}),r=!0;try{return await B(()=>F.link(n,e)),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}})}finally{r&&await B(()=>F.unlink(n),3).catch(()=>{})}}async function _t(e,t){try{return await ft(L.dirname(t),()=>B(()=>F.link(e,t))),`linked`}catch(e){if(e.code===`EEXIST`)return`exists`;if(e.code===`ENOENT`)return`missing`;throw e}}async function Y(e){return vt(e,`.json`)}async function vt(e,t){try{return(await F.readdir(e)).filter(e=>e.endsWith(t)).map(e=>e.slice(0,-t.length))}catch(e){if(e.code===`ENOENT`)return[];throw e}}function yt(e){if(!e)return null;let t=e.split(`|`);return{timestamp:new Date(t[0]),id:t[1]||null}}function bt(e,t){return t?`${e.toISOString()}|${t}`:e.toISOString()}async function X(e){let{directory:t,schema:n,cachedItems:r,filePrefix:i,fileIdFilter:a,filter:o,sortOrder:s=`desc`,limit:c=20,cursor:l,getCreatedAt:u,getId:d}=e;i!==void 0&&R(`filePrefix`,i);let f=L.resolve(t),p=await Y(f),m=i?p.filter(e=>e.startsWith(i)):p,h=a?m.filter(a):m,g=yt(l),_=h;g&&(_=h.filter(e=>{let t=u(`${e}.json`);if(t){let e=g.timestamp.getTime(),n=t.getTime();return g.id?s===`desc`?n<=e:n>=e:s===`desc`?n<e:n>e}return!0}));let v=[];for(let e=0;e<_.length;e+=32){let t=_.slice(e,e+32),i=await Promise.all(t.map(async e=>{let t=L.join(f,`${e}.json`);try{let e=r?.get(t);return e===void 0?await K(t,n):structuredClone(e)}catch(t){if(t instanceof M)return console.warn(`Skipping item ${e} due to malformed JSON: ${t.message}`),null;throw t}}));for(let e of i)if(e&&!(o&&!o(e))){if(g){let t=e.createdAt.getTime(),n=g.timestamp.getTime();if(s===`desc`){if(t>n||t===n&&g.id&&d&&d(e)>=g.id)continue}else if(t<n||t===n&&g.id&&d&&d(e)<=g.id)continue}v.push(e)}}v.sort((e,t)=>{let n=e.createdAt.getTime(),r=t.createdAt.getTime(),i=s===`asc`?n-r:r-n;if(i===0&&d){let n=d(e),r=d(t);return s===`asc`?n.localeCompare(r):r.localeCompare(n)}return i});let ee=v.length>c,y=ee?v.slice(0,c):v;return{data:y,cursor:y.length>0?bt(y[y.length-1].createdAt,d?.(y[y.length-1])):null,hasMore:ee}}let Z=null;function xt(){return typeof import.meta.url==`string`&&import.meta.url?L.dirname(me(import.meta.url)):null}async function St(){if(Z)return Z;let e=xt();if(e)try{let t=await ve(L.join(e,`../package.json`),`utf-8`);return Z=JSON.parse(t),Z}catch{}return Z={name:`@workflow/world-local`,version:`5.0.0-beta.32`},Z}const Ct=`version.txt`;var wt=class extends Error{dataDir;code;constructor(e,t,n){super(e),this.name=`DataDirAccessError`,this.dataDir=t,this.code=n}},Tt=class extends Error{oldVersion;newVersion;suggestedVersion;constructor(e,t,n,r){super(e),this.name=`DataDirVersionError`,this.oldVersion=t,this.newVersion=n,this.suggestedVersion=r}};function Et(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw Error(`Invalid version string: "${e}"`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),prerelease:t[4],raw:e}}function Q(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease?`${t}-${e.prerelease}`:t}function Dt(e){let t=e.trim(),n=t.lastIndexOf(`@`);if(n<=0)throw Error(`Invalid version file content: "${e}"`);return{packageName:t.substring(0,n),version:Et(t.substring(n+1))}}function Ot(e,t){return`${e}@${Q(t)}`}function kt(e,t){console.log(`[world-local] Upgrading from version ${Q(e)} to ${Q(t)}`)}async function At(e){let t=L.resolve(e);try{await _e(t,{recursive:!0})}catch(e){let n=e;if(n.code!==`EEXIST`)throw new wt(`Failed to create data directory "${t}": ${n.message}`,t,n.code)}try{await he(t,ge.R_OK)}catch(e){let n=e;throw new wt(`Data directory "${t}" is not readable: ${n.message}`,t,n.code)}let n=L.join(t,`.workflow-write-test-${Date.now()}`);try{await Ce(n,``),await Se(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}catch(e){let n=e;throw new wt(`Data directory "${t}" is not writable: ${n.message}`,t,n.code)}}async function jt(e){let t=L.join(L.resolve(e),Ct);try{return Dt(await ve(t,`utf-8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Mt(e,t){await Ce(L.join(L.resolve(e),Ct),Ot((await St()).name,t))}function Nt(e,t){return t||Q(e)}async function Pt(e){await At(e);let t=await St(),n=Et(t.version),r=await jt(e);if(r===null){await Mt(e,n);return}let{version:i}=r;if(Q(i)!==Q(n))try{kt(i,n),await Mt(e,n)}catch(e){let r=Nt(i,e instanceof Tt?e.suggestedVersion:void 0);throw console.error(`[world-local] Failed to upgrade data directory from version ${Q(i)} to ${Q(n)}:`,e instanceof Error?e.message:e),console.error(`[world-local] Data is not compatible with the current version. Please downgrade to ${t.name}@${r}`),e}}let Ft=null;async function It(){return Ft||=import(`../../_chunks/workflow/src-Cj3P1ChQ.js`).then(e=>t(e.t(),1)).catch(()=>null),Ft}let Lt=null;async function Rt(){return Lt||=It().then(e=>e?e.trace.getTracer(`workflow`):null),Lt}async function zt(e,...t){let[n,r]=await Promise.all([Rt(),It()]),{fn:i,opts:a}=typeof t[0]==`function`?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!i)throw Error(`Function to trace must be provided`);return!n||!r?await i():n.startActiveSpan(e,a,async e=>{try{let t=await i(e);return e.setStatus({code:r.SpanStatusCode.OK}),t}catch(t){throw e.setStatus({code:r.SpanStatusCode.ERROR,message:t.message}),t}finally{e.end()}})}async function Bt(e){let t=await It();if(t)return t.SpanKind[e]}function Vt(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const Ht=Vt(`peer.service`),Ut=Vt(`rpc.system`),Wt=Vt(`rpc.service`),Gt=Vt(`rpc.method`),Kt=Vt(`workflow.run.id`),qt=Vt(`step.id`),Jt={peerService:`world-local`,rpcSystem:`local`,rpcService:`world-local`},Yt={"world.runs.get":0,"world.runs.experimentalSetAttributes":0,"world.steps.get":0,"world.events.create":0,"world.events.get":0},Xt=new Set([`world.steps.list`,`world.events.list`,`world.hooks.list`]);function Zt(e){if(e.length>=2&&typeof e[1]==`object`&&e[1]!==null){let t=e[1];if(typeof t.eventType==`string`)return t.eventType}}function Qt(e,t){return typeof e[t]==`string`?e[t]:void 0}function $t(e){if(typeof e!=`object`||!e)return;let t=e.runId;return typeof t==`string`?t:void 0}function en(e){if(typeof e!=`object`||!e)return;let t=e;if(typeof t.runId==`string`)return t.runId;for(let e of[`run`,`step`,`hook`,`wait`]){let n=t[e];if(typeof n==`object`&&n){let e=n.runId;if(typeof e==`string`)return e}}}function tn(e,t,n){let r=`${e}.${t}`,i={},a=Yt[r],o=a===void 0?Xt.has(r)?$t(n[0]):void 0:Qt(n,a);if(o&&Object.assign(i,Kt(o)),r===`world.steps.get`){let e=Qt(n,1);e&&Object.assign(i,qt(e))}return i}function nn(e,t){let n={};for(let r of Object.keys(t))if(typeof t[r]!=`function`)n[r]=t[r];else{let i=t[r],a=String(r);n[r]=async(...t)=>{let n=`${e}.${a}`;if(e===`world.events`&&a===`create`){let r=Zt(t);r&&(n=`${e}.${a} ${r}`)}return zt(n,{kind:await Bt(`INTERNAL`)},async r=>{r?.setAttributes({...Ht(Jt.peerService),...Ut(Jt.rpcSystem),...Wt(Jt.rpcService),...Gt(n),...tn(e,a,t)});let o=await i(...t),s=en(o);return s&&r?.setAttributes(Kt(s)),o})}}return n}var rn=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RateLimit=t.Sema=void 0;let r=n(e(`events`));function i(e,t,n,r,i){for(let a=0;a<i;++a)n[a+r]=e[a+t],e[a+t]=void 0}function a(e){return e>>>=0,--e,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function o(e){return a(Math.min(Math.max(16,e),1073741824))}var s=class{constructor(e){this._capacity=o(e),this._length=0,this._front=0,this.arr=[]}push(e){let t=this._length;this.checkCapacity(t+1);let n=this._front+t&this._capacity-1;return this.arr[n]=e,this._length=t+1,t+1}pop(){let e=this._length;if(e===0)return;let t=this._front+e-1&this._capacity-1,n=this.arr[t];return this.arr[t]=void 0,this._length=e-1,n}shift(){let e=this._length;if(e===0)return;let t=this._front,n=this.arr[t];return this.arr[t]=void 0,this._front=t+1&this._capacity-1,this._length=e-1,n}get length(){return this._length}checkCapacity(e){this._capacity<e&&this.resizeTo(o(this._capacity*1.5+16))}resizeTo(e){let t=this._capacity;this._capacity=e;let n=this._front,r=this._length;if(n+r>t){let e=n+r&t-1;i(this.arr,0,this.arr,t,e)}}},c=class extends r.default{};function l(e){return typeof e==`function`}function u(){return`1`}var d=class{constructor(e,{initFn:t=u,pauseFn:n,resumeFn:r,capacity:i=10}={}){if(l(n)!==l(r))throw Error(`pauseFn and resumeFn must be both set for pausing`);this.nrTokens=e,this.free=new s(e),this.waiting=new s(i),this.releaseEmitter=new c,this.noTokens=t===u,this.pauseFn=n,this.resumeFn=r,this.paused=!1,this.releaseEmitter.on(`release`,e=>{let t=this.waiting.shift();t?t.resolve(e):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(e))});for(let n=0;n<e;n++)this.free.push(t())}tryAcquire(){return this.free.pop()}async acquire(){let e=this.tryAcquire();return e===void 0?new Promise((e,t)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn()),this.waiting.push({resolve:e,reject:t})}):e}release(e){this.releaseEmitter.emit(`release`,this.noTokens?`1`:e)}drain(){let e=Array(this.nrTokens);for(let t=0;t<this.nrTokens;t++)e[t]=this.acquire();return Promise.all(e)}nrWaiting(){return this.waiting.length}};t.Sema=d;function f(e,{timeUnit:t=1e3,uniformDistribution:n=!1}={}){let r=new d(n?1:e),i=n?t/e:t;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}t.RateLimit=f}))(),an=P(),on=class{contentType=`application/json`;serialize(e){return Buffer.from(JSON.stringify(e,W))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}let r=Buffer.concat(t).toString();return JSON.parse(r,pt)}};const sn=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY??`0`,10)||1/0,cn=2147483647,ln=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY??`0`,10)||1e3,un=`Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer`;function dn(e){let t=e,n=new Set;for(;t&&typeof t==`object`&&!n.has(t);){if(n.add(t),`message`in t&&typeof t.message==`string`&&t.message.includes(un))return!0;t=`cause`in t?t.cause:void 0}return!1}function fn(e){let t=new an.Agent({headersTimeout:0,connections:1e3,keepAliveTimeout:3e4}),n=new on,i=A(),a=new rn.Sema(ln),o=new AbortController,s=o.signal,c=new Map,l=new Map,u=async(o,u,d)=>{let f=[];if(d?.idempotencyKey){let e=c.get(d.idempotencyKey);if(e)return{messageId:e}}let p=n.serialize(u),{prefix:m}=w(o),h=ae.parse(`msg_${i()}`),g=u,_=g.runId??void 0,v=g.stepId??void 0;if(d?.idempotencyKey){let e=d.idempotencyKey;c.set(e,h),f.push(()=>{c.delete(e)})}return(async()=>{d?.delaySeconds&&d.delaySeconds>0&&await Ee(Math.min(d.delaySeconds*1e3,cn),void 0,{signal:s}),a.tryAcquire()||(console.warn(`[world-local]: concurrency limit (${ln}) reached, waiting for queue to free up`),await a.acquire());let n=0;try{for(let i=0;i<256;i++){let a={...d?.headers,"content-type":`application/json`,"x-vqs-queue-name":o,"x-vqs-message-id":h,"x-vqs-message-attempt":String(n+1)},c=l.get(m),u;try{if(c)u=await c(new Request(r(Xe(e),{type:`flow`}),{method:`POST`,headers:a,body:p}));else{let n=await Ze(e);u=await fetch(r(n,{type:`flow`}),{method:`POST`,duplex:`half`,dispatcher:t,headers:a,body:p})}}catch(e){let t=e?.name;if(s.aborted||t===`AbortError`||t===`ResponseAborted`)return;if(dn(e))throw e;console.error(`[world-local] Queue delivery failed at the transport (loop ${i+1}), retrying`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v},error:String(e)}),await Ee(5e3,void 0,{signal:s});continue}n++;let f=await u.text();if(u.ok){try{let e=Number(JSON.parse(f).timeoutSeconds);if(Number.isFinite(e)&&e>=0){e>0&&await Ee(Math.min(e*1e3,cn),void 0,{signal:s});continue}}catch{}return}console.error(`[world-local] Queue message failed (attempt ${n}, HTTP ${u.status})`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v},handlerError:f}),await Ee(5e3,void 0,{signal:s})}console.error(`[world-local] Queue message exhausted safety limit (256 attempts)`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v}})}finally{a.release()}})().catch(e=>{e?.name===`AbortError`||e?.name===`ResponseAborted`||(dn(e)?console.error(`[local world] Queue operation failed: detected "${un}". This usually means a Next.js proxy/middleware consumed Workflow's internal request before the executor could read it. Exclude \`/.well-known/workflow/*\` from your matcher. See https://workflow-sdk.dev/docs/getting-started/next#configure-proxy-handler`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v},originalError:e}):console.error(`[local world] Queue operation failed:`,e))}).finally(()=>{for(let e of f)e()}),{messageId:h}},d=N({"x-vqs-queue-name":k,"x-vqs-message-id":ae,"x-vqs-message-attempt":C()});return{queue:u,createQueueHandler:(e,t)=>async n=>{let r=d.safeParse(Object.fromEntries(n.headers));if(!r.success||!n.body)return Response.json({error:n.body?`Missing required headers`:`Missing request body`},{status:400});let i=r.data[`x-vqs-queue-name`],a=r.data[`x-vqs-message-id`],o=r.data[`x-vqs-message-attempt`];if(!i.startsWith(e))return Response.json({error:`Unhandled queue`},{status:400});let s=await new on().deserialize(n.body);try{let e=await t(s,{attempt:o,queueName:i,messageId:a}),n=null;return typeof e?.timeoutSeconds==`number`&&(n=Math.min(e.timeoutSeconds,sn)),n==null?Response.json({ok:!0}):Response.json({timeoutSeconds:n})}catch(e){return Response.json(String(e),{status:500})}},getDeploymentId:async()=>`dpl_local@${(await St()).version}`,registerHandler(e,t){l.set(e,t)},async close(){s.aborted||(o.abort(),await t.close())}}}function pn(e){return fe(`sha256`).update(e).digest(`hex`)}function mn(e,t,n){return z(e,`.locks`,`hooks`,n?`${t}.disposed.${n}`:`${t}.disposed`)}async function hn(e,t,n){let r=[mn(e,t)];n&&r.push(mn(e,t,n));for(let e of r)try{return await I.access(e),!0}catch{}return!1}function gn(e,t,n){return z(e,`.locks`,`runs`,n?`${t}.terminal.${n}`:`${t}.terminal`)}async function _n(e,t,n){let r=[gn(e,t)];n&&r.push(gn(e,t,n));for(let e of r)try{return await I.access(e),!0}catch(e){if(e.code!==`ENOENT`)throw e}return!1}function vn(e,t,n){return z(e,`.locks`,`runs`,n?`${t}.pending.${n}`:`${t}.pending`)}function yn(e,t,n,r){return L.join(vn(e,t,r),`${n}.json`)}async function bn(e,t,n){let r=[vn(e,t)];n&&r.push(vn(e,t,n));for(let e of r){let t;try{t=await I.readdir(e)}catch(e){if(e.code===`ENOENT`)continue;throw e}for(let n of t)try{await B(()=>I.unlink(L.join(e,n)))}catch(e){if(e.code!==`ENOENT`)throw e}await I.rmdir(e).catch(()=>{})}}async function xn(e,t,n){let r=[];try{r=await I.readdir(L.join(e,`events`))}catch(e){if(e.code!==`ENOENT`)throw e}let i=`${t}-`,a=null;for(let e of r){if(!e.startsWith(i)||!e.endsWith(`.json`))continue;let t=e.slice(0,-5);if(!st(t)&&!(n&&ot(t,n)))continue;let r=V(t).slice(i.length);(!a||r>a)&&(a=r)}let o=Date.now();if(a)try{let e=re(a.replace(/^evnt_/,``));o<=e&&(o=e+1)}catch{}return{eventId:`evnt_${Tn(o)}`,createdAt:new Date(o)}}function Sn(e,t){return L.join(e,`hooks`,`tokens`,`${pn(t)}.json`)}async function Cn(e,t,n,r){let i=Sn(e,t),a;try{a=JSON.parse(await I.readFile(i,`utf8`))}catch{return}a.runId!==n||a.hookId!==r||await I.unlink(i).catch(()=>{})}function wn(e,t,n,r){let i=fe(`sha256`).update(`${t}\x00${n}\x00${r}`).digest(`hex`);return L.join(e,`hooks`,`tokens`,`${i}.recovery.json`)}const Tn=A(()=>Math.random()),$=e=>{let t=RegExp(`^${e}_`,`g`);return n=>{let r=V(n.replace(/\.json$/,``))+`.json`,i=r.indexOf(`-`);return i===-1?oe(r.replace(/\.json$/,``).replace(t,``)):e===`step`?null:oe(r.substring(i+1).replace(/\.json$/,``).replace(t,``))}},En=N({runId:E()}),Dn=N({hookId:E(),tag:E().optional()});function On(e,t){return z(e,`hooks`,`token-index`,pn(t))}function kn(e,t){return R(`hookId`,t),z(e,`hooks`,`id-index`,t)}function An(e){return z(e,`hooks`,`by-run`)}function jn(e){let t=V(e);return t===e?void 0:e.slice(t.length+1)}function Mn(e,t){return t?st(e)||ot(e,t):st(e)}async function Nn(e){try{return await K(e,T)}catch(e){if(e instanceof SyntaxError||e instanceof M)return null;throw e}}async function Pn(e,t,n,r,i,a){R(`runId`,n),R(`eventId`,i),a!==void 0&&R(`tag`,a);let o=a?`${i}.${a}.json`:`${i}.json`,s=JSON.stringify({runId:n});await Promise.all([J(L.join(On(e,t),o),s),J(L.join(kn(e,r),o),s)])}function Fn(e,t,n,r){return H(e,`hooks/by-run`,`${t}-${n}`,r)}async function In(e,t,n,r){await J(Fn(e,t,n,r),JSON.stringify(r?{hookId:n,tag:r}:{hookId:n}))}async function Ln(e,t,n,r){await q(Fn(e,t,n,r)),r&&await q(Fn(e,t,n))}async function Rn(e,t){R(`runId`,t);let n=An(e),r=`${t}-`,i=[];for(let e of await Y(n)){if(!e.startsWith(r))continue;let t=null;try{t=await K(L.join(n,`${e}.json`),Dn)}catch(e){if(!(e instanceof SyntaxError||e instanceof M))throw e}i.push({fileId:e,hookId:t?.hookId??null,tag:t?.tag})}return i}async function zn(e,t){await q(L.join(An(e),`${t}.json`))}const Bn=new Map;function Vn(){Bn.clear()}async function Hn(e){let t=L.resolve(e),n=Bn.get(t);return n||(n=Wn(t).catch(e=>{throw Bn.delete(t),e}),Bn.set(t,n)),n}async function Un(e,t,n){for(let r=0;r<e.length;r+=t)await Promise.all(e.slice(r,r+t).map(n))}async function Wn(e){let t=L.join(e,`hooks`,`.hook-index-complete`);try{await I.access(t);return}catch{}let n=L.join(e,`events`);await Un(await Y(n),32,async t=>{let r=await Nn(L.join(n,`${t}.json`));if(!r||r.eventType!==`hook_created`||typeof r.correlationId!=`string`)return;let i=r.eventData?.token;if(typeof i==`string`)try{await Pn(e,i,r.runId,r.correlationId,r.eventId,jn(t))}catch{}});let r=L.join(e,`hooks`);await Un(await Y(r),32,async t=>{let n=null;try{n=await K(L.join(r,`${t}.json`),j)}catch(e){if(!(e instanceof SyntaxError||e instanceof M))throw e}if(n)try{await In(e,n.runId,n.hookId,jn(t))}catch{}}),await J(t,``)}async function Gn(e,t,n,r){await Hn(e);let i;try{i=t.kind===`token`?On(e,t.token):kn(e,t.hookId)}catch{return null}let a=(await Y(i)).filter(e=>Mn(e,r)).sort((e,t)=>V(t).localeCompare(V(e)));for(let t of a){let r=null;try{r=await K(L.join(i,`${t}.json`),En)}catch(e){if(!(e instanceof SyntaxError||e instanceof M))throw e}if(!r)continue;let a=V(t),o;try{o=H(e,`events`,`${r.runId}-${a}`,jn(t))}catch{continue}let s=await Nn(o);if(s&&s.eventType===`hook_created`&&typeof s.correlationId==`string`&&n(s))return s}return null}function Kn(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function qn(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function Jn(e,t){if(t===`none`){let{metadata:t,...n}=e;return n}return e}function Yn(e){if(e.eventType!==`hook_created`)return;let t=e.eventData.token;return typeof t==`string`?t:void 0}function Xn(e){let{token:t,metadata:n,isWebhook:r,isSystem:i}=e.eventData;return{runId:e.runId,hookId:e.correlationId,token:t,metadata:n,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:e.createdAt,specVersion:e.specVersion,isWebhook:r??!0,isSystem:i??!1}}function Zn(e,t){return e.eventType===`hook_created`&&typeof e.correlationId==`string`&&t(e)}async function Qn(e,t,n){let r=await U(e,`runs`,t,D,n);return r?m(r.status):!1}async function $n(e,t,n,r){let i=await Gn(e,t,e=>Zn(e,n),r);return!i||!Zn(i,n)||await Qn(e,i.runId,r)||await hn(e,i.correlationId,r)?null:i}async function er(e,t,n){let r=Xn(t);return await J(L.join(e,`hooks`,`tokens`,`${pn(r.token)}.json`),JSON.stringify({token:r.token,hookId:r.hookId,runId:r.runId,eventId:t.eventId})),await In(e,r.runId,r.hookId,n),await J(H(e,`hooks`,r.hookId,n),JSON.stringify(r,W,2)),r}async function tr(e,t,n){let r=await $n(e,{kind:`token`,token:t},e=>Yn(e)===t,n);return r?er(e,r,n):null}async function nr(e,t,n){let r=await $n(e,{kind:`id`,hookId:t},e=>e.correlationId===t,n);return r?er(e,r,n):null}function rr(e,t){let n=N({hookId:E().optional()});async function r(r){let i=null;try{i=await K(Sn(e,r),n)}catch(e){if(!(e instanceof SyntaxError||e instanceof M))throw e}if(i?.hookId)try{let n=await U(e,`hooks`,i.hookId,j,t);if(n&&n.token===r)return{...n,isWebhook:n.isWebhook??!0}}catch(e){if(!et.is(e))throw e}let a=L.join(e,`hooks`),o=await Y(a);for(let e of o){let t=await K(L.join(a,`${e}.json`),j);if(t&&t.token===r)return{...t,isWebhook:t.isWebhook??!0}}return null}async function i(n,r){R(`hookId`,n);let i=await U(e,`hooks`,n,j,t);if(!i){let i=await nr(e,n,t);if(!i)throw new f(n);let a=r?.resolveData||`all`;return Jn({...i,isWebhook:i.isWebhook??!0},a)}let a=r?.resolveData||`all`;return Jn({...i,isWebhook:i.isWebhook??!0},a)}async function a(n){let i=await r(n)??await tr(e,n,t);if(!i)throw new f(n);return i}async function o(t){let n=L.join(e,`hooks`),r=t.resolveData||`all`,i=await X({directory:n,schema:j,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,filePrefix:void 0,filter:e=>!(t.runId&&e.runId!==t.runId),getCreatedAt:()=>null,getId:e=>e.hookId});return{...i,data:i.data.map(e=>Jn(e,r))}}return{get:i,getByToken:a,list:o}}async function ir(e,t){await Hn(e);for(let n of await Rn(e,t)){if(n.hookId){let r=null,i=null;try{i=H(e,`hooks`,n.hookId,n.tag),r=await K(i,j)}catch(e){if(!et.is(e)&&!(e instanceof SyntaxError||e instanceof M))throw e}r&&i&&r.runId===t&&(await Cn(e,r.token,r.runId,r.hookId),await q(wn(e,r.token,r.runId,r.hookId)),await q(i))}await zn(e,n.fileId)}}async function ar(e,t,n,r,i,a){if(m(a.status)||await _n(e,t))throw new u(`Workflow run "${t}" is already in a terminal state`);let o=yn(e,t,n);await J(o,r);try{if(await _n(e,t)||await _t(o,i)!==`linked`)throw new u(`Workflow run "${t}" is already in a terminal state`)}finally{await I.unlink(o).catch(()=>{})}}async function or(e,t,n,r,i){R(`runId`,t);let a=i?.resolveData??`all`;switch(n.eventType){case`run_cancelled`:{await J(gn(e,t),``),await bn(e,t);let n=new Date,i={runId:r.runId,deploymentId:r.deploymentId,workflowName:r.workflowName,specVersion:r.specVersion,executionContext:r.executionContext,input:r.input,createdAt:r.createdAt,expiredAt:r.expiredAt,startedAt:r.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:n,updatedAt:n,attributes:r.attributes};return await G(z(e,`runs`,`${t}.json`),i,{overwrite:!0}),await ir(e,t),{event:void 0,run:Kn(i,a)}}case`wait_completed`:case`hook_received`:{let i=`evnt_${Tn()}`,o=new Date,s={...n,runId:t,eventId:i,createdAt:o,specVersion:5},c=z(e,`events`,`${`${t}-${i}`}.json`);return n.eventType===`hook_received`?await ar(e,t,i,JSON.stringify(s,W,2),c,r):await G(c,s),{event:S(s,a)}}default:throw Error(`Event type '${n.eventType}' not supported for legacy runs (specVersion: ${r.specVersion||`undefined`}). Please upgrade 'workflow' package.`)}}const sr=new Map;function cr(e,t){let n=sr.get(e),r={},i=(async()=>{n&&await n.catch(()=>void 0);try{return await t()}finally{sr.get(e)===r.task&&sr.delete(e)}})();return r.task=i,sr.set(e,i),i}function lr(e,t){let n=(async(n,r)=>{R(`runId`,n);let i=await U(e,`runs`,n,D,t);if(!i)throw new c(n);return Kn(i,r?.resolveData??`all`)});return{get:n,getMany:(async(e,t)=>{let r=[...new Set(e)],i=await Promise.all(r.map(async e=>{try{return await n(e,t)}catch(e){if(e instanceof c)return null;throw e}})),a=new Map(r.map((e,t)=>[e,i[t]]));return e.map(e=>a.get(e)??null)}),list:(async t=>{let n=t?.resolveData??`all`,r=await X({directory:L.join(e,`runs`),schema:D,fileIdFilter:t?.fileIdFilter,filter:e=>!(t?.workflowName&&e.workflowName!==t.workflowName||t?.status&&e.status!==t.status),sortOrder:t?.pagination?.sortOrder??`desc`,limit:t?.pagination?.limit??200,cursor:t?.pagination?.cursor,getCreatedAt:$(`wrun`),getId:e=>e.runId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r}),experimentalSetAttributes:async(n,r,i)=>(R(`runId`,n),cr(n,async()=>{let a=await U(e,`runs`,n,D,t);if(!a)throw new c(n);try{se(r,{existingKeys:Object.keys(a.attributes??{}),allowReservedAttributes:i?.allowReservedAttributes})}catch(e){throw e instanceof x,e}let o=y(a.attributes,r),s={...a,attributes:o,updatedAt:new Date};return await G(H(e,`runs`,n,t),s,{overwrite:!0}),{attributes:o}}))}}function ur(){let e=process.env.WORKFLOW_MAX_EVENTS,t=e===void 0?NaN:Number(e);return Number.isInteger(t)&&t>0?t:25e3}const dr=N({hookId:E().optional(),runId:E(),eventId:E().optional()}),fr=N({eventId:E()});async function pr(e){try{return await K(e,dr)}catch(e){if(e instanceof SyntaxError||e instanceof M)return null;throw e}}async function mr(e,t,n){if(t.hookId&&await hn(e,t.hookId,n))return!0;let r=await U(e,`runs`,t.runId,D,n);return!r||m(r.status)}async function hr(e){try{return await K(e,fr)}catch(e){if(e instanceof SyntaxError||e instanceof M)return null;throw e}}async function gr(e,t,n){return(await X({directory:L.join(e,`events`),schema:T,filePrefix:`${t}-`,filter:e=>e.eventType===`hook_created`&&e.correlationId===n,limit:1,getCreatedAt:$(`evnt`),getId:e=>e.eventId})).data[0]?.eventId??null}async function _r(e,t,n,r,i){let a=await U(e,`events`,`${t}-${r}`,T,i);if(!a||a.eventType!==`hook_created`||a.correlationId!==n||await U(e,`hooks`,n,j,i))return;let o=a.eventData??{};if(typeof o.token!=`string`)return;let s={runId:t,hookId:n,token:o.token,metadata:o.metadata,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:a.createdAt,specVersion:a.specVersion,isWebhook:o.isWebhook??!0,isSystem:o.isSystem??!1};await Pn(e,o.token,t,n,r,i),await In(e,t,n,i),await J(H(e,`hooks`,n,i),JSON.stringify(s,W,2))}async function vr(e,t,n,r,i){let a=wn(e,t,n,r);return await J(a,JSON.stringify({eventId:i}))?i:(await hr(a))?.eventId??null}function yr(e,t,n){let r=e.get(t),i={},a=(async()=>{r&&await r.catch(()=>void 0);try{return await n()}finally{e.get(t)===i.task&&e.delete(t)}})();return i.task=a,e.set(t,a),a}async function br(e,t){let n=L.join(e,`waits`),r=await Y(n);for(let e of r)e.startsWith(`${t}-`)&&await q(L.join(n,`${e}.json`))}async function xr(e,t,n,r){return cr(t,async()=>{let i=await K(H(e,`runs`,t,n),D),a={...r,attributes:i?.attributes??r.attributes};return await G(H(e,`runs`,t,n),a,{overwrite:!0}),a})}function Sr(e,t){let n=4*1024*1024,r=new Map,i=new Map,a=new Map,o=0;function x(e){let t=r.get(e);if(!t)return;r.delete(e),o-=i.get(e)??0,i.delete(e);let n=a.get(t.runId);n?.delete(e),n?.size===0&&a.delete(t.runId)}function C(e){for(let t of a.get(e)??[])x(t)}function w(){r.clear(),i.clear(),a.clear(),o=0}function re(e,t,s){if(s>n)return;for(;r.size>0&&(r.size>=1e3||o+s>n);){let e=r.keys().next().value;x(e)}r.set(e,t),i.set(e,s),o+=s;let c=a.get(t.runId)??new Set;c.add(e),a.set(t.runId,c)}function ie(e,t,r){if(le(e.eventType)){C(e.runId);return}let i=Buffer.byteLength(r);if(i>n)return;let a=T.safeParse(JSON.parse(r,pt));a.success&&re(t,a.data,i)}async function ae(n){let r=H(e,`events`,`${n.runId}-${n.eventId}`,t),i=JSON.stringify(n,W,2);await mt(r,i),ie(n,r,i)}let E=new Map,O=new Map;return{clearCache:w,async create(n,i,a){if(n!=null&&n!==``&&R(`runId`,n),`correlationId`in i&&typeof i.correlationId==`string`&&R(`correlationId`,i.correlationId),te(i.eventType)&&n&&i.correlationId){let e=t?`${n}-${i.correlationId}.${t}`:`${n}-${i.correlationId}`;return yr(E,e,()=>o())}if(b(i.eventType)&&n&&i.correlationId){let e=t?`${n}-${i.correlationId}.hook.${t}`:`${n}-${i.correlationId}.hook`;return yr(O,e,()=>o())}return o();async function o(){let o=`evnt_${Tn()}`,b=new Date,x;if(i.eventType===`run_created`&&(!n||n===``))x=`wrun_${Tn()}`;else if(n)x=n;else throw Error(`runId is required for non-run_created events`);if(i.eventType===`run_created`&&n&&n!==``){let e=ce(x,`wrun_`);if(e)throw new s(e)}let C=i.specVersion??5,w=null;if(i.eventType!==`run_created`&&![`step_completed`,`step_retrying`].includes(i.eventType)&&(w=await U(e,`runs`,x,D,t),i.eventType===`run_started`&&!w&&`eventData`in i&&i.eventData)){let n=i.eventData;if(n.deploymentId&&n.workflowName&&n.input!==void 0){se(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0});let r={runId:x,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:C,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:b,updatedAt:b};if(await J(H(e,`runs`,x,t),JSON.stringify(r,W))){let e=`evnt_${Tn()}`;await ae({eventType:`run_created`,runId:x,eventId:e,createdAt:b,specVersion:C,eventData:{deploymentId:n.deploymentId,workflowName:n.workflowName,input:n.input,executionContext:n.executionContext,attributes:n.attributes,allowReservedAttributes:n.allowReservedAttributes,encryptionPublicKey:n.encryptionPublicKey}}),w=r}else w=await U(e,`runs`,x,D,t)}}if(i.eventType===`run_failed`&&!w||i.eventType===`attr_set`&&!w)throw new c(x);if(w){if(ue(w.specVersion))throw new d(w.specVersion,5);if(de(w.specVersion))return or(e,x,i,w,a)}let re=v(i),E=re&&i.eventType===`step_started`;if(w&&m(w.status)){if(i.eventType===`run_cancelled`&&w.status===`cancelled`){let e={...i,runId:x,eventId:o,createdAt:b,specVersion:C};return await ae(e),{event:S(e,a?.resolveData??`all`),run:w,...w?{maxEvents:ur()}:{}}}if(i.eventType===`run_started`)throw new u(`Workflow run "${x}" is already in terminal state "${w.status}"`);if(le(i.eventType))throw new p(`Cannot transition run from terminal state "${w.status}"`);if(re)throw new p(`Cannot create new entities on run in terminal state "${w.status}"`);if(i.eventType===`attr_set`)throw new p(`Cannot set attributes on run in terminal state "${w.status}"`)}let O=null;if(te(i.eventType)&&i.eventType!==`step_created`&&i.correlationId){if(O=await U(e,`steps`,`${x}-${i.correlationId}`,_,t),!O&&!E)throw new s(`Step "${i.correlationId}" not found`);if(E&&O)throw new p(`Step "${i.correlationId}" already created`);if(O){if(g(O.status))throw new p(`Cannot modify step in terminal state "${O.status}"`);if(w&&m(w.status)&&O.status!==`running`)throw new u(`Cannot modify non-running step on run in terminal state "${w.status}"`)}}if(ee(i.eventType)&&i.correlationId&&(i.eventType===`hook_received`&&await hn(e,i.correlationId,t)||!await U(e,`hooks`,i.correlationId,j,t)))throw new f(i.correlationId);let k={...i,runId:x,eventId:o,createdAt:b,specVersion:C};if(i.eventType===`run_started`&&`eventData`in k&&delete k.eventData,E&&k.eventType===`step_started`&&k.eventData){let{input:e,...t}=k.eventData;k={...k,eventData:t}}let A,M,N,P,fe=!1,pe;if(le(i.eventType)&&w){await J(gn(e,x,t),``),await bn(e,x,t);let n=await xn(e,x,t);o=n.eventId,k={...k,eventId:o,createdAt:n.createdAt}}if(i.eventType===`run_created`&&`eventData`in i){let n=i.eventData;if(se(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0}),A={runId:x,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:C,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:b,updatedAt:b},!await J(H(e,`runs`,x,t),JSON.stringify(A,W,2)))throw new p(`Workflow run "${x}" already exists`)}else if(i.eventType===`run_started`){if(w){if(w.status===`running`)return{run:w,maxEvents:ur()};A=await xr(e,x,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,status:`running`,output:void 0,error:void 0,completedAt:void 0,startedAt:w.startedAt??b,updatedAt:b,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey})}}else if(i.eventType===`run_completed`&&`eventData`in i){let n=i.eventData;w&&(A=await xr(e,x,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,startedAt:w.startedAt,status:`completed`,output:n.output,error:void 0,completedAt:b,updatedAt:b,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey}),await Promise.all([ir(e,x),br(e,x)]))}else if(i.eventType===`run_failed`&&`eventData`in i){let n=i.eventData;w&&(A=await xr(e,x,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,startedAt:w.startedAt,status:`failed`,output:void 0,error:n.error,errorCode:n.errorCode,completedAt:b,updatedAt:b,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey}),await Promise.all([ir(e,x),br(e,x)]))}else if(i.eventType===`run_cancelled`)w&&(A=await xr(e,x,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,startedAt:w.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:b,updatedAt:b,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey}),await Promise.all([ir(e,x),br(e,x)]));else if(i.eventType===`attr_set`&&w)A=await cr(x,async()=>{let n=await K(H(e,`runs`,x,t),D);if(!n)throw new c(x);if(se(i.eventData.changes,{existingKeys:Object.keys(n.attributes),allowReservedAttributes:i.eventData.allowReservedAttributes===!0}),i.correlationId&&i.eventData.writer.type===`workflow`&&!await J(z(e,`.locks`,`attributes`,t?`${x}-${i.correlationId}.created.${t}`:`${x}-${i.correlationId}.created`),``))throw new p(`Attribute event "${i.correlationId}" already exists`);let r={...n,attributes:y(n.attributes,i.eventData.changes),updatedAt:b};return await G(H(e,`runs`,x,t),r,{overwrite:!0}),r});else if(i.eventType===`step_created`&&`eventData`in i){if(!await J(z(e,`.locks`,`steps`,t?`${x}-${i.correlationId}.created.${t}`:`${x}-${i.correlationId}.created`),``))throw new p(`Step "${i.correlationId}" already created`);let n=i.eventData;M={runId:x,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:b,updatedAt:b,specVersion:C},await G(H(e,`steps`,`${x}-${i.correlationId}`,t),M)}else if(i.eventType===`step_started`){if(!O&&E){let n=i.eventData;if(await J(z(e,`.locks`,`steps`,t?`${x}-${i.correlationId}.created.${t}`:`${x}-${i.correlationId}.created`),``)){let r={runId:x,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:b,updatedAt:b,specVersion:C};await G(H(e,`steps`,`${x}-${i.correlationId}`,t),r);let a=`evnt_${Tn()}`,o={eventType:`step_created`,runId:x,eventId:a,createdAt:b,specVersion:C,correlationId:i.correlationId,eventData:{stepName:n.stepName,input:n.input}};await G(H(e,`events`,`${x}-${a}`,t),o),O=r,fe=!0}else throw new p(`Step "${i.correlationId}" already created`)}if(O){if(O.retryAfter&&O.retryAfter.getTime()>Date.now())throw new l(`Cannot start step "${i.correlationId}": retryAfter timestamp has not been reached yet`,{retryAfter:Math.ceil((O.retryAfter.getTime()-Date.now())/1e3)});let n=`${x}-${i.correlationId}`,r=await U(e,`steps`,n,_,t);if(r&&g(r.status))throw new p(`Cannot modify step in terminal state "${r.status}"`);M={...O,status:`running`,startedAt:O.startedAt??b,attempt:O.attempt+1,retryAfter:void 0,updatedAt:b},await G(H(e,`steps`,n,t),M,{overwrite:!0})}}else if(i.eventType===`step_completed`&&`eventData`in i){let n=i.eventData;if(O){let r=`${x}-${i.correlationId}`;if(!await J(z(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new p(`Cannot modify step in terminal state`);M={...O,status:`completed`,output:n.result,completedAt:b,updatedAt:b},await G(H(e,`steps`,r,t),M,{overwrite:!0})}}else if(i.eventType===`step_failed`&&`eventData`in i){let n=i.eventData;if(O){let r=`${x}-${i.correlationId}`;if(!await J(z(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new p(`Cannot modify step in terminal state`);M={...O,status:`failed`,error:n.error,completedAt:b,updatedAt:b},await G(H(e,`steps`,r,t),M,{overwrite:!0})}}else if(i.eventType===`step_retrying`&&`eventData`in i){let n=i.eventData;if(O){let r=`${x}-${i.correlationId}`;M={...O,status:`pending`,error:n.error,retryAfter:n.retryAfter,updatedAt:b},await G(H(e,`steps`,r,t),M,{overwrite:!0})}}else if(i.eventType===`hook_created`&&`eventData`in i){let n=i.eventData,r=Sn(e,n.token),s=JSON.stringify({token:n.token,hookId:i.correlationId,runId:x,eventId:o}),c=!1,l=null,u=0,d=0;for(let a=0;a<10&&(await pr(r)||await tr(e,n.token,t),c=await J(r,s),!c);a++){if(l=await pr(r),!l){d++,d>=3&&await q(r);continue}if(l.runId===x&&l.hookId===i.correlationId||!await mr(e,l,t))break;u++,u<3?await new Promise(e=>setTimeout(e,10)):(await q(r),l.hookId&&(await q(H(e,`hooks`,l.hookId,t)),await q(wn(e,n.token,l.runId,l.hookId)))),l=null}let f=!1;if(!c)if(l?.runId===x&&l.hookId===i.correlationId){let r;if(l.eventId)r=l.eventId;else{let a=await gr(e,x,i.correlationId);if(a!==null)throw await _r(e,x,i.correlationId,a,t),new p(`Hook "${i.correlationId}" already created`);let s=await vr(e,n.token,x,i.correlationId,o);if(s===null)throw new p(`Hook "${i.correlationId}" already created`);r=s}o=r;let a=oe(o.replace(/^evnt_/,``))??b;k={...i,runId:x,eventId:o,createdAt:a,specVersion:C},f=!0}else{let e={eventType:`hook_conflict`,correlationId:i.correlationId,eventData:{token:n.token,...l?{conflictingRunId:l.runId}:{}},runId:x,eventId:o,createdAt:b,specVersion:C};return await ae(e),{event:S(e,a?.resolveData??`all`),run:A,step:M,hook:void 0}}N={runId:x,hookId:i.correlationId,token:n.token,metadata:n.metadata,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:k.createdAt,specVersion:C,isWebhook:n.isWebhook??!1,isSystem:n.isSystem??!1},pe=f?{overwrite:!0}:void 0,await Pn(e,n.token,x,i.correlationId,o,t)}else if(i.eventType===`hook_disposed`){if(!await J(mn(e,i.correlationId,t),``))throw new p(`Hook "${i.correlationId}" already disposed`);let n=H(e,`hooks`,i.correlationId,t),r=await U(e,`hooks`,i.correlationId,j,t);r&&(await Cn(e,r.token,r.runId,r.hookId),await q(wn(e,r.token,r.runId,r.hookId))),await q(n),await Ln(e,x,i.correlationId,t)}else if(i.eventType===`wait_created`&&`eventData`in i){let n=`${x}-${i.correlationId}`;if(!await J(z(e,`.locks`,`waits`,t?`${n}.created.${t}`:`${n}.created`),``))throw new p(`Wait "${i.correlationId}" already exists`);let r=i.eventData;P={waitId:n,runId:x,status:`waiting`,resumeAt:r.resumeAt,completedAt:void 0,createdAt:b,updatedAt:b,specVersion:C},await G(H(e,`waits`,n,t),P)}else if(i.eventType===`wait_completed`){let n=`${x}-${i.correlationId}`,r=z(e,`.locks`,`waits`,t?`${n}.completed.${t}`:`${n}.completed`);if(!await J(r,``))throw new p(`Wait "${i.correlationId}" already completed`);let a=await U(e,`waits`,n,ne,t);if(!a)throw await I.unlink(r).catch(()=>{}),new s(`Wait "${i.correlationId}" not found`);P={...a,status:`completed`,completedAt:b,updatedAt:b},await G(H(e,`waits`,n,t),P,{overwrite:!0})}if(i.eventType===`hook_received`&&i.correlationId&&await hn(e,i.correlationId,t))throw new f(i.correlationId);let me=H(e,`events`,`${x}-${o}`,t),F=JSON.stringify(k,W,2),he;if(i.eventType===`hook_received`){let n=await _n(e,x,t),r=n?null:await U(e,`runs`,x,D,t);if(n||r&&m(r.status))throw new u(`Workflow run "${x}" is already in a terminal state`);let i=yn(e,x,o,t);if(!await J(i,F))throw new p(`Event "${o}" already exists for run "${x}"`);try{if(await _n(e,x,t))throw new u(`Workflow run "${x}" is already in a terminal state`);let n=await _t(i,me);if(n===`missing`)throw new u(`Workflow run "${x}" is already in a terminal state`);he=n===`linked`}finally{await q(i).catch(()=>{})}}else he=await J(me,F);if(!he)throw i.eventType===`hook_created`&&i.correlationId&&await _r(e,x,i.correlationId,o,t),new p(`Event "${o}" already exists for run "${x}"`);ie(k,me,F),N&&i.eventType===`hook_created`&&(await In(e,N.runId,N.hookId,t),await G(H(e,`hooks`,N.hookId,t),N,pe));let ge=a?.resolveData??`all`,_e=S(k,ge),ve,ye,be;if(i.eventType===`run_started`&&A){let t=await X({directory:L.join(e,`events`),schema:T,cachedItems:r,filePrefix:`${x}-`,sortOrder:`asc`,limit:1e3,getCreatedAt:$(`evnt`),getId:e=>e.eventId});ve=t.data,ye=t.cursor,be=t.hasMore}if(h(i.eventType)&&typeof a?.sinceCursor==`string`){let t=await X({directory:L.join(e,`events`),schema:T,filePrefix:`${x}-`,sortOrder:`asc`,cursor:a.sinceCursor,getCreatedAt:$(`evnt`),getId:e=>e.eventId});ve=ge===`none`?t.data.map(e=>S(e,ge)):t.data,ye=t.cursor,be=t.hasMore}return{event:_e,run:A,step:M,hook:N,wait:P,events:ve,cursor:ye,hasMore:be,...fe?{stepCreated:!0}:{},...A?{maxEvents:ur()}:{}}}},async get(n,r,i){R(`runId`,n),R(`eventId`,r);let a=await U(e,`events`,`${n}-${r}`,T,t);if(!a)throw Error(`Event ${r} in run ${n} not found`);return S(a,i?.resolveData??`all`)},async list(t){let{runId:n}=t;R(`runId`,n);let i=t.resolveData??`all`,a=await X({directory:L.join(e,`events`),schema:T,cachedItems:r,filePrefix:`${n}-`,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:$(`evnt`),getId:e=>e.eventId});return i===`none`?{...a,data:a.data.map(e=>S(e,i))}:a},async listByCorrelationId(t){let n=t.correlationId;R(`correlationId`,n);let i=t.resolveData??`all`,a=await X({directory:L.join(e,`events`),schema:T,cachedItems:r,filter:e=>e.correlationId===n,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:$(`evnt`),getId:e=>e.eventId});return i===`none`?{...a,data:a.data.map(e=>S(e,i))}:a}}}function Cr(e,t){return{get:(async(n,r,i)=>{R(`runId`,n),R(`stepId`,r);let a=await U(e,`steps`,`${n}-${r}`,_,t);if(!a)throw Error(`Step ${r} in run ${n} not found`);return qn(a,i?.resolveData??`all`)}),list:(async t=>{R(`runId`,t.runId);let n=t.resolveData??`all`,r=await X({directory:L.join(e,`steps`),schema:_,filePrefix:`${t.runId}-`,sortOrder:t.pagination?.sortOrder??`desc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:$(`step`),getId:e=>e.stepId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r})}}function wr(e,t){let n=lr(e,t),r=Cr(e,t),i=Sr(e,t),a=rr(e,t);return{runs:nn(`world.runs`,n),steps:nn(`world.steps`,r),events:nn(`world.events`,i),hooks:nn(`world.hooks`,a),clearCache:()=>i.clearCache()}}const Tr=A(()=>Math.random()),Er=N({streams:ie(E())});function Dr(e){return e===1}function Or(e){let t=Buffer.from([+!!e.eof]);return Buffer.concat([t,e.chunk])}function kr(e){return Dr(e[0])}function Ar(e){return{eof:kr(e),chunk:Buffer.from(e.subarray(1))}}async function jr(e){try{return await I.readdir(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}}function Mr(e,t,n,r=n,i=()=>!0){for(let a of t){if(!a.endsWith(n))continue;let t=a.slice(0,-n.length);i(t)&&e.set(t,r)}}function Nr(e,t){return R(`streamName`,t),L.join(e,t)}async function Pr(e,t,n){let r=Nr(e,t),i=await jr(r),a=new Map;return Mr(a,i,`.json`),Mr(a,i,`.bin`,`.bin`,n?e=>!e.endsWith(`.${n}`):void 0),n&&Mr(a,i,`.${n}.bin`),{files:[...a.keys()].sort(),extMap:a,dir:r}}function Fr(e,t){let n=t?`.${t}`:``,r=new De,i=new Set;async function a(n,r){R(`runId`,n),R(`streamName`,r);let a=`${n}:${r}`;if(i.has(a))return;let o=H(e,`streams/runs`,n,t),s=(await U(e,`streams/runs`,n,Er,t))?.streams??[];s.includes(r)||(s.push(r),await G(o,{streams:s},{overwrite:!0})),i.add(a)}function o(e){return typeof e==`string`?Buffer.from(new TextEncoder().encode(e)):e instanceof Buffer?e:Buffer.from(e)}return{streams:{async write(t,i,s){let c=`chnk_${Tr()}`;await a(await t,i);let l=o(s),u=Or({chunk:l,eof:!1});await mt(L.join(Nr(L.join(e,`streams`,`chunks`),i),`${c}${n}.bin`),u);let d=Uint8Array.from(l);r.emit(`chunk:${i}`,{streamName:i,chunkData:d,chunkId:c})},async writeMulti(t,i,s){if(s.length===0)return;let c=s.map(()=>`chnk_${Tr()}`);await a(await t,i);let l=s.map(e=>o(e)).map(async(t,r)=>{let a=c[r],o=Or({chunk:t,eof:!1});return await mt(L.join(Nr(L.join(e,`streams`,`chunks`),i),`${a}${n}.bin`),o),{chunkId:a,chunkData:Uint8Array.from(t)}});for(let e of l){let{chunkId:t,chunkData:n}=await e;r.emit(`chunk:${i}`,{streamName:i,chunkData:n,chunkId:t})}},async close(t,i){let o=`chnk_${Tr()}`;await a(await t,i),await mt(L.join(Nr(L.join(e,`streams`,`chunks`),i),`${o}${n}.bin`),Or({chunk:Buffer.from([]),eof:!0})),r.emit(`close:${i}`,{streamName:i})},async list(n){return R(`runId`,n),(await U(e,`streams/runs`,n,Er,t))?.streams??[]},async getChunks(n,r,i){let a=i?.limit??100,{files:o,extMap:s,dir:c}=await Pr(L.join(e,`streams`,`chunks`),r,t),l=0;if(i?.cursor)try{l=JSON.parse(Buffer.from(i.cursor,`base64`).toString(`utf-8`)).i}catch{l=0}let u=!1,d=[],f=0;for(let e of o){let t=s.get(e)??`.bin`,n=L.join(c,`${e}${t}`);if(f<l){if(Dr(await gt(n))){u=!0;break}f++;continue}if(d.length>=a){Dr(await gt(n))?u=!0:f++;break}let r=Ar(await ht(n));if(r.eof){u=!0;break}d.push({index:f,data:Uint8Array.from(r.chunk)}),f++}let p=!u&&f>l+d.length,m=l+d.length;return{data:d,cursor:p?Buffer.from(JSON.stringify({i:m})).toString(`base64`):null,hasMore:p,done:u}},async getInfo(n,r){let{files:i,extMap:a,dir:o}=await Pr(L.join(e,`streams`,`chunks`),r,t),s=!1,c=0;for(let e of i){let t=a.get(e)??`.bin`;if(Dr(await gt(L.join(o,`${e}${t}`)))){s=!0;break}c++}return{tailIndex:c-1,done:s}},async get(n,i,a=0){let o=L.join(e,`streams`,`chunks`),s=()=>{},c=null,l=!1;return new ReadableStream({async start(e){let n=new Set,u=[],d=!0,f=!1,p=t=>{if(t.chunkData.byteLength===0){n.add(t.chunkId);return}d?(n.add(t.chunkId),u.push({chunkId:t.chunkId,chunkData:Uint8Array.from(t.chunkData)})):n.has(t.chunkId)||(n.add(t.chunkId),e.enqueue(Uint8Array.from(t.chunkData)))},m=()=>{if(d){f=!0;return}l=!0,s();try{e.close()}catch{}};s=()=>{r.off(`chunk:${i}`,p),r.off(`close:${i}`,m),c&&=(clearInterval(c),null)},r.on(`chunk:${i}`,p),r.on(`close:${i}`,m);let{files:h,extMap:g,dir:_}=await Pr(o,i,t),v=h.length;if(typeof a==`number`&&a<0&&h.length>0){let e=h[h.length-1],t=g.get(e)??`.bin`;Dr(await gt(L.join(_,`${e}${t}`)))&&v--}let ee=typeof a==`number`&&a<0?Math.max(0,v+a):a,y=!1;for(let t=ee;t<h.length;t++){let r=h[t],i=r;if(n.has(i))continue;let a=g.get(r)??`.bin`,o=Ar(await ht(L.join(_,`${r}${a}`)));if(o?.eof===!0){y=!0;break}n.add(i),o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}d=!1,u.sort((e,t)=>e.chunkId.localeCompare(t.chunkId));for(let t of u)e.enqueue(Uint8Array.from(t.chunkData));if(y){l=!0,s();try{e.close()}catch{}return}if(f){l=!0,s();try{e.close()}catch{}return}for(let e=0;e<ee&&e<h.length;e++)n.add(h[e]);if(l){s();return}let b=!1;c=setInterval(async()=>{if(!b){b=!0;try{let{files:r,extMap:a}=await Pr(o,i,t);for(let t of r){let r=t;if(n.has(r))continue;n.add(r);let i=a.get(t)??`.bin`,o=Ar(await ht(L.join(_,`${t}${i}`)));if(o?.eof===!0){l=!0,s();try{e.close()}catch{}return}if(l)return;o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}}catch(e){e instanceof Error&&`code`in e||console.error(`[world-local] Unexpected polling error:`,e)}finally{b=!1}}},100)},cancel(){l=!0,s()}})}}}}function Ir(e){let t=e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{},n={...Je.value,...t};Me(n.dataDir);let r=n.tag,i=fn(n),{clearCache:a,...o}=wr(n.dataDir,r),s=Ye(n);return{specVersion:5,...i,...o,...nn(`world.streams`,{...Fr(n.dataDir,r),...n.streamFlushIntervalMs!==void 0&&{streamFlushIntervalMs:n.streamFlushIntervalMs}}),async start(){if(await Pt(n.dataDir),!s)return;let e=r?e=>ot(e,r):st;await O({...o.runs,list:(t=>o.runs.list({...t,fileIdFilter:e}))},i.queue,`world-local`)},async close(){a(),await i.close()},async clear(){if(a(),r){let e=n.dataDir,t=L.join(e,`hooks`),i=await ct(t,r),{HookSchema:a}=await import(`../../_chunks/workflow/dist-WjtNsOyf.js`).then(e=>e.t);await Promise.all(i.map(async n=>{let r=await K(L.join(t,n),a);r?.token&&(await q(L.join(t,`tokens`,`${pn(r.token)}.json`)),await q(wn(e,r.token,r.runId,r.hookId)))})),await Promise.all([`runs`,`steps`,`events`,`hooks`,`hooks/by-run`,`waits`,`streams/runs`].map(async t=>{let n=L.join(e,t),i=await ct(n,r);await Promise.all(i.map(e=>q(L.join(n,e))))}));for(let t of[`token-index`,`id-index`]){let n=L.join(e,`hooks`,t),i;try{i=await F.readdir(n,{withFileTypes:!0})}catch{i=[]}await Promise.all(i.filter(e=>e.isDirectory()).map(async e=>{let t=L.join(n,e.name),i=await ct(t,r);await Promise.all(i.map(e=>q(L.join(t,e))))}))}await F.rm(L.join(e,`.locks`),{recursive:!0,force:!0}).catch(()=>{});let o=L.join(e,`streams`,`chunks`),s;try{s=await F.readdir(o,{withFileTypes:!0})}catch{s=[]}await Promise.all(s.filter(e=>e.isDirectory()).map(async e=>{let t=L.join(o,e.name),n=await lt(t,r,`.bin`);await Promise.all(n.map(e=>F.unlink(L.join(t,e)).catch(()=>{})))})),it()}else it(),Vn(),await xe(n.dataDir,{recursive:!0,force:!0}),await Pt(n.dataDir)}}}export{wt as DataDirAccessError,Tt as DataDirVersionError,Oe as UnwritableDataDirError,Ir as createWorld,At as ensureDataDir,Pt as initDataDir,Et as parseVersion};
|
|
4
|
+
`);for(let e of r)if(e.includes(`LISTEN`)){let t=e.trim().split(/\s+/)[8];if(t){let e=t.lastIndexOf(`:`);if(e!==-1){let r=Ie(t.slice(e+1));r!==void 0&&n.push(r)}}}return n}catch{return[]}}async function Be(e){try{let{stdout:t}=await Fe(`cmd`,[`/c`,`netstat -ano -p tcp | findstr LISTENING`]);return Pe(t,e)}catch{return[]}}async function Ve(){let{pid:e,platform:t}=process;try{switch(t){case`linux`:return await Re(e);case`darwin`:return await ze(e);case`win32`:return await Be(e);default:return[]}}catch(e){return process.env.NODE_ENV===`development`&&console.debug(`[getAllPorts] Detection failed:`,e),[]}}const He=`${o}/flow?__health`;async function Ue(e,t={}){let{endpoint:n=He,timeout:r=500}=t,i=new AbortController,a=setTimeout(()=>i.abort(),r);try{return(await fetch(`http://localhost:${e}${n}`,{method:`HEAD`,signal:i.signal})).status===200}catch{return!1}finally{clearTimeout(a)}}async function We(e){let t=await Ve();if(t.length===0)return;if(t.length===1)return t[0];let n=(await Promise.all(t.map(async t=>({port:t,isWorkflow:await Ue(t,e)})))).find(e=>e.isWorkflow);return n?n.port:(process.env.NODE_ENV===`development`&&console.debug(`[getWorkflowPort] Probing failed, falling back to first port:`,t[0]),t[0])}function Ge(e){let t={get value(){let n=e();return Object.defineProperty(t,"value",{value:n}),n}};return t}const Ke=()=>process.env.WORKFLOW_LOCAL_DATA_DIR||`.workflow-data`,qe=()=>process.env.WORKFLOW_LOCAL_BASE_URL,Je=Ge(()=>({dataDir:Ke(),baseUrl:qe()}));function Ye(e){if(e.recoverActiveRuns!==void 0)return e.recoverActiveRuns;let t=process.env.WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS?.toLowerCase();return!(t===`0`||t===`false`)}function Xe(e){return e.baseUrl??process.env.WORKFLOW_LOCAL_BASE_URL??i(`http://localhost`)}async function Ze(e){if(e.baseUrl)return e.baseUrl;if(process.env.WORKFLOW_LOCAL_BASE_URL)return process.env.WORKFLOW_LOCAL_BASE_URL;if(typeof e.port==`number`)return i(`http://localhost:${e.port}`);if(process.env.PORT)return i(`http://localhost:${process.env.PORT}`);let t=await We({endpoint:a()});if(t)return i(`http://localhost:${t}`);throw Error(`Unable to resolve base URL for workflow queue.`)}const Qe=D(()=>Math.random());function $e(e){let t=typeof e==`string`?e:String(e);return t.length>48?`${t.slice(0,48)}…`:t}var et=class extends s{constructor(e,t){super(`Unsafe ${e} "${$e(t)}": must not be empty, contain ".", "/", "\\", or null bytes`),this.name=`UnsafeEntityIdError`}static is(e){return e instanceof Error&&e.name===`UnsafeEntityIdError`}};function R(e,t){if(t.length===0||t.startsWith(`.`)||t.includes(`/`)||t.includes(`\\`)||t.includes(`\0`)||t.includes(`.`))throw new et(e,t)}function z(e,...t){let n=L.resolve(e),r=L.resolve(e,...t);if(r!==n&&!r.startsWith(n+L.sep))throw new et(`path`,t.join(`/`));return r}const tt=process.platform===`win32`;async function B(e,t=5){if(!tt)return e();let n=[`EPERM`,`EBUSY`,`EACCES`];for(let r=0;r<=t;r++)try{return await e()}catch(e){if(!(r<t&&n.includes(e.code)))throw e;let i=10*2**r+Math.random()*10;await new Promise(e=>setTimeout(e,i))}throw Error(`Retry loop exited unexpectedly`)}const nt=new Set,rt=new Set;function it(){nt.clear(),rt.clear()}const at=/\.[a-zA-Z][a-zA-Z0-9-]*$/;function V(e){return e.replace(at,``)}function ot(e,t){return e.endsWith(`.${t}`)}function st(e){return!at.test(e)}function H(e,t,n,r){return R(`fileId`,n),r!==void 0&&R(`tag`,r),z(e,t,r?`${n}.${r}.json`:`${n}.json`)}async function U(e,t,n,r,i){if(R(`fileId`,n),i!==void 0&&R(`tag`,i),i){let a=await K(z(e,t,`${n}.${i}.json`),r);if(a!==null)return a}return K(z(e,t,`${n}.json`),r)}async function ct(e,t){let n=`.${t}.json`;try{return(await P.readdir(e)).filter(e=>e.endsWith(n))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function lt(e,t,n){let r=`.${t}${n}`;try{return(await P.readdir(e)).filter(e=>e.endsWith(r))}catch(e){if(e.code===`ENOENT`)return[];throw e}}async function ut(e){let t=L.resolve(e);if(!rt.has(t))try{await P.mkdir(t,{recursive:!0}),rt.add(t)}catch(e){let n=e.code;if(Ae(n)&&!await dt(t))throw new Oe(t,n)}}async function dt(e){try{return(await P.stat(e)).isDirectory()}catch{return!1}}async function ft(e,t){await ut(e);try{return await t()}catch(n){if(n.code!==`ENOENT`)throw n;return rt.delete(L.resolve(e)),await ut(e),t()}}function W(e,t){return t instanceof Uint8Array?{__type:`Uint8Array`,data:Buffer.from(t).toString(`base64`)}:t}function pt(e,t){return typeof t==`object`&&t&&t.__type===`Uint8Array`&&typeof t.data==`string`?new Uint8Array(Buffer.from(t.data,`base64`)):t}async function G(e,t,n){return mt(e,JSON.stringify(t,W,2),n)}async function mt(e,t,n){if(!n?.overwrite){if(nt.has(e))throw new p(`File ${e} already exists and 'overwrite' is false`);try{throw await P.access(e),nt.add(e),new p(`File ${e} already exists and 'overwrite' is false`)}catch(e){if(e.code!==`ENOENT`)throw e}}let r=`${e}.tmp.${Qe()}`,i=!1;try{await ft(L.dirname(e),async()=>{await P.writeFile(r,t),i=!0,await B(()=>P.rename(r,e))}),nt.add(e)}catch(e){throw i&&await B(()=>P.unlink(r),3).catch(()=>{}),e}}async function K(e,t){try{let n=await P.readFile(e,`utf-8`);return t.parse(JSON.parse(n,pt))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function ht(e){return await P.readFile(e)}async function gt(e){let t=await P.open(e,`r`);try{let e=Buffer.allocUnsafe(1),{bytesRead:n}=await t.read(e,0,1,0);return n===0?void 0:e[0]}finally{await t.close()}}async function q(e){try{await B(()=>P.unlink(e))}catch(e){if(e.code!==`ENOENT`)throw e}}async function J(e,t){let n=`${e}.tmp.${Qe()}`,r=!1;try{return await ft(L.dirname(e),async()=>{await P.writeFile(n,t,{flag:`wx`}),r=!0;try{return await B(()=>P.link(n,e)),!0}catch(e){if(e.code===`EEXIST`)return!1;throw e}})}finally{r&&await B(()=>P.unlink(n),3).catch(()=>{})}}async function _t(e,t){try{return await ft(L.dirname(t),()=>B(()=>P.link(e,t))),`linked`}catch(e){if(e.code===`EEXIST`)return`exists`;if(e.code===`ENOENT`)return`missing`;throw e}}async function Y(e){return vt(e,`.json`)}async function vt(e,t){try{return(await P.readdir(e)).filter(e=>e.endsWith(t)).map(e=>e.slice(0,-t.length))}catch(e){if(e.code===`ENOENT`)return[];throw e}}function yt(e){if(!e)return null;let t=e.split(`|`);return{timestamp:new Date(t[0]),id:t[1]||null}}function bt(e,t){return t?`${e.toISOString()}|${t}`:e.toISOString()}async function X(e){let{directory:t,schema:n,cachedItems:r,filePrefix:i,fileIdFilter:a,filter:o,sortOrder:s=`desc`,limit:c=20,cursor:l,getCreatedAt:u,getId:d}=e;i!==void 0&&R(`filePrefix`,i);let f=L.resolve(t),p=await Y(f),m=i?p.filter(e=>e.startsWith(i)):p,h=a?m.filter(a):m,g=yt(l),_=h;g&&(_=h.filter(e=>{let t=u(`${e}.json`);if(t){let e=g.timestamp.getTime(),n=t.getTime();return g.id?s===`desc`?n<=e:n>=e:s===`desc`?n<e:n>e}return!0}));let v=[];for(let e=0;e<_.length;e+=32){let t=_.slice(e,e+32),i=await Promise.all(t.map(async e=>{let t=L.join(f,`${e}.json`);try{let e=r?.get(t);return e===void 0?await K(t,n):structuredClone(e)}catch(t){if(t instanceof E)return console.warn(`Skipping item ${e} due to malformed JSON: ${t.message}`),null;throw t}}));for(let e of i)if(e&&!(o&&!o(e))){if(g){let t=e.createdAt.getTime(),n=g.timestamp.getTime();if(s===`desc`){if(t>n||t===n&&g.id&&d&&d(e)>=g.id)continue}else if(t<n||t===n&&g.id&&d&&d(e)<=g.id)continue}v.push(e)}}v.sort((e,t)=>{let n=e.createdAt.getTime(),r=t.createdAt.getTime(),i=s===`asc`?n-r:r-n;if(i===0&&d){let n=d(e),r=d(t);return s===`asc`?n.localeCompare(r):r.localeCompare(n)}return i});let ee=v.length>c,y=ee?v.slice(0,c):v;return{data:y,cursor:y.length>0?bt(y[y.length-1].createdAt,d?.(y[y.length-1])):null,hasMore:ee}}let Z=null;function xt(){return typeof import.meta.url==`string`&&import.meta.url?L.dirname(he(import.meta.url)):null}async function St(){if(Z)return Z;let e=xt();if(e)try{let t=await I(L.join(e,`../package.json`),`utf-8`);return Z=JSON.parse(t),Z}catch{}return Z={name:`@workflow/world-local`,version:`5.0.0-beta.33`},Z}const Ct=`version.txt`;var wt=class extends Error{dataDir;code;constructor(e,t,n){super(e),this.name=`DataDirAccessError`,this.dataDir=t,this.code=n}},Tt=class extends Error{oldVersion;newVersion;suggestedVersion;constructor(e,t,n,r){super(e),this.name=`DataDirVersionError`,this.oldVersion=t,this.newVersion=n,this.suggestedVersion=r}};function Et(e){let t=e.match(/^(\d+)\.(\d+)\.(\d+)(?:-(.+))?$/);if(!t)throw Error(`Invalid version string: "${e}"`);return{major:parseInt(t[1],10),minor:parseInt(t[2],10),patch:parseInt(t[3],10),prerelease:t[4],raw:e}}function Q(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease?`${t}-${e.prerelease}`:t}function Dt(e){let t=e.trim(),n=t.lastIndexOf(`@`);if(n<=0)throw Error(`Invalid version file content: "${e}"`);return{packageName:t.substring(0,n),version:Et(t.substring(n+1))}}function Ot(e,t){return`${e}@${Q(t)}`}function kt(e,t){console.log(`[world-local] Upgrading from version ${Q(e)} to ${Q(t)}`)}async function At(e){let t=L.resolve(e);try{await ve(t,{recursive:!0})}catch(e){let n=e;if(n.code!==`EEXIST`)throw new wt(`Failed to create data directory "${t}": ${n.message}`,t,n.code)}try{await ge(t,_e.R_OK)}catch(e){let n=e;throw new wt(`Data directory "${t}" is not readable: ${n.message}`,t,n.code)}let n=L.join(t,`.workflow-write-test-${Date.now()}`);try{await Ce(n,``),await Se(n).catch(e=>{if(e.code!==`ENOENT`)throw e})}catch(e){let n=e;throw new wt(`Data directory "${t}" is not writable: ${n.message}`,t,n.code)}}async function jt(e){let t=L.join(L.resolve(e),Ct);try{return Dt(await I(t,`utf-8`))}catch(e){if(e.code===`ENOENT`)return null;throw e}}async function Mt(e,t){await Ce(L.join(L.resolve(e),Ct),Ot((await St()).name,t))}function Nt(e,t){return t||Q(e)}async function Pt(e){await At(e);let t=await St(),n=Et(t.version),r=await jt(e);if(r===null){await Mt(e,n);return}let{version:i}=r;if(Q(i)!==Q(n))try{kt(i,n),await Mt(e,n)}catch(e){let r=Nt(i,e instanceof Tt?e.suggestedVersion:void 0);throw console.error(`[world-local] Failed to upgrade data directory from version ${Q(i)} to ${Q(n)}:`,e instanceof Error?e.message:e),console.error(`[world-local] Data is not compatible with the current version. Please downgrade to ${t.name}@${r}`),e}}let Ft=null;async function It(){return Ft||=import(`../../_chunks/workflow/src-Cj3P1ChQ.js`).then(e=>t(e.t(),1)).catch(()=>null),Ft}let Lt=null;async function Rt(){return Lt||=It().then(e=>e?e.trace.getTracer(`workflow`):null),Lt}async function zt(e,...t){let[n,r]=await Promise.all([Rt(),It()]),{fn:i,opts:a}=typeof t[0]==`function`?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!i)throw Error(`Function to trace must be provided`);return!n||!r?await i():n.startActiveSpan(e,a,async e=>{try{let t=await i(e);return e.setStatus({code:r.SpanStatusCode.OK}),t}catch(t){throw e.setStatus({code:r.SpanStatusCode.ERROR,message:t.message}),t}finally{e.end()}})}async function Bt(e){let t=await It();if(t)return t.SpanKind[e]}function Vt(...e){return t=>Object.fromEntries(e.map(e=>[e,t]))}const Ht=Vt(`peer.service`),Ut=Vt(`rpc.system`),Wt=Vt(`rpc.service`),Gt=Vt(`rpc.method`),Kt=Vt(`workflow.run.id`),qt=Vt(`step.id`),Jt={peerService:`world-local`,rpcSystem:`local`,rpcService:`world-local`},Yt={"world.runs.get":0,"world.runs.experimentalSetAttributes":0,"world.steps.get":0,"world.events.create":0,"world.events.get":0},Xt=new Set([`world.steps.list`,`world.events.list`,`world.hooks.list`]);function Zt(e){if(e.length>=2&&typeof e[1]==`object`&&e[1]!==null){let t=e[1];if(typeof t.eventType==`string`)return t.eventType}}function Qt(e,t){return typeof e[t]==`string`?e[t]:void 0}function $t(e){if(typeof e!=`object`||!e)return;let t=e.runId;return typeof t==`string`?t:void 0}function en(e){if(typeof e!=`object`||!e)return;let t=e;if(typeof t.runId==`string`)return t.runId;for(let e of[`run`,`step`,`hook`,`wait`]){let n=t[e];if(typeof n==`object`&&n){let e=n.runId;if(typeof e==`string`)return e}}}function tn(e,t,n){let r=`${e}.${t}`,i={},a=Yt[r],o=a===void 0?Xt.has(r)?$t(n[0]):void 0:Qt(n,a);if(o&&Object.assign(i,Kt(o)),r===`world.steps.get`){let e=Qt(n,1);e&&Object.assign(i,qt(e))}return i}function nn(e,t){let n={};for(let r of Object.keys(t))if(typeof t[r]!=`function`)n[r]=t[r];else{let i=t[r],a=String(r);n[r]=async(...t)=>{let n=`${e}.${a}`;if(e===`world.events`&&a===`create`){let r=Zt(t);r&&(n=`${e}.${a} ${r}`)}return zt(n,{kind:await Bt(`INTERNAL`)},async r=>{r?.setAttributes({...Ht(Jt.peerService),...Ut(Jt.rpcSystem),...Wt(Jt.rpcService),...Gt(n),...tn(e,a,t)});let o=await i(...t),s=en(o);return s&&r?.setAttributes(Kt(s)),o})}}return n}var rn=n((t=>{var n=t&&t.__importDefault||function(e){return e&&e.__esModule?e:{default:e}};Object.defineProperty(t,"__esModule",{value:!0}),t.RateLimit=t.Sema=void 0;let r=n(e(`events`));function i(e,t,n,r,i){for(let a=0;a<i;++a)n[a+r]=e[a+t],e[a+t]=void 0}function a(e){return e>>>=0,--e,e|=e>>1,e|=e>>2,e|=e>>4,e|=e>>8,e|=e>>16,e+1}function o(e){return a(Math.min(Math.max(16,e),1073741824))}var s=class{constructor(e){this._capacity=o(e),this._length=0,this._front=0,this.arr=[]}push(e){let t=this._length;this.checkCapacity(t+1);let n=this._front+t&this._capacity-1;return this.arr[n]=e,this._length=t+1,t+1}pop(){let e=this._length;if(e===0)return;let t=this._front+e-1&this._capacity-1,n=this.arr[t];return this.arr[t]=void 0,this._length=e-1,n}shift(){let e=this._length;if(e===0)return;let t=this._front,n=this.arr[t];return this.arr[t]=void 0,this._front=t+1&this._capacity-1,this._length=e-1,n}get length(){return this._length}checkCapacity(e){this._capacity<e&&this.resizeTo(o(this._capacity*1.5+16))}resizeTo(e){let t=this._capacity;this._capacity=e;let n=this._front,r=this._length;if(n+r>t){let e=n+r&t-1;i(this.arr,0,this.arr,t,e)}}},c=class extends r.default{};function l(e){return typeof e==`function`}function u(){return`1`}var d=class{constructor(e,{initFn:t=u,pauseFn:n,resumeFn:r,capacity:i=10}={}){if(l(n)!==l(r))throw Error(`pauseFn and resumeFn must be both set for pausing`);this.nrTokens=e,this.free=new s(e),this.waiting=new s(i),this.releaseEmitter=new c,this.noTokens=t===u,this.pauseFn=n,this.resumeFn=r,this.paused=!1,this.releaseEmitter.on(`release`,e=>{let t=this.waiting.shift();t?t.resolve(e):(this.resumeFn&&this.paused&&(this.paused=!1,this.resumeFn()),this.free.push(e))});for(let n=0;n<e;n++)this.free.push(t())}tryAcquire(){return this.free.pop()}async acquire(){let e=this.tryAcquire();return e===void 0?new Promise((e,t)=>{this.pauseFn&&!this.paused&&(this.paused=!0,this.pauseFn()),this.waiting.push({resolve:e,reject:t})}):e}release(e){this.releaseEmitter.emit(`release`,this.noTokens?`1`:e)}drain(){let e=Array(this.nrTokens);for(let t=0;t<this.nrTokens;t++)e[t]=this.acquire();return Promise.all(e)}nrWaiting(){return this.waiting.length}};t.Sema=d;function f(e,{timeUnit:t=1e3,uniformDistribution:n=!1}={}){let r=new d(n?1:e),i=n?t/e:t;return async function(){await r.acquire(),setTimeout(()=>r.release(),i)}}t.RateLimit=f}))(),an=N(),on=class{contentType=`application/json`;serialize(e){return Buffer.from(JSON.stringify(e,W))}async deserialize(e){let t=[],n=e.getReader();for(;;){let{done:e,value:r}=await n.read();if(e)break;r&&t.push(r)}let r=Buffer.concat(t).toString();return JSON.parse(r,pt)}};const sn=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY??`0`,10)||1/0,cn=2147483647,ln=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY??`0`,10)||1e3;function un(e,t){let n=process.env[e];if(n===void 0||n===``)return t;let r=Number.parseInt(n,10);return Number.isFinite(r)&&r>=0?r:t}function dn(){return{bodyTimeout:un(`WORKFLOW_LOCAL_BODY_TIMEOUT_MS`,3e4),connections:1e3,headersTimeout:un(`WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS`,3e4),keepAliveTimeout:3e4}}const fn=`Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer`;function pn(e){let t=e,n=new Set;for(;t&&typeof t==`object`&&!n.has(t);){if(n.add(t),`message`in t&&typeof t.message==`string`&&t.message.includes(fn))return!0;t=`cause`in t?t.cause:void 0}return!1}function mn(e){let t=new an.Agent(dn()),n=new on,i=D(),a=new rn.Sema(ln),o=new AbortController,s=o.signal,c=new Map,l=new Map,u=async(o,u,d)=>{let f=[];if(d?.idempotencyKey){let e=c.get(d.idempotencyKey);if(e)return{messageId:e}}let p=n.serialize(u),{prefix:m}=A(o),h=O.parse(`msg_${i()}`),g=u,_=g.runId??void 0,v=g.stepId??void 0;if(d?.idempotencyKey){let e=d.idempotencyKey;c.set(e,h),f.push(()=>{c.delete(e)})}return(async()=>{d?.delaySeconds&&d.delaySeconds>0&&await Ee(Math.min(d.delaySeconds*1e3,cn),void 0,{signal:s}),a.tryAcquire()||(console.warn(`[world-local]: concurrency limit (${ln}) reached, waiting for queue to free up`),await a.acquire());let n=0;try{for(let i=0;i<256;i++){let a={...d?.headers,"content-type":`application/json`,"x-vqs-queue-name":o,"x-vqs-message-id":h,"x-vqs-message-attempt":String(n+1)},c=l.get(m),u,f;try{if(c)u=await c(new Request(r(Xe(e),{type:`flow`}),{method:`POST`,headers:a,body:p}));else{let n=await Ze(e);u=await fetch(r(n,{type:`flow`}),{method:`POST`,duplex:`half`,dispatcher:t,headers:a,body:p})}n++,f=await u.text()}catch(e){let t=e?.name;if(s.aborted||t===`AbortError`||t===`ResponseAborted`)return;if(pn(e))throw e;console.error(`[world-local] Queue delivery failed at the transport (loop ${i+1}), retrying`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v},error:String(e)}),await Ee(5e3,void 0,{signal:s});continue}if(u.ok){try{let e=Number(JSON.parse(f).timeoutSeconds);if(Number.isFinite(e)&&e>=0){e>0&&await Ee(Math.min(e*1e3,cn),void 0,{signal:s});continue}}catch{}return}console.error(`[world-local] Queue message failed (attempt ${n}, HTTP ${u.status})`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v},handlerError:f}),await Ee(5e3,void 0,{signal:s})}console.error(`[world-local] Queue message exhausted safety limit (256 attempts)`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v}})}finally{a.release()}})().catch(e=>{e?.name===`AbortError`||e?.name===`ResponseAborted`||(pn(e)?console.error(`[local world] Queue operation failed: detected "${fn}". This usually means a Next.js proxy/middleware consumed Workflow's internal request before the executor could read it. Exclude \`/.well-known/workflow/*\` from your matcher. See https://workflow-sdk.dev/docs/getting-started/next#configure-proxy-handler`,{queueName:o,messageId:h,..._&&{runId:_},...v&&{stepId:v},originalError:e}):console.error(`[local world] Queue operation failed:`,e))}).finally(()=>{for(let e of f)e()}),{messageId:h}},d=M({"x-vqs-queue-name":ae,"x-vqs-message-id":O,"x-vqs-message-attempt":w()});return{queue:u,createQueueHandler:(e,t)=>async n=>{let r=d.safeParse(Object.fromEntries(n.headers));if(!r.success||!n.body)return Response.json({error:n.body?`Missing required headers`:`Missing request body`},{status:400});let i=r.data[`x-vqs-queue-name`],a=r.data[`x-vqs-message-id`],o=r.data[`x-vqs-message-attempt`];if(!i.startsWith(e))return Response.json({error:`Unhandled queue`},{status:400});let s=await new on().deserialize(n.body);try{let e=await t(s,{attempt:o,queueName:i,messageId:a}),n=null;return typeof e?.timeoutSeconds==`number`&&(n=Math.min(e.timeoutSeconds,sn)),n==null?Response.json({ok:!0}):Response.json({timeoutSeconds:n})}catch(e){return Response.json(String(e),{status:500})}},getDeploymentId:async()=>`dpl_local@${(await St()).version}`,registerHandler(e,t){l.set(e,t)},async close(){s.aborted||(o.abort(),await t.close())}}}function hn(e){return pe(`sha256`).update(e).digest(`hex`)}function gn(e,t,n){return z(e,`.locks`,`hooks`,n?`${t}.disposed.${n}`:`${t}.disposed`)}async function _n(e,t,n){let r=[gn(e,t)];n&&r.push(gn(e,t,n));for(let e of r)try{return await F.access(e),!0}catch{}return!1}function vn(e,t,n){return z(e,`.locks`,`runs`,n?`${t}.terminal.${n}`:`${t}.terminal`)}async function yn(e,t,n){let r=[vn(e,t)];n&&r.push(vn(e,t,n));for(let e of r)try{return await F.access(e),!0}catch(e){if(e.code!==`ENOENT`)throw e}return!1}function bn(e,t,n){return z(e,`.locks`,`runs`,n?`${t}.pending.${n}`:`${t}.pending`)}function xn(e,t,n,r){return L.join(bn(e,t,r),`${n}.json`)}async function Sn(e,t,n){let r=[bn(e,t)];n&&r.push(bn(e,t,n));for(let e of r){let t;try{t=await F.readdir(e)}catch(e){if(e.code===`ENOENT`)continue;throw e}for(let n of t)try{await B(()=>F.unlink(L.join(e,n)))}catch(e){if(e.code!==`ENOENT`)throw e}await F.rmdir(e).catch(()=>{})}}async function Cn(e,t,n){let r=[];try{r=await F.readdir(L.join(e,`events`))}catch(e){if(e.code!==`ENOENT`)throw e}let i=`${t}-`,a=null;for(let e of r){if(!e.startsWith(i)||!e.endsWith(`.json`))continue;let t=e.slice(0,-5);if(!st(t)&&!(n&&ot(t,n)))continue;let r=V(t).slice(i.length);(!a||r>a)&&(a=r)}let o=Date.now();if(a)try{let e=ie(a.replace(/^evnt_/,``));o<=e&&(o=e+1)}catch{}return{eventId:`evnt_${On(o)}`,createdAt:new Date(o)}}function wn(e,t){return L.join(e,`hooks`,`tokens`,`${hn(t)}.json`)}function Tn(e,t,n){let r=pe(`sha256`).update(`${t}\x00${n}`).digest(`hex`);return L.join(e,`hooks`,`resumes`,`${r}.json`)}async function En(e,t,n,r){let i=wn(e,t),a;try{a=JSON.parse(await F.readFile(i,`utf8`))}catch{return}a.runId!==n||a.hookId!==r||await F.unlink(i).catch(()=>{})}function Dn(e,t,n,r){let i=pe(`sha256`).update(`${t}\x00${n}\x00${r}`).digest(`hex`);return L.join(e,`hooks`,`tokens`,`${i}.recovery.json`)}const On=D(()=>Math.random()),$=e=>{let t=RegExp(`^${e}_`,`g`);return n=>{let r=V(n.replace(/\.json$/,``))+`.json`,i=r.indexOf(`-`);return i===-1?se(r.replace(/\.json$/,``).replace(t,``)):e===`step`?null:se(r.substring(i+1).replace(/\.json$/,``).replace(t,``))}},kn=M({runId:x()}),An=M({hookId:x(),tag:x().optional()});function jn(e,t){return z(e,`hooks`,`token-index`,hn(t))}function Mn(e,t){return R(`hookId`,t),z(e,`hooks`,`id-index`,t)}function Nn(e){return z(e,`hooks`,`by-run`)}function Pn(e){let t=V(e);return t===e?void 0:e.slice(t.length+1)}function Fn(e,t){return t?st(e)||ot(e,t):st(e)}async function In(e){try{return await K(e,b)}catch(e){if(e instanceof SyntaxError||e instanceof E)return null;throw e}}async function Ln(e,t,n,r,i,a){R(`runId`,n),R(`eventId`,i),a!==void 0&&R(`tag`,a);let o=a?`${i}.${a}.json`:`${i}.json`,s=JSON.stringify({runId:n});await Promise.all([J(L.join(jn(e,t),o),s),J(L.join(Mn(e,r),o),s)])}function Rn(e,t,n,r){return H(e,`hooks/by-run`,`${t}-${n}`,r)}async function zn(e,t,n,r){await J(Rn(e,t,n,r),JSON.stringify(r?{hookId:n,tag:r}:{hookId:n}))}async function Bn(e,t,n,r){await q(Rn(e,t,n,r)),r&&await q(Rn(e,t,n))}async function Vn(e,t){R(`runId`,t);let n=Nn(e),r=`${t}-`,i=[];for(let e of await Y(n)){if(!e.startsWith(r))continue;let t=null;try{t=await K(L.join(n,`${e}.json`),An)}catch(e){if(!(e instanceof SyntaxError||e instanceof E))throw e}i.push({fileId:e,hookId:t?.hookId??null,tag:t?.tag})}return i}async function Hn(e,t){await q(L.join(Nn(e),`${t}.json`))}const Un=new Map;function Wn(){Un.clear()}async function Gn(e){let t=L.resolve(e),n=Un.get(t);return n||(n=qn(t).catch(e=>{throw Un.delete(t),e}),Un.set(t,n)),n}async function Kn(e,t,n){for(let r=0;r<e.length;r+=t)await Promise.all(e.slice(r,r+t).map(n))}async function qn(e){let t=L.join(e,`hooks`,`.hook-index-complete`);try{await F.access(t);return}catch{}let n=L.join(e,`events`);await Kn(await Y(n),32,async t=>{let r=await In(L.join(n,`${t}.json`));if(!r||r.eventType!==`hook_created`||typeof r.correlationId!=`string`)return;let i=r.eventData?.token;if(typeof i==`string`)try{await Ln(e,i,r.runId,r.correlationId,r.eventId,Pn(t))}catch{}});let r=L.join(e,`hooks`);await Kn(await Y(r),32,async t=>{let n=null;try{n=await K(L.join(r,`${t}.json`),T)}catch(e){if(!(e instanceof SyntaxError||e instanceof E))throw e}if(n)try{await zn(e,n.runId,n.hookId,Pn(t))}catch{}}),await J(t,``)}async function Jn(e,t,n,r){await Gn(e);let i;try{i=t.kind===`token`?jn(e,t.token):Mn(e,t.hookId)}catch{return null}let a=(await Y(i)).filter(e=>Fn(e,r)).sort((e,t)=>V(t).localeCompare(V(e)));for(let t of a){let r=null;try{r=await K(L.join(i,`${t}.json`),kn)}catch(e){if(!(e instanceof SyntaxError||e instanceof E))throw e}if(!r)continue;let a=V(t),o;try{o=H(e,`events`,`${r.runId}-${a}`,Pn(t))}catch{continue}let s=await In(o);if(s&&s.eventType===`hook_created`&&typeof s.correlationId==`string`&&n(s))return s}return null}function Yn(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function Xn(e,t){return t===`none`?{...e,input:void 0,output:void 0}:e}function Zn(e,t){if(t===`none`){let{metadata:t,...n}=e;return n}return e}function Qn(e){if(e.eventType!==`hook_created`)return;let t=e.eventData.token;return typeof t==`string`?t:void 0}function $n(e){let{token:t,metadata:n,isWebhook:r,isSystem:i}=e.eventData;return{runId:e.runId,hookId:e.correlationId,token:t,metadata:n,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:e.createdAt,specVersion:e.specVersion,isWebhook:r??!0,isSystem:i??!1}}function er(e,t){return e.eventType===`hook_created`&&typeof e.correlationId==`string`&&t(e)}async function tr(e,t,n){let r=await U(e,`runs`,t,m,n);return r?oe(r.status):!1}async function nr(e,t,n,r){let i=await Jn(e,t,e=>er(e,n),r);return!i||!er(i,n)||await tr(e,i.runId,r)||await _n(e,i.correlationId,r)?null:i}async function rr(e,t,n){let r=$n(t);return await J(L.join(e,`hooks`,`tokens`,`${hn(r.token)}.json`),JSON.stringify({token:r.token,hookId:r.hookId,runId:r.runId,eventId:t.eventId})),await zn(e,r.runId,r.hookId,n),await J(H(e,`hooks`,r.hookId,n),JSON.stringify(r,W,2)),r}async function ir(e,t,n){let r=await nr(e,{kind:`token`,token:t},e=>Qn(e)===t,n);return r?rr(e,r,n):null}async function ar(e,t,n){let r=await nr(e,{kind:`id`,hookId:t},e=>e.correlationId===t,n);return r?rr(e,r,n):null}function or(e,t){let n=M({hookId:x().optional()});async function r(r){let i=null;try{i=await K(wn(e,r),n)}catch(e){if(!(e instanceof SyntaxError||e instanceof E))throw e}if(i?.hookId)try{let n=await U(e,`hooks`,i.hookId,T,t);if(n&&n.token===r)return{...n,isWebhook:n.isWebhook??!0}}catch(e){if(!et.is(e))throw e}let a=L.join(e,`hooks`),o=await Y(a);for(let e of o){let t=await K(L.join(a,`${e}.json`),T);if(t&&t.token===r)return{...t,isWebhook:t.isWebhook??!0}}return null}async function i(n,r){R(`hookId`,n);let i=await U(e,`hooks`,n,T,t);if(!i){let i=await ar(e,n,t);if(!i)throw new f(n);let a=r?.resolveData||`all`;return Zn({...i,isWebhook:i.isWebhook??!0},a)}let a=r?.resolveData||`all`;return Zn({...i,isWebhook:i.isWebhook??!0},a)}async function a(n){let i=await r(n)??await ir(e,n,t);if(!i)throw new f(n);return i}async function o(t){let n=L.join(e,`hooks`),r=t.resolveData||`all`,i=await X({directory:n,schema:T,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,filePrefix:void 0,filter:e=>!(t.runId&&e.runId!==t.runId),getCreatedAt:()=>null,getId:e=>e.hookId});return{...i,data:i.data.map(e=>Zn(e,r))}}return{get:i,getByToken:a,list:o}}async function sr(e,t){await Gn(e);for(let n of await Vn(e,t)){if(n.hookId){let r=null,i=null;try{i=H(e,`hooks`,n.hookId,n.tag),r=await K(i,T)}catch(e){if(!et.is(e)&&!(e instanceof SyntaxError||e instanceof E))throw e}r&&i&&r.runId===t&&(await En(e,r.token,r.runId,r.hookId),await q(Dn(e,r.token,r.runId,r.hookId)),await q(i))}await Hn(e,n.fileId)}}async function cr(e,t,n,r,i,a){if(oe(a.status)||await yn(e,t))throw new u(`Workflow run "${t}" is already in a terminal state`);let o=xn(e,t,n);await J(o,r);try{if(await yn(e,t)||await _t(o,i)!==`linked`)throw new u(`Workflow run "${t}" is already in a terminal state`)}finally{await F.unlink(o).catch(()=>{})}}async function lr(e,t,n,r,i){R(`runId`,t);let a=i?.resolveData??`all`;switch(n.eventType){case`run_cancelled`:{await J(vn(e,t),``),await Sn(e,t);let n=new Date,i={runId:r.runId,deploymentId:r.deploymentId,workflowName:r.workflowName,specVersion:r.specVersion,executionContext:r.executionContext,input:r.input,createdAt:r.createdAt,expiredAt:r.expiredAt,startedAt:r.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:n,updatedAt:n,attributes:r.attributes};return await G(z(e,`runs`,`${t}.json`),i,{overwrite:!0}),await sr(e,t),{event:void 0,run:Yn(i,a)}}case`wait_completed`:case`hook_received`:{let i=`evnt_${On()}`,o=new Date,s={...n,runId:t,eventId:i,createdAt:o,specVersion:5},c=z(e,`events`,`${`${t}-${i}`}.json`);return n.eventType===`hook_received`?await cr(e,t,i,JSON.stringify(s,W,2),c,r):await G(c,s),{event:v(s,a)}}default:throw Error(`Event type '${n.eventType}' not supported for legacy runs (specVersion: ${r.specVersion||`undefined`}). Please upgrade 'workflow' package.`)}}const ur=new Map;function dr(e,t){let n=ur.get(e),r={},i=(async()=>{n&&await n.catch(()=>void 0);try{return await t()}finally{ur.get(e)===r.task&&ur.delete(e)}})();return r.task=i,ur.set(e,i),i}function fr(e,t){let n=(async(n,r)=>{R(`runId`,n);let i=await U(e,`runs`,n,m,t);if(!i)throw new c(n);return Yn(i,r?.resolveData??`all`)});return{get:n,getMany:(async(e,t)=>{let r=[...new Set(e)],i=await Promise.all(r.map(async e=>{try{return await n(e,t)}catch(e){if(e instanceof c)return null;throw e}})),a=new Map(r.map((e,t)=>[e,i[t]]));return e.map(e=>a.get(e)??null)}),list:(async t=>{let n=t?.resolveData??`all`,r=await X({directory:L.join(e,`runs`),schema:m,fileIdFilter:t?.fileIdFilter,filter:e=>!(t?.workflowName&&e.workflowName!==t.workflowName||t?.status&&e.status!==t.status),sortOrder:t?.pagination?.sortOrder??`desc`,limit:t?.pagination?.limit??200,cursor:t?.pagination?.cursor,getCreatedAt:$(`wrun`),getId:e=>e.runId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r}),experimentalSetAttributes:async(n,r,i)=>(R(`runId`,n),dr(n,async()=>{let a=await U(e,`runs`,n,m,t);if(!a)throw new c(n);try{y(r,{existingKeys:Object.keys(a.attributes??{}),allowReservedAttributes:i?.allowReservedAttributes})}catch(e){throw e instanceof C,e}let o=ce(a.attributes,r),s={...a,attributes:o,updatedAt:new Date};return await G(H(e,`runs`,n,t),s,{overwrite:!0}),{attributes:o}}))}}function pr(){let e=process.env.WORKFLOW_MAX_EVENTS,t=e===void 0?NaN:Number(e);return Number.isInteger(t)&&t>0?t:25e3}const mr=M({hookId:x().optional(),runId:x(),eventId:x().optional()}),hr=M({eventId:x()}),gr=M({runId:x(),resumeId:x(),hookId:x(),eventId:x(),payloadDigest:x().optional()});async function _r(e){try{return await K(e,mr)}catch(e){if(e instanceof SyntaxError||e instanceof E)return null;throw e}}async function vr(e,t,n){if(t.hookId&&await _n(e,t.hookId,n))return!0;let r=await U(e,`runs`,t.runId,m,n);return!r||oe(r.status)}async function yr(e){try{return await K(e,hr)}catch(e){if(e instanceof SyntaxError||e instanceof E)return null;throw e}}async function br(e,t,n){return(await X({directory:L.join(e,`events`),schema:b,filePrefix:`${t}-`,filter:e=>e.eventType===`hook_created`&&e.correlationId===n,limit:1,getCreatedAt:$(`evnt`),getId:e=>e.eventId})).data[0]?.eventId??null}async function xr(e,t,n,r,i){let a=await U(e,`events`,`${t}-${r}`,b,i);if(!a||a.eventType!==`hook_created`||a.correlationId!==n||await U(e,`hooks`,n,T,i))return;let o=a.eventData??{};if(typeof o.token!=`string`)return;let s={runId:t,hookId:n,token:o.token,metadata:o.metadata,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:a.createdAt,specVersion:a.specVersion,isWebhook:o.isWebhook??!0,isSystem:o.isSystem??!1};await Ln(e,o.token,t,n,r,i),await zn(e,t,n,i),await J(H(e,`hooks`,n,i),JSON.stringify(s,W,2))}async function Sr(e,t,n,r,i){let a=Dn(e,t,n,r);return await J(a,JSON.stringify({eventId:i}))?i:(await yr(a))?.eventId??null}function Cr(e,t,n){let r=e.get(t),i={},a=(async()=>{r&&await r.catch(()=>void 0);try{return await n()}finally{e.get(t)===i.task&&e.delete(t)}})();return i.task=a,e.set(t,a),a}async function wr(e,t){let n=L.join(e,`waits`),r=await Y(n);for(let e of r)e.startsWith(`${t}-`)&&await q(L.join(n,`${e}.json`))}async function Tr(e,t,n,r){return dr(t,async()=>{let i=await K(H(e,`runs`,t,n),m),a={...r,attributes:i?.attributes??r.attributes};return await G(H(e,`runs`,t,n),a,{overwrite:!0}),a})}function Er(e,t){let n=4*1024*1024,r=new Map,i=new Map,a=new Map,o=0;function x(e){let t=r.get(e);if(!t)return;r.delete(e),o-=i.get(e)??0,i.delete(e);let n=a.get(t.runId);n?.delete(e),n?.size===0&&a.delete(t.runId)}function C(e){for(let t of a.get(e)??[])x(t)}function w(){r.clear(),i.clear(),a.clear(),o=0}function ie(e,t,s){if(s>n)return;for(;r.size>0&&(r.size>=1e3||o+s>n);){let e=r.keys().next().value;x(e)}r.set(e,t),i.set(e,s),o+=s;let c=a.get(t.runId)??new Set;c.add(e),a.set(t.runId,c)}function E(e,t,r){if(h(e.eventType)){C(e.runId);return}let i=Buffer.byteLength(r);if(i>n)return;let a=b.safeParse(JSON.parse(r,pt));a.success&&ie(t,a.data,i)}async function ae(n){let r=H(e,`events`,`${n.runId}-${n.eventId}`,t),i=JSON.stringify(n,W,2);await mt(r,i),E(n,r,i)}let D=new Map,O=new Map;return{clearCache:w,async create(n,i,a){if(n!=null&&n!==``&&R(`runId`,n),`correlationId`in i&&typeof i.correlationId==`string`&&R(`correlationId`,i.correlationId),ue(i.eventType)&&n&&i.correlationId){let e=t?`${n}-${i.correlationId}.${t}`:`${n}-${i.correlationId}`;return Cr(D,e,()=>o())}if(S(i.eventType)&&n&&i.correlationId){let e=t?`${n}-${i.correlationId}.hook.${t}`:`${n}-${i.correlationId}.hook`;return Cr(O,e,()=>o())}return o();async function o(){let o=`evnt_${On()}`,x=new Date,S;if(i.eventType===`run_created`&&(!n||n===``))S=`wrun_${On()}`;else if(n)S=n;else throw Error(`runId is required for non-run_created events`);if(i.eventType===`run_created`&&n&&n!==``){let e=le(S,`wrun_`);if(e)throw new s(e)}let C=i.specVersion??5,w=null;if(i.eventType!==`run_created`&&![`step_completed`,`step_retrying`].includes(i.eventType)&&(w=await U(e,`runs`,S,m,t),i.eventType===`run_started`&&!w&&`eventData`in i&&i.eventData)){let n=i.eventData;if(n.deploymentId&&n.workflowName&&n.input!==void 0){y(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0});let r={runId:S,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:C,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:x,updatedAt:x};if(await J(H(e,`runs`,S,t),JSON.stringify(r,W))){let e=`evnt_${On()}`;await ae({eventType:`run_created`,runId:S,eventId:e,createdAt:x,specVersion:C,eventData:{deploymentId:n.deploymentId,workflowName:n.workflowName,input:n.input,executionContext:n.executionContext,attributes:n.attributes,allowReservedAttributes:n.allowReservedAttributes,encryptionPublicKey:n.encryptionPublicKey}}),w=r}else w=await U(e,`runs`,S,m,t)}}if(i.eventType===`run_failed`&&!w||i.eventType===`attr_set`&&!w)throw new c(S);if(w){if(de(w.specVersion))throw new d(w.specVersion,5);if(fe(w.specVersion))return lr(e,S,i,w,a)}let ie=ee(i),D=ie&&i.eventType===`step_started`;if(w&&oe(w.status)){if(i.eventType===`run_cancelled`&&w.status===`cancelled`){let e={...i,runId:S,eventId:o,createdAt:x,specVersion:C};return await ae(e),{event:v(e,a?.resolveData??`all`),run:w,...w?{maxEvents:pr()}:{}}}if(i.eventType===`run_started`)throw new u(`Workflow run "${S}" is already in terminal state "${w.status}"`);if(h(i.eventType))throw new p(`Cannot transition run from terminal state "${w.status}"`);if(ie)throw new p(`Cannot create new entities on run in terminal state "${w.status}"`);if(i.eventType===`attr_set`)throw new p(`Cannot set attributes on run in terminal state "${w.status}"`)}let O=null;if(ue(i.eventType)&&i.eventType!==`step_created`&&i.correlationId){if(O=await U(e,`steps`,`${S}-${i.correlationId}`,g,t),!O&&!D)throw new s(`Step "${i.correlationId}" not found`);if(D&&O)throw new p(`Step "${i.correlationId}" already created`);if(O){if(ne(O.status))throw new p(`Cannot modify step in terminal state "${O.status}"`);if(w&&oe(w.status)&&O.status!==`running`)throw new u(`Cannot modify non-running step on run in terminal state "${w.status}"`)}}if(te(i.eventType)&&i.correlationId){if(i.eventType===`hook_received`&&a?.resumeId){let n=await K(Tn(e,S,a.resumeId),gr);if(n&&n.hookId===i.correlationId&&(!a.resumePayloadDigest||!n.payloadDigest||n.payloadDigest===a.resumePayloadDigest)){let r=await U(e,`events`,`${S}-${n.eventId}`,b,t);if(r)return{event:r}}}if(i.eventType===`hook_received`&&await _n(e,i.correlationId,t)||!await U(e,`hooks`,i.correlationId,T,t))throw new f(i.correlationId);if(i.eventType===`hook_received`&&a?.resumeId){let n=Tn(e,S,a.resumeId),r=async n=>{if(n.hookId!==i.correlationId)throw new p(`hook_received resumeId "${a.resumeId}" already recorded for a different hook`);if(a.resumePayloadDigest&&n.payloadDigest&&n.payloadDigest!==a.resumePayloadDigest)throw new p(`hook_received resumeId "${a.resumeId}" already recorded with a different payload`);let r=await U(e,`events`,`${S}-${n.eventId}`,b,t);return r?{event:r}:(o=n.eventId,null)},s=await K(n,gr);if(s){let e=await r(s);if(e)return e}else if(!await J(n,JSON.stringify({runId:S,resumeId:a.resumeId,hookId:i.correlationId,eventId:o,...a.resumePayloadDigest?{payloadDigest:a.resumePayloadDigest}:{}}))){let e=await K(n,gr);if(e){let t=await r(e);if(t)return t}}}}let k={...i,runId:S,eventId:o,createdAt:x,specVersion:C,...i.eventType===`hook_received`&&a?.resumeId?{resumeId:a.resumeId}:{}};if(i.eventType===`run_started`&&`eventData`in k&&delete k.eventData,D&&k.eventType===`step_started`&&k.eventData){let{input:e,...t}=k.eventData;k={...k,eventData:t}}let A,j,M,N,pe=!1,me;if(h(i.eventType)&&w){await J(vn(e,S,t),``),await Sn(e,S,t);let n=await Cn(e,S,t);o=n.eventId,k={...k,eventId:o,createdAt:n.createdAt}}if(i.eventType===`run_created`&&`eventData`in i){let n=i.eventData;if(y(Object.entries(n.attributes??{}).map(([e,t])=>({key:e,value:t})),{allowReservedAttributes:n.allowReservedAttributes===!0}),A={runId:S,deploymentId:n.deploymentId,status:`pending`,workflowName:n.workflowName,specVersion:C,executionContext:n.executionContext,input:n.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:n.attributes??{},encryptionPublicKey:n.encryptionPublicKey,createdAt:x,updatedAt:x},!await J(H(e,`runs`,S,t),JSON.stringify(A,W,2)))throw new p(`Workflow run "${S}" already exists`)}else if(i.eventType===`run_started`){if(w){if(w.status===`running`)return{run:w,maxEvents:pr()};A=await Tr(e,S,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,status:`running`,output:void 0,error:void 0,completedAt:void 0,startedAt:w.startedAt??x,updatedAt:x,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey})}}else if(i.eventType===`run_completed`&&`eventData`in i){let n=i.eventData;w&&(A=await Tr(e,S,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,startedAt:w.startedAt,status:`completed`,output:n.output,error:void 0,completedAt:x,updatedAt:x,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey}),await Promise.all([sr(e,S),wr(e,S)]))}else if(i.eventType===`run_failed`&&`eventData`in i){let n=i.eventData;w&&(A=await Tr(e,S,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,startedAt:w.startedAt,status:`failed`,output:void 0,error:n.error,errorCode:n.errorCode,completedAt:x,updatedAt:x,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey}),await Promise.all([sr(e,S),wr(e,S)]))}else if(i.eventType===`run_cancelled`)w&&(A=await Tr(e,S,t,{runId:w.runId,deploymentId:w.deploymentId,workflowName:w.workflowName,specVersion:w.specVersion,executionContext:w.executionContext,input:w.input,createdAt:w.createdAt,expiredAt:w.expiredAt,startedAt:w.startedAt,status:`cancelled`,output:void 0,error:void 0,completedAt:x,updatedAt:x,attributes:w.attributes,encryptionPublicKey:w.encryptionPublicKey}),await Promise.all([sr(e,S),wr(e,S)]));else if(i.eventType===`attr_set`&&w)A=await dr(S,async()=>{let n=await K(H(e,`runs`,S,t),m);if(!n)throw new c(S);if(y(i.eventData.changes,{existingKeys:Object.keys(n.attributes),allowReservedAttributes:i.eventData.allowReservedAttributes===!0}),i.correlationId&&i.eventData.writer.type===`workflow`&&!await J(z(e,`.locks`,`attributes`,t?`${S}-${i.correlationId}.created.${t}`:`${S}-${i.correlationId}.created`),``))throw new p(`Attribute event "${i.correlationId}" already exists`);let r={...n,attributes:ce(n.attributes,i.eventData.changes),updatedAt:x};return await G(H(e,`runs`,S,t),r,{overwrite:!0}),r});else if(i.eventType===`step_created`&&`eventData`in i){if(!await J(z(e,`.locks`,`steps`,t?`${S}-${i.correlationId}.created.${t}`:`${S}-${i.correlationId}.created`),``))throw new p(`Step "${i.correlationId}" already created`);let n=i.eventData;j={runId:S,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:x,updatedAt:x,specVersion:C},await G(H(e,`steps`,`${S}-${i.correlationId}`,t),j)}else if(i.eventType===`step_started`){if(!O&&D){let n=i.eventData;if(await J(z(e,`.locks`,`steps`,t?`${S}-${i.correlationId}.created.${t}`:`${S}-${i.correlationId}.created`),``)){let r={runId:S,stepId:i.correlationId,stepName:n.stepName,status:`pending`,input:n.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:x,updatedAt:x,specVersion:C};await G(H(e,`steps`,`${S}-${i.correlationId}`,t),r);let a=`evnt_${On()}`,o={eventType:`step_created`,runId:S,eventId:a,createdAt:x,specVersion:C,correlationId:i.correlationId,eventData:{stepName:n.stepName,input:n.input}};await G(H(e,`events`,`${S}-${a}`,t),o),O=r,pe=!0}else throw new p(`Step "${i.correlationId}" already created`)}if(O){if(O.retryAfter&&O.retryAfter.getTime()>Date.now())throw new l(`Cannot start step "${i.correlationId}": retryAfter timestamp has not been reached yet`,{retryAfter:Math.ceil((O.retryAfter.getTime()-Date.now())/1e3)});let n=`${S}-${i.correlationId}`,r=await U(e,`steps`,n,g,t);if(r&&ne(r.status))throw new p(`Cannot modify step in terminal state "${r.status}"`);j={...O,status:`running`,startedAt:O.startedAt??x,attempt:O.attempt+1,retryAfter:void 0,updatedAt:x},await G(H(e,`steps`,n,t),j,{overwrite:!0})}}else if(i.eventType===`step_completed`&&`eventData`in i){let n=i.eventData;if(O){let r=`${S}-${i.correlationId}`;if(!await J(z(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new p(`Cannot modify step in terminal state`);j={...O,status:`completed`,output:n.result,completedAt:x,updatedAt:x},await G(H(e,`steps`,r,t),j,{overwrite:!0})}}else if(i.eventType===`step_failed`&&`eventData`in i){let n=i.eventData;if(O){let r=`${S}-${i.correlationId}`;if(!await J(z(e,`.locks`,`steps`,t?`${r}.terminal.${t}`:`${r}.terminal`),``))throw new p(`Cannot modify step in terminal state`);j={...O,status:`failed`,error:n.error,completedAt:x,updatedAt:x},await G(H(e,`steps`,r,t),j,{overwrite:!0})}}else if(i.eventType===`step_retrying`&&`eventData`in i){let n=i.eventData;if(O){let r=`${S}-${i.correlationId}`;j={...O,status:`pending`,error:n.error,retryAfter:n.retryAfter,updatedAt:x},await G(H(e,`steps`,r,t),j,{overwrite:!0})}}else if(i.eventType===`hook_created`&&`eventData`in i){let n=i.eventData,r=wn(e,n.token),s=JSON.stringify({token:n.token,hookId:i.correlationId,runId:S,eventId:o}),c=!1,l=null,u=0,d=0;for(let a=0;a<10&&(await _r(r)||await ir(e,n.token,t),c=await J(r,s),!c);a++){if(l=await _r(r),!l){d++,d>=3&&await q(r);continue}if(l.runId===S&&l.hookId===i.correlationId||!await vr(e,l,t))break;u++,u<3?await new Promise(e=>setTimeout(e,10)):(await q(r),l.hookId&&(await q(H(e,`hooks`,l.hookId,t)),await q(Dn(e,n.token,l.runId,l.hookId)))),l=null}let f=!1;if(!c)if(l?.runId===S&&l.hookId===i.correlationId){let r;if(l.eventId)r=l.eventId;else{let a=await br(e,S,i.correlationId);if(a!==null)throw await xr(e,S,i.correlationId,a,t),new p(`Hook "${i.correlationId}" already created`);let s=await Sr(e,n.token,S,i.correlationId,o);if(s===null)throw new p(`Hook "${i.correlationId}" already created`);r=s}o=r;let a=se(o.replace(/^evnt_/,``))??x;k={...i,runId:S,eventId:o,createdAt:a,specVersion:C},f=!0}else{let e={eventType:`hook_conflict`,correlationId:i.correlationId,eventData:{token:n.token,...l?{conflictingRunId:l.runId}:{}},runId:S,eventId:o,createdAt:x,specVersion:C};return await ae(e),{event:v(e,a?.resolveData??`all`),run:A,step:j,hook:void 0}}M={runId:S,hookId:i.correlationId,token:n.token,metadata:n.metadata,ownerId:`local-owner`,projectId:`local-project`,environment:`local`,createdAt:k.createdAt,specVersion:C,isWebhook:n.isWebhook??!1,isSystem:n.isSystem??!1},me=f?{overwrite:!0}:void 0,await Ln(e,n.token,S,i.correlationId,o,t)}else if(i.eventType===`hook_disposed`){if(!await J(gn(e,i.correlationId,t),``))throw new p(`Hook "${i.correlationId}" already disposed`);let n=H(e,`hooks`,i.correlationId,t),r=await U(e,`hooks`,i.correlationId,T,t);r&&(await En(e,r.token,r.runId,r.hookId),await q(Dn(e,r.token,r.runId,r.hookId))),await q(n),await Bn(e,S,i.correlationId,t)}else if(i.eventType===`wait_created`&&`eventData`in i){let n=`${S}-${i.correlationId}`;if(!await J(z(e,`.locks`,`waits`,t?`${n}.created.${t}`:`${n}.created`),``))throw new p(`Wait "${i.correlationId}" already exists`);let r=i.eventData;N={waitId:n,runId:S,status:`waiting`,resumeAt:r.resumeAt,completedAt:void 0,createdAt:x,updatedAt:x,specVersion:C},await G(H(e,`waits`,n,t),N)}else if(i.eventType===`wait_completed`){let n=`${S}-${i.correlationId}`,r=z(e,`.locks`,`waits`,t?`${n}.completed.${t}`:`${n}.completed`);if(!await J(r,``))throw new p(`Wait "${i.correlationId}" already completed`);let a=await U(e,`waits`,n,_,t);if(!a)throw await F.unlink(r).catch(()=>{}),new s(`Wait "${i.correlationId}" not found`);N={...a,status:`completed`,completedAt:x,updatedAt:x},await G(H(e,`waits`,n,t),N,{overwrite:!0})}if(i.eventType===`hook_received`&&i.correlationId&&await _n(e,i.correlationId,t))throw new f(i.correlationId);let he=H(e,`events`,`${S}-${o}`,t),P=JSON.stringify(k,W,2),ge;if(i.eventType===`hook_received`){let n=await yn(e,S,t),r=n?null:await U(e,`runs`,S,m,t);if(n||r&&oe(r.status))throw new u(`Workflow run "${S}" is already in a terminal state`);let i=xn(e,S,o,t);if(!await J(i,P))throw new p(`Event "${o}" already exists for run "${S}"`);try{if(await yn(e,S,t))throw new u(`Workflow run "${S}" is already in a terminal state`);let n=await _t(i,he);if(n===`missing`)throw new u(`Workflow run "${S}" is already in a terminal state`);ge=n===`linked`}finally{await q(i).catch(()=>{})}}else ge=await J(he,P);if(!ge)throw i.eventType===`hook_created`&&i.correlationId&&await xr(e,S,i.correlationId,o,t),new p(`Event "${o}" already exists for run "${S}"`);E(k,he,P),M&&i.eventType===`hook_created`&&(await zn(e,M.runId,M.hookId,t),await G(H(e,`hooks`,M.hookId,t),M,me));let _e=a?.resolveData??`all`,ve=v(k,_e),I,ye,be;if(i.eventType===`run_started`&&A){let t=await X({directory:L.join(e,`events`),schema:b,cachedItems:r,filePrefix:`${S}-`,sortOrder:`asc`,limit:1e3,getCreatedAt:$(`evnt`),getId:e=>e.eventId});I=t.data,ye=t.cursor,be=t.hasMore}if(re(i.eventType)&&typeof a?.sinceCursor==`string`){let t=await X({directory:L.join(e,`events`),schema:b,filePrefix:`${S}-`,sortOrder:`asc`,cursor:a.sinceCursor,getCreatedAt:$(`evnt`),getId:e=>e.eventId});I=_e===`none`?t.data.map(e=>v(e,_e)):t.data,ye=t.cursor,be=t.hasMore}return{event:ve,run:A,step:j,hook:M,wait:N,events:I,cursor:ye,hasMore:be,...pe?{stepCreated:!0}:{},...A?{maxEvents:pr()}:{}}}},async get(n,r,i){R(`runId`,n),R(`eventId`,r);let a=await U(e,`events`,`${n}-${r}`,b,t);if(!a)throw Error(`Event ${r} in run ${n} not found`);return v(a,i?.resolveData??`all`)},async list(t){let{runId:n}=t;R(`runId`,n);let i=t.resolveData??`all`,a=await X({directory:L.join(e,`events`),schema:b,cachedItems:r,filePrefix:`${n}-`,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:$(`evnt`),getId:e=>e.eventId});return i===`none`?{...a,data:a.data.map(e=>v(e,i))}:a},async listByCorrelationId(t){let n=t.correlationId;R(`correlationId`,n);let i=t.resolveData??`all`,a=await X({directory:L.join(e,`events`),schema:b,cachedItems:r,filter:e=>e.correlationId===n,sortOrder:t.pagination?.sortOrder??`asc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:$(`evnt`),getId:e=>e.eventId});return i===`none`?{...a,data:a.data.map(e=>v(e,i))}:a}}}function Dr(e,t){return{get:(async(n,r,i)=>{R(`runId`,n),R(`stepId`,r);let a=await U(e,`steps`,`${n}-${r}`,g,t);if(!a)throw Error(`Step ${r} in run ${n} not found`);return Xn(a,i?.resolveData??`all`)}),list:(async t=>{R(`runId`,t.runId);let n=t.resolveData??`all`,r=await X({directory:L.join(e,`steps`),schema:g,filePrefix:`${t.runId}-`,sortOrder:t.pagination?.sortOrder??`desc`,limit:t.pagination?.limit,cursor:t.pagination?.cursor,getCreatedAt:$(`step`),getId:e=>e.stepId});return n===`none`?{...r,data:r.data.map(e=>({...e,input:void 0,output:void 0}))}:r})}}function Or(e,t){let n=fr(e,t),r=Dr(e,t),i=Er(e,t),a=or(e,t);return{runs:nn(`world.runs`,n),steps:nn(`world.steps`,r),events:nn(`world.events`,i),hooks:nn(`world.hooks`,a),clearCache:()=>i.clearCache()}}const kr=D(()=>Math.random()),Ar=M({streams:j(x())});function jr(e){return e===1}function Mr(e){let t=Buffer.from([+!!e.eof]);return Buffer.concat([t,e.chunk])}function Nr(e){return jr(e[0])}function Pr(e){return{eof:Nr(e),chunk:Buffer.from(e.subarray(1))}}async function Fr(e){try{return await F.readdir(e)}catch(e){if(e.code===`ENOENT`)return[];throw e}}function Ir(e,t,n,r=n,i=()=>!0){for(let a of t){if(!a.endsWith(n))continue;let t=a.slice(0,-n.length);i(t)&&e.set(t,r)}}function Lr(e,t){return R(`streamName`,t),L.join(e,t)}async function Rr(e,t,n){let r=Lr(e,t),i=await Fr(r),a=new Map;return Ir(a,i,`.json`),Ir(a,i,`.bin`,`.bin`,n?e=>!e.endsWith(`.${n}`):void 0),n&&Ir(a,i,`.${n}.bin`),{files:[...a.keys()].sort(),extMap:a,dir:r}}function zr(e,t){let n=t?`.${t}`:``,r=new De,i=new Set;async function a(n,r){R(`runId`,n),R(`streamName`,r);let a=`${n}:${r}`;if(i.has(a))return;let o=H(e,`streams/runs`,n,t),s=(await U(e,`streams/runs`,n,Ar,t))?.streams??[];s.includes(r)||(s.push(r),await G(o,{streams:s},{overwrite:!0})),i.add(a)}function o(e){return typeof e==`string`?Buffer.from(new TextEncoder().encode(e)):e instanceof Buffer?e:Buffer.from(e)}return{streams:{async write(t,i,s){let c=`chnk_${kr()}`;await a(await t,i);let l=o(s),u=Mr({chunk:l,eof:!1});await mt(L.join(Lr(L.join(e,`streams`,`chunks`),i),`${c}${n}.bin`),u);let d=Uint8Array.from(l);r.emit(`chunk:${i}`,{streamName:i,chunkData:d,chunkId:c})},async writeMulti(t,i,s){if(s.length===0)return;let c=s.map(()=>`chnk_${kr()}`);await a(await t,i);let l=s.map(e=>o(e)).map(async(t,r)=>{let a=c[r],o=Mr({chunk:t,eof:!1});return await mt(L.join(Lr(L.join(e,`streams`,`chunks`),i),`${a}${n}.bin`),o),{chunkId:a,chunkData:Uint8Array.from(t)}});for(let e of l){let{chunkId:t,chunkData:n}=await e;r.emit(`chunk:${i}`,{streamName:i,chunkData:n,chunkId:t})}},async close(t,i){let o=`chnk_${kr()}`;await a(await t,i),await mt(L.join(Lr(L.join(e,`streams`,`chunks`),i),`${o}${n}.bin`),Mr({chunk:Buffer.from([]),eof:!0})),r.emit(`close:${i}`,{streamName:i})},async list(n){return R(`runId`,n),(await U(e,`streams/runs`,n,Ar,t))?.streams??[]},async getChunks(n,r,i){let a=i?.limit??100,{files:o,extMap:s,dir:c}=await Rr(L.join(e,`streams`,`chunks`),r,t),l=0;if(i?.cursor)try{l=JSON.parse(Buffer.from(i.cursor,`base64`).toString(`utf-8`)).i}catch{l=0}let u=!1,d=[],f=0;for(let e of o){let t=s.get(e)??`.bin`,n=L.join(c,`${e}${t}`);if(f<l){if(jr(await gt(n))){u=!0;break}f++;continue}if(d.length>=a){jr(await gt(n))?u=!0:f++;break}let r=Pr(await ht(n));if(r.eof){u=!0;break}d.push({index:f,data:Uint8Array.from(r.chunk)}),f++}let p=!u&&f>l+d.length,m=l+d.length;return{data:d,cursor:p?Buffer.from(JSON.stringify({i:m})).toString(`base64`):null,hasMore:p,done:u}},async getInfo(n,r){let{files:i,extMap:a,dir:o}=await Rr(L.join(e,`streams`,`chunks`),r,t),s=!1,c=0;for(let e of i){let t=a.get(e)??`.bin`;if(jr(await gt(L.join(o,`${e}${t}`)))){s=!0;break}c++}return{tailIndex:c-1,done:s}},async get(n,i,a=0){let o=L.join(e,`streams`,`chunks`),s=()=>{},c=null,l=!1;return new ReadableStream({async start(e){let n=new Set,u=[],d=!0,f=!1,p=t=>{if(t.chunkData.byteLength===0){n.add(t.chunkId);return}d?(n.add(t.chunkId),u.push({chunkId:t.chunkId,chunkData:Uint8Array.from(t.chunkData)})):n.has(t.chunkId)||(n.add(t.chunkId),e.enqueue(Uint8Array.from(t.chunkData)))},m=()=>{if(d){f=!0;return}l=!0,s();try{e.close()}catch{}};s=()=>{r.off(`chunk:${i}`,p),r.off(`close:${i}`,m),c&&=(clearInterval(c),null)},r.on(`chunk:${i}`,p),r.on(`close:${i}`,m);let{files:h,extMap:g,dir:_}=await Rr(o,i,t),v=h.length;if(typeof a==`number`&&a<0&&h.length>0){let e=h[h.length-1],t=g.get(e)??`.bin`;jr(await gt(L.join(_,`${e}${t}`)))&&v--}let ee=typeof a==`number`&&a<0?Math.max(0,v+a):a,y=!1;for(let t=ee;t<h.length;t++){let r=h[t],i=r;if(n.has(i))continue;let a=g.get(r)??`.bin`,o=Pr(await ht(L.join(_,`${r}${a}`)));if(o?.eof===!0){y=!0;break}n.add(i),o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}d=!1,u.sort((e,t)=>e.chunkId.localeCompare(t.chunkId));for(let t of u)e.enqueue(Uint8Array.from(t.chunkData));if(y){l=!0,s();try{e.close()}catch{}return}if(f){l=!0,s();try{e.close()}catch{}return}for(let e=0;e<ee&&e<h.length;e++)n.add(h[e]);if(l){s();return}let te=!1;c=setInterval(async()=>{if(!te){te=!0;try{let{files:r,extMap:a}=await Rr(o,i,t);for(let t of r){let r=t;if(n.has(r))continue;n.add(r);let i=a.get(t)??`.bin`,o=Pr(await ht(L.join(_,`${t}${i}`)));if(o?.eof===!0){l=!0,s();try{e.close()}catch{}return}if(l)return;o.chunk.byteLength&&e.enqueue(Uint8Array.from(o.chunk))}}catch(e){e instanceof Error&&`code`in e||console.error(`[world-local] Unexpected polling error:`,e)}finally{te=!1}}},100)},cancel(){l=!0,s()}})}}}}function Br(e){let t=e?Object.fromEntries(Object.entries(e).filter(([,e])=>e!==void 0)):{},n={...Je.value,...t};Me(n.dataDir);let r=n.tag,i=mn(n),{clearCache:a,...o}=Or(n.dataDir,r),s=Ye(n);return{specVersion:5,capabilities:{hookResumeDedup:!0},...i,...o,...nn(`world.streams`,{...zr(n.dataDir,r),...n.streamFlushIntervalMs!==void 0&&{streamFlushIntervalMs:n.streamFlushIntervalMs}}),async start(){if(await Pt(n.dataDir),!s)return;let e=r?e=>ot(e,r):st;await k({...o.runs,list:(t=>o.runs.list({...t,fileIdFilter:e}))},i.queue,`world-local`)},async close(){a(),await i.close()},async clear(){if(a(),r){let e=n.dataDir,t=L.join(e,`hooks`),i=await ct(t,r),{HookSchema:a}=await import(`../../_chunks/workflow/dist-D5bR13zs.js`).then(e=>e.t);await Promise.all(i.map(async n=>{let r=await K(L.join(t,n),a);r?.token&&(await q(L.join(t,`tokens`,`${hn(r.token)}.json`)),await q(Dn(e,r.token,r.runId,r.hookId)))})),await Promise.all([`runs`,`steps`,`events`,`hooks`,`hooks/by-run`,`waits`,`streams/runs`].map(async t=>{let n=L.join(e,t),i=await ct(n,r);await Promise.all(i.map(e=>q(L.join(n,e))))}));for(let t of[`token-index`,`id-index`]){let n=L.join(e,`hooks`,t),i;try{i=await P.readdir(n,{withFileTypes:!0})}catch{i=[]}await Promise.all(i.filter(e=>e.isDirectory()).map(async e=>{let t=L.join(n,e.name),i=await ct(t,r);await Promise.all(i.map(e=>q(L.join(t,e))))}))}await P.rm(L.join(e,`.locks`),{recursive:!0,force:!0}).catch(()=>{});let o=L.join(e,`streams`,`chunks`),s;try{s=await P.readdir(o,{withFileTypes:!0})}catch{s=[]}await Promise.all(s.filter(e=>e.isDirectory()).map(async e=>{let t=L.join(o,e.name),n=await lt(t,r,`.bin`);await Promise.all(n.map(e=>P.unlink(L.join(t,e)).catch(()=>{})))})),it()}else it(),Wn(),await xe(n.dataDir,{recursive:!0,force:!0}),await Pt(n.dataDir)}}}export{wt as DataDirAccessError,Tt as DataDirVersionError,Oe as UnwritableDataDirError,Br as createWorld,At as ensureDataDir,Pt as initDataDir,Et as parseVersion};
|