experimental-ash 0.22.2 → 0.23.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/CHANGELOG.md +14 -0
  2. package/dist/docs/public/faqs.md +67 -0
  3. package/dist/docs/public/meta.json +1 -0
  4. package/dist/docs/public/schedules.md +11 -0
  5. package/dist/docs/public/session-context.md +46 -89
  6. package/dist/docs/public/skills.md +13 -0
  7. package/dist/docs/public/subagents.md +12 -6
  8. package/dist/docs/public/tools.md +9 -13
  9. package/dist/docs/public/typescript-api.md +2 -2
  10. package/dist/src/chunks/{client-CKsU8Li3.js → client-nshDsWNF.js} +1 -1
  11. package/dist/src/chunks/{dev-authored-source-watcher-BLzYWh05.js → dev-authored-source-watcher-d_35Mp8T.js} +1 -1
  12. package/dist/src/chunks/{host-DREC8e8Z.js → host-tji7W0Nn.js} +2 -2
  13. package/dist/src/chunks/paths-YoCQlavu.js +89 -0
  14. package/dist/src/chunks/{prewarm-hz8p2jlZ.js → prewarm-6duWvvb5.js} +1 -1
  15. package/dist/src/cli/commands/info.js +1 -1
  16. package/dist/src/cli/dev/repl.js +2 -2
  17. package/dist/src/cli/run.js +1 -1
  18. package/dist/src/client/session.js +8 -0
  19. package/dist/src/client/types.d.ts +12 -1
  20. package/dist/src/compiled/.vendor-stamp.json +1 -1
  21. package/dist/src/compiled/@workflow/core/_ms.d.ts +4 -0
  22. package/dist/src/compiled/@workflow/core/_workflow-serde.d.ts +5 -0
  23. package/dist/src/compiled/@workflow/core/_workflow-utils.d.ts +8 -0
  24. package/dist/src/compiled/@workflow/core/_workflow-world.d.ts +59 -0
  25. package/dist/src/compiled/@workflow/core/capabilities.d.ts +45 -0
  26. package/dist/src/compiled/@workflow/core/capture-stack.d.ts +16 -0
  27. package/dist/src/compiled/@workflow/core/class-serialization.d.ts +31 -0
  28. package/dist/src/compiled/@workflow/core/classify-error.d.ts +19 -0
  29. package/dist/src/compiled/@workflow/core/context-errors.d.ts +27 -0
  30. package/dist/src/compiled/@workflow/core/context-violation-error.d.ts +97 -0
  31. package/dist/src/compiled/@workflow/core/create-hook.d.ts +179 -0
  32. package/dist/src/compiled/@workflow/core/define-hook.d.ts +68 -0
  33. package/dist/src/compiled/@workflow/core/describe-error.d.ts +70 -0
  34. package/dist/src/compiled/@workflow/core/encryption.d.ts +45 -0
  35. package/dist/src/compiled/@workflow/core/events-consumer.d.ts +64 -0
  36. package/dist/src/compiled/@workflow/core/flushable-stream.d.ts +82 -0
  37. package/dist/src/compiled/@workflow/core/global.d.ts +48 -0
  38. package/dist/src/compiled/@workflow/core/index.d.ts +19 -38
  39. package/dist/src/compiled/@workflow/core/log-format.d.ts +25 -0
  40. package/dist/src/compiled/@workflow/core/logger.d.ts +29 -0
  41. package/dist/src/compiled/@workflow/core/private.d.ts +59 -10
  42. package/dist/src/compiled/@workflow/core/runtime/constants.d.ts +4 -0
  43. package/dist/src/compiled/@workflow/core/runtime/get-port-lazy.d.ts +10 -0
  44. package/dist/src/compiled/@workflow/core/runtime/get-world-lazy.d.ts +32 -0
  45. package/dist/src/compiled/@workflow/core/runtime/helpers.d.ts +97 -0
  46. package/dist/src/compiled/@workflow/core/runtime/resume-hook.d.ts +77 -0
  47. package/dist/src/compiled/@workflow/core/runtime/run.d.ts +134 -0
  48. package/dist/src/compiled/@workflow/core/runtime/runs.d.ts +50 -0
  49. package/dist/src/compiled/@workflow/core/runtime/start.d.ts +59 -0
  50. package/dist/src/compiled/@workflow/core/runtime/step-executor.d.ts +40 -0
  51. package/dist/src/compiled/@workflow/core/runtime/step-handler.d.ts +2 -0
  52. package/dist/src/compiled/@workflow/core/runtime/suspension-handler.d.ts +42 -0
  53. package/dist/src/compiled/@workflow/core/runtime/world-init.d.ts +75 -0
  54. package/dist/src/compiled/@workflow/core/runtime/world.d.ts +32 -0
  55. package/dist/src/compiled/@workflow/core/runtime.d.ts +22 -67
  56. package/dist/src/compiled/@workflow/core/schemas.d.ts +15 -0
  57. package/dist/src/compiled/@workflow/core/serialization/client.d.ts +17 -0
  58. package/dist/src/compiled/@workflow/core/serialization/codec-devalue.d.ts +14 -0
  59. package/dist/src/compiled/@workflow/core/serialization/codec.d.ts +90 -0
  60. package/dist/src/compiled/@workflow/core/serialization/encryption.d.ts +32 -0
  61. package/dist/src/compiled/@workflow/core/serialization/errors.d.ts +21 -0
  62. package/dist/src/compiled/@workflow/core/serialization/format.d.ts +60 -0
  63. package/dist/src/compiled/@workflow/core/serialization/index.d.ts +18 -0
  64. package/dist/src/compiled/@workflow/core/serialization/reducers/class.d.ts +11 -0
  65. package/dist/src/compiled/@workflow/core/serialization/reducers/common.d.ts +16 -0
  66. package/dist/src/compiled/@workflow/core/serialization/reducers/step-function.d.ts +35 -0
  67. package/dist/src/compiled/@workflow/core/serialization/step.d.ts +17 -0
  68. package/dist/src/compiled/@workflow/core/serialization/types.d.ts +201 -0
  69. package/dist/src/compiled/@workflow/core/serialization/workflow.d.ts +29 -0
  70. package/dist/src/compiled/@workflow/core/serialization-format.d.ts +171 -0
  71. package/dist/src/compiled/@workflow/core/serialization.d.ts +329 -0
  72. package/dist/src/compiled/@workflow/core/sleep.d.ts +33 -0
  73. package/dist/src/compiled/@workflow/core/source-map.d.ts +10 -0
  74. package/dist/src/compiled/@workflow/core/step/context-storage.d.ts +13 -0
  75. package/dist/src/compiled/@workflow/core/step/get-closure-vars.d.ts +9 -0
  76. package/dist/src/compiled/@workflow/core/step/get-step-metadata.d.ts +42 -0
  77. package/dist/src/compiled/@workflow/core/step/get-workflow-metadata.d.ts +7 -0
  78. package/dist/src/compiled/@workflow/core/step/writable-stream.d.ts +22 -0
  79. package/dist/src/compiled/@workflow/core/step.d.ts +4 -0
  80. package/dist/src/compiled/@workflow/core/symbols.d.ts +20 -0
  81. package/dist/src/compiled/@workflow/core/telemetry/semantic-conventions.d.ts +283 -0
  82. package/dist/src/compiled/@workflow/core/telemetry.d.ts +53 -0
  83. package/dist/src/compiled/@workflow/core/types.d.ts +14 -0
  84. package/dist/src/compiled/@workflow/core/util.d.ts +40 -0
  85. package/dist/src/compiled/@workflow/core/version.d.ts +2 -0
  86. package/dist/src/compiled/@workflow/core/vm/index.d.ts +17 -0
  87. package/dist/src/compiled/@workflow/core/vm/uint8array-base64.d.ts +21 -0
  88. package/dist/src/compiled/@workflow/core/vm/uuid.d.ts +10 -0
  89. package/dist/src/compiled/@workflow/core/workflow/abort-controller.d.ts +65 -0
  90. package/dist/src/compiled/@workflow/core/workflow/create-hook.d.ts +7 -0
  91. package/dist/src/compiled/@workflow/core/workflow/define-hook.d.ts +10 -0
  92. package/dist/src/compiled/@workflow/core/workflow/get-workflow-metadata.d.ts +32 -0
  93. package/dist/src/compiled/@workflow/core/workflow/hook.d.ts +4 -0
  94. package/dist/src/compiled/@workflow/core/workflow/index.d.ts +11 -0
  95. package/dist/src/compiled/@workflow/core/workflow/sleep.d.ts +4 -0
  96. package/dist/src/compiled/@workflow/core/workflow/world-init-stub.d.ts +15 -0
  97. package/dist/src/compiled/@workflow/core/workflow/writable-stream.d.ts +3 -0
  98. package/dist/src/compiled/@workflow/core/workflow.d.ts +1 -38
  99. package/dist/src/evals/cli/eval.js +1 -1
  100. package/dist/src/internal/application/package.js +1 -1
  101. package/dist/src/protocol/message.d.ts +6 -1
  102. package/dist/src/public/channels/ash.js +50 -3
  103. package/dist/src/public/context/index.d.ts +4 -7
  104. package/dist/src/public/context/index.js +4 -5
  105. package/dist/src/public/definitions/state.d.ts +33 -0
  106. package/dist/src/public/definitions/state.js +34 -0
  107. package/dist/src/public/next/index.d.ts +7 -0
  108. package/dist/src/public/next/index.js +2 -0
  109. package/dist/src/public/next/vercel-json.d.ts +1 -0
  110. package/dist/src/public/next/vercel-json.js +1 -0
  111. package/dist/src/react/index.d.ts +1 -1
  112. package/dist/src/react/use-ash-agent.d.ts +8 -0
  113. package/dist/src/react/use-ash-agent.js +26 -4
  114. package/dist/src/services/dev-client.d.ts +4 -1
  115. package/dist/src/services/dev-client.js +1 -0
  116. package/package.json +1 -1
  117. package/dist/src/chunks/paths-C6sp4T2U.js +0 -88
@@ -0,0 +1,179 @@
1
+ import type { Serializable } from './schemas.js';
2
+ /**
3
+ * An object that can be awaited to receive a value.
4
+ */
5
+ interface Thenable<T> {
6
+ then: Promise<T>['then'];
7
+ }
8
+ /**
9
+ * A `Request` that can be responded to within a workflow
10
+ * step function by calling the `respondWith()` method.
11
+ */
12
+ export interface RequestWithResponse extends Request {
13
+ respondWith: (response: Response) => Promise<void>;
14
+ }
15
+ /**
16
+ * A hook that can be awaited and/or iterated over to receive
17
+ * a value within a workflow from an external system.
18
+ *
19
+ * Hooks implement the TC39 Explicit Resource Management proposal,
20
+ * allowing them to be used with the `using` keyword for automatic disposal.
21
+ */
22
+ export interface Hook<T = any> extends AsyncIterable<T>, Thenable<T> {
23
+ /**
24
+ * The token used to identify this hook.
25
+ */
26
+ token: string;
27
+ /**
28
+ * Disposes the hook, releasing its token for reuse by other workflows.
29
+ *
30
+ * After calling `dispose()`, the hook will no longer receive any events.
31
+ * This is useful when you want to explicitly release a hook token before
32
+ * the workflow completes, allowing another workflow to register a hook
33
+ * with the same token.
34
+ *
35
+ * @example
36
+ * ```ts
37
+ * const hook = createHook<{ message: string }>({ token: 'my-token' });
38
+ *
39
+ * for await (const payload of hook) {
40
+ * if (payload.message === 'done') {
41
+ * hook.dispose(); // Release the token early
42
+ * break;
43
+ * }
44
+ * }
45
+ * ```
46
+ */
47
+ dispose(): void;
48
+ /**
49
+ * Implements the TC39 Explicit Resource Management proposal.
50
+ * Called automatically when using the `using` keyword.
51
+ *
52
+ * @example
53
+ * ```ts
54
+ * {
55
+ * using hook = createHook<{ message: string }>({ token: 'my-token' });
56
+ * const payload = await hook;
57
+ * // hook is automatically disposed when the block exits
58
+ * }
59
+ * ```
60
+ */
61
+ [Symbol.dispose](): void;
62
+ }
63
+ /**
64
+ * A webhook that can be used to suspend and resume the workflow run
65
+ * upon receiving an HTTP request to the specified URL.
66
+ *
67
+ * @see {@link createWebhook}
68
+ * @see https://developer.mozilla.org/en-US/docs/Web/API/Request
69
+ */
70
+ export interface Webhook<T extends Request> extends Hook<T> {
71
+ /**
72
+ * The URL that external systems can call to send data to the workflow.
73
+ */
74
+ url: string;
75
+ }
76
+ export interface HookOptions {
77
+ /**
78
+ * Unique token that is used to associate with the hook.
79
+ *
80
+ * When specifying an explicit token, the token should be constructed
81
+ * with information that the dispatching side can reliably reconstruct
82
+ * the token with the information it has available.
83
+ *
84
+ * Deterministic tokens are intended for use with `createHook()` and
85
+ * server-side `resumeHook()` only. For webhooks (`createWebhook()`),
86
+ * tokens are always randomly generated to prevent unauthorized access
87
+ * to the public webhook endpoint.
88
+ *
89
+ * If not provided, a randomly generated token will be assigned.
90
+ *
91
+ * @example
92
+ *
93
+ * ```ts
94
+ * // Explicit token for a Slack bot (one workflow run per channel)
95
+ * const hook = createHook<SlackMessage>({
96
+ * token: `slack_webhook:${channelId}`,
97
+ * });
98
+ * ```
99
+ */
100
+ token?: string;
101
+ /**
102
+ * Additional user-defined data to include with the hook payload.
103
+ *
104
+ * @example
105
+ *
106
+ * ```ts
107
+ * const hook = createHook<{ name: string }>({
108
+ * metadata: {
109
+ * type: "cat",
110
+ * color: "orange",
111
+ * },
112
+ * });
113
+ * ```
114
+ */
115
+ metadata?: Serializable;
116
+ /**
117
+ * Whether this hook can be resumed via the public webhook endpoint.
118
+ *
119
+ * When `true`, the hook can be triggered by sending an HTTP request to the
120
+ * public `/.well-known/workflow/v1/webhook/{token}` URL. This is automatically
121
+ * set when using `createWebhook()`.
122
+ *
123
+ * When `false` (the default), the hook can only be resumed server-side
124
+ * via `resumeHook()`.
125
+ *
126
+ * @default false
127
+ */
128
+ isWebhook?: boolean;
129
+ }
130
+ export interface WebhookOptions extends Omit<HookOptions, 'token' | 'isWebhook'> {
131
+ /**
132
+ * If set to a `Response` object, the webhook will automatically
133
+ * respond with the specified response.
134
+ *
135
+ * If set to `"manual"`, each individual request will need to
136
+ * be responded to manually from within the workflow by calling the
137
+ * `respondWith()` method.
138
+ *
139
+ * If not set then the webhook will automatically respond with
140
+ * a `202 Accepted` response.
141
+ */
142
+ respondWith?: Response | 'manual';
143
+ }
144
+ /**
145
+ * Creates a {@link Hook} that can be used to suspend and resume the workflow run with a payload.
146
+ *
147
+ * Hooks allow external systems to send arbitrary serializable data into a workflow.
148
+ *
149
+ * @param options - Configuration options for the hook.
150
+ * @returns A `Hook` that can be awaited to receive one or more payloads.
151
+ *
152
+ * @example
153
+ *
154
+ * ```ts
155
+ * export async function workflowWithHook() {
156
+ * "use workflow";
157
+ *
158
+ * const hook = createHook<{ message: string }>();
159
+ * console.log('Hook token:', hook.token);
160
+ *
161
+ * const payload = await hook;
162
+ * console.log('Received:', payload.message);
163
+ * }
164
+ * ```
165
+ */
166
+ export declare function createHook<T = any>(options?: HookOptions): Hook<T>;
167
+ /**
168
+ * Creates a {@link Webhook} that can be used to suspend and resume the workflow
169
+ * run upon receiving an HTTP request to the specified URL.
170
+ *
171
+ * Webhooks will result in a {@link https://developer.mozilla.org/en-US/docs/Web/API/Request | Request} object
172
+ * that can be interacted with in workflow functions.
173
+ */
174
+ export declare function createWebhook(options: WebhookOptions & {
175
+ respondWith: 'manual';
176
+ }): Webhook<RequestWithResponse>;
177
+ export declare function createWebhook(options?: WebhookOptions): Webhook<Request>;
178
+ export {};
179
+ //# sourceMappingURL=create-hook.d.ts.map
@@ -0,0 +1,68 @@
1
+ import type { StandardSchemaV1 } from '#compiled/@standard-schema/spec/index.js';
2
+ import type { Hook as HookEntity } from './_workflow-world.js';
3
+ import type { Hook, HookOptions } from './create-hook.js';
4
+ /**
5
+ * A typed hook interface for type-safe hook creation and resumption.
6
+ */
7
+ export interface TypedHook<TInput, TOutput> {
8
+ /**
9
+ * Creates a new hook with the defined output type.
10
+ *
11
+ * Note: This method is not available in runtime bundles. Use it from workflow contexts only.
12
+ *
13
+ * @param options - Optional hook configuration
14
+ * @returns A Hook that resolves to the defined output type
15
+ */
16
+ create(options?: HookOptions): Hook<TOutput>;
17
+ /**
18
+ * Resumes a hook by sending a payload with the defined input type.
19
+ * This is a type-safe wrapper around the `resumeHook` runtime function.
20
+ *
21
+ * @param token - The unique token identifying the hook
22
+ * @param payload - The payload to send; if a `schema` is configured it is validated/transformed before resuming
23
+ * @returns Promise resolving to the hook entity
24
+ * @throws Error if the hook is not found or if there's an error during the process
25
+ */
26
+ resume(token: string, payload: TInput): Promise<HookEntity>;
27
+ }
28
+ export declare namespace TypedHook {
29
+ /**
30
+ * Extracts the input type from a {@link TypedHook}
31
+ */
32
+ type Input<T extends TypedHook<any, any>> = T extends TypedHook<infer I, any> ? I : never;
33
+ }
34
+ /**
35
+ * Defines a typed hook for type-safe hook creation and resumption.
36
+ *
37
+ * This helper provides type safety by allowing you to define the input and output types
38
+ * for the hook's payload, with optional validation and transformation via a schema.
39
+ *
40
+ * @param schema - Schema used to validate and transform the input payload before resuming
41
+ * @returns An object with `create` and `resume` functions pre-typed with the input and output types
42
+ *
43
+ * @example
44
+ *
45
+ * ```ts
46
+ * // Define a hook with a specific payload type
47
+ * const approvalHook = defineHook<{ approved: boolean; comment: string }>();
48
+ *
49
+ * // In a workflow
50
+ * export async function workflowWithApproval() {
51
+ * "use workflow";
52
+ *
53
+ * const hook = approvalHook.create();
54
+ * const result = await hook; // Fully typed as { approved: boolean; comment: string; }
55
+ * }
56
+ *
57
+ * // In an API route
58
+ * export async function POST(request: Request) {
59
+ * const { token, approved, comment } = await request.json();
60
+ * await approvalHook.resume(token, { approved, comment }); // Input type
61
+ * return Response.json({ success: true });
62
+ * }
63
+ * ```
64
+ */
65
+ export declare function defineHook<TInput, TOutput = TInput>({ schema, }?: {
66
+ schema?: StandardSchemaV1<TInput, TOutput>;
67
+ }): TypedHook<TInput, TOutput>;
68
+ //# sourceMappingURL=define-hook.d.ts.map
@@ -0,0 +1,70 @@
1
+ import { type RunErrorCode } from '#compiled/@workflow/errors/index.js';
2
+ /**
3
+ * Attribution of a workflow/step failure for presentation.
4
+ *
5
+ * - `user`: the error came from customer code (a step or workflow function
6
+ * threw, or a value they passed across a boundary wasn't serializable).
7
+ * - `sdk`: the SDK produced the error itself — an internal invariant broke,
8
+ * or a runtime guard rejected the call. These should be rare; when they
9
+ * happen we want to frame the terminal output as "this is us, not you."
10
+ */
11
+ export type ErrorAttribution = 'user' | 'sdk';
12
+ export interface ErrorDescription {
13
+ attribution: ErrorAttribution;
14
+ errorCode: RunErrorCode;
15
+ /**
16
+ * Short, class-aware hint to help a user understand what the error means.
17
+ * Only set for well-known SDK error classes (SerializationError,
18
+ * WorkflowRuntimeError, context-violation errors); `undefined` for plain
19
+ * user errors, where the stack is already the most useful thing to show.
20
+ */
21
+ hint?: string;
22
+ }
23
+ /**
24
+ * Error signal fields carried on persisted failure events (e.g.
25
+ * `run_failed` / `step_failed`). The shape is intentionally loose:
26
+ *
27
+ * - `errorCode` is typed as `string` rather than `RunErrorCode` because
28
+ * the value comes from stored JSON/CBOR and may predate the current
29
+ * enum — callers should not narrow on it blindly. Values that don't
30
+ * match a known `RUN_ERROR_CODES` entry fall through to USER_ERROR.
31
+ * - `errorName` is the thrown `Error#name`. It is not universally
32
+ * persisted today; callers that have access to it (either via an
33
+ * in-memory throw or a richer payload) can pass it in to sharpen
34
+ * the attribution and hint. When absent, `describeRunError` still
35
+ * returns a sensible attribution from `errorCode` alone.
36
+ */
37
+ export interface PersistedErrorSignal {
38
+ errorCode?: string;
39
+ errorName?: string;
40
+ }
41
+ /**
42
+ * Data-driven variant of {@link describeError} that works from persisted
43
+ * event fields instead of a live `Error` instance. Intended for CLI/web
44
+ * renderers that read failure events and no longer have the original
45
+ * thrown object.
46
+ */
47
+ export declare function describeRunError(signal: PersistedErrorSignal): ErrorDescription;
48
+ /**
49
+ * Describe an error for user-facing presentation. Purely informational —
50
+ * does not change any persisted event data or error classification used by
51
+ * the runtime.
52
+ *
53
+ * The attribution here is more nuanced than `classifyRunError`:
54
+ *
55
+ * - `SerializationError` is technically raised by the SDK, but it almost
56
+ * always points at something the caller did (passed a non-serializable
57
+ * value, didn't register a class). We attribute it to the user.
58
+ * - Context-violation errors (`NotInWorkflowContextError`, etc.) likewise
59
+ * describe a user mistake.
60
+ * - `WorkflowRuntimeError` (and subclasses like `StepNotRegisteredError`)
61
+ * indicates an internal SDK invariant broke — surface that as `sdk`.
62
+ *
63
+ * @param err The error value thrown by the workflow / step.
64
+ * @param errorCode Optional precomputed error code. Callers that already
65
+ * know the code (e.g. `REPLAY_TIMEOUT` or `MAX_DELIVERIES_EXCEEDED`, which
66
+ * `classifyRunError` can't derive from the error alone) should pass it so
67
+ * the attribution and hint reflect the actual failure category.
68
+ */
69
+ export declare function describeError(err: unknown, errorCode?: RunErrorCode): ErrorDescription;
70
+ //# sourceMappingURL=describe-error.d.ts.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Browser-compatible AES-256-GCM encryption module.
3
+ *
4
+ * Uses the Web Crypto API (`globalThis.crypto.subtle`) which works in
5
+ * both modern browsers and Node.js 20+. This module is intentionally
6
+ * free of Node.js-specific imports so it can be bundled for the browser.
7
+ *
8
+ * The World interface (`getEncryptionKeyForRun`) returns a raw 32-byte
9
+ * AES-256 key. Callers should use `importKey()` once to convert it to a
10
+ * `CryptoKey`, then pass that to `encrypt()`/`decrypt()` for all
11
+ * operations within the same run. This avoids repeated `importKey()`
12
+ * calls on every encrypt/decrypt invocation.
13
+ *
14
+ * Wire format: `[nonce (12 bytes)][ciphertext + auth tag]`
15
+ * The `encr` format prefix is NOT part of this module — it's added/stripped
16
+ * by the serialization layer in `maybeEncrypt`/`maybeDecrypt`.
17
+ */
18
+ export type CryptoKey = import('node:crypto').webcrypto.CryptoKey;
19
+ /**
20
+ * Import a raw AES-256 key as a `CryptoKey` for use with `encrypt()`/`decrypt()`.
21
+ *
22
+ * Callers should call this once per run (after `getEncryptionKeyForRun()`)
23
+ * and pass the resulting `CryptoKey` to all subsequent encrypt/decrypt calls.
24
+ *
25
+ * @param raw - Raw 32-byte AES-256 key (from World.getEncryptionKeyForRun)
26
+ * @returns CryptoKey ready for AES-GCM operations
27
+ */
28
+ export declare function importKey(raw: Uint8Array): Promise<import("crypto").webcrypto.CryptoKey>;
29
+ /**
30
+ * Encrypt data using AES-256-GCM.
31
+ *
32
+ * @param key - CryptoKey from `importKey()`
33
+ * @param data - Plaintext to encrypt
34
+ * @returns `[nonce (12 bytes)][ciphertext + GCM auth tag]`
35
+ */
36
+ export declare function encrypt(key: CryptoKey, data: Uint8Array): Promise<Uint8Array>;
37
+ /**
38
+ * Decrypt data using AES-256-GCM.
39
+ *
40
+ * @param key - CryptoKey from `importKey()`
41
+ * @param data - `[nonce (12 bytes)][ciphertext + GCM auth tag]`
42
+ * @returns Decrypted plaintext
43
+ */
44
+ export declare function decrypt(key: CryptoKey, data: Uint8Array): Promise<Uint8Array>;
45
+ //# sourceMappingURL=encryption.d.ts.map
@@ -0,0 +1,64 @@
1
+ import type { Event } from './_workflow-world.js';
2
+ /**
3
+ * Delay before firing the deferred unconsumed-event check after the promise
4
+ * queue has drained. Must be long enough for cross-VM microtask chains to
5
+ * propagate (resolve in host → workflow code in VM → subscribe call back
6
+ * in host). Any subscribe() arriving during this window cancels the check.
7
+ */
8
+ export declare const DEFERRED_CHECK_DELAY_MS = 100;
9
+ export declare enum EventConsumerResult {
10
+ /**
11
+ * Callback consumed the event, but should not be removed from the callbacks list
12
+ */
13
+ Consumed = 0,
14
+ /**
15
+ * Callback did not consume the event, so it should be passed to the next callback
16
+ */
17
+ NotConsumed = 1,
18
+ /**
19
+ * Callback consumed the event, and should be removed from the callbacks list
20
+ */
21
+ Finished = 2
22
+ }
23
+ type EventConsumerCallback = (event: Event | null) => EventConsumerResult;
24
+ export interface EventsConsumerOptions {
25
+ /**
26
+ * Callback invoked when a non-null event cannot be consumed by any registered
27
+ * callback, indicating an orphaned or invalid event in the event log. The
28
+ * check is deferred until after the promise queue has drained, ensuring that
29
+ * any pending async work (e.g., deserialization/decryption) completes and
30
+ * downstream subscribe() calls have a chance to cancel the check first.
31
+ */
32
+ onUnconsumedEvent: (event: Event) => void;
33
+ /**
34
+ * Returns the current promise queue. The unconsumed event check is chained
35
+ * onto this queue so it only fires after all pending async work (e.g.,
36
+ * deserialization) has completed. This prevents false positives when async
37
+ * deserialization delays the resolve() that triggers the next subscribe().
38
+ */
39
+ getPromiseQueue: () => Promise<void>;
40
+ }
41
+ export declare class EventsConsumer {
42
+ eventIndex: number;
43
+ readonly events: Event[];
44
+ readonly callbacks: EventConsumerCallback[];
45
+ private onUnconsumedEvent;
46
+ private getPromiseQueue;
47
+ private pendingUnconsumedCheck;
48
+ private pendingUnconsumedTimeout;
49
+ private unconsumedCheckVersion;
50
+ constructor(events: Event[], options: EventsConsumerOptions);
51
+ /**
52
+ * Registers a callback function to be called after an event has been consumed
53
+ * by a different callback. The callback can return:
54
+ * - `EventConsumerResult.Consumed` the event is considered consumed and will not be passed to any other callback, but the callback will remain in the callbacks list
55
+ * - `EventConsumerResult.NotConsumed` the event is passed to the next callback
56
+ * - `EventConsumerResult.Finished` the event is considered consumed and the callback is removed from the callbacks list
57
+ *
58
+ * @param fn - The callback function to register.
59
+ */
60
+ subscribe(fn: EventConsumerCallback): void;
61
+ private consume;
62
+ }
63
+ export {};
64
+ //# sourceMappingURL=events-consumer.d.ts.map
@@ -0,0 +1,82 @@
1
+ import { type PromiseWithResolvers } from './_workflow-utils.js';
2
+ /**
3
+ * Polling interval (in ms) for lock release detection.
4
+ *
5
+ * The Web Streams API does not expose an event for "lock released but stream
6
+ * still open"; we can only distinguish that state by periodically attempting
7
+ * to acquire a reader/writer. For that reason we use polling instead of a
8
+ * fully event-driven approach here.
9
+ *
10
+ * 10ms is chosen so the polling tick almost never sits on the critical path:
11
+ * the V2 step-executor's `opsSettled` race waits for this state to resolve
12
+ * after each step body returns, so a coarser interval (the previous 100ms)
13
+ * adds visible per-step latency to streaming workflows. With a uniformly
14
+ * distributed offset between step return and the next tick, the expected
15
+ * wait is half the interval — so 10ms means ~5ms average wait per step
16
+ * instead of ~50ms. The per-tick work is `writable.locked` plus a
17
+ * `getWriter()`/`releaseLock()` probe, both microsecond-scale; 10× more
18
+ * ticks during a stream's lifetime is not measurable in practice.
19
+ */
20
+ export declare const LOCK_POLL_INTERVAL_MS = 10;
21
+ /**
22
+ * State tracker for flushable stream operations.
23
+ * Resolves when either:
24
+ * 1. Stream completes (close/error), OR
25
+ * 2. Lock is released AND all pending operations are flushed
26
+ *
27
+ * Note: `doneResolved` and `streamEnded` are separate:
28
+ * - `doneResolved`: The `done` promise has been resolved (step can complete)
29
+ * - `streamEnded`: The underlying stream has actually closed/errored
30
+ *
31
+ * Once `doneResolved` is set to true, the `done` promise will not resolve
32
+ * again. Re-acquiring locks after release is not supported as a way to
33
+ * trigger additional completion signaling.
34
+ */
35
+ export interface FlushableStreamState extends PromiseWithResolvers<void> {
36
+ /** Number of write operations currently in flight to the server */
37
+ pendingOps: number;
38
+ /** Whether the `done` promise has been resolved */
39
+ doneResolved: boolean;
40
+ /** Whether the underlying stream has actually closed/errored */
41
+ streamEnded: boolean;
42
+ /** Interval ID for writable lock polling (if active) */
43
+ writablePollingInterval?: ReturnType<typeof setInterval>;
44
+ /** Interval ID for readable lock polling (if active) */
45
+ readablePollingInterval?: ReturnType<typeof setInterval>;
46
+ }
47
+ export declare function createFlushableState(): FlushableStreamState;
48
+ /**
49
+ * Polls a WritableStream to check if the user has released their lock.
50
+ * Resolves the done promise when lock is released and no pending ops remain.
51
+ *
52
+ * Note: Only resolves if stream is unlocked but NOT closed. If the user closes
53
+ * the stream, the pump will handle resolution via the stream ending naturally.
54
+ *
55
+ * Protection: If polling is already active on this state, the existing interval
56
+ * is used to avoid creating multiple simultaneous polling operations.
57
+ */
58
+ export declare function pollWritableLock(writable: WritableStream, state: FlushableStreamState): void;
59
+ /**
60
+ * Polls a ReadableStream to check if the user has released their lock.
61
+ * Resolves the done promise when lock is released and no pending ops remain.
62
+ *
63
+ * Note: Only resolves if stream is unlocked but NOT closed. If the user closes
64
+ * the stream, the pump will handle resolution via the stream ending naturally.
65
+ *
66
+ * Protection: If polling is already active on this state, the existing interval
67
+ * is used to avoid creating multiple simultaneous polling operations.
68
+ */
69
+ export declare function pollReadableLock(readable: ReadableStream, state: FlushableStreamState): void;
70
+ /**
71
+ * Creates a flushable pipe from a ReadableStream to a WritableStream.
72
+ * Unlike pipeTo(), this resolves when:
73
+ * 1. The source stream completes (close/error), OR
74
+ * 2. The user releases their lock on userStream AND all pending writes are flushed
75
+ *
76
+ * @param source - The readable stream to read from (e.g., transform's readable)
77
+ * @param sink - The writable stream to write to (e.g., server writable)
78
+ * @param state - The flushable state tracker
79
+ * @returns Promise that resolves when stream ends (not when done promise resolves)
80
+ */
81
+ export declare function flushablePipe(source: ReadableStream, sink: WritableStream, state: FlushableStreamState): Promise<void>;
82
+ //# sourceMappingURL=flushable-stream.d.ts.map
@@ -0,0 +1,48 @@
1
+ import type { Serializable } from './schemas.js';
2
+ export interface StepInvocationQueueItem {
3
+ type: 'step';
4
+ correlationId: string;
5
+ stepName: string;
6
+ args: Serializable[];
7
+ closureVars?: Record<string, Serializable>;
8
+ thisVal?: Serializable;
9
+ hasCreatedEvent?: boolean;
10
+ }
11
+ export interface HookInvocationQueueItem {
12
+ type: 'hook';
13
+ correlationId: string;
14
+ token: string;
15
+ metadata?: Serializable;
16
+ hasCreatedEvent?: boolean;
17
+ disposed?: boolean;
18
+ isWebhook?: boolean;
19
+ isSystem?: boolean;
20
+ abortRequested?: boolean;
21
+ abortReason?: unknown;
22
+ }
23
+ export interface WaitInvocationQueueItem {
24
+ type: 'wait';
25
+ correlationId: string;
26
+ resumeAt: Date;
27
+ hasCreatedEvent?: boolean;
28
+ }
29
+ export type QueueItem = StepInvocationQueueItem | HookInvocationQueueItem | WaitInvocationQueueItem;
30
+ /**
31
+ * An error that is thrown when one or more operations (steps/hooks/etc.) are called but do
32
+ * not yet have corresponding entries in the event log. The workflow
33
+ * dispatcher will catch this error and push the operations
34
+ * onto the queue.
35
+ */
36
+ export declare class WorkflowSuspension extends Error {
37
+ steps: QueueItem[];
38
+ globalThis: typeof globalThis;
39
+ stepCount: number;
40
+ hookCount: number;
41
+ waitCount: number;
42
+ hookDisposedCount: number;
43
+ abortCount: number;
44
+ constructor(stepsInput: Map<string, QueueItem>, global: typeof globalThis);
45
+ static is(value: unknown): value is WorkflowSuspension;
46
+ }
47
+ export declare function ENOTSUP(): never;
48
+ //# sourceMappingURL=global.d.ts.map
@@ -1,38 +1,19 @@
1
- import type { WorkflowWritableStreamOptions } from "./runtime.js";
2
-
3
- export interface Hook<T = unknown> extends AsyncIterable<T> {
4
- readonly token: string;
5
- dispose(): void;
6
- [Symbol.dispose](): void;
7
- }
8
- export interface HookOptions {
9
- token?: string | undefined;
10
- timeout?: string | number | undefined;
11
- }
12
- export type RequestWithResponse<T = unknown> = any;
13
- export type RetryableErrorOptions = any;
14
- export type Webhook<T = unknown> = any;
15
- export type WebhookOptions = HookOptions;
16
- export interface StepMetadata {
17
- [key: string]: unknown;
18
- }
19
- export interface WorkflowMetadata {
20
- readonly url: string;
21
- readonly workflowRunId: string;
22
- readonly workflowName: string;
23
- readonly workflowStartedAt: Date;
24
- [key: string]: unknown;
25
- }
26
- export declare class FatalError extends Error {}
27
- export declare class RetryableError extends Error {
28
- constructor(message: string, options?: RetryableErrorOptions);
29
- }
30
- export declare function createHook<T = unknown>(options?: HookOptions): Hook<T>;
31
- export declare function createWebhook<T = unknown>(options?: WebhookOptions): Webhook<T>;
32
- export declare function defineHook<T = unknown>(): Hook<T>;
33
- export declare function getStepMetadata(): StepMetadata;
34
- export declare function getWorkflowMetadata(): WorkflowMetadata;
35
- export declare function getWritable<T = unknown>(
36
- options?: WorkflowWritableStreamOptions,
37
- ): WritableStream<T>;
38
- export declare function sleep(duration: string | number): Promise<void>;
1
+ /**
2
+ * Just the core utilities that are meant to be imported by user
3
+ * steps/workflows. This allows the bundler to tree-shake and limit what goes
4
+ * into the final user bundles. Logic for running/handling steps/workflows
5
+ * should live in runtime. Eventually these might be separate packages
6
+ * `workflow` and `workflow/runtime`?
7
+ *
8
+ * Everything here will get re-exported under the 'workflow' top level package.
9
+ * This should be a minimal set of APIs so **do not anything here** unless it's
10
+ * needed for userland workflow code.
11
+ */
12
+ export { FatalError, RetryableError, type RetryableErrorOptions, } from '#compiled/@workflow/errors/index.js';
13
+ export { createHook, createWebhook, type Hook, type HookOptions, type RequestWithResponse, type Webhook, type WebhookOptions, } from './create-hook.js';
14
+ export { defineHook, type TypedHook } from './define-hook.js';
15
+ export { sleep } from './sleep.js';
16
+ export { getStepMetadata, type StepMetadata, } from './step/get-step-metadata.js';
17
+ export { getWorkflowMetadata, type WorkflowMetadata, } from './step/get-workflow-metadata.js';
18
+ export { getWritable, type WorkflowWritableStreamOptions, } from './step/writable-stream.js';
19
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Structured-log composition for `console.error` / `console.warn`. Emits
3
+ * one string in three sections so the most useful information is at the
4
+ * top, stack trace at the bottom:
5
+ *
6
+ * [workflow-sdk] <framing line>
7
+ * user error · FatalError
8
+ * run wrun_…
9
+ * step step_… · add (./workflows/x)
10
+ * hint: Move the call to a step function.
11
+ * FatalError: …
12
+ * at … (trimmed stack — internals collapsed)
13
+ *
14
+ * Without this composition, callers passing `${framing}\n${stack}` as the
15
+ * message and structured fields as the metadata object got `util.inspect`'s
16
+ * default object dump appended *after* the stack, which buries the run ID
17
+ * and attribution badge under 30+ lines of `node_modules/.pnpm/...` frames.
18
+ *
19
+ * The same metadata is also emitted as structured OTel span events from
20
+ * the logger itself, so backends that want JSON-shaped data still get it.
21
+ * web/web-shared do not consume stderr at all — they read CBOR/JSON event
22
+ * payloads from the World event log.
23
+ */
24
+ export declare function composeLogLine(prefix: string, message: string, metadata: Record<string, unknown> | undefined): string;
25
+ //# sourceMappingURL=log-format.d.ts.map
@@ -0,0 +1,29 @@
1
+ type LogMetadata = Record<string, unknown>;
2
+ type LogFn = (message: string, metadata?: LogMetadata) => void;
3
+ export interface Logger {
4
+ debug: LogFn;
5
+ info: LogFn;
6
+ warn: LogFn;
7
+ error: LogFn;
8
+ /**
9
+ * Returns a child logger that merges the given metadata into every call.
10
+ * Useful for attaching stable context (e.g. `workflowRunId`, `workflowName`,
11
+ * `stepId`) so callers don't have to repeat it on every log.
12
+ *
13
+ * Call-site metadata wins on conflict, so children can still override.
14
+ */
15
+ child: (metadata: LogMetadata) => Logger;
16
+ /**
17
+ * Convenience child logger for a workflow run. Equivalent to
18
+ * `logger.child({ workflowRunId, workflowName })`, but centralized so all
19
+ * runtime code structures run metadata consistently.
20
+ */
21
+ forRun: (workflowRunId: string, workflowName?: string, extra?: LogMetadata) => Logger;
22
+ }
23
+ export declare const stepLogger: Logger;
24
+ export declare const runtimeLogger: Logger;
25
+ export declare const webhookLogger: Logger;
26
+ export declare const eventsLogger: Logger;
27
+ export declare const adapterLogger: Logger;
28
+ export {};
29
+ //# sourceMappingURL=logger.d.ts.map