libfx 0.0.14 → 0.0.15-dev.1784.g30b6bacc9fc9
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/README.md +17 -8
- package/browser-agent.js +21 -0
- package/browser-terminal.js +7 -0
- package/browser.js +12 -37
- package/bundled-asset.js +12 -0
- package/durable/local.mjs +3 -0
- package/durable/local.mjs.map +1 -0
- package/durable/vercel.mjs +3 -0
- package/durable/vercel.mjs.map +1 -0
- package/durable/world.mjs +3 -0
- package/durable/world.mjs.map +1 -0
- package/durable.js +490 -50
- package/engine.js +2498 -0
- package/fx-core.wasm +0 -0
- package/fx-harness.js +9 -2
- package/fx-sdk.js +27 -3493
- package/fx-term.wasm +0 -0
- package/mcp.js +3 -3
- package/node-wasm.js +63 -0
- package/node.cjs +8 -7603
- package/node.js +94 -103
- package/package.json +10 -3
- package/types/durable-world.d.ts +4 -1
- package/types/libfx.d.cts +10 -4
- package/types/node.d.ts +1 -1
- package/wasm-runtime.js +1049 -0
- package/wasm-terminal.js +80 -0
- package/xterm.js +112 -0
- package/libfx.darwin-arm64.node +0 -0
- package/libfx.darwin-x64.node +0 -0
- package/libfx.linux-arm64.node +0 -0
- package/libfx.linux-x64.node +0 -0
package/README.md
CHANGED
|
@@ -25,7 +25,7 @@ for await (const event of turn) {
|
|
|
25
25
|
await agent.close();
|
|
26
26
|
```
|
|
27
27
|
|
|
28
|
-
Set `AI_GATEWAY_API_KEY` and run it with Node.js 20 or newer. Model calls go through [AI Gateway](https://vercel.com/docs/ai-gateway), so any model it lists works, and on Vercel libfx uses the deployment's OIDC token instead of a key. libfx can also run on a user's own ChatGPT or Grok plan, or on another server through the OpenAI Chat Completions API. See [Providers](#providers).
|
|
28
|
+
Set `AI_GATEWAY_API_KEY` and run it with Node.js 20.19, 22.12, or newer. Model calls go through [AI Gateway](https://vercel.com/docs/ai-gateway), so any model it lists works, and on Vercel libfx uses the deployment's OIDC token instead of a key. libfx can also run on a user's own ChatGPT or Grok plan, or on another server through the OpenAI Chat Completions API. See [Providers](#providers).
|
|
29
29
|
|
|
30
30
|
Importing libfx and calling `createFxAgent()` touch no network, files or processes. The engine loads when a session runs its first turn.
|
|
31
31
|
|
|
@@ -55,9 +55,10 @@ agent.session(sessionId).prompt("Start with the schema.");
|
|
|
55
55
|
|
|
56
56
|
- **One turn at a time.** A prompt sent while a turn runs waits behind it, even when it reaches a different server.
|
|
57
57
|
- **Turns finish on their own.** A turn runs to the end whether or not anyone reads its events, and a turn nobody reads holds no connection open: its view starts reading only once you use its events, `readable` or `result`. Stop it with `session.cancel()`, or with the `signal` you passed to `prompt()`.
|
|
58
|
-
- **Steering.** `session.steer(input)` steers the running turn the way the fx CLI does. While the model streams a reply, the steer cuts it short and the turn continues with it. While a tool runs, the steer waits for the tool. A steer sent while a turn waits to start joins that turn, and when no turn runs or waits, the steer becomes the next turn. A steer with images can't join a turn, so the running turn ends at its next safe point and the steer runs next.
|
|
58
|
+
- **Steering.** `session.steer(input)` steers the running turn the way the fx CLI does. While the model streams a reply, the steer cuts it short and the turn continues with it. While a tool runs, the steer waits for the tool. A steer sent while a turn waits to start joins that turn, and when no turn runs or waits, the steer becomes the next turn. A steer with images can't join a turn, so the running turn ends at its next safe point and the steer runs next. Its images are saved once with the session before the steer is sent, as a prompt's are, and a steer whose image can't be saved throws the store's error.
|
|
59
59
|
- **Retries are safe.** Give a prompt or a steer a `messageId`, and a repeated request with the same id runs nothing new. A repeated prompt follows the original turn, and its result has `repeated: true`. One id names one input, so a steer that reuses a prompt's id is rejected with `FX_MESSAGE_ID_IN_USE`. A steer's `user_message` event carries its id as `id` where it joined a turn.
|
|
60
60
|
- **Inputs have a size limit.** A prompt or steer whose input, with the session's `context` and settings, comes to more than 8 MiB of JSON is rejected with `FX_INPUT_TOO_LARGE` before anything is stored. The model can't take a larger one.
|
|
61
|
+
- **A refused prompt is never stored.** `prompt()` checks a prompt as the engine's `prompt()` does and throws a `TypeError` or `RangeError` for one libfx would refuse, such as an empty prompt, base64 that isn't canonical, an image whose bytes aren't its type, or more than 8 images. A prompt whose `signal` aborts before the prompt is stored isn't stored either, and its turn ends `cancelled`.
|
|
61
62
|
|
|
62
63
|
Each conversation can bring its own settings, which apply to the turns that session object starts:
|
|
63
64
|
|
|
@@ -326,6 +327,8 @@ const agent = createFxAgent({
|
|
|
326
327
|
});
|
|
327
328
|
```
|
|
328
329
|
|
|
330
|
+
Name a model the plan serves, here or in `agent.session(id, { model })`. fx's default model is an AI Gateway id, so libfx refuses a Codex engine or session without one.
|
|
331
|
+
|
|
329
332
|
libfx calls `credentials()` in whichever process runs the turn. It refreshes the credentials shortly before they expire and once after a rejected request, then passes the new ones to `onCredentials` for you to save. Codex doesn't accept requests from web pages, so these turns run on your server.
|
|
330
333
|
|
|
331
334
|
To sign a user in, use `libfx/chatgpt`:
|
|
@@ -346,7 +349,7 @@ The sign-in uses the same OpenAI client as the Codex CLI, and the user's ChatGPT
|
|
|
346
349
|
|
|
347
350
|
### Grok plans
|
|
348
351
|
|
|
349
|
-
`provider: "grok"` runs on a user's Grok plan, with the same `credentials` and `onCredentials` callbacks, called with `provider: "grok"`. libfx also checks that refreshed credentials still belong to the same xAI account. These turns run on your server too.
|
|
352
|
+
`provider: "grok"` runs on a user's Grok plan, with the same `credentials` and `onCredentials` callbacks, called with `provider: "grok"`. It needs a Grok model too, such as `model: "grok-4.7"`; the AI Gateway id `spacexai/grok-4.7` doesn't work on a Grok plan. libfx also checks that refreshed credentials still belong to the same xAI account. These turns run on your server too.
|
|
350
353
|
|
|
351
354
|
To sign a user in, use `libfx/grok`. Device code is the simplest:
|
|
352
355
|
|
|
@@ -407,7 +410,7 @@ agent.session().prompt([
|
|
|
407
410
|
]);
|
|
408
411
|
```
|
|
409
412
|
|
|
410
|
-
A session stores each prompt as JSON before it runs, so a session prompt takes image data as a base64 string. `createFxEngine()` also takes bytes, a `Blob` or a `File`. Each prompt takes up to 8 PNG, JPEG, GIF or WebP images, at most 3.75 MiB each and 6 MiB together. Pass `resizeImage` to downscale or convert prompt images before they're sent.
|
|
413
|
+
A session stores each prompt as JSON before it runs, so a session prompt takes image data as a base64 string. `createFxEngine()` also takes bytes, a `Blob` or a `File`. A session saves each image once, named by its SHA-256, before it stores the prompt, and the saved conversation refers to it by that name, so images don't count toward the 4 MiB the session's own checkpoints hold. Images a host tool returns are saved the same way; one that can't be saved stays in the tool's result, held inline. A session keeps its newest 4,096 images, up to 512 MiB of them; an older image leaves the conversation, and the model sees a note in its place. A checkpoint you take with `checkpoint()` carries the images' bytes, within its 4 MiB. An engine with a `persistence` store of its own keeps images inside its records and checkpoints, so they count toward that 4 MiB; for a conversation with many images, use a session with [durability](#durability). libfx never deletes a saved image; it lasts as long as the session's storage. Each prompt takes up to 8 PNG, JPEG, GIF or WebP images, at most 3.75 MiB each and 6 MiB together. Pass `resizeImage` to downscale or convert prompt images before they're sent.
|
|
411
414
|
|
|
412
415
|
## Diagnostics
|
|
413
416
|
|
|
@@ -436,7 +439,7 @@ const agent = createFxAgent({
|
|
|
436
439
|
|
|
437
440
|
`wait.start` and `wait.end` describe actual input requests separately from permission evaluation. Their `kind` is `approval`, `question`, `mcp_form`, or `mcp_url`; request IDs pair outcomes, including denial, cancellation, and failure. Native delegation events carry the child session and durable work ID. Child events retain that work ID, their own session/turn/execution identity, and the root and parent session IDs, so the host can join them even if delivery interleaves.
|
|
438
441
|
|
|
439
|
-
MCP events include the configured server, original remote tool name, and owning fx call ID. `mcp.request.data.requestIdKind` distinguishes a native JSON-RPC ID, an MCP
|
|
442
|
+
MCP events include the configured server, original remote tool name, and owning fx call ID. `mcp.request.data.requestIdKind` distinguishes a native JSON-RPC ID, an MCP engine handle, and an explicitly propagated host correlation token. Hooks don't change remote MCP requests by default: the host adapter emits `mcp.start` and `mcp.end` without adding metadata or emitting a request ID. Opt in with `createMcpAdapter(client, { propagateCorrelation: true })` to send an opaque UUID as `_meta["libfx/correlationId"]` and record it in `mcp.request`. It contains no internal execution/call IDs and doesn't request progress notifications. Give the adapter a `serverName` for a stable local identity; otherwise it uses the client's reported server name when available. Native resource/prompt operations also report their server and action.
|
|
440
443
|
|
|
441
444
|
`mcp.end.status` uses `success`, `failure`, `cancelled`, `input_required`, `unavailable`, or `unknown`. Native tool/protocol failures map to `failure`; `unavailable` means no operation result was available, and `unknown` means observation couldn't classify a returned host result.
|
|
442
445
|
|
|
@@ -498,9 +501,9 @@ interface JournalRecord {
|
|
|
498
501
|
}
|
|
499
502
|
```
|
|
500
503
|
|
|
501
|
-
Reject an `append()` whose `expected` isn't the last stored cursor with `FxFencedError`, so two processes can't write the same conversation. If your store keeps entries of its own after the last record, return the cursor the next `append()` should name as `head`. When a resumed turn left a tool call running, `resume({ onAmbiguous })` lets you return `"rerun"` to run it again under the same `executionId`.
|
|
504
|
+
Reject an `append()` whose `expected` isn't the last stored cursor with `FxFencedError`, so two processes can't write the same conversation. If your store keeps entries of its own after the last record, return the cursor the next `append()` should name as `head`. When a resumed turn left a tool call running, `resume({ onAmbiguous })` lets you return `"rerun"` to run it again under the same `executionId`. A resumed turn first sends, as `text_delta`, the reply the last process had started, since the new engine's host saw none of it. If that process stopped after the turn's final reply was stored but before the turn's end was, `resume()` then ends the turn with that reply instead of asking the model again.
|
|
502
505
|
|
|
503
|
-
The engine sends one `append()` at a time, and everything that happens while one is in flight goes in the next record. `barrier` is `true` when
|
|
506
|
+
The engine sends one `append()` at a time, and everything that happens while one is in flight goes in the next record. `barrier` is `true` when something waits for the record, such as a tool call with effects, or a turn's `result`, which resolves only once the record that ends the turn is stored and rejects if that record can't be stored. A store may acknowledge a record with `barrier: false` before it is durable, as long as it keeps records in order and acknowledges a barrier only once it and every record before it are durable. Set `marks: true` to receive each record's `marks`, which say where turns start (`{ start: turnId }`), yield and end, and which inputs a turn took (`{ accepted: id }`), so a store can track turns without reading records.
|
|
504
507
|
|
|
505
508
|
`prompt()` and `resume()` take `yieldAt`, a time in milliseconds since the epoch: the turn stops before its next model request after that time, with the stop reason `yielded`, and the next `resume()` continues it without telling the model it was interrupted.
|
|
506
509
|
|
|
@@ -510,15 +513,21 @@ A journal or `checkpoint` from a newer libfx fails with `FxJournalVersionError`.
|
|
|
510
513
|
|
|
511
514
|
| Runtime | Backend |
|
|
512
515
|
| --- | --- |
|
|
513
|
-
| Node.js 20
|
|
516
|
+
| Node.js 20.19, 22.12, or newer on macOS or Linux, x64 or arm64 | Native addon. Linux needs glibc 2.34 or newer. |
|
|
514
517
|
| Node.js elsewhere | WebAssembly with JSPI. Some Node versions need `--experimental-wasm-jspi`. |
|
|
515
518
|
| Browsers | WebAssembly with JSPI, from `libfx/browser` |
|
|
516
519
|
| Bun | The same as Node.js. For WebAssembly, use Bun 1.4.2 or newer. |
|
|
517
520
|
|
|
518
521
|
The default `backend: "auto"` tries the native addon first. Pass `"native"` or `"wasm"` to require one, and call `getBackendInfo()` to see what would load without creating anything.
|
|
519
522
|
|
|
523
|
+
Each platform's addon is its own package, such as `@libfx/libfx-linux-x64-gnu`, and npm installs only the one for your machine as an optional dependency of libfx. When it is missing, for example because optional dependencies were omitted or the lockfile came from another platform, `getBackendInfo()` names the package and `"auto"` uses WebAssembly instead. Node.js loads the WebAssembly backend only for that fallback.
|
|
524
|
+
|
|
520
525
|
Next.js works in Node.js route handlers, with webpack or Turbopack, and doesn't need `serverExternalPackages`. CommonJS apps can `require("libfx")`. With TypeScript's `moduleResolution: "bundler"`, add `"node"` to `customConditions` to get the Node.js types.
|
|
521
526
|
|
|
527
|
+
In a browser build, `createFxAgent` and `createFxEngine` load `fx-core.wasm`, and `createFxTerminal` loads `fx-term.wasm`. Importing `libfx/browser` does no work, so a client component that a server renders can import it. Next.js copies only the files an app's client code uses into the build. Vite 8 copies both unless you set `build.rolldownOptions.experimental.lazyBarrel` to `true`, though a browser still downloads only the file the app uses. esbuild copies neither, so serve the file yourself and pass its URL as `wasm`.
|
|
528
|
+
|
|
529
|
+
If a CDN serves the `.wasm` files, for example through Next.js's `assetPrefix`, it must send `Content-Type: application/wasm` so the browser can compile while it downloads. Otherwise libfx downloads the whole file before compiling it. When the files come from a different origin than the page, the response also needs CORS headers, such as `Access-Control-Allow-Origin`, or the browser blocks the request.
|
|
530
|
+
|
|
522
531
|
## The fx terminal in a browser
|
|
523
532
|
|
|
524
533
|
```js
|
package/browser-agent.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// The agent and engine for `libfx/browser`, with their packaged fx-core.wasm.
|
|
2
|
+
import { createDurableAgentFactory, memory } from "./durable.js";
|
|
3
|
+
import { createFxEngine as createEngine } from "./engine.js";
|
|
4
|
+
import { fxHarness } from "./fx-harness.js";
|
|
5
|
+
import { wasmRuntimeFactory } from "./wasm-runtime.js";
|
|
6
|
+
|
|
7
|
+
export const libfxApiVersion = 3;
|
|
8
|
+
|
|
9
|
+
/** One fx session on WebAssembly, with no durability of its own. */
|
|
10
|
+
export function createFxEngine(options = {}) {
|
|
11
|
+
// A literal URL, which bundlers rewrite to the fx-core.wasm they emit.
|
|
12
|
+
return createEngine({ ...options, wasm: options.wasm ?? new URL("./fx-core.wasm", import.meta.url).href }, wasmRuntimeFactory());
|
|
13
|
+
}
|
|
14
|
+
|
|
15
|
+
/** An agent whose sessions live in this page unless `durability` says otherwise. */
|
|
16
|
+
export const createFxAgent = /* @__PURE__ */ createDurableAgentFactory({
|
|
17
|
+
name: "createFxAgent",
|
|
18
|
+
label: "fx agent",
|
|
19
|
+
defaultDurability: async () => memory(),
|
|
20
|
+
harness: /* @__PURE__ */ fxHarness({ createEngine: createFxEngine }),
|
|
21
|
+
});
|
|
@@ -0,0 +1,7 @@
|
|
|
1
|
+
// The fx terminal for `libfx/browser`, with its packaged fx-term.wasm.
|
|
2
|
+
import { createFxTerminal as createWasmTerminal } from "./wasm-terminal.js";
|
|
3
|
+
|
|
4
|
+
export function createFxTerminal(options = {}) {
|
|
5
|
+
// A literal URL, which bundlers rewrite to the fx-term.wasm they emit.
|
|
6
|
+
return createWasmTerminal({ ...options, wasm: options.wasm ?? new URL("./fx-term.wasm", import.meta.url).href });
|
|
7
|
+
}
|
package/browser.js
CHANGED
|
@@ -1,37 +1,12 @@
|
|
|
1
|
-
|
|
2
|
-
|
|
3
|
-
|
|
4
|
-
|
|
5
|
-
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
|
|
12
|
-
|
|
13
|
-
xtermAdapter,
|
|
14
|
-
} from "./fx-sdk.js";
|
|
15
|
-
|
|
16
|
-
export { createMemoryPersistence, encodeXtermKeyEvent, FxFencedError, FxJournalVersionError, fxSdkApiVersion, listModels, memory, supportsJspi, xtermAdapter };
|
|
17
|
-
export const libfxApiVersion = 3;
|
|
18
|
-
|
|
19
|
-
const defaultCoreWasm = new URL("./fx-core.wasm", import.meta.url).href;
|
|
20
|
-
const defaultTermWasm = new URL("./fx-term.wasm", import.meta.url).href;
|
|
21
|
-
|
|
22
|
-
/** One fx session on WebAssembly, with no durability of its own. */
|
|
23
|
-
export function createFxEngine(options = {}) {
|
|
24
|
-
return createWasmAgent({ ...options, wasm: options.wasm ?? defaultCoreWasm });
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
/** An agent whose sessions live in this page unless `durability` says otherwise. */
|
|
28
|
-
export const createFxAgent = createDurableAgentFactory({
|
|
29
|
-
name: "createFxAgent",
|
|
30
|
-
label: "fx agent",
|
|
31
|
-
defaultDurability: async () => memory(),
|
|
32
|
-
harness: fxHarness({ createEngine: createFxEngine }),
|
|
33
|
-
});
|
|
34
|
-
|
|
35
|
-
export function createFxTerminal(options = {}) {
|
|
36
|
-
return createWasmTerminal({ ...options, wasm: options.wasm ?? defaultTermWasm });
|
|
37
|
-
}
|
|
1
|
+
// `libfx` in browsers, and `libfx/browser`. Importing it does no work: each
|
|
2
|
+
// factory names its WebAssembly module only when called, so a server can render
|
|
3
|
+
// a client component that imports it.
|
|
4
|
+
//
|
|
5
|
+
// This module only re-exports, and each .wasm is named in the module of the
|
|
6
|
+
// factory that loads it. A bundler that skips unused re-exports, such as
|
|
7
|
+
// Rolldown with lazy barrel optimization, then emits only the .wasm an app uses.
|
|
8
|
+
export { createFxAgent, createFxEngine, libfxApiVersion } from "./browser-agent.js";
|
|
9
|
+
export { createFxTerminal } from "./browser-terminal.js";
|
|
10
|
+
export { memory } from "./durable.js";
|
|
11
|
+
export { createMemoryPersistence, FxFencedError, FxJournalVersionError, fxSdkApiVersion, listModels, supportsJspi } from "./engine.js";
|
|
12
|
+
export { encodeXtermKeyEvent, xtermAdapter } from "./xterm.js";
|
package/bundled-asset.js
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
// webpack rewrites `new URL("./asset", import.meta.url)` in a bundled
|
|
2
|
+
// module to a relative URL object under its public path. This maps one back
|
|
3
|
+
// to the file webpack emitted, which Node can read or load.
|
|
4
|
+
export function bundledAssetUrl(asset) {
|
|
5
|
+
if (asset.protocol !== "" || typeof asset.href !== "string" ||
|
|
6
|
+
typeof __webpack_base_uri__ === "undefined" || typeof __webpack_public_path__ !== "string" ||
|
|
7
|
+
!asset.href.startsWith(__webpack_public_path__)) {
|
|
8
|
+
throw new TypeError("Bundled asset URL has no filesystem mapping");
|
|
9
|
+
}
|
|
10
|
+
// Webpack's relative URL is a public asset address, not a Node URL instance.
|
|
11
|
+
return new URL(asset.href.slice(__webpack_public_path__.length), __webpack_base_uri__);
|
|
12
|
+
}
|
package/durable/local.mjs
CHANGED
|
@@ -188,3 +188,6 @@ Caused by: ${t.cause.stack}`}static is(e){return vt(e)&&e.name==="WorkflowError"
|
|
|
188
188
|
`);for(let o of n){let A=o.trim().split(/\s+/);if(A.length<5||A[0]?.toUpperCase()!=="TCP")continue;let[,s,,i,a]=A;if(i?.toUpperCase()!=="LISTENING"||a!==t.toString())continue;let c=s.lastIndexOf(":");if(c===-1)continue;let u=HV(s.slice(c+1));if(u!==void 0)r.push(u)}return r}var WS=$V(YV);function zS(e,t=10){let r=parseInt(e,t);if(!Number.isNaN(r)&&r>=0&&r<=65535)return r;return}var JV=(e,t)=>e.join(t),Hd=JV(["","proc"],"/");async function WV(e){let r=[`${Hd}/net/tcp`,`${Hd}/net/tcp6`],n=[],o=new Set,A=`${Hd}/${e}/fd`;try{let c=(await VV(A)).sort((l,f)=>{let g=Number.parseInt(l,10),h=Number.parseInt(f,10);return g-h}),u=await Promise.allSettled(c.map(async(l)=>(await GV(`${A}/${l}`)).match(/^socket:\[(\d+)\]$/)?.[1]??null));for(let l of u)if(l.status==="fulfilled"&&l.value)n.push(l.value),o.add(l.value)}catch{return[]}if(n.length===0)return[];let s=new Map;for(let a of r)try{let u=(await PV(a,"utf8")).split(`
|
|
189
189
|
`).slice(1);for(let l of u){if(!l.trim())continue;let f=l.trim().split(/\s+/);if(f.length<10)continue;let g=f[1],h=f[3],d=f[9];if(!g||h!=="0A"||!d)continue;if(!o.has(d))continue;let I=g.indexOf(":");if(I===-1)continue;let C=g.slice(I+1);if(!C)continue;let p=zS(C,16);if(p!==void 0)s.set(d,p)}}catch{}let i=[];for(let a of n){let c=s.get(a);if(c!==void 0)i.push(c)}return i}async function zV(e){try{let{stdout:t}=await WS("lsof",["-a","-i","-P","-n","-p",e.toString()]),r=[],n=t.split(`
|
|
190
190
|
`);for(let o of n)if(o.includes("LISTEN")){let s=o.trim().split(/\s+/)[8];if(s){let i=s.lastIndexOf(":");if(i!==-1){let a=zS(s.slice(i+1));if(a!==void 0)r.push(a)}}}return r}catch{return[]}}async function qV(e){try{let{stdout:t}=await WS("cmd",["/c","netstat -ano -p tcp | findstr LISTENING"]);return JS(t,e)}catch{return[]}}async function ZV(){let{pid:e,platform:t}=process;try{switch(t){case"linux":return await WV(e);case"darwin":return await zV(e);case"win32":return await qV(e);default:return[]}}catch(r){return Fs("[getAllPorts] Detection failed:",r),[]}}var jV=500,KV=`${Fd}/flow?__health`;async function XV(e,t={}){let{endpoint:r=KV,timeout:n=jV}=t,o=new AbortController,A=setTimeout(()=>o.abort(),n);try{return(await fetch(`http://localhost:${e}${r}`,{method:"HEAD",signal:o.signal})).status===200}catch{return!1}finally{clearTimeout(A)}}async function qS(e){let t=await ZV();if(t.length===0)return;if(t.length===1)return t[0];let n=(await Promise.all(t.map(async(o)=>({port:o,isWorkflow:await XV(o,e)})))).find((o)=>o.isWorkflow);if(n)return n.port;return Fs("[getWorkflowPort] Probing failed, falling back to first port:",t[0]),t[0]}function ZS(e){let t={get value(){let r=e();return Object.defineProperty(t,"value",{value:r}),r}};return t}function vs(e,t,r){let n=e.get(t),o={},A=(async()=>{if(n)await n.catch(()=>{return});try{return await r()}finally{if(e.get(t)===o.task)e.delete(t)}})();return o.task=A,e.set(t,A),A}var eP=()=>process.env.WORKFLOW_LOCAL_DATA_DIR||".workflow-data",Bt="all",tP=()=>process.env.WORKFLOW_LOCAL_BASE_URL,jS=ZS(()=>{let e=eP(),t=tP();return{dataDir:e,baseUrl:t}});function KS(e){if(e.recoverActiveRuns!==void 0)return e.recoverActiveRuns;let t=process.env.WORKFLOW_LOCAL_RECOVER_ACTIVE_RUNS?.toLowerCase();if(t==="0"||t==="false")return!1;if(t==="1"||t==="true")return!0;return!0}function XS(e){return e.baseUrl??process.env.WORKFLOW_LOCAL_BASE_URL??Ls("http://localhost")}async function e0(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 Ls(`http://localhost:${e.port}`);if(process.env.PORT)return Ls(`http://localhost:${process.env.PORT}`);let t=await qS({endpoint:_d()});if(t)return Ls(`http://localhost:${t}`);throw Error("Unable to resolve base URL for workflow queue.")}import{promises as mt}from"node:fs";import yt from"node:path";xs();pt();Lt();var En=Qt("@workflow/world-local//fs",1,()=>({ulid:ho(()=>Math.random()),createdFilesCache:new Set,createdDirectoriesCache:new Set}));function rP(e){let t=typeof e==="string"?e:String(e),r=48;return t.length>48?`${t.slice(0,48)}…`:t}class Os extends We{constructor(e,t){super(`Unsafe ${e} "${rP(t)}": must not be empty, contain ".", "/", "\\", or null bytes`);this.name="UnsafeEntityIdError"}static is(e){return e instanceof Error&&e.name==="UnsafeEntityIdError"}}function de(e,t){if(t.length===0||t.startsWith(".")||t.includes("/")||t.includes("\\")||t.includes("\x00")||t.includes("."))throw new Os(e,t)}function ze(e,...t){let r=yt.resolve(e),n=yt.resolve(e,...t);if(n!==r&&!n.startsWith(r+yt.sep))throw new Os("path",t.join("/"));return n}var nP=process.platform==="win32";async function on(e,t=5){if(!nP)return e();let r=["EPERM","EBUSY","EACCES"],n=10;for(let o=0;o<=t;o++)try{return await e()}catch(A){if(!(o<t&&r.includes(A.code)))throw A;let i=n*2**o+Math.random()*n;await new Promise((a)=>setTimeout(a,i))}throw Error("Retry loop exited unexpectedly")}async function An(e){let t=await Promise.allSettled(e),r=t.find((n)=>n.status==="rejected");if(r)throw r.reason;return t.map((n)=>n.value)}function ba(){En.createdFilesCache.clear(),En.createdDirectoriesCache.clear()}var t0=/\.[a-zA-Z][a-zA-Z0-9-]*$/;function In(e){return e.replace(t0,"")}function Hs(e,t){return e.endsWith(`.${t}`)}function EA(e){return!t0.test(e)}function pe(e,t,r,n){if(de("fileId",r),n!==void 0)de("tag",n);let o=n?`${r}.${n}.json`:`${r}.json`;return ze(e,t,o)}var Yd=["events","steps"];function Qe(e,t){return de("runId",t),yt.join(e,t)}async function Me(e,t,r,n,o){if(de("fileId",r),o!==void 0)de("tag",o);if(o){let A=await $e(ze(e,t,`${r}.${o}.json`),n);if(A!==null)return A}return $e(ze(e,t,`${r}.json`),n)}async function Ta(e,t){let r=`.${t}.json`;try{return await Mr(e),(await mt.readdir(e)).filter((o)=>o.endsWith(r))}catch(n){if(n.code==="ENOENT")return[];throw n}}async function r0(e,t,r){let n=`.${t}${r}`;try{return await Mr(e),(await mt.readdir(e)).filter((A)=>A.endsWith(n))}catch(o){if(o.code==="ENOENT")return[];throw o}}async function rl(e){let t=yt.resolve(e);if(En.createdDirectoriesCache.has(t)){await Mr(t);return}let r;try{await mt.mkdir(t,{recursive:!0})}catch(n){r=n;let o=n.code;if(GS(o)&&!await oP(t))throw new tl(t,o)}if(r!==void 0){await Mr(t);return}await Mr(t),En.createdDirectoriesCache.add(t)}class n0 extends We{constructor(e){super(`Refusing to use symlinked run directory ${e}: replace it with a real directory.`);this.name="SymlinkedRunDirError"}}async function Mr(e){let t=yt.basename(yt.dirname(e));if(!Yd.includes(t))return;let r;try{r=await mt.lstat(e)}catch(n){if(n.code==="ENOENT")return;throw n}if(r.isSymbolicLink())throw new n0(e)}async function oP(e){try{return(await mt.stat(e)).isDirectory()}catch{return!1}}async function Vd(e,t){await rl(e);try{return await t()}catch(r){if(r.code!=="ENOENT")throw r;return En.createdDirectoriesCache.delete(yt.resolve(e)),await rl(e),t()}}function qt(e,t){if(t instanceof Uint8Array)return{__type:"Uint8Array",data:Buffer.from(t).toString("base64")};return t}function xa(e,t){if(t!==null&&typeof t==="object"&&t.__type==="Uint8Array"&&typeof t.data==="string")return new Uint8Array(Buffer.from(t.data,"base64"));return t}async function Ke(e,t,r){return _r(e,JSON.stringify(t,qt,2),r)}async function _r(e,t,r){if(!r?.overwrite){if(En.createdFilesCache.has(e))throw new Ge(`File ${e} already exists and 'overwrite' is false`);try{throw await mt.access(e),En.createdFilesCache.add(e),new Ge(`File ${e} already exists and 'overwrite' is false`)}catch(A){if(A.code!=="ENOENT")throw A}}let n=`${e}.tmp.${En.ulid()}`,o=!1;try{await Vd(yt.dirname(e),async()=>{await mt.writeFile(n,t),o=!0,await on(()=>mt.rename(n,e))}),En.createdFilesCache.add(e)}catch(A){if(o)await on(()=>mt.unlink(n),3).catch(()=>{});throw A}}async function $e(e,t){await Mr(yt.dirname(e));try{let r=await on(()=>mt.readFile(e,"utf-8"));return t.parse(JSON.parse(r,xa))}catch(r){if(r.code==="ENOENT")return null;throw r}}async function Ys(e){return await Mr(yt.dirname(e)),await mt.readFile(e)}async function Fa(e){await Mr(yt.dirname(e));let t=await mt.open(e,"r");try{let r=Buffer.allocUnsafe(1),{bytesRead:n}=await t.read(r,0,1,0);return n===0?void 0:r[0]}finally{await t.close()}}async function rt(e){await Mr(yt.dirname(e));try{await on(()=>mt.unlink(e))}catch(t){if(t.code!=="ENOENT")throw t}}async function ke(e,t){let r=`${e}.tmp.${En.ulid()}`,n=!1;try{return await Vd(yt.dirname(e),async()=>{await mt.writeFile(r,t,{flag:"wx"}),n=!0;try{return await on(()=>mt.link(r,e)),!0}catch(o){if(o.code==="EEXIST")return!1;throw o}})}finally{if(n)await on(()=>mt.unlink(r),3).catch(()=>{})}}async function nl(e,t){try{return await Vd(yt.dirname(t),()=>on(()=>mt.link(e,t))),"linked"}catch(r){if(r.code==="EEXIST")return"exists";if(r.code==="ENOENT")return"missing";throw r}}async function Lr(e){return AP(e,".json")}async function AP(e,t){try{return await Mr(e),(await mt.readdir(e)).filter((n)=>n.endsWith(t)).map((n)=>n.slice(0,-t.length))}catch(r){if(r.code==="ENOENT")return[];throw r}}async function o0(e,t){let r=yt.join(e,t),n;try{n=await mt.readdir(r,{withFileTypes:!0})}catch(o){if(o.code==="ENOENT")return[];throw o}return n.filter((o)=>o.isDirectory()).map((o)=>yt.join(r,o.name))}var ka="key:";function sP(e){if(!e)return null;if(e.startsWith(ka))return{timestamp:new Date(0),id:null,sortKey:e.slice(ka.length)};let t=e.split("|");return{timestamp:new Date(t[0]),id:t[1]||null,sortKey:null}}function iP(e,t,r){if(r)return`${ka}${r}`;return t?`${e.toISOString()}|${t}`:e.toISOString()}async function pn(e){let{directory:t,schema:r,cachedItems:n,filePrefix:o,fileIdFilter:A,filter:s,sortOrder:i="desc",limit:a=20,cursor:c,getCreatedAt:u,getId:l,getSortKey:f,getSortKeyFromFileId:g}=e;if(o!==void 0)de("filePrefix",o);let h=yt.resolve(t),d=await Lr(h),I=o?d.filter((y)=>y.startsWith(o)):d,C=A?I.filter(A):I,p=sP(c),Q=C;if(p?.sortKey&&g){let y=p.sortKey;Q=C.filter((M)=>{let U=g(M);if(U===null)return!0;let v=U.localeCompare(y);return i==="desc"?v<0:v>0})}else if(p&&!p.sortKey)Q=C.filter((y)=>{let M=u(`${y}.json`);if(M){let U=p.timestamp.getTime(),v=M.getTime();if(p.id)return i==="desc"?v<=U:v>=U;else return i==="desc"?v<U:v>U}return!0});let D=32,S=[];for(let y=0;y<Q.length;y+=D){let M=Q.slice(y,y+D),U=await Promise.all(M.map(async(v)=>{let te=yt.join(h,`${v}.json`),q;try{let G=n?.get(te);q=G===void 0?await $e(te,r):structuredClone(G)}catch(G){if(G instanceof uo)return console.warn(`Skipping item ${v} due to malformed JSON: ${G.message}`),null;throw G}return q&&s&&!await s(q)?null:q}));for(let v of U){if(!v)continue;let te=f?.(v)??null;if(p?.sortKey){if(te){let q=te.localeCompare(p.sortKey);if(i==="desc"?q>=0:q<=0)continue}S.push(v);continue}if(p){let q=v.createdAt.getTime(),G=p.timestamp.getTime();if(i==="desc"){if(q>G)continue;if(q===G&&p.id&&l){if(l(v)>=p.id)continue}}else{if(q<G)continue;if(q===G&&p.id&&l){if(l(v)<=p.id)continue}}}S.push(v)}}S.sort((y,M)=>{if(f){let q=f(y),G=f(M);if(q!==null&&G!==null)return i==="asc"?q.localeCompare(G):G.localeCompare(q)}let U=y.createdAt.getTime(),v=M.createdAt.getTime(),te=i==="asc"?U-v:v-U;if(te===0&&l){let q=l(y),G=l(M);return i==="asc"?q.localeCompare(G):G.localeCompare(q)}return te});let x=S.length>a,H=x?S.slice(0,a):S,L=H.length>0?iP(H[H.length-1].createdAt,l?.(H[H.length-1]),f?.(H[H.length-1])):null;return{data:H,cursor:L,hasMore:x}}import{access as r1,constants as n1,mkdir as o1,opendir as A1,readFile as O0,rm as s1,unlink as i1,writeFile as H0}from"node:fs/promises";import Or from"node:path";import{fileURLToPath as a1}from"node:url";import ZP from"node:fs/promises";import sn from"node:path";Lt();pt();import{createHash as sE}from"node:crypto";import Bo from"node:fs/promises";import mA from"node:path";Lt();xs();pt();var b0=zi(dl(),1);function Oa(e){return sE("sha256").update(e).digest("hex")}function BA(e,t,r){let n=r?`${t}.disposed.${r}`:`${t}.disposed`;return ze(e,".locks","hooks",n)}async function Ha(e,t,r){let n=[BA(e,t)];if(r)n.push(BA(e,t,r));for(let o of n){let A;try{A=await Bo.readFile(o,"utf8")}catch{continue}if(A.trim()==="")return{committed:!0};try{let i=JSON.parse(A).forceClaimedBy;if(i&&typeof i.runId==="string"&&typeof i.hookId==="string")return{committed:!0,forceClaimedBy:{runId:i.runId,hookId:i.hookId}}}catch{}return{committed:!0}}return{committed:!1}}async function Ya(e,t,r){let n=[BA(e,t)];if(r)n.push(BA(e,t,r));for(let o of n)try{return await Bo.access(o),!0}catch{}return!1}function Js(e,t,r){let n=r?`${t}.terminal.${r}`:`${t}.terminal`;return ze(e,".locks","runs",n)}async function Ws(e,t,r){let n=[Js(e,t)];if(r)n.push(Js(e,t,r));for(let o of n)try{return await Bo.access(o),!0}catch(A){if(A.code!=="ENOENT")throw A}return!1}function AE(e,t,r){let n=r?`${t}.pending.${r}`:`${t}.pending`;return ze(e,".locks","runs",n)}function El(e,t,r,n){return mA.join(AE(e,t,n),`${r}.json`)}async function Il(e,t,r){let n=[AE(e,t)];if(r)n.push(AE(e,t,r));for(let o of n){let A;try{A=await Bo.readdir(o)}catch(s){if(s.code==="ENOENT")continue;throw s}for(let s of A)try{await on(()=>Bo.unlink(mA.join(o,s)))}catch(i){if(i.code!=="ENOENT")throw i}await Bo.rmdir(o).catch(()=>{})}}async function T0(e,t,r){let n=await zs(e,t,r),o=Date.now();if(n.maxId)try{let A=ju(n.maxId.replace(/^evnt_/,""));if(o<=A)o=A+1}catch{}return{eventId:`evnt_${wA(o)}`,createdAt:new Date(o)}}async function zs(e,t,r){let n=[];try{let u=mA.join(e,Qe("events",t));await Mr(u),n=await Bo.readdir(u)}catch(u){if(u.code!=="ENOENT")throw u}let o=`${t}-`,A=[],s=null,i=0,a=!1,c=0;for(let u of n){if(!u.startsWith(o)||!u.endsWith(".json"))continue;let l=u.slice(0,-5);if(!EA(l)&&!(r&&Hs(l,r)))continue;let f=In(l).slice(o.length);if(c+=1,A.push(f),!s||f>s)s=f;let g=fo(f);if(g!==null){if(a=!0,g>i)i=g}}return{maxId:s,usesSlots:a,maxSlot:i,count:c,ids:A}}function yA(e,t){return mA.join(e,"hooks","tokens",`${Oa(t)}.json`)}var zP=z(W({hookId:m().optional(),runId:m(),eventId:m().optional(),tokenRetentionUntil:Ce.date().optional(),claimedFrom:W({runId:m(),hookId:m(),workflowName:m().optional(),deploymentId:m().optional(),runSpecVersion:ie().optional()}).optional()}));async function qs(e){try{return await $e(e,zP)}catch(t){if(t instanceof SyntaxError||t instanceof uo)return null;throw t}}async function iE(e,t,r){let n=yA(e,t);await Bo.mkdir(mA.dirname(n),{recursive:!0});let o=new AbortController,A;try{A=await b0.lock(n,{realpath:!1,stale:30000,update:1000,retries:{retries:350,factor:1,minTimeout:100,maxTimeout:100},onCompromised(i){o.abort(new We("Hook token claim lock was compromised",{cause:i}))}})}catch(i){throw new We("Could not acquire Hook token claim lock",{cause:i})}let s;try{s=await r(o.signal),o.signal.throwIfAborted()}catch(i){if(!o.signal.aborted)await A().catch(()=>{});throw i}try{await A()}catch(i){throw new We("Could not release Hook token claim lock",{cause:i})}return s}function pl(e,t,r){let n=sE("sha256").update(`${t}\x00${r}`).digest("hex");return mA.join(e,"hooks","resumes",`${n}.json`)}async function Cl(e,t,r,n){await iE(e,t,async(o)=>{let A=yA(e,t),s=await qs(A);if(!s)return;if(s.runId===r&&s.hookId===n)o.throwIfAborted(),await rt(A)})}function mo(e,t,r,n){let o=sE("sha256").update(`${t}\x00${r}\x00${n}`).digest("hex");return mA.join(e,"hooks","tokens",`${o}.recovery.json`)}var qP=Qt("@workflow/world-local//storageMonotonicUlid",1,()=>({next:ho(()=>Math.random())})),wA=(e)=>qP.next(e),yo=(e)=>{let t=new RegExp(`^${e}_`,"g");return(r)=>{let n=In(r.replace(/\.json$/,""))+".json",o=n.indexOf("-");if(o===-1){let i=n.replace(/\.json$/,"").replace(t,"");return Eo(i)}if(e==="step")return null;let s=n.substring(o+1).replace(/\.json$/,"").replace(t,"");return Eo(s)}};var jP=z(W({runId:m()})),KP=z(W({hookId:m(),tag:m().optional()})),XP=".hook-index-complete";function x0(e,t){return ze(e,"hooks","token-index",Oa(t))}function F0(e,t){return de("hookId",t),ze(e,"hooks","id-index",t)}function U0(e){return ze(e,"hooks","by-run")}function cE(e){let t=In(e);return t===e?void 0:e.slice(t.length+1)}function e1(e,t){return t?EA(e)||Hs(e,t):EA(e)}async function M0(e){try{return await $e(e,pa)}catch(t){if(t instanceof SyntaxError||t instanceof uo)return null;throw t}}async function Bl(e,t,r,n,o,A){if(de("runId",r),de("eventId",o),A!==void 0)de("tag",A);let s=A?`${r}-${o}.${A}.json`:`${r}-${o}.json`,i=JSON.stringify({runId:r});await Promise.all([ke(sn.join(x0(e,t),s),i),ke(sn.join(F0(e,n),s),i)])}function uE(e,t,r,n){return pe(e,"hooks/by-run",`${t}-${r}`,n)}async function DA(e,t,r,n){await ke(uE(e,t,r,n),JSON.stringify(n?{hookId:r,tag:n}:{hookId:r}))}async function lE(e,t,r,n){if(await rt(uE(e,t,r,n)),n)await rt(uE(e,t,r))}async function ml(e,t){de("runId",t);let r=U0(e),n=`${t}-`,o=[];for(let A of await Lr(r)){if(!A.startsWith(n))continue;let s=null;try{s=await $e(sn.join(r,`${A}.json`),KP)}catch(i){if(!(i instanceof SyntaxError||i instanceof uo))throw i}o.push({fileId:A,hookId:s?.hookId??null,tag:s?.tag})}return o}async function _0(e,t){await rt(sn.join(U0(e),`${t}.json`))}var Ql=Qt("@workflow/world-local//hookIndexEnsureCache",1,()=>({ensuredBasedirs:new Map}));function yl(){Ql.ensuredBasedirs.clear()}async function Va(e){let t=sn.resolve(e),r=Ql.ensuredBasedirs.get(t);if(!r)r=t1(t).catch((n)=>{throw Ql.ensuredBasedirs.delete(t),n}),Ql.ensuredBasedirs.set(t,r);return r}async function aE(e,t,r){for(let n=0;n<e.length;n+=t)await Promise.all(e.slice(n,n+t).map(r))}async function t1(e){let t=sn.join(e,"hooks",XP);try{await ZP.access(t);return}catch{}let r=async(o)=>{let A=sn.basename(o,".json"),s=await M0(o);if(!s||s.eventType!=="hook_created")return;if(typeof s.correlationId!=="string")return;let i=s.eventData?.token;if(typeof i!=="string")return;try{await Bl(e,i,s.runId,s.correlationId,s.eventId,cE(A))}catch{}};await aE(await o0(e,"events"),8,async(o)=>aE(await Lr(o),32,(A)=>r(sn.join(o,`${A}.json`))));let n=sn.join(e,"hooks");await aE(await Lr(n),32,async(o)=>{let A=null;try{A=await $e(sn.join(n,`${o}.json`),zt)}catch(s){if(!(s instanceof SyntaxError||s instanceof uo))throw s}if(!A)return;try{await DA(e,A.runId,A.hookId,cE(o))}catch{}}),await ke(t,"")}async function L0(e,t,r,n){await Va(e);let o;try{o=t.kind==="token"?x0(e,t.token):F0(e,t.hookId)}catch{return null}let A=(i,a)=>{let c=In(i);return c.startsWith(`${a}-`)?c.slice(a.length+1):c},s=(await Lr(o)).filter((i)=>e1(i,n)).sort((i,a)=>In(a).localeCompare(In(i)));for(let i of s){let a=null;try{a=await $e(sn.join(o,`${i}.json`),jP)}catch(f){if(!(f instanceof SyntaxError||f instanceof uo))throw f}if(!a)continue;let c=A(i,a.runId),u;try{u=pe(e,Qe("events",a.runId),`${a.runId}-${c}`,cE(i))}catch{continue}let l=await M0(u);if(!l)continue;if(l.eventType!=="hook_created")continue;if(typeof l.correlationId!=="string")continue;if(!await r(l))continue;return l}return null}var gE="@workflow/world-local",Zs=Qt("@workflow/world-local//packageInfo",1,()=>({cached:null}));function c1(){if(typeof import.meta.url==="string"&&import.meta.url)return Or.dirname(a1(import.meta.url));return null}async function wl(){return{name:"@workflow/world-local",version:"5.1.1"}}var Y0="version.txt";class Pa extends Error{dataDir;code;constructor(e,t,r){super(e);this.name="DataDirAccessError",this.dataDir=t,this.code=r}}class hE extends Error{oldVersion;newVersion;suggestedVersion;constructor(e,t,r,n){super(e);this.name="DataDirVersionError",this.oldVersion=t,this.newVersion=r,this.suggestedVersion=n}}function dE(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 wo(e){let t=`${e.major}.${e.minor}.${e.patch}`;return e.prerelease?`${t}-${e.prerelease}`:t}function u1(e){let t=e.trim(),r=t.lastIndexOf("@");if(r<=0)throw Error(`Invalid version file content: "${e}"`);let n=t.substring(0,r),o=t.substring(r+1);return{packageName:n,version:dE(o)}}function l1(e,t){return`${e}@${wo(t)}`}function f1(e,t){console.warn(`[world-local] Upgrading from version ${wo(e)} to ${wo(t)}`)}async function fE(e){let t=Or.resolve(e);try{await o1(t,{recursive:!0})}catch(n){let o=n;if(o.code!=="EEXIST")throw new Pa(`Failed to create data directory "${t}": ${o.message}`,t,o.code)}try{await r1(t,n1.R_OK)}catch(n){let o=n;throw new Pa(`Data directory "${t}" is not readable: ${o.message}`,t,o.code)}let r=Or.join(t,`.workflow-write-test-${Date.now()}`);try{await H0(r,""),await i1(r).catch((n)=>{if(n.code!=="ENOENT")throw n})}catch(n){let o=n;throw new Pa(`Data directory "${t}" is not writable: ${o.message}`,t,o.code)}}async function g1(e){let t=Or.join(Or.resolve(e),Y0);try{let r=await O0(t,"utf-8");return u1(r)}catch(r){if(r.code==="ENOENT")return null;throw r}}async function v0(e,t){let r=Or.join(Or.resolve(e),Y0),n=await wl(),o=l1(n.name,t);await H0(r,o)}var h1=/^wrun_[0-9A-Za-z]+-[^/\\]+\.json$/;function d1(e,t,r){if(r.isDirectory()){e.runScoped=!0;return}if(!r.name.endsWith(".json"))return;let n=Or.join(t,r.name);if(r.isFile()&&h1.test(r.name))e.flat.push(n);else e.unrecognized.push(n)}async function E1(e){let t={flat:[],unrecognized:[],runScoped:!1};for(let r of Yd)try{for await(let n of await A1(Or.join(e,r)))d1(t,r,n)}catch(n){if(n.code==="ENOENT")continue;throw n}return t}class EE extends Error{dataDir;files;constructor(e,t){let r=t.slice(0,5).join(", ");super(`[world-local] ${Or.resolve(e)} holds ${t.length} event/step file(s) this version does not read (${r}${t.length>5?", …":""}). If an older version of ${gE} is using this directory, stop it. Then delete the directory, or move or remove those files.`);this.dataDir=e,this.files=t,this.name="DataDirLayoutError"}}function I1(e,t){if(t)return t;return wo(e)}async function Dl(e){await fE(e);let t=await E1(e);if(t.unrecognized.length>0||t.runScoped&&t.flat.length>0)throw new EE(e,[...t.unrecognized,...t.flat]);if(t.flat.length>0)console.warn(`[world-local] Deleting local workflow data in "${Or.resolve(e)}": it was written by an older version of ${gE} with an incompatible storage layout.`),ba(),yl(),await s1(e,{recursive:!0,force:!0,maxRetries:3}),await fE(e);let r=await wl(),n=dE(r.version),o=await g1(e);if(o===null){await v0(e,n);return}let{version:A}=o;if(wo(A)===wo(n))return;try{f1(A,n),await v0(e,n)}catch(s){let i=s instanceof hE?s.suggestedVersion:void 0,a=I1(A,i);throw console.error(`[world-local] Failed to upgrade data directory from version ${wo(A)} to ${wo(n)}:`,s instanceof Error?s.message:s),console.error(`[world-local] Data is not compatible with the current version. Please downgrade to ${r.name}@${a}`),s}}var js=Qt("@workflow/world-local//telemetry",1,()=>({apiPromise:null,tracerPromise:null}));async function IE(){if(!js.apiPromise)js.apiPromise=import("@opentelemetry/api").catch(()=>null);return js.apiPromise}async function p1(){if(!js.tracerPromise)js.tracerPromise=IE().then((e)=>e?e.trace.getTracer("workflow"):null);return js.tracerPromise}async function V0(e,...t){let[r,n]=await Promise.all([p1(),IE()]),{fn:o,opts:A}=typeof t[0]==="function"?{fn:t[0],opts:{}}:{fn:t[1],opts:t[0]};if(!o)throw Error("Function to trace must be provided");if(!r||!n)return await o();return r.startActiveSpan(e,A,async(s)=>{try{let i=await o(s);return s.setStatus({code:n.SpanStatusCode.OK}),i}catch(i){throw s.setStatus({code:n.SpanStatusCode.ERROR,message:i.message}),i}finally{s.end()}})}async function P0(e){let t=await IE();if(!t)return;return t.SpanKind[e]}function Ks(...e){return(t)=>Object.fromEntries(e.map((r)=>[r,t]))}var G0=Ks("peer.service"),$0=Ks("rpc.system"),J0=Ks("rpc.service"),W0=Ks("rpc.method"),pE=Ks("workflow.run.id"),z0=Ks("step.id");var CE={peerService:"world-local",rpcSystem:"local",rpcService:"world-local"},C1={"world.runs.get":0,"world.runs.experimentalSetAttributes":0,"world.steps.get":0,"world.events.create":0,"world.events.get":0},Q1=new Set(["world.steps.list","world.events.list","world.hooks.list"]);function B1(e){if(e.length>=2&&typeof e[1]==="object"&&e[1]!==null){let t=e[1];if(typeof t.eventType==="string")return t.eventType}return}function q0(e,t){return typeof e[t]==="string"?e[t]:void 0}function m1(e){if(typeof e!=="object"||e===null)return;let t=e.runId;return typeof t==="string"?t:void 0}function y1(e){if(typeof e!=="object"||e===null)return;let t=e;if(typeof t.runId==="string")return t.runId;for(let r of["run","step","hook","wait"]){let n=t[r];if(typeof n==="object"&&n!==null){let o=n.runId;if(typeof o==="string")return o}}return}function w1(e,t,r){let n=`${e}.${t}`,o={},A=C1[n],s=A===void 0?Q1.has(n)?m1(r[0]):void 0:q0(r,A);if(s)Object.assign(o,pE(s));if(n==="world.steps.get"){let i=q0(r,1);if(i)Object.assign(o,z0(i))}return o}function Do(e,t){let r={};for(let n of Object.keys(t))if(typeof t[n]!=="function")r[n]=t[n];else{let o=t[n],A=String(n);r[n]=async(...s)=>{let i=`${e}.${A}`;if(e==="world.events"&&A==="create"){let a=B1(s);if(a)i=`${e}.${A} ${a}`}return V0(i,{kind:await P0("INTERNAL")},async(a)=>{a?.setAttributes({...G0(CE.peerService),...$0(CE.rpcSystem),...J0(CE.rpcService),...W0(i),...w1(e,A,s)});let c=await o(...s),u=y1(c);if(u)a?.setAttributes(pE(u));return c})}}return r}import{setTimeout as ig}from"node:timers/promises";Lt();import{Buffer as Z0}from"node:buffer";import K0 from"node:http";import X0 from"node:https";import{Transform as D1}from"node:stream";import So from"node:zlib";function eN(e){let t={keepAlive:!0,keepAliveMsecs:e.keepAliveMs,maxSockets:e.maxSockets};return{http:new K0.Agent(t),https:new X0.Agent(t)}}function tN(e){e.http.destroy(),e.https.destroy()}var S1=new Set([204,205,304]),N1="gzip, deflate, br",j0="ETIMEDOUT";function Ga(e,t){return Object.assign(Error(e),{code:t})}function R1(e){let t={};return e?.forEach((r,n)=>{t[n]=r}),t}function k1(e){let t=new Headers;for(let[r,n]of Object.entries(e.headers)){if(n===void 0)continue;if(Array.isArray(n))for(let o of n)t.append(r,o);else t.append(r,n)}return t}var QE={flush:So.constants.Z_SYNC_FLUSH,finishFlush:So.constants.Z_SYNC_FLUSH},b1={flush:So.constants.BROTLI_OPERATION_FLUSH,finishFlush:So.constants.BROTLI_OPERATION_FLUSH};class rN extends D1{inner;_transform(e,t,r){if(!this.inner){if(e.length===0){r();return}let n=(e[0]&15)===8?So.createInflate(QE):So.createInflateRaw(QE);n.on("data",(o)=>this.push(o)),n.on("end",()=>this.push(null)),n.on("error",(o)=>this.destroy(o)),this.inner=n}this.inner.write(e,r)}_final(e){if(this.inner)this.inner.end();else this.push(null);e()}_destroy(e,t){this.inner?.destroy(),t(e)}}function T1(e){let t=e.headers["content-encoding"]?.toLowerCase().trim();if(!t||t==="identity")return e;let r;if(t==="gzip"||t==="x-gzip")r=So.createGunzip(QE);else if(t==="deflate")r=new rN;else if(t==="br")r=So.createBrotliDecompress(b1);else return e;return e.on("error",(n)=>r.destroy(n)),e.on("close",()=>{if(e.complete)return;r.destroy(Ga("socket hang up","ECONNRESET"))}),r.on("close",()=>{if(!e.complete)e.destroy()}),e.pipe(r)}function x1(e,t){let r=!1,n=(o)=>{if(r)return;r=!0,t.done(),o()};return new ReadableStream({start(o){e.on("data",(A)=>{if(t.progress(),o.enqueue(new Uint8Array(A)),(o.desiredSize??1)<=0)e.pause()}),e.on("end",()=>n(()=>o.close())),e.on("error",(A)=>n(()=>o.error(t.failure(A)))),e.on("close",()=>n(()=>o.error(t.failure())))},pull(){e.resume()},cancel(o){n(()=>{}),e.destroy?.(o instanceof Error?o:void 0)}})}function nN(e,t={}){let{method:r="GET",headers:n,body:o,signal:A,agents:s,headersTimeoutMs:i,bodyTimeoutMs:a}=t,c=new URL(e),u=c.protocol==="https:";if(!u&&c.protocol!=="http:")return Promise.reject(TypeError(`node:http transport cannot request ${c.protocol}// URLs`));let l=R1(n),f=o==null?void 0:typeof o==="string"?Z0.from(o,"utf8"):Z0.from(o.buffer,o.byteOffset,o.byteLength);if(f)l["content-length"]=String(f.byteLength);if(!("accept-encoding"in l))l["accept-encoding"]=N1;return new Promise((g,h)=>{if(A?.aborted){h(A.reason);return}let d=!1,I,C,p,Q=()=>{clearTimeout(I),clearTimeout(C),I=void 0,C=void 0},D=(u?X0:K0).request(c,{method:r,headers:l,agent:s?u?s.https:s.http:void 0}),S=()=>{if(A?.reason instanceof Error)p=A.reason;D.destroy(A?.reason)};A?.addEventListener("abort",S,{once:!0});let x=()=>{A?.removeEventListener("abort",S)},H=(L)=>{if(Q(),x(),d)return;d=!0,h(L)};if(i)D.on("socket",()=>{I=setTimeout(()=>{D.destroy(Ga(`no response headers within ${i}ms`,j0))},i)});if(D.on("error",H),D.on("response",(L)=>{clearTimeout(I),I=void 0;let y=L.statusCode??0;if(y<200||y>599){D.destroy(),H(Ga(`origin returned an unusable status line (${y})`,"UNSUPPORTED_STATUS"));return}let M=k1(L),U=L.statusMessage??"";if(S1.has(y)||r.toUpperCase()==="HEAD"){L.resume(),Q(),x(),d=!0,g(new Response(null,{status:y,statusText:U,headers:M}));return}let te=()=>{if(!a)return;clearTimeout(C),C=setTimeout(()=>{p=Ga(`no response body progress for ${a}ms`,j0),D.destroy(p)},a)};te();let q=T1(L);if(q!==L)M.delete("content-encoding"),M.delete("content-length");let G=x1(q,{progress:te,done:()=>{Q(),x()},failure:(P)=>p??P??Ga("socket hang up","ECONNRESET")});d=!0,g(new Response(G,{status:y,statusText:U,headers:M}))}),f)D.write(f);D.end()})}xs();var Lv=zi(aN(),1);var __filename="/home/runner/work/fx/fx/sdk/durable/node_modules/undici/index.js",dae=Lo(),G6=qa(),Eae=YA(),Iae=TT(),pae=_T(),$6=GA(),Cae=Ap(),Qae=np(),Bae=Nx(),mae=_x(),yae=Hx(),J6=ue(),Tv=fe(),{InvalidArgumentError:sg}=J6,Yi=RF(),wae=kA(),Dae=xp(),{MockCallHistory:Sae,MockCallHistoryLog:Nae}=Mp(),Rae=Vp(),kae=vp(),bae=MU(),Tae=Ip(),xae=lf(),{getGlobalDispatcher:W6,setGlobalDispatcher:Fae}=wf(),Uae=yi(),Mae=qp();Object.assign(G6.prototype,Yi);var qC=$6;var j6={redirect:JU(),responseError:qU(),retry:jU(),dump:tM(),dns:aM(),cache:PM(),decompress:jM(),deduplicate:r_()},xv={MemoryCacheStore:rC()};var z6=o_();xv.SqliteCacheStore=z6;function ru(e){return(t,r,n)=>{if(typeof r==="function")n=r,r=null;if(!t||typeof t!=="string"&&typeof t!=="object"&&!(t instanceof URL))throw new sg("invalid url");if(r!=null&&typeof r!=="object")throw new sg("invalid opts");if(r&&r.path!=null){if(typeof r.path!=="string")throw new sg("invalid opts.path");let s=r.path;if(!r.path.startsWith("/"))s=`/${s}`;t=new URL(Tv.parseOrigin(t).origin+s)}else{if(!r)r=typeof t==="object"?t:{};t=Tv.parseURL(t)}let{agent:o,dispatcher:A=W6()}=r;if(o)throw new sg("unsupported opts.agent. Did you mean opts.client?");return e.call(A,{...r,origin:t.origin,path:t.search?`${t.pathname}${t.search}`:t.pathname,method:r.method||(r.body?"PUT":"GET")},n)}}var _ae=Wc().fetch;var K6=ss().Headers,X6=Gc().Response,e7=ki().Request,t7=Yl().FormData;var{setGlobalOrigin:Lae,getGlobalOrigin:vae}=nI();var{CacheStorage:q6}=hL(),{kConstruct:Z6}=He();var r7=new q6(Z6);var{deleteCookie:Oae,getCookies:Hae,getSetCookies:Yae,setCookie:Vae,parseCookie:Pae}=SL();var{parseMIMEType:Gae,serializeAMimeType:$ae}=Yr();var{CloseEvent:Jae,ErrorEvent:Wae,MessageEvent:zae}=Zf(),{WebSocket:qae,ping:Zae}=cv();var n7=Iv().WebSocketStream,o7=GC().WebSocketError,A7=ru(Yi.request),s7=ru(Yi.stream),i7=ru(Yi.pipeline),a7=ru(Yi.connect),c7=ru(Yi.upgrade);var{EventSource:jae}=bv();fd();class ZC{contentType="application/json";serialize(e){return Buffer.from(JSON.stringify(e,qt))}async deserialize(e){let t=[],r=e.getReader();while(!0){let{done:o,value:A}=await r.read();if(o)break;if(A)t.push(A)}let n=Buffer.concat(t).toString();return JSON.parse(n,xa)}}var u7=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_MAX_VISIBILITY??"0",10)||1/0,Fv=2147483647,l7=1000,Uv=parseInt(process.env.WORKFLOW_LOCAL_QUEUE_CONCURRENCY??"0",10)||l7,f7=0,g7=0;function Mv(e,t){let r=process.env[e];if(r===void 0||r==="")return t;let n=Number.parseInt(r,10);return Number.isFinite(n)&&n>=0?n:t}function h7(){return{bodyTimeout:Mv("WORKFLOW_LOCAL_BODY_TIMEOUT_MS",g7),connections:1000,headersTimeout:Mv("WORKFLOW_LOCAL_HEADERS_TIMEOUT_MS",f7),keepAliveTimeout:30000}}var vv="Cannot perform ArrayBuffer.prototype.slice on a detached ArrayBuffer",d7="https://workflow-sdk.dev/docs/getting-started/next#configure-proxy-handler";function _v(e){let t=e,r=new Set;while(t&&typeof t==="object"&&!r.has(t)){if(r.add(t),"message"in t&&typeof t.message==="string"&&t.message.includes(vv))return!0;t="cause"in t?t.cause:void 0}return!1}function Ov(e){let t=h7(),r=Qd()?eN({maxSockets:t.connections,keepAliveMs:t.keepAliveTimeout}):void 0,n=r?void 0:new qC(t),o=new ZC,A=ho(),s=new Lv.Sema(Uv),i=new AbortController,a=i.signal,c=new Map,u=new Map,l=new Map,f=(C,p)=>{let Q=l.get(p);return Q?Md(C,Q):Ud(C,{type:"flow"})},g=async(C,p,Q)=>{let D=[];if(Q?.idempotencyKey){let v=c.get(Q.idempotencyKey);if(v)return{messageId:v}}let S=o.serialize(p),{prefix:x}=pd(C),H=Wu.parse(`msg_${A()}`),L=new Date().toISOString(),y=p,M=y.runId??void 0,U=y.stepId??void 0;if(Q?.idempotencyKey){let v=Q.idempotencyKey;c.set(v,H),D.push(()=>{c.delete(v)})}return(async()=>{if(Q?.delaySeconds&&Q.delaySeconds>0){let G=Math.min(Q.delaySeconds*1000,Fv);await ig(G,void 0,{signal:a})}if(!s.tryAcquire())Fs(`[world-local]: concurrency limit (${Uv}) reached, waiting for queue to free up`),await s.acquire();let te=256,q=0;try{for(let G=0;G<te;G++){let P={...Q?.headers,"content-type":"application/json","x-vqs-queue-name":C,"x-vqs-message-id":H,"x-vqs-message-attempt":String(q+1),"x-vqs-message-created-at":L},ae=u.get(x),Ee,ye;try{if(ae){let At=new Request(f(XS(e),x),{method:"POST",headers:P,body:S});Ee=await ae(At)}else{let At=await e0(e),ur=f(At,x);Ee=r?await nN(ur,{method:"POST",headers:new Headers(P),body:S,agents:r,signal:a,headersTimeoutMs:t.headersTimeout,bodyTimeoutMs:t.bodyTimeout}):await fetch(ur,{method:"POST",duplex:"half",dispatcher:n,headers:P,body:S,signal:a})}q++,ye=await Ee.text()}catch(At){let ur=At?.name;if(a.aborted||ur==="AbortError"||ur==="ResponseAborted")return;if(_v(At))throw At;console.error(`[world-local] Queue delivery failed at the transport (loop ${G+1}), retrying`,{queueName:C,messageId:H,...M&&{runId:M},...U&&{stepId:U},error:String(At)}),await ig(5000,void 0,{signal:a});continue}if(Ee.ok){try{let At=Number(JSON.parse(ye).timeoutSeconds);if(Number.isFinite(At)&&At>=0){if(At>0){let ur=Math.min(At*1000,Fv);await ig(ur,void 0,{signal:a})}continue}}catch{}return}console.error(`[world-local] Queue message failed (attempt ${q}, HTTP ${Ee.status})`,{queueName:C,messageId:H,...M&&{runId:M},...U&&{stepId:U},handlerError:ye,...!ae&&!l.has(x)&&(Ee.status===400||Ee.status===404)&&{hint:`No route or handler is registered for queue prefix "${x}", so its messages go to the Workflow SDK's flow route (${dd}). A queue consumer of its own registers one with world.registerRoute(prefix, path) or world.registerHandler(prefix, handler).`}}),await ig(5000,void 0,{signal:a})}console.error(`[world-local] Queue message exhausted safety limit (${te} attempts)`,{queueName:C,messageId:H,...M&&{runId:M},...U&&{stepId:U}})}finally{s.release()}})().catch((v)=>{if(!(v?.name==="AbortError"||v?.name==="ResponseAborted"))if(_v(v))console.error(`[local world] Queue operation failed: detected "${vv}". 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 ${d7}`,{queueName:C,messageId:H,...M&&{runId:M},...U&&{stepId:U},originalError:v});else console.error("[local world] Queue operation failed:",v)}).finally(()=>{for(let v of D)v()}),{messageId:H}},h=z(W({"x-vqs-queue-name":gd,"x-vqs-message-id":Wu,"x-vqs-message-attempt":Ce.number(),"x-vqs-message-delivery-count":Ce.number().int().positive().optional(),"x-vqs-message-created-at":Wh.datetime().optional()}));return{queue:g,createQueueHandler:(C,p)=>async(Q)=>{let D=h.safeParse(Object.fromEntries(Q.headers));if(!D.success||!Q.body)return Response.json({error:!Q.body?"Missing request body":"Missing required headers"},{status:400});let S=D.data["x-vqs-queue-name"],x=D.data["x-vqs-message-id"],H=D.data["x-vqs-message-attempt"],L=D.data["x-vqs-message-delivery-count"],y=D.data["x-vqs-message-created-at"];if(!S.startsWith(C))return Response.json({error:"Unhandled queue",detail:`This route handles queue prefix "${C}", not "${S}".`},{status:400});let M=await new ZC().deserialize(Q.body);try{let U=await p(M,{attempt:H,deliveryCount:L??H,...y?{createdAt:new Date(y)}:{},queueName:S,messageId:x});if(typeof M==="object"&&M!==null&&"invoke"in M&&M.invoke===!0)return Response.json({result:U});let v=null;if(typeof U==="object"&&U!==null&&"timeoutSeconds"in U&&typeof U.timeoutSeconds==="number")v=Math.min(U.timeoutSeconds,u7);if(v!=null)return Response.json({timeoutSeconds:v});return Response.json({ok:!0})}catch(U){return Response.json(String(U),{status:500})}},getDeploymentId:async()=>`dpl_local@${(await wl()).version}`,registerHandler(C,p){u.set(C,p)},registerRoute(C,p){l.set($u.parse(C),Ed(p))},async close(){if(a.aborted)return;if(i.abort(),r)tN(r);await n?.close()}}}import iQ from"node:assert";import aQ from"node:fs/promises";import ds from"node:path";Lt();pt();var uO=zi(dl(),1);Lt();function nu(e,t){if(t==="none"){let{dynamicWorkflowCode:r,...n}=e;return{...n,input:void 0,output:void 0}}return e}function Hv(e,t){if(t==="none")return{...e,input:void 0,output:void 0};return e}function jC(e,t){if(t==="none"){let{metadata:r,...n}=e;return n}return e}import KC from"node:path";Lt();pt();function E7(e){if(e.eventType!=="hook_created")return;let t=e.eventData.token;return typeof t==="string"?t:void 0}function XC(e){let{token:t,metadata:r,isWebhook:n,isSystem:o,tokenRetentionUntil:A,forceClaimedFrom:s}=e.eventData;return{runId:e.runId,hookId:e.correlationId,token:t,...s!==void 0&&{claimedFrom:s},metadata:r,ownerId:"local-owner",projectId:"local-project",environment:"local",createdAt:e.createdAt,specVersion:e.specVersion,isWebhook:n??!0,isSystem:o??!1,tokenRetentionUntil:A}}function Yv(e,t){return e.eventType==="hook_created"&&typeof e.correlationId==="string"&&t(e)}async function Vv(e,t,r){let n=await Me(e,"runs",t,Wt,r);return n?Jt(n.status):!1}async function Pv(e,t,r,n){let o=async(s)=>{if(await Vv(e,s.runId,n)){let i=s.eventData.tokenRetentionUntil;if(!i||i.getTime()<=Date.now())return!1}return!await Ya(e,s.correlationId,n)},A=await L0(e,t,(s)=>Yv(s,r)&&o(s),n);return A&&Yv(A,r)?A:null}async function Gv(e,t,r){let n=XC(t),o=yA(e,n.token);return await ke(o,JSON.stringify({token:n.token,hookId:n.hookId,runId:n.runId,eventId:t.eventId,tokenRetentionUntil:t.eventData.tokenRetentionUntil,...n.claimedFrom&&{claimedFrom:n.claimedFrom}})),await DA(e,n.runId,n.hookId,r),await ke(pe(e,"hooks",n.hookId,r),JSON.stringify(n,qt,2)),n}async function eQ(e,t,r){let n=await Pv(e,{kind:"token",token:t},(o)=>E7(o)===t,r);return n?Gv(e,n,r):null}async function I7(e,t,r){let n=await Pv(e,{kind:"id",hookId:t},(o)=>o.correlationId===t,r);return n?Gv(e,n,r):null}function $v(e,t){async function r(a){if(await Ya(e,a.hookId,t))return!1;if(a.tokenRetentionUntil&&a.tokenRetentionUntil.getTime()>Date.now())return!0;return!await Vv(e,a.runId,t)}async function n(a){let c=await Ha(e,a.hookId,t);return c.committed&&c.forceClaimedBy!==void 0}async function o(a){let c=await qs(yA(e,a));if(c?.hookId)try{let g=await Me(e,"hooks",c.hookId,zt,t);if(g?.token===a){if(await r(g))return{...g,isWebhook:g.isWebhook??!0};if(!await n(g))throw new Fr(a)}else if(g)return null}catch(g){if(!Os.is(g))throw g;return null}let u=KC.join(e,"hooks"),l=await Lr(u),f=!1;for(let g of l){let h=KC.join(u,`${g}.json`),d=await $e(h,zt);if(d?.token===a){if(await r(d))return{...d,isWebhook:d.isWebhook??!0};if(await n(d)){f=!0;continue}throw new Fr(a)}}if(f)throw new Fr(a);return null}async function A(a,c){de("hookId",a);let u=await Me(e,"hooks",a,zt,t);if(u&&!await r(u))throw new Fr(a);let l=u??await I7(e,a,t);if(!l)throw new Fr(a);let f=c?.resolveData||Bt;return jC({...l,isWebhook:l.isWebhook??!0},f)}async function s(a){let c=await o(a)??await eQ(e,a,t);if(!c)throw new Fr(a);return c}async function i(a){let c=KC.join(e,"hooks"),u=a.resolveData||Bt,l=await pn({directory:c,schema:zt,sortOrder:a.pagination?.sortOrder??"asc",limit:a.pagination?.limit,cursor:a.pagination?.cursor,filePrefix:void 0,filter:async(f)=>{if(a.runId&&f.runId!==a.runId)return!1;return r(f)},getCreatedAt:()=>null,getId:(f)=>f.hookId});return{...l,data:l.data.map((f)=>jC(f,u))}}return{get:A,getByToken:s,list:i}}async function Vi(e,t){await Va(e);for(let r of await ml(e,t)){if(r.hookId){let n=null,o=null;try{o=pe(e,"hooks",r.hookId,r.tag),n=await $e(o,zt)}catch(A){if(!Os.is(A)&&!(A instanceof SyntaxError||A instanceof uo))throw A}if(n&&o&&n.runId===t){if(n.tokenRetentionUntil&&n.tokenRetentionUntil.getTime()>Date.now())continue;await Cl(e,n.token,n.runId,n.hookId),await rt(mo(e,n.token,n.runId,n.hookId)),await rt(o)}}await _0(e,r.fileId)}}import D7 from"node:fs/promises";Lt();Lt();pt();import sQ from"node:path";import{EventEmitter as p7}from"node:events";import AQ from"node:fs/promises";import Dt from"node:path";xs();pt();var Wv=zi(dl(),1);var C7=Qt("@workflow/world-local//streamerMonotonicUlid",1,()=>({next:ho(()=>Math.random())})),tQ=(e)=>C7.next(e),zv=z(W({streams:On(m())})),Q7={realpath:!1,stale:1e4,retries:{retries:150,factor:1,minTimeout:100,maxTimeout:100}},qv=1;function ou(e){return e===qv}function cg(e){let t=Buffer.from([e.eof?qv:0]);return Buffer.concat([t,e.chunk])}function B7(e){return ou(e[0])}function rQ(e){let t=B7(e),r=Buffer.from(e.subarray(1));return{eof:t,chunk:r}}async function Zv(e){try{return await AQ.readdir(e)}catch(t){if(t.code==="ENOENT")return[];throw t}}function nQ(e,t,r,n=r,o=()=>!0){for(let A of t){if(!A.endsWith(r))continue;let s=A.slice(0,-r.length);if(o(s))e.set(s,n)}}function Au(e,t){return de("streamName",t),Dt.join(e,t)}async function ag(e,t,r){let n=Au(e,t),o=await Zv(n),A=new Map;if(nQ(A,o,".json"),nQ(A,o,".bin",".bin",r?(i)=>!i.endsWith(`.${r}`):void 0),r){let i=`.${r}.bin`;nQ(A,o,i)}return{files:[...A.keys()].sort(),extMap:A,dir:n}}var Jv=`chnk_${"0".repeat(26)}`;async function jv(e,t,r){let n=Dt.join(e,"streams","chunks"),o=r?`.${r}`:"",A;try{de("runId",t),A=(await Me(e,"streams/runs",t,zv,r))?.streams??[]}catch(s){oQ(`streams of ${t}`,s);return}for(let s of A)try{let i=Au(n,s);await _r(Dt.join(i,`${Jv}${o}.bin`),cg({chunk:Buffer.from([]),eof:!0}),{overwrite:!0});for(let a of await Zv(i)){if(a.startsWith(Jv))continue;if(!a.endsWith(".bin")&&!a.endsWith(".json"))continue;await on(()=>AQ.unlink(Dt.join(i,a))).catch((c)=>{if(c.code!=="ENOENT")oQ(a,c)})}}catch(i){oQ(s,i)}}function oQ(e,t){console.warn(`[world-local] Failed to purge stream data for ${e}:`,t instanceof Error?t.message:t)}function Kv(e,t){let r=t?`.${t}`:"",n=new p7,o=new Set,A=new Map,s=!1;async function i(l){return(await Me(e,"streams/runs",l,zv,t))?.streams??[]}async function a(l,f,{verify:g=!1}={}){de("runId",l),de("streamName",f);let h=`${l}:${f}`;if(o.has(h)){if(!g)return;let I=await i(l).catch(()=>null);if(I===null||I.includes(f))return;o.delete(h)}let d=pe(e,"streams/runs",l,t);await vs(A,d,async()=>{if(o.has(h))return;if(await c(d,l,f))o.add(h)})}async function c(l,f,g){await AQ.mkdir(Dt.dirname(l),{recursive:!0});let h=!1,d;try{d=await Wv.lock(l,{...Q7,onCompromised:()=>{h=!0}})}catch(I){if(!s)s=!0,console.warn(`[world-local] Could not lock the stream index of run ${f}; updating it without the lock:`,I instanceof Error?I.message:I)}try{let I=await i(f);if(!I.includes(g))I.push(g),await Ke(l,{streams:I},{overwrite:!0})}finally{if(d&&!h)await d().catch(()=>{})}return!h}function u(l){if(typeof l==="string")return Buffer.from(new TextEncoder().encode(l));else if(l instanceof Buffer)return l;else return Buffer.from(l)}return{clearCache(){o.clear()},streams:{async write(l,f,g){let h=`chnk_${tQ()}`,d=await l;await a(d,f);let I=u(g),C=cg({chunk:I,eof:!1}),p=Dt.join(Au(Dt.join(e,"streams","chunks"),f),`${h}${r}.bin`);await _r(p,C);let Q=Uint8Array.from(I);n.emit(`chunk:${f}`,{streamName:f,chunkData:Q,chunkId:h})},async writeMulti(l,f,g){if(g.length===0)return;let h=g.map(()=>`chnk_${tQ()}`),d=await l;await a(d,f);let C=g.map((p)=>u(p)).map(async(p,Q)=>{let D=h[Q],S=cg({chunk:p,eof:!1}),x=Dt.join(Au(Dt.join(e,"streams","chunks"),f),`${D}${r}.bin`);return await _r(x,S),{chunkId:D,chunkData:Uint8Array.from(p)}});for(let p of C){let{chunkId:Q,chunkData:D}=await p;n.emit(`chunk:${f}`,{streamName:f,chunkData:D,chunkId:Q})}},async close(l,f){let g=`chnk_${tQ()}`,h=await l;await a(h,f,{verify:!0});let d=Dt.join(Au(Dt.join(e,"streams","chunks"),f),`${g}${r}.bin`);await _r(d,cg({chunk:Buffer.from([]),eof:!0})),n.emit(`close:${f}`,{streamName:f})},async list(l){return de("runId",l),i(l)},async getChunks(l,f,g){let h=g?.limit??100,d=Dt.join(e,"streams","chunks"),{files:I,extMap:C,dir:p}=await ag(d,f,t),Q=0;if(g?.cursor)try{Q=JSON.parse(Buffer.from(g.cursor,"base64").toString("utf-8")).i}catch{Q=0}let D=!1,S=[],x=0;for(let M of I){let U=C.get(M)??".bin",v=Dt.join(p,`${M}${U}`);if(x<Q){if(ou(await Fa(v))){D=!0;break}x++;continue}if(S.length>=h){if(ou(await Fa(v)))D=!0;else x++;break}let te=rQ(await Ys(v));if(te.eof){D=!0;break}S.push({index:x,data:Uint8Array.from(te.chunk)}),x++}let H=!D&&x>Q+S.length,L=Q+S.length,y=H?Buffer.from(JSON.stringify({i:L})).toString("base64"):null;return{data:S,cursor:y,hasMore:H,done:D}},async getInfo(l,f){let g=Dt.join(e,"streams","chunks"),{files:h,extMap:d,dir:I}=await ag(g,f,t),C=!1,p=0;for(let Q of h){let D=d.get(Q)??".bin";if(ou(await Fa(Dt.join(I,`${Q}${D}`)))){C=!0;break}p++}return{tailIndex:p-1,done:C}},async get(l,f,g=0){let h=Dt.join(e,"streams","chunks"),d=()=>{},I=null,C=!1;return new ReadableStream({async start(p){let Q=new Set,D=[],S=!0,x=!1,H=(P)=>{if(P.chunkData.byteLength===0){Q.add(P.chunkId);return}if(S)Q.add(P.chunkId),D.push({chunkId:P.chunkId,chunkData:Uint8Array.from(P.chunkData)});else if(!Q.has(P.chunkId))Q.add(P.chunkId),p.enqueue(Uint8Array.from(P.chunkData))},L=()=>{if(S){x=!0;return}C=!0,d();try{p.close()}catch{}};d=()=>{if(n.off(`chunk:${f}`,H),n.off(`close:${f}`,L),I)clearInterval(I),I=null},n.on(`chunk:${f}`,H),n.on(`close:${f}`,L);let{files:y,extMap:M,dir:U}=await ag(h,f,t),v=y.length;if(typeof g==="number"&&g<0&&y.length>0){let P=y[y.length-1],ae=M.get(P)??".bin";if(ou(await Fa(Dt.join(U,`${P}${ae}`))))v--}let te=typeof g==="number"&&g<0?Math.max(0,v+g):g,q=!1;for(let P=te;P<y.length;P++){let ae=y[P],Ee=ae;if(Q.has(Ee))continue;let ye=M.get(ae)??".bin",At=rQ(await Ys(Dt.join(U,`${ae}${ye}`)));if(At?.eof===!0){q=!0;break}if(Q.add(Ee),At.chunk.byteLength)p.enqueue(Uint8Array.from(At.chunk))}S=!1,D.sort((P,ae)=>P.chunkId.localeCompare(ae.chunkId));for(let P of D)p.enqueue(Uint8Array.from(P.chunkData));if(q){C=!0,d();try{p.close()}catch{}return}if(x){C=!0,d();try{p.close()}catch{}return}for(let P=0;P<te&&P<y.length;P++)Q.add(y[P]);if(C){d();return}let G=!1;I=setInterval(async()=>{if(G)return;G=!0;try{let{files:P,extMap:ae}=await ag(h,f,t);for(let Ee of P){let ye=Ee;if(Q.has(ye))continue;Q.add(ye);let At=ae.get(Ee)??".bin",ur=rQ(await Ys(Dt.join(U,`${Ee}${At}`)));if(ur?.eof===!0){C=!0,d();try{p.close()}catch{}return}if(C)return;if(ur.chunk.byteLength)p.enqueue(Uint8Array.from(ur.chunk))}}catch(P){if(!(P instanceof Error&&("code"in P)))console.error("[world-local] Unexpected polling error:",P)}finally{G=!1}},100)},cancel(){C=!0,d()}})}}}}function lg(e){let t=Zh(e);if(t.unsupported)console.warn(`[world-local] Ignoring unrecognized ${qh} value ${JSON.stringify(t.raw)}; keeping the run's data.`);return t.mode==="none"}function fg(e,t){return{...e,input:void 0,output:void 0,error:void 0,dynamicWorkflowCode:void 0,expiredAt:t}}async function gg(e,t,r){await Promise.all([Xv(sQ.join(e,Qe("steps",t)),t,(n)=>{n.input=void 0,n.output=void 0,n.error=void 0}),Xv(sQ.join(e,Qe("events",t)),t,(n)=>{let o=n.eventData;if(!o||typeof o!=="object")return;for(let A of ks(String(n.eventType)))delete o[A];if(n.eventType==="run_created"||n.eventType==="run_started")delete o.dynamicWorkflowCode,delete o.dynamicWorkflowCodeRef}),m7(e,t),jv(e,t,r)])}var eO=br(m(),Ss()),Zr=cD((e)=>{if(e&&typeof e==="object"&&"eventType"in e&&"eventData"in e){let t=e.eventData;if(t&&typeof t==="object"){for(let r of ks(String(e.eventType)))if(!(r in t))t[r]=void 0}}return e},pa);async function Xv(e,t,r){let n;try{n=await Lr(e)}catch(o){ug(e,o);return}for(let o of n){if(!o.startsWith(`${t}-`))continue;let A=sQ.join(e,`${o}.json`);try{let s=await $e(A,eO);if(!s)continue;r(s),await Ke(A,s,{overwrite:!0})}catch(s){ug(A,s)}}}async function m7(e,t){let r;try{await Va(e),r=await ml(e,t)}catch(n){ug(`hooks of ${t}`,n);return}for(let n of r){if(!n.hookId)continue;try{let o=pe(e,"hooks",n.hookId,n.tag),A=await $e(o,eO);if(!A||A.runId!==t)continue;A.metadata=void 0,await Ke(o,A,{overwrite:!0})}catch(o){ug(n.hookId,o)}}}function ug(e,t){console.warn(`[world-local] Failed to purge user data for ${e}:`,t instanceof Error?t.message:t)}Lt();import{EventEmitter as y7}from"node:events";var hg=new y7;hg.setMaxListeners(0);var w7=100;function tO(){return Pu("WORKFLOW_LOCAL_RUN_STATUS_POLL_INTERVAL_MS",w7,{integer:!0,min:1})}function dg(e){hg.emit(`run:${e}`)}function rO(e,t,r){if(t<=0||r?.aborted)return Promise.resolve();return new Promise((n)=>{let o=`run:${e}`,A=!1,s=()=>{if(A)return;A=!0,clearTimeout(i),hg.off(o,s),r?.removeEventListener("abort",s),n()},i=setTimeout(s,t);hg.once(o,s),r?.addEventListener("abort",s,{once:!0})})}async function S7(e,t,r,n,o,A){if(Jt(A.status)||await Ws(e,t))throw new Ur(`Workflow run "${t}" is already in a terminal state`);let s=El(e,t,r);await ke(s,n);try{if(await Ws(e,t))throw new Ur(`Workflow run "${t}" is already in a terminal state`);if(await nl(s,o)!=="linked")throw new Ur(`Workflow run "${t}" is already in a terminal state`)}finally{await D7.unlink(s).catch(()=>{})}}async function nO(e,t,r,n,o){de("runId",t);let A=o?.resolveData??Bt;switch(r.eventType){case"run_cancelled":{await ke(Js(e,t),""),await Il(e,t);let s=new Date,i={runId:n.runId,deploymentId:n.deploymentId,workflowName:n.workflowName,specVersion:n.specVersion,executionContext:n.executionContext,input:n.input,createdAt:n.createdAt,expiredAt:n.expiredAt,startedAt:n.startedAt,status:"cancelled",output:void 0,error:void 0,completedAt:s,updatedAt:s,attributes:n.attributes},a=lg(i.attributes),c=a?fg(i,s):i,u=ze(e,"runs",`${t}.json`);if(await Ke(u,c,{overwrite:!0}),dg(t),await Vi(e,t),a)await gg(e,t,void 0);return{event:void 0,run:nu(c,A)}}case"wait_completed":case"hook_received":{let s=`evnt_${wA()}`,a={...r,runId:t,eventId:s,createdAt:new Date,specVersion:hA},c=`${t}-${s}`,u=ze(e,Qe("events",t),`${c}.json`);if(r.eventType==="hook_received")await S7(e,t,s,JSON.stringify(a,qt,2),u,n);else await Ke(u,a);return{event:dr(a,A)}}default:throw Error(`Event type '${r.eventType}' not supported for legacy runs (specVersion: ${n.specVersion||"undefined"}). Please upgrade 'workflow' package.`)}}import N7 from"node:path";Lt();var Eg=Qt("@workflow/world-local//runFileLocks",1,()=>({byKey:new Map}));function Ig(e,t){let r=Eg.byKey.get(e),n={},o=(async()=>{if(r)await r.catch(()=>{return});try{return await t()}finally{if(Eg.byKey.get(e)===n.task)Eg.byKey.delete(e)}})();return n.task=o,Eg.byKey.set(e,o),o}function oO(e,t){let r=async(n,o)=>{de("runId",n);let A=await Me(e,"runs",n,Wt,t);if(!A)throw new Vn(n);let s=o?.resolveData??Bt;return nu(A,s)};return{get:r,waitForTerminalStatus:async(n,o)=>{let A=Date.now()+(o?.timeoutMs??0);while(!0){let s=await r(n,o);if(Jt(s.status))return s;let i=A-Date.now();if(i<=0||o?.signal?.aborted)return s;await rO(n,Math.min(i,tO()),o?.signal)}},getMany:async(n,o)=>{let A=[...new Set(n)],s=await Promise.all(A.map(async(a)=>{try{return await r(a,o)}catch(c){if(c instanceof Vn)return null;throw c}})),i=new Map(A.map((a,c)=>[a,s[c]]));return n.map((a)=>i.get(a)??null)},list:async(n)=>{let o=n?.resolveData??Bt,A=await pn({directory:N7.join(e,"runs"),schema:Wt,fileIdFilter:n?.fileIdFilter,filter:(s)=>{if(n?.workflowName&&s.workflowName!==n.workflowName)return!1;if(n?.status!==void 0){if(!(Array.isArray(n.status)?n.status:[n.status]).includes(s.status))return!1}return!0},sortOrder:n?.pagination?.sortOrder??"desc",limit:n?.pagination?.limit??200,cursor:n?.pagination?.cursor,getCreatedAt:yo("wrun"),getId:(s)=>s.runId});if(o==="none")return{...A,data:A.data.map((s)=>nu(s,"none"))};return A},experimentalSetAttributes:async(n,o,A)=>(de("runId",n),Ig(n,async()=>{let s=await Me(e,"runs",n,Wt,t);if(!s)throw new Vn(n);try{lA(o,{existingKeys:Object.keys(s.attributes??{}),allowReservedAttributes:A?.allowReservedAttributes})}catch(c){if(c instanceof rr)throw c;throw c}let i=Ea(s.attributes,o),a={...s,attributes:i,updatedAt:new Date};return await Ke(pe(e,"runs",n,t),a,{overwrite:!0}),{attributes:i}}))}}var lO=86400000,R7=1000;function k7(){let e=Number(process.env.WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS??30);if(!Number.isFinite(e)||e<=0)throw new We("WORKFLOW_LOCAL_HOOK_RETENTION_LIMIT_DAYS must be a positive number",{status:400});return e*lO}var b7=z(W({eventId:m()})),cQ=z(W({runId:m(),resumeId:m(),hookId:m(),eventId:m(),payloadDigest:m().optional()}));function Cg(e,t){return e.eventType==="hook_received"&&e.correlationId===t.hookId&&(e.resumeId===void 0||e.resumeId===t.resumeId)}async function AO(e,t,r,n){let o=await zs(e,t,n);for(let A of o.ids){let s=await Me(e,Qe("events",t),`${t}-${A}`,Zr,n);if(s&&s.resumeId===r.resumeId&&Cg(s,r))return s}return null}async function T7(e,t,r){if(t.hookId&&await Ya(e,t.hookId,r))return!0;let n=await Me(e,"runs",t.runId,Wt,r);if(!n)return!0;if(!Jt(n.status))return!1;return!t.tokenRetentionUntil||t.tokenRetentionUntil.getTime()<=Date.now()}async function x7(e){try{return await $e(e,b7)}catch(t){if(t instanceof SyntaxError||t instanceof uo)return null;throw t}}function sO(e){return Da(e.eventId)?e.eventId:null}function iO(e,t){let r=In(t).slice(e.length+1);return Da(r)?r:null}async function aO(e,t,r){return(await pn({directory:ds.join(e,Qe("events",t)),schema:Zr,filePrefix:`${t}-`,filter:(o)=>o.eventType==="hook_created"&&o.correlationId===r,limit:1,getCreatedAt:yo("evnt"),getId:(o)=>o.eventId})).data[0]?.eventId??null}async function cO(e,t,r,n,o){let A=`${t}-${n}`,s=await Me(e,Qe("events",t),A,Zr,o);if(!s||s.eventType!=="hook_created"||s.correlationId!==r)return;if(await Me(e,"hooks",r,zt,o))return;let a=XC(s);await Bl(e,a.token,t,r,n,o),await DA(e,t,r,o),await ke(pe(e,"hooks",r,o),JSON.stringify(a,qt,2))}async function F7(e,t,r,n,o){let A=mo(e,t,r,n),s=JSON.stringify({eventId:o});if(await ke(A,s))return o;return(await x7(A))?.eventId??null}function U7(e){if(Ge.is(e)||Ur.is(e)||Xu.is(e)||Fr.is(e)||Ra.is(e)||Vn.is(e)||el.is(e))return!0;let t=e?.status;return typeof t==="number"&&t>=400&&t<500}async function uQ(e,t){let r=ds.join(e,"waits"),n=await Lr(r);for(let o of n)if(o.startsWith(`${t}-`)){let A=ds.join(r,`${o}.json`);await rt(A)}}async function pg(e,t,r,n){return Ig(t,async()=>{let A=(await $e(pe(e,"runs",t,r),Wt))?.attributes??n.attributes,s={...n,attributes:A},i=Jt(s.status)&&lg(A);if(i)s=fg(s,new Date);if(await Ke(pe(e,"runs",t,r),s,{overwrite:!0}),Jt(s.status))dg(t);return{run:s,purged:i}})}function M7(){return Qt("@workflow/world-local//inBandFence",2,()=>({locks:new Map}))}var _7=W({seqInBand:ie().int().nonnegative(),pending:ie().int().nonnegative().optional()});function lQ(e,t,r){let n=r?`${t}.in-band.${r}`:`${t}.in-band`;return ze(e,".locks","runs",n)}function fO(e,t){let r=k7(),n=4194304,o=R7,A=new Map,s=new Map,i=new Map,a=0;function c(N){let E=A.get(N);if(!E)return;A.delete(N),a-=s.get(N)??0,s.delete(N);let F=i.get(E.runId);if(F?.delete(N),F?.size===0)i.delete(E.runId)}function u(N){for(let E of i.get(N)??[])c(E)}function l(){A.clear(),s.clear(),i.clear(),a=0,f.clear()}let f=new Map;function g(N){return t?`${N}.${t}`:N}async function h(N,E){let F=`${N}-${lo(E)}`;for(let Z of t?[pe(e,Qe("events",N),F,t),pe(e,Qe("events",N),F)]:[pe(e,Qe("events",N),F)])try{return await aQ.stat(Z),!0}catch(O){if(O.code!=="ENOENT")throw O}return!1}async function d(N,E){let F=g(N),Z=f.get(F);if(Z===void 0||E?.rescan){let Pe=await zs(e,N,t);if(Z===void 0)Z=Pe.count>0&&!Pe.usesSlots?null:{published:Pe.maxSlot},f.set(F,Z);else if(Z!==null)Z.published=Math.max(Z.published,Pe.maxSlot)}if(Z===null)return null;let O=Math.max(Z.published+1,ya,E?.atLeast??ya);while(await h(N,O))Z.published=Math.max(Z.published,O),O+=1;return O}function I(N,E){let F=fo(E);if(F===null)return;let Z=f.get(g(N));if(Z)Z.published=Math.max(Z.published,F)}async function C(N){let E=await d(N);return E===null?`evnt_${wA()}`:lo(E)}async function p(N){let E=await d(N,{rescan:!0});if(E!==null)return{eventId:lo(E),createdAt:new Date};return T0(e,N,t)}function Q(N,E,F){if(F>4194304)return;while(A.size>0&&(A.size>=o||a+F>4194304)){let O=A.keys().next().value;c(O)}A.set(N,E),s.set(N,F),a+=F;let Z=i.get(E.runId)??new Set;Z.add(N),i.set(E.runId,Z)}function D(N,E,F){if(Ia(N.eventType)){u(N.runId);return}let Z=Buffer.byteLength(F);if(Z>4194304)return;let O=Zr.safeParse(JSON.parse(F,xa));if(O.success)Q(E,O.data,Z)}async function S(N){let E=N;for(let F=0;;F++){let Z=pe(e,Qe("events",E.runId),`${E.runId}-${E.eventId}`,t),O=JSON.stringify(E,qt,2),Pe=fo(E.eventId);if(Pe===null)return await _r(Z,O),D(E,Z,O),E;if(await ke(Z,O))return I(E.runId,E.eventId),D(E,Z,O),E;let St=await d(E.runId,{rescan:F>0&&F%8===0,atLeast:Pe+1});iQ(St!==null),E={...E,eventId:lo(St)}}}async function x(N,E){let F=await Ha(e,N,t);if(!F.committed)return;if(F.forceClaimedBy)throw new Ra(typeof E==="string"?E:"",F.forceClaimedBy.runId,F.forceClaimedBy.hookId);throw new Fr(N)}let H=(N,E)=>pn({directory:ds.join(e,Qe("events",N)),schema:Zr,cachedItems:A,filePrefix:`${N}-`,sortOrder:E.sortOrder??"asc",limit:E.limit,cursor:E.cursor,getCreatedAt:yo("evnt"),getId:(F)=>F.eventId,getSortKey:sO,getSortKeyFromFileId:(F)=>iO(N,F)}),L=new Map,y=new Map,M={clearCache:l,async create(N,E,F){if(E.eventType==="hook_created"&&E.eventData.tokenRetentionUntil!==void 0&&E.eventData.tokenRetentionUntil.getTime()>Date.now()+r)throw new We(`Hook minimum retention cannot exceed ${r/lO} days in the Local World.`,{status:400});if(N!=null&&N!=="")de("runId",N);if("correlationId"in E&&typeof E.correlationId==="string")de("correlationId",E.correlationId);if(Ou(E.eventType)&&N&&E.correlationId){let O=t?`${N}-${E.correlationId}.${t}`:`${N}-${E.correlationId}`;return vs(L,O,Z)}if(rd(E.eventType)&&N&&E.correlationId){let O=t?`${N}-${E.correlationId}.hook.${t}`:`${N}-${E.correlationId}.hook`;return vs(y,O,Z)}return Z();async function Z(){let O="",Pe=!1,St=null,he=new Date,b;if(E.eventType==="run_created"&&(!N||N===""))b=`wrun_${wA()}`;else if(!N)throw Error("runId is required for non-run_created events");else b=N;if(E.eventType==="run_created"&&N&&N!==""){let T=Td(b,"wrun_");if(T)throw new We(T)}let lr=E.specVersion??hA,V=null,CO=["step_completed","step_retrying"];if(E.eventType!=="run_created"&&!CO.includes(E.eventType)){if(V=await Me(e,"runs",b,Wt,t),E.eventType==="run_started"&&!V&&"eventData"in E&&E.eventData){let T=E.eventData;if(T.deploymentId&&T.workflowName&&T.input!==void 0){lA(Object.entries(T.attributes??{}).map(([ge,it])=>({key:ge,value:it})),{allowReservedAttributes:T.allowReservedAttributes===!0});let Y={runId:b,deploymentId:T.deploymentId,status:"pending",workflowName:T.workflowName,specVersion:lr,executionContext:T.executionContext,input:T.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:T.attributes??{},encryptionPublicKey:T.encryptionPublicKey,dynamicWorkflowCode:T.dynamicWorkflowCode,createdAt:he,updatedAt:he},le=pe(e,"runs",b,t);if(await ke(le,JSON.stringify(Y,qt))){let ge=await C(b),it={eventType:"run_created",runId:b,eventId:ge,createdAt:he,specVersion:lr,eventData:{deploymentId:T.deploymentId,workflowName:T.workflowName,input:T.input,executionContext:T.executionContext,attributes:T.attributes,allowReservedAttributes:T.allowReservedAttributes,encryptionPublicKey:T.encryptionPublicKey}};await S(it),V=Y}else V=await Me(e,"runs",b,Wt,t)}}}if(O=await C(b),!V&&(E.eventType==="run_failed"||E.eventType==="attr_set"||E.eventType==="run_started"))throw new Vn(b);if(V){if(kd(V.specVersion))throw new el(V.specVersion,hA);if(Rd(V.specVersion))return nO(e,b,E,V,F&&{resolveData:md(F.resolveData)})}let gQ=Ad(E),su=gQ&&E.eventType==="step_started";if(V&&Jt(V.status)){if(E.eventType==="run_cancelled"&&V.status==="cancelled"){let T=await S({...E,runId:b,eventId:O,createdAt:he,specVersion:lr}),Y=F?.resolveData??Bt;return{event:dr(T,Y),run:V,...V?{maxEvents:Yn()}:{}}}if(E.eventType==="run_started")throw new Ur(`Workflow run "${b}" is already in terminal state "${V.status}"`);if(Ia(E.eventType))throw new Ge(`Cannot transition run from terminal state "${V.status}"`);if(gQ)throw new Ge(`Cannot create new entities on run in terminal state "${V.status}"`);if(E.eventType==="attr_set")throw new Ge(`Cannot set attributes on run in terminal state "${V.status}"`)}let st=null;if(Ou(E.eventType)&&E.eventType!=="step_created"&&E.correlationId){let T=`${b}-${E.correlationId}`;if(st=await Me(e,Qe("steps",b),T,gA,t),!st&&!su)throw new We(`Step "${E.correlationId}" not found`);if(su&&st)throw new Ge(`Step "${E.correlationId}" already created`);if(st){if(Hu(st.status))throw new Ge(`Cannot modify step in terminal state "${st.status}"`);if(V&&Jt(V.status)){if(st.status!=="running"||E.eventType==="step_started")throw new Ur(`Cannot ${E.eventType==="step_started"?"start":"modify non-running"} step on run in terminal state "${V.status}"`)}}}if(nd(E.eventType)&&E.correlationId){if(E.eventType==="hook_received"&&F?.resumeId){let Y=await $e(pl(e,b,F.resumeId),cQ);if(Y&&Y.hookId===E.correlationId&&(!F.resumePayloadDigest||!Y.payloadDigest||Y.payloadDigest===F.resumePayloadDigest)){let le=await Me(e,Qe("events",b),`${b}-${Y.eventId}`,Zr,t),me=le&&Cg(le,Y)?le:await AO(e,b,Y,t);if(me)return{event:me}}}if(E.eventType==="hook_received")await x(E.correlationId,E.eventData?.token);if(!await Me(e,"hooks",E.correlationId,zt,t))throw new Fr(E.correlationId);if(E.eventType==="hook_received"&&F?.resumeId){let Y=pl(e,b,F.resumeId),le=async(ge)=>{if(ge.hookId!==E.correlationId)throw new Ge(`hook_received resumeId "${F.resumeId}" already recorded for a different hook`);if(F.resumePayloadDigest&&ge.payloadDigest&&ge.payloadDigest!==F.resumePayloadDigest)throw new Ge(`hook_received resumeId "${F.resumeId}" already recorded with a different payload`);let it=await Me(e,Qe("events",b),`${b}-${ge.eventId}`,Zr,t);if(it&&Cg(it,ge))return{event:it};let It=await AO(e,b,ge,t);if(It)return{event:It};if(St=ge.eventId,!it)O=ge.eventId,Pe=!0;return null},me=await $e(Y,cQ);if(me){let ge=await le(me);if(ge)return ge}else if(Pe=!Da(O),St=O,!await ke(Y,JSON.stringify({runId:b,resumeId:F.resumeId,hookId:E.correlationId,eventId:O,...F.resumePayloadDigest?{payloadDigest:F.resumePayloadDigest}:{}}))){St=null;let it=await $e(Y,cQ);if(it){let It=await le(it);if(It)return It}}}}let Pi,Fe={...E,runId:b,eventId:O,createdAt:he,specVersion:lr,...E.eventType==="hook_received"&&F?.resumeId?{resumeId:F.resumeId}:{}};if(E.eventType==="run_started"&&"eventData"in Fe)delete Fe.eventData;if(Fe.eventType==="run_created"&&Fe.eventData){let{dynamicWorkflowCode:T,dynamicWorkflowCodeRef:Y,...le}=Fe.eventData;Fe={...Fe,eventData:le}}if(su&&Fe.eventType==="step_started"&&Fe.eventData){let{input:T,...Y}=Fe.eventData;Fe={...Fe,eventData:Y}}let jr,Gi=!1,Sr,Xo,$i,hQ=!1,dQ;if(Ia(E.eventType)&&V){await ke(Js(e,b,t),""),await Il(e,b,t);let T=await p(b);O=T.eventId,Fe={...Fe,eventId:O,createdAt:T.createdAt}}if(E.eventType==="run_created"&&"eventData"in E){let T=E.eventData;lA(Object.entries(T.attributes??{}).map(([me,ge])=>({key:me,value:ge})),{allowReservedAttributes:T.allowReservedAttributes===!0}),jr={runId:b,deploymentId:T.deploymentId,status:"pending",workflowName:T.workflowName,specVersion:lr,executionContext:T.executionContext,input:T.input,output:void 0,error:void 0,startedAt:void 0,completedAt:void 0,attributes:T.attributes??{},encryptionPublicKey:T.encryptionPublicKey,dynamicWorkflowCode:T.dynamicWorkflowCode,createdAt:he,updatedAt:he};let Y=pe(e,"runs",b,t);if(!await ke(Y,JSON.stringify(jr,qt,2)))throw new Ge(`Workflow run "${b}" already exists`)}else if(E.eventType==="run_started"){if(V){if(V.status==="running"){if(F?.skipPreload)return{run:V,maxEvents:Yn()};let Y=await H(b,{limit:Yn()});return{run:V,events:Y.data,cursor:Y.cursor,hasMore:Y.hasMore,maxEvents:Yn()}}let T=await pg(e,b,t,{runId:V.runId,deploymentId:V.deploymentId,workflowName:V.workflowName,specVersion:V.specVersion,executionContext:V.executionContext,input:V.input,createdAt:V.createdAt,expiredAt:V.expiredAt,status:"running",output:void 0,error:void 0,completedAt:void 0,startedAt:V.startedAt??he,updatedAt:he,attributes:V.attributes,encryptionPublicKey:V.encryptionPublicKey,dynamicWorkflowCode:V.dynamicWorkflowCode});jr=T.run,Gi=T.purged}}else if(E.eventType==="run_completed"&&"eventData"in E){let T=E.eventData;if(V){let Y=await pg(e,b,t,{runId:V.runId,deploymentId:V.deploymentId,workflowName:V.workflowName,specVersion:V.specVersion,executionContext:V.executionContext,input:V.input,createdAt:V.createdAt,expiredAt:V.expiredAt,startedAt:V.startedAt,status:"completed",output:T.output,error:void 0,completedAt:he,updatedAt:he,attributes:V.attributes,encryptionPublicKey:V.encryptionPublicKey,dynamicWorkflowCode:V.dynamicWorkflowCode});jr=Y.run,Gi=Y.purged,await Promise.all([Vi(e,b),uQ(e,b)])}}else if(E.eventType==="run_failed"&&"eventData"in E){let T=E.eventData;if(V){let Y=await pg(e,b,t,{runId:V.runId,deploymentId:V.deploymentId,workflowName:V.workflowName,specVersion:V.specVersion,executionContext:V.executionContext,input:V.input,createdAt:V.createdAt,expiredAt:V.expiredAt,startedAt:V.startedAt,status:"failed",output:void 0,error:T.error,errorCode:T.errorCode,completedAt:he,updatedAt:he,attributes:V.attributes,encryptionPublicKey:V.encryptionPublicKey,dynamicWorkflowCode:V.dynamicWorkflowCode});jr=Y.run,Gi=Y.purged,await Promise.all([Vi(e,b),uQ(e,b)])}}else if(E.eventType==="run_cancelled"){if(V){let T=await pg(e,b,t,{runId:V.runId,deploymentId:V.deploymentId,workflowName:V.workflowName,specVersion:V.specVersion,executionContext:V.executionContext,input:V.input,createdAt:V.createdAt,expiredAt:V.expiredAt,startedAt:V.startedAt,status:"cancelled",output:void 0,error:void 0,completedAt:he,updatedAt:he,attributes:V.attributes,encryptionPublicKey:V.encryptionPublicKey,dynamicWorkflowCode:V.dynamicWorkflowCode});jr=T.run,Gi=T.purged,await Promise.all([Vi(e,b),uQ(e,b)])}}else if(E.eventType==="attr_set"&&V)jr=await Ig(b,async()=>{let T=await $e(pe(e,"runs",b,t),Wt);if(!T)throw new Vn(b);if(lA(E.eventData.changes,{existingKeys:Object.keys(T.attributes),allowReservedAttributes:E.eventData.allowReservedAttributes===!0}),E.correlationId&&E.eventData.writer.type==="workflow"){let le=t?`${b}-${E.correlationId}.created.${t}`:`${b}-${E.correlationId}.created`,me=ze(e,".locks","attributes",le);if(!await ke(me,""))throw new Ge(`Attribute event "${E.correlationId}" already exists`)}let Y={...T,attributes:Ea(T.attributes,E.eventData.changes),updatedAt:he};return await Ke(pe(e,"runs",b,t),Y,{overwrite:!0}),Y});else if(E.eventType==="step_created"&&"eventData"in E){let T=t?`${b}-${E.correlationId}.created.${t}`:`${b}-${E.correlationId}.created`,Y=ze(e,".locks","steps",T);if(!await ke(Y,""))throw new Ge(`Step "${E.correlationId}" already created`);let me=E.eventData;Sr={runId:b,stepId:E.correlationId,stepName:me.stepName,status:"pending",input:me.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:he,updatedAt:he,specVersion:lr};let ge=`${b}-${E.correlationId}`;await Ke(pe(e,Qe("steps",b),ge,t),Sr)}else if(E.eventType==="step_started"){if(!st&&su){let T=E.eventData,Y=t?`${b}-${E.correlationId}.created.${t}`:`${b}-${E.correlationId}.created`,le=ze(e,".locks","steps",Y);if(!await ke(le,""))throw new Ge(`Step "${E.correlationId}" already created`);else{let ge={runId:b,stepId:E.correlationId,stepName:T.stepName,status:"pending",input:T.input,output:void 0,error:void 0,attempt:0,startedAt:void 0,completedAt:void 0,createdAt:he,updatedAt:he,specVersion:lr};await Ke(pe(e,Qe("steps",b),`${b}-${E.correlationId}`,t),ge);let it=await C(b),It={eventType:"step_created",runId:b,eventId:it,createdAt:he,specVersion:lr,correlationId:E.correlationId,eventData:{stepName:T.stepName,input:T.input}};await S(It),st=ge,hQ=!0}}if(st){if(st.retryAfter&&st.retryAfter.getTime()>Date.now())throw new Xu(`Cannot start step "${E.correlationId}": retryAfter timestamp has not been reached yet`,{retryAfter:Math.ceil((st.retryAfter.getTime()-Date.now())/1000)});let T=`${b}-${E.correlationId}`,Y=await Me(e,Qe("steps",b),T,gA,t);if(Y&&Hu(Y.status))throw new Ge(`Cannot modify step in terminal state "${Y.status}"`);Sr={...st,status:"running",startedAt:st.startedAt??he,attempt:st.attempt+1,retryAfter:void 0,updatedAt:he},await Ke(pe(e,Qe("steps",b),T,t),Sr,{overwrite:!0})}}else if(E.eventType==="step_completed"&&"eventData"in E){let T=E.eventData;if(st){let Y=`${b}-${E.correlationId}`,le=t?`${Y}.terminal.${t}`:`${Y}.terminal`,me=ze(e,".locks","steps",le);if(!await ke(me,""))throw new Ge("Cannot modify step in terminal state");Sr={...st,status:"completed",output:T.result,completedAt:he,updatedAt:he},await Ke(pe(e,Qe("steps",b),Y,t),Sr,{overwrite:!0})}}else if(E.eventType==="step_failed"&&"eventData"in E){let T=E.eventData;if(st){let Y=`${b}-${E.correlationId}`,le=t?`${Y}.terminal.${t}`:`${Y}.terminal`,me=ze(e,".locks","steps",le);if(!await ke(me,""))throw new Ge("Cannot modify step in terminal state");Sr={...st,status:"failed",error:T.error,completedAt:he,updatedAt:he},await Ke(pe(e,Qe("steps",b),Y,t),Sr,{overwrite:!0})}}else if(E.eventType==="step_retrying"&&"eventData"in E){let T=E.eventData;if(st){let Y=`${b}-${E.correlationId}`;Sr={...st,status:"pending",error:T.error,retryAfter:T.retryAfter,updatedAt:he},await Ke(pe(e,Qe("steps",b),Y,t),Sr,{overwrite:!0})}}else if(E.eventType==="hook_created"&&"eventData"in E){let T=E.eventData,Y=yA(e,T.token),le,me=()=>JSON.stringify({token:T.token,hookId:E.correlationId,runId:b,eventId:O,tokenRetentionUntil:T.tokenRetentionUntil,...le&&{claimedFrom:le}}),ge=await iE(e,T.token,async(It)=>{let Oe=await qs(Y);if(!Oe)It.throwIfAborted(),await rt(Y),await eQ(e,T.token,t),Oe=await qs(Y);if(!Oe)return It.throwIfAborted(),iQ(await ke(Y,me())),{status:"claimed"};if(Oe.runId===b&&Oe.hookId===E.correlationId)return{status:"owned",claim:Oe};if(!await T7(e,Oe,t)){if(T.force!==!0||!Oe.hookId)return{status:"conflict",claim:Oe};It.throwIfAborted();let Kr=await Me(e,"runs",Oe.runId,Wt,t),gn=Kr!==null&&!Jt(Kr.status);if(le={runId:Oe.runId,hookId:Oe.hookId,...gn&&{workflowName:Kr.workflowName,deploymentId:Kr.deploymentId,runSpecVersion:Kr.specVersion}},gn&&(Kr.specVersion??qu)<Sa)return{status:"conflict",claim:Oe,forceRefusedReason:"victim-spec-version"};let Xr=await aO(e,b,E.correlationId);if(Xr)O=Xr,Pi={...Fe,eventId:O};else Pi=await S({...Fe,eventData:{...Fe.eventData,forceClaimedFrom:le}}),O=Pi.eventId;await DA(e,b,E.correlationId,t),await Ke(pe(e,"hooks",E.correlationId,t),{runId:b,hookId:E.correlationId,token:T.token,metadata:T.metadata,ownerId:"local-owner",projectId:"local-project",environment:"local",createdAt:he,specVersion:lr,isWebhook:T.isWebhook??!1,isSystem:T.isSystem??!1,tokenRetentionUntil:T.tokenRetentionUntil,claimedFrom:le},{overwrite:!0});let iu=await ke(BA(e,Oe.hookId,t),JSON.stringify({forceClaimedBy:{runId:b,hookId:E.correlationId}}));if(gn){if(iu){let Bg={eventType:"hook_disposed",correlationId:Oe.hookId,eventData:{token:T.token,forceClaimedBy:{runId:b,hookId:E.correlationId}},runId:Oe.runId,eventId:await C(Oe.runId),createdAt:new Date,specVersion:Kr.specVersion};await S(Bg)}}}if(It.throwIfAborted(),le)await _r(Y,me(),{overwrite:!0});else await rt(Y);if(Oe.hookId)await rt(pe(e,"hooks",Oe.hookId,t)),await rt(mo(e,T.token,Oe.runId,Oe.hookId)),await lE(e,Oe.runId,Oe.hookId,t);if(It.throwIfAborted(),!le)iQ(await ke(Y,me()));return{status:"claimed"}});if(ge.status==="owned"&&ge.claim.claimedFrom)le=ge.claim.claimedFrom;if(ge.status==="owned"){let It=ge.claim,Oe;if(It.eventId)Oe=It.eventId;else{let gn=await aO(e,b,E.correlationId);if(gn!==null)throw await cO(e,b,E.correlationId,gn,t),new Ge(`Hook "${E.correlationId}" already created`);let Xr=await F7(e,T.token,b,E.correlationId,O);if(Xr===null)throw new Ge(`Hook "${E.correlationId}" already created`);Oe=Xr}O=Oe,Pe=!0;let Kr=Eo(O.replace(/^evnt_/,""))??he;Fe={...E,eventData:{...E.eventData,tokenRetentionUntil:It.tokenRetentionUntil},runId:b,eventId:O,createdAt:Kr,specVersion:lr}}if(ge.status==="conflict"){let It=ge.claim,Oe={eventType:"hook_conflict",correlationId:E.correlationId,eventData:{token:T.token,conflictingRunId:It.runId,...ge.forceRefusedReason!==void 0&&{forceRefusedReason:ge.forceRefusedReason}},runId:b,eventId:O,createdAt:he,specVersion:lr},Kr=await S(Oe),gn=F?.resolveData??Bt,Xr=typeof F?.sinceCursor==="string"?await H(b,{sortOrder:"asc",cursor:F.sinceCursor}):void 0,iu={event:dr(Kr,gn),run:jr,step:Sr,hook:void 0};if(!Xr)return iu;return{...iu,events:gn==="none"?Xr.data.map((Bg)=>dr(Bg,gn)):Xr.data,cursor:Xr.cursor,hasMore:Xr.hasMore}}if(le)Fe={...Fe,eventData:{...Fe.eventData,forceClaimedFrom:le}};let it=Fe.eventData;Xo={runId:b,hookId:E.correlationId,token:it.token,metadata:it.metadata,ownerId:"local-owner",projectId:"local-project",environment:"local",createdAt:Fe.createdAt,specVersion:lr,isWebhook:it.isWebhook??!1,isSystem:it.isSystem??!1,tokenRetentionUntil:it.tokenRetentionUntil,...le&&{claimedFrom:le}},dQ=ge.status==="owned"||le?{overwrite:!0}:void 0,await Bl(e,T.token,b,E.correlationId,O,t)}else if(E.eventType==="hook_disposed"){let T=BA(e,E.correlationId,t);if(!await ke(T,""))throw new Ge(`Hook "${E.correlationId}" already disposed`);let le=pe(e,"hooks",E.correlationId,t),me=await Me(e,"hooks",E.correlationId,zt,t);if(me)await Cl(e,me.token,me.runId,me.hookId),await rt(mo(e,me.token,me.runId,me.hookId));await rt(le),await lE(e,b,E.correlationId,t)}else if(E.eventType==="wait_created"&&"eventData"in E){let T=`${b}-${E.correlationId}`,Y=t?`${T}.created.${t}`:`${T}.created`,le=ze(e,".locks","waits",Y);if(!await ke(le,""))throw new Ge(`Wait "${E.correlationId}" already exists`);let ge=E.eventData;$i={waitId:T,runId:b,status:"waiting",resumeAt:ge.resumeAt,completedAt:void 0,createdAt:he,updatedAt:he,specVersion:lr},await Ke(pe(e,"waits",T,t),$i)}else if(E.eventType==="wait_completed"){let T=`${b}-${E.correlationId}`,Y=t?`${T}.completed.${t}`:`${T}.completed`,le=ze(e,".locks","waits",Y);if(!await ke(le,""))throw new Ge(`Wait "${E.correlationId}" already completed`);let ge=await Me(e,"waits",T,ud,t);if(!ge)throw await aQ.unlink(le).catch(()=>{}),new We(`Wait "${E.correlationId}" not found`);$i={...ge,status:"completed",completedAt:he,updatedAt:he},await Ke(pe(e,"waits",T,t),$i,{overwrite:!0})}if(E.eventType==="hook_received"&&E.correlationId)await x(E.correlationId,E.eventData?.token);if(E.eventType==="hook_created"&&E.correlationId){let T=await Ha(e,E.correlationId,t);if(T.committed&&T.forceClaimedBy)throw new Ge(`Hook "${E.correlationId}" was force-claimed by another run before its creation was journaled`)}let Ji=pe(e,Qe("events",b),`${b}-${O}`,t),Wi=JSON.stringify(Fe,qt,2),QO=async(T)=>{let Y=fo(O);if(Pe||Y===null)return!1;let le=await d(b,{rescan:T>0&&T%8===0,atLeast:Y+1});if(le===null)return!1;return O=lo(le),Fe={...Fe,eventId:O},Ji=pe(e,Qe("events",b),`${b}-${O}`,t),Wi=JSON.stringify(Fe,qt,2),!0},Is=!1;if(Pi)Fe=Pi,Ji=pe(e,Qe("events",b),`${b}-${O}`,t),Wi=JSON.stringify(Fe,qt,2),Is=!0;for(let T=0;!Is;T++){if(E.eventType==="hook_received"){let Y=await Ws(e,b,t),le=Y?null:await Me(e,"runs",b,Wt,t);if(Y||le&&Jt(le.status))throw new Ur(`Workflow run "${b}" is already in a terminal state`);let me=El(e,b,`${O}.${wA()}`,t);if(!await ke(me,Wi))throw new We(`Failed to stage event "${O}" for run "${b}": staging path already exists`);try{if(await Ws(e,b,t))throw new Ur(`Workflow run "${b}" is already in a terminal state`);let it=await nl(me,Ji);if(it==="missing")throw new Ur(`Workflow run "${b}" is already in a terminal state`);Is=it==="linked"}finally{await rt(me).catch(()=>{})}}else Is=await ke(Ji,Wi);if(Is){I(b,O);break}if(E.eventType==="hook_received"&&F?.resumeId){let Y=await Me(e,Qe("events",b),`${b}-${O}`,Zr,t);if(Y&&Cg(Y,{runId:b,resumeId:F.resumeId,hookId:E.correlationId,eventId:O}))return{event:Y}}if(E.eventType==="hook_created"&&E.correlationId){let Y=await Me(e,Qe("events",b),`${b}-${O}`,Zr,t);if(Y?.eventType==="hook_created"&&Y.correlationId===E.correlationId)break}if(!await QO(T))break}if(!Is){if(E.eventType==="hook_created"&&E.correlationId)await cO(e,b,E.correlationId,O,t);throw new Ge(`Event "${O}" already exists for run "${b}"`)}if(D(Fe,Ji,Wi),E.eventType==="hook_received"&&F?.resumeId&&St!==null&&St!==O)await _r(pl(e,b,F.resumeId),JSON.stringify({runId:b,resumeId:F.resumeId,hookId:E.correlationId,eventId:O,...F.resumePayloadDigest?{payloadDigest:F.resumePayloadDigest}:{}}),{overwrite:!0});if(Xo&&E.eventType==="hook_created")await DA(e,Xo.runId,Xo.hookId,t),await Ke(pe(e,"hooks",Xo.hookId,t),Xo,dQ);if(Gi)await gg(e,b,t),u(b);let Qg=F?.resolveData??Bt,BO=dr(Fe,Qg),ps;if(E.eventType==="run_started"&&jr&&!F?.skipPreload)ps=await H(b,{limit:Yn()});if(typeof F?.sinceCursor==="string"){let T=await H(b,{sortOrder:"asc",cursor:F.sinceCursor});ps=Qg==="none"?{...T,data:T.data.map((Y)=>dr(Y,Qg))}:T}let EQ={event:BO,run:jr,step:Sr,hook:Xo,wait:$i,...hQ?{stepCreated:!0}:{},...jr?{maxEvents:Yn()}:{}};if(!ps)return EQ;return{...EQ,events:ps.data,cursor:ps.cursor,hasMore:ps.hasMore}}},async get(N,E,F){de("runId",N),de("eventId",E);let Z=`${N}-${E}`,O=await Me(e,Qe("events",N),Z,Zr,t);if(!O)throw Error(`Event ${E} in run ${N} not found`);let Pe=F?.resolveData??Bt;return dr(O,Pe)},async list(N){let{runId:E}=N;de("runId",E);let F=N.resolveData??Bt,Z=await H(E,{...N.pagination,limit:N.pagination?.limit??Yn()});if(F==="none")return{...Z,data:Z.data.map((O)=>dr(O,F))};return Z},async listByCorrelationId(N){let E=N.correlationId;de("correlationId",E),de("runId",N.runId);let F=N.resolveData??Bt,Z=await pn({directory:ds.join(e,Qe("events",N.runId)),schema:Zr,cachedItems:A,filePrefix:`${N.runId}-`,filter:(O)=>O.correlationId===E,sortOrder:N.pagination?.sortOrder??"asc",limit:N.pagination?.limit,cursor:N.pagination?.cursor,getCreatedAt:yo("evnt"),getId:(O)=>O.eventId,getSortKey:sO,getSortKeyFromFileId:(O)=>iO(N.runId,O)});if(F==="none")return{...Z,data:Z.data.map((O)=>dr(O,F))};return Z}};async function U(N,E,F){if(!N.event)return N;let Z=fo(N.event.eventId);if(Z===null||E<ya||Z<=E+1)return N;let O=Z-E-1,Pe=await M.list({runId:N.event.runId,pagination:{cursor:`${ka}${lo(E)}`,limit:O,sortOrder:"asc"},resolveData:F}),St=N.event.eventId,he=Pe.data.filter((b)=>b.eventId<St);return{...N,events:he,cursor:null,hasMore:he.length<Z-E-1}}let v=async(N,E,F)=>{if(F?.eventCount===void 0)return M.create(N,E,F);let Z=F.resolveData??Bt,O=await M.create(N,E,F);if(typeof F.sinceCursor==="string")return O;return U(O,F.eventCount,Z)},te=M7(),q=(N)=>`${ds.resolve(e)}\x00${g(N)}`,G=async(N)=>await $e(lQ(e,N,t),_7)??{seqInBand:sd},P=(N,E)=>Ke(lQ(e,N,t),E,{overwrite:!0});async function ae(N){let E=f.get(g(N));if(E===null)return;let F=await zs(e,N,t);if(E===void 0&&F.count>0&&!F.usesSlots)return;return Math.max(E?.published??0,F.maxSlot)}async function Ee(N){let E=await G(N);if(E.pending===void 0)return E.seqInBand;let F=Math.max(E.seqInBand,E.pending+1);return await P(N,{seqInBand:F}),F}async function ye(N,E,F){let Z=await ae(N).catch(()=>{return});return new Od(`In-band write on run ${N} expected seqInBand ${E}, but the run is at ${F}. Another orchestrator wrote in-band events this one has not seen; stop writing and redeliver.`,{seqInBand:F,...Z!==void 0?{seq:Z}:{}})}function At(N,E){return vs(te.locks,q(N),async()=>{let F=lQ(e,N,t);await aQ.mkdir(ds.dirname(F),{recursive:!0});let Z,O;try{O=await uO.lock(F,{realpath:!1,stale:30000,update:1000,retries:{retries:350,factor:1,minTimeout:100,maxTimeout:100},onCompromised(St){Z=St}})}catch(St){throw new We(`Could not acquire the in-band fence lock of run ${N}`,{cause:St})}let Pe;try{Pe=await E()}finally{if(!Z)await O().catch(()=>{})}if(Z)throw new We(`The in-band fence lock of run ${N} was lost while a write held it`,{cause:Z});return Pe})}let ur=async(N,E,F)=>{let Z=E;if(!F?.inBand||!N||E.eventType==="run_created")return v(N,Z,F);let O=F.expectedSeqInBand;if(O===void 0||!Number.isSafeInteger(O)||O<0)throw new We(`An in-band write to run ${N} must carry a nonnegative integer expectedSeqInBand`,{status:400});return de("runId",N),At(N,async()=>{let Pe=await Ee(N);if(Pe!==O)throw await ye(N,O,Pe);await P(N,{seqInBand:Pe,pending:Pe});let St;try{St=await v(N,Z,F)}catch(b){throw await P(N,{seqInBand:U7(b)?Pe:Pe+1}),b}let he=St.event?1:0;return await P(N,{seqInBand:Pe+he}),{...St,allocated:he}})};async function pO(N){let{seqInBand:E}=await G(N),F=f.get(g(N));if(F===null)return;if(F!==void 0)return{seq:F.published,seqInBand:E};let Z=await zs(e,N,t);if(Z.count>0&&!Z.usesSlots)return;return{seq:Z.maxSlot,seqInBand:E}}return{...M,create:ur,list:async(N)=>{de("runId",N.runId);let E=await pO(N.runId),F=await M.list(N);return E?{...F,snapshot:E}:F}}}Lt();import L7 from"node:fs/promises";import v7 from"node:path";function gO(e){let t=v7.join(e,"snapshots");function r(n){return de("runId",n),ze(t,`${n}.snapshot`)}return{async save(n,o,A){await rl(t),await _r(r(n),Buffer.from(Dd(A,o)),{overwrite:!0})},async load(n){let o;try{o=await Ys(r(n))}catch(A){if(A.code==="ENOENT")return null;throw A}return Sd(new Uint8Array(o.buffer,o.byteOffset,o.byteLength))},async delete(n){await L7.rm(r(n),{force:!0})}}}Lt();import O7 from"node:path";function hO(e,t){return{get:async(r,n,o)=>{de("runId",r),de("stepId",n);let A=`${r}-${n}`,s=await Me(e,Qe("steps",r),A,gA,t);if(!s)throw Error(`Step ${n} in run ${r} not found`);let i=o?.resolveData??Bt;return Hv(s,i)},list:async(r)=>{de("runId",r.runId);let n=r.resolveData??Bt,o=await pn({directory:O7.join(e,Qe("steps",r.runId)),schema:gA,filePrefix:`${r.runId}-`,sortOrder:r.pagination?.sortOrder??"desc",limit:r.pagination?.limit,cursor:r.pagination?.cursor,getCreatedAt:yo("step"),getId:(A)=>A.stepId});if(n==="none")return{...o,data:o.data.map((A)=>({...A,input:void 0,output:void 0}))};return o}}}function fQ(e,t){let r=oO(e,t),n=hO(e,t),o=fO(e,t),A=$v(e,t),s=gO(e);return{runs:Do("world.runs",r),steps:Do("world.steps",n),events:Do("world.events",o),hooks:Do("world.hooks",A),experimental_snapshots:Do("world.experimental_snapshots",s),clearCache:()=>o.clearCache()}}async function Y7(e,t){let r=Tt.join(e,".locks"),n;try{n=await Es.readdir(r,{withFileTypes:!0})}catch{n=[]}await An(n.filter((o)=>o.isDirectory()).map(async(o)=>{let A=Tt.join(r,o.name),s=await Es.readdir(A).catch(()=>[]);await An(s.filter((i)=>i.endsWith(`.${t}`)).map((i)=>Es.rm(Tt.join(A,i),{recursive:!0,force:!0})))}))}function dO(e){let t=e?Object.fromEntries(Object.entries(e).filter(([,u])=>u!==void 0)):{},r={...jS.value,...t};$S(r.dataDir);let n=r.tag,o=Ov(r),{clearCache:A,...s}=fQ(r.dataDir,n),{clearCache:i,...a}=Kv(r.dataDir,n),c=KS(r);return{specVersion:Nd(),capabilities:{hookRetention:{active:!0},dynamicWorkflowCode:!0,hookResumeDedup:!0,hookForceClaim:!0,inBandFence:!0},...o,...s,...Do("world.streams",{...a,...r.streamFlushIntervalMs!==void 0&&{streamFlushIntervalMs:r.streamFlushIntervalMs}}),async start(){if(await Dl(r.dataDir),!c)return;let u=n?(f)=>Hs(f,n):EA,l={...s.runs,list:(f)=>s.runs.list({...f,fileIdFilter:u})};await Bd(l,o.queue,"world-local")},async close(){A(),await o.close()},async clear(){if(A(),n){let u=r.dataDir,l=Tt.join(u,"hooks"),f=await Ta(l,n);await Promise.resolve().then(() => Lt());await An(f.map(async(p)=>{let Q=await $e(Tt.join(l,p),zt);if(Q?.token)await rt(Tt.join(l,"tokens",`${Oa(Q.token)}.json`)),await rt(mo(u,Q.token,Q.runId,Q.hookId))}));let h=(await Ta(Tt.join(u,"runs"),n)).flatMap((p)=>{let Q=p.slice(0,-`.${n}.json`.length);return[Tt.join("steps",Q),Tt.join("events",Q)]}),d=["runs",...h,"hooks","hooks/by-run","waits","streams/runs"];await An(d.map(async(p)=>{let Q=Tt.join(u,p),D=await Ta(Q,n);await An(D.map((S)=>rt(Tt.join(Q,S))))})),await An(h.map((p)=>Es.rmdir(Tt.join(u,p)).catch(()=>{})));for(let p of["token-index","id-index"]){let Q=Tt.join(u,"hooks",p),D;try{D=await Es.readdir(Q,{withFileTypes:!0})}catch{D=[]}await An(D.filter((S)=>S.isDirectory()).map(async(S)=>{let x=Tt.join(Q,S.name),H=await Ta(x,n);await An(H.map((L)=>rt(Tt.join(x,L))))}))}await Y7(u,n);let I=Tt.join(u,"streams","chunks"),C;try{C=await Es.readdir(I,{withFileTypes:!0})}catch{C=[]}await An(C.filter((p)=>p.isDirectory()).map(async(p)=>{let Q=Tt.join(I,p.name),D=await r0(Q,n,".bin");await An(D.map((S)=>Es.unlink(Tt.join(Q,S)).catch(()=>{})))})),ba()}else ba(),yl(),await H7(r.dataDir,{recursive:!0,force:!0}),await Dl(r.dataDir);i()}}}var V7=Symbol.for("libfx.durability");function EO(e,t={}){let r=typeof e==="function";if(!r&&!(e&&typeof e==="object"))throw TypeError("world() takes a World or a function that creates one");if(!t||typeof t!=="object"||Array.isArray(t))throw TypeError("world() options must be an object");let{name:n="world",store:o=n,livenessKnown:A=!1,queueLeases:s=!1,runInRequest:i=s,waitUntil:a,queueDurable:c=!1,pollMs:u,leaseMs:l,maxDurationMs:f,reserveMs:g,alive:h,holderInfo:d,gatewayKey:I}=t;if(typeof n!=="string"||n.length===0)throw TypeError("world() name must be a non-empty string");if(typeof o!=="string"||o.length===0)throw TypeError(`${n}() store must be a non-empty string`);for(let[C,p]of Object.entries({livenessKnown:A,queueLeases:s,runInRequest:i,queueDurable:c}))if(typeof p!=="boolean")throw TypeError(`${n}() ${C} must be a boolean`);if(u!==void 0&&!(Number.isSafeInteger(u)&&u>0))throw TypeError(`${n}() pollMs must be a positive integer`);if(l!==void 0&&!(Number.isSafeInteger(l)&&l>=1000))throw TypeError(`${n}() leaseMs must be an integer of at least 1000`);for(let[C,p]of Object.entries({maxDurationMs:f,reserveMs:g}))if(p!==void 0&&!(Number.isSafeInteger(p)&&p>=0))throw TypeError(`${n}() ${C} must be a non-negative integer`);for(let[C,p]of Object.entries({alive:h,holderInfo:d,gatewayKey:I,waitUntil:a}))if(p!==void 0&&typeof p!=="function")throw TypeError(`${n}() ${C} must be a function`);if(A&&!h)throw TypeError(`${n}() livenessKnown needs alive()`);if(i&&!s)throw TypeError(`${n}() runInRequest needs queueLeases`);return{[V7]:!0,name:n,store:o,world:r?e:()=>e,owned:r,livenessKnown:A,queueLeases:s,runInRequest:i,queueDurable:c,...u===void 0?{}:{pollMs:u},...l===void 0?{}:{leaseMs:l},...f===void 0?{}:{maxDurationMs:f},...g===void 0?{}:{reserveMs:g},...h===void 0?{}:{alive:h},...d===void 0?{}:{holderInfo:d},...I===void 0?{}:{gatewayKey:I},...a===void 0?{}:{waitUntil:a}}}var IO=P7();function Ele({dir:e,maxDurationMs:t,reserveMs:r}={}){if(e!==void 0&&(typeof e!=="string"||e.length===0))throw TypeError("local() dir must be a path");return EO(()=>dO({...e===void 0?{}:{dataDir:e},recoverActiveRuns:!1}),{name:"local",store:`local:${e===void 0?"":G7(e)}`,livenessKnown:!0,queueDurable:!1,pollMs:250,maxDurationMs:t,reserveMs:r,holderInfo:()=>({pid:process.pid,host:IO}),alive(n){if(n.host!==IO||!Number.isSafeInteger(n.pid))return null;try{return process.kill(n.pid,0),!0}catch(o){return o?.code==="EPERM"}}})}export{Ele as local};
|
|
191
|
+
|
|
192
|
+
//# debugId=6631C98D8FAEA5D564756E2164756E21
|
|
193
|
+
//# sourceMappingURL=local.mjs.map
|