@workflow/world-testing 5.0.0-beta.35 → 5.0.0-beta.37

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.
@@ -356,6 +356,8 @@ var init_error_codes = __esm({
356
356
  REPLAY_DIVERGENCE: "REPLAY_DIVERGENCE",
357
357
  /** Run exceeded the maximum number of queue deliveries */
358
358
  MAX_DELIVERIES_EXCEEDED: "MAX_DELIVERIES_EXCEEDED",
359
+ /** Run exceeded the maximum number of events per run */
360
+ MAX_EVENTS_EXCEEDED: "MAX_EVENTS_EXCEEDED",
359
361
  /** Workflow replay exceeded the maximum allowed duration */
360
362
  REPLAY_TIMEOUT: "REPLAY_TIMEOUT",
361
363
  /** World response violated the SDK contract and cannot be retried safely */
@@ -394,7 +396,7 @@ function buildFramedDetails(hint2, slug) {
394
396
  });
395
397
  return out;
396
398
  }
397
- var BASE_URL, ERROR_SLUGS, WorkflowError, WorkflowWorldError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRuntimeError, RuntimeDecryptionError, SerializationError, StepNotRegisteredError, WorkflowNotRegisteredError, WorkflowRunNotFoundError, HookConflictError, HookNotFoundError, EntityConflictError, ThrottleError, WorkflowRunCancelledError, FatalError, RetryableError, FATAL_ERROR_KEY, RETRYABLE_ERROR_KEY, HOOK_CONFLICT_ERROR_KEY, RUNTIME_DECRYPTION_ERROR_KEY;
399
+ var BASE_URL, ERROR_SLUGS, WorkflowError, WorkflowWorldError, WorkflowRunFailedError, WorkflowRunNotCompletedError, WorkflowRuntimeError, RuntimeDecryptionError, SerializationError, StepNotRegisteredError, WorkflowNotRegisteredError, WorkflowRunNotFoundError, HookConflictError, HookNotFoundError, EntityConflictError, RunExpiredError, ThrottleError, WorkflowRunCancelledError, FatalError, RetryableError, FATAL_ERROR_KEY, RETRYABLE_ERROR_KEY, HOOK_CONFLICT_ERROR_KEY, RUNTIME_DECRYPTION_ERROR_KEY;
398
400
  var init_dist2 = __esm({
399
401
  "../errors/dist/index.js"() {
400
402
  "use strict";
@@ -657,6 +659,18 @@ Caused by: ${options.cause.stack}`;
657
659
  return isError(value) && value.name === "EntityConflictError";
658
660
  }
659
661
  };
662
+ RunExpiredError = class extends WorkflowWorldError {
663
+ static {
664
+ __name(this, "RunExpiredError");
665
+ }
666
+ constructor(message) {
667
+ super(message);
668
+ this.name = "RunExpiredError";
669
+ }
670
+ static is(value) {
671
+ return isError(value) && value.name === "RunExpiredError";
672
+ }
673
+ };
660
674
  ThrottleError = class extends WorkflowWorldError {
661
675
  static {
662
676
  __name(this, "ThrottleError");
@@ -16713,6 +16727,7 @@ var init_events = __esm({
16713
16727
  correlationId: external_exports.string(),
16714
16728
  eventData: external_exports.object({
16715
16729
  token: external_exports.string(),
16730
+ tokenRetentionUntil: external_exports.coerce.date().optional(),
16716
16731
  metadata: SerializedDataSchema.optional(),
16717
16732
  isWebhook: external_exports.boolean().optional(),
16718
16733
  isSystem: external_exports.boolean().optional()
@@ -16784,7 +16799,14 @@ var init_events = __esm({
16784
16799
  input: SerializedDataSchema,
16785
16800
  executionContext: external_exports.record(external_exports.string(), external_exports.any()).optional(),
16786
16801
  attributes: external_exports.record(external_exports.string(), external_exports.string()).optional(),
16787
- allowReservedAttributes: external_exports.literal(true).optional()
16802
+ allowReservedAttributes: external_exports.literal(true).optional(),
16803
+ /**
16804
+ * The run's X25519 public key (base64), stamped by SDKs that support
16805
+ * sealed (`encp`) envelopes. Persisted onto the run entity so that
16806
+ * cross-run writers can seal payloads to this run without holding its
16807
+ * symmetric key. Not secret — see `WorkflowRunBaseSchema`.
16808
+ */
16809
+ encryptionPublicKey: external_exports.string().optional()
16788
16810
  })
16789
16811
  });
16790
16812
  RunStartedEventSchema = BaseEventSchema.extend({
@@ -16795,7 +16817,14 @@ var init_events = __esm({
16795
16817
  workflowName: external_exports.string().optional(),
16796
16818
  executionContext: external_exports.record(external_exports.string(), external_exports.any()).optional(),
16797
16819
  attributes: external_exports.record(external_exports.string(), external_exports.string()).optional(),
16798
- allowReservedAttributes: external_exports.literal(true).optional()
16820
+ allowReservedAttributes: external_exports.literal(true).optional(),
16821
+ /**
16822
+ * Mirrors `run_created.eventData.encryptionPublicKey`. Carried here for
16823
+ * the resilient-start path: when the `run_created` write failed, the
16824
+ * server creates the run from this event instead, and without the key
16825
+ * the run would silently lose its ability to receive sealed writes.
16826
+ */
16827
+ encryptionPublicKey: external_exports.string().optional()
16799
16828
  }).optional()
16800
16829
  });
16801
16830
  RunCompletedEventSchema = BaseEventSchema.extend({
@@ -16882,6 +16911,9 @@ var init_events = __esm({
16882
16911
  });
16883
16912
 
16884
16913
  // ../world/dist/runs.js
16914
+ function isTerminalWorkflowRunStatus(status) {
16915
+ return TERMINAL_WORKFLOW_RUN_STATUSES.includes(status);
16916
+ }
16885
16917
  var WorkflowRunStatusSchema, TerminalWorkflowRunStatusSchema, TERMINAL_WORKFLOW_RUN_STATUSES, WorkflowRunBaseSchema, WorkflowRunSchema;
16886
16918
  var init_runs = __esm({
16887
16919
  "../world/dist/runs.js"() {
@@ -16901,6 +16933,7 @@ var init_runs = __esm({
16901
16933
  "cancelled"
16902
16934
  ]);
16903
16935
  TERMINAL_WORKFLOW_RUN_STATUSES = TerminalWorkflowRunStatusSchema.options;
16936
+ __name(isTerminalWorkflowRunStatus, "isTerminalWorkflowRunStatus");
16904
16937
  WorkflowRunBaseSchema = external_exports.object({
16905
16938
  runId: external_exports.string(),
16906
16939
  status: WorkflowRunStatusSchema,
@@ -16963,6 +16996,26 @@ var init_runs = __esm({
16963
16996
  * the attributes-mvp changelog entry.
16964
16997
  */
16965
16998
  attributes: external_exports.record(external_exports.string(), external_exports.string()).default({}),
16999
+ /**
17000
+ * The run's X25519 public key, base64-encoded (~44 chars).
17001
+ *
17002
+ * Lets any party that can read this run seal a payload *to* it without
17003
+ * being able to read the run's data — used for cross-run writes such as a
17004
+ * hook resumption from another deployment, or a child workflow writing into
17005
+ * a forwarded stream. The matching private scalar is never stored: it is
17006
+ * re-derived on demand from the deployment's own key material, so this
17007
+ * field is not secret and its presence does not weaken the run's
17008
+ * confidentiality.
17009
+ *
17010
+ * Stamped at run creation by SDKs that support sealed (`encp`) envelopes.
17011
+ * **Presence is the writer-side gate**: a run only carries a public key if
17012
+ * the runtime that created it could also open sealed payloads, and runs are
17013
+ * pinned to their creating deployment. Writers therefore seal iff this
17014
+ * field is set, and otherwise fall back to fetching the symmetric per-run
17015
+ * key. Absent on runs created by older SDKs, and on worlds that do not
17016
+ * implement `getEncryptionKeyForRun` (encryption disabled).
17017
+ */
17018
+ encryptionPublicKey: external_exports.string().optional(),
16966
17019
  expiredAt: external_exports.coerce.date().optional(),
16967
17020
  startedAt: external_exports.coerce.date().optional(),
16968
17021
  completedAt: external_exports.coerce.date().optional(),
@@ -17248,30 +17301,6 @@ var init_env_config = __esm({
17248
17301
  }
17249
17302
  });
17250
17303
 
17251
- // ../world/dist/hooks.js
17252
- var HookSchema;
17253
- var init_hooks = __esm({
17254
- "../world/dist/hooks.js"() {
17255
- "use strict";
17256
- init_zod();
17257
- init_serialization();
17258
- HookSchema = external_exports.object({
17259
- runId: external_exports.string(),
17260
- hookId: external_exports.string(),
17261
- token: external_exports.string(),
17262
- ownerId: external_exports.string(),
17263
- projectId: external_exports.string(),
17264
- environment: external_exports.string(),
17265
- metadata: SerializedDataSchema.optional(),
17266
- createdAt: external_exports.coerce.date(),
17267
- // Optional in database for backwards compatibility, defaults to 1 (legacy) when reading
17268
- specVersion: external_exports.number().optional(),
17269
- isWebhook: external_exports.boolean().optional(),
17270
- isSystem: external_exports.boolean().optional()
17271
- });
17272
- }
17273
- });
17274
-
17275
17304
  // ../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js
17276
17305
  var init_classic = __esm({
17277
17306
  "../../node_modules/.pnpm/zod@4.3.6/node_modules/zod/v4/classic/index.js"() {
@@ -17295,19 +17324,22 @@ function resolveQueueNamespace(namespace) {
17295
17324
  return namespace ?? process.env.WORKFLOW_QUEUE_NAMESPACE ?? void 0;
17296
17325
  }
17297
17326
  function getQueueTopicPrefix(kind, namespace) {
17327
+ if (kind !== "workflow") {
17328
+ throw new Error(`Unsupported queue kind: ${kind}`);
17329
+ }
17298
17330
  if (namespace !== void 0) {
17299
17331
  QueueNamespace.parse(namespace);
17300
- return `__${namespace}_wkf_${kind}_`;
17332
+ return `__${namespace}_wkf_workflow_`;
17301
17333
  }
17302
- return `__wkf_${kind}_`;
17334
+ return "__wkf_workflow_";
17303
17335
  }
17304
- var QueuePrefix, ValidQueueName, QueueNamespace, MessageId, TraceCarrierSchema, RunInputSchema, WorkflowInvokePayloadSchema, StepInvokePayloadSchema, HealthCheckPayloadSchema, QueuePayloadSchema;
17336
+ var QueuePrefix, ValidQueueName, QueueNamespace, MessageId, TraceCarrierSchema, RunInputSchema, WorkflowInvokePayloadSchema, HealthCheckPayloadSchema, QueuePayloadSchema;
17305
17337
  var init_queue = __esm({
17306
17338
  "../world/dist/queue.js"() {
17307
17339
  "use strict";
17308
17340
  init_v4();
17309
- QueuePrefix = external_exports.string().regex(/^__(?:[a-z][a-z0-9]*_)?wkf_(?:workflow|step)_$/, "Must match __wkf_{workflow|step}_ or __{namespace}_wkf_{workflow|step}_");
17310
- ValidQueueName = external_exports.string().regex(/^__(?:[a-z][a-z0-9]*_)?wkf_(?:workflow|step)_.+$/, "Must be a valid queue name with a recognized prefix");
17341
+ QueuePrefix = external_exports.string().regex(/^__(?:[a-z][a-z0-9]*_)?wkf_workflow_$/, "Must match __wkf_workflow_ or __{namespace}_wkf_workflow_");
17342
+ ValidQueueName = external_exports.string().regex(/^__(?:[a-z][a-z0-9]*_)?wkf_workflow_.+$/, "Must be a valid queue name with a recognized prefix");
17311
17343
  QueueNamespace = external_exports.string().regex(/^[a-z][a-z0-9]*$/, "Must be lowercase alphanumeric, starting with a letter");
17312
17344
  __name(resolveQueueNamespace, "resolveQueueNamespace");
17313
17345
  __name(getQueueTopicPrefix, "getQueueTopicPrefix");
@@ -17347,26 +17379,71 @@ var init_queue = __esm({
17347
17379
  /** Run creation data, only present on the first queue delivery from start() */
17348
17380
  runInput: RunInputSchema.optional()
17349
17381
  });
17350
- StepInvokePayloadSchema = external_exports.object({
17351
- workflowName: external_exports.string(),
17352
- workflowRunId: external_exports.string(),
17353
- workflowStartedAt: external_exports.number(),
17354
- stepId: external_exports.string(),
17355
- traceCarrier: TraceCarrierSchema.optional(),
17356
- requestedAt: external_exports.coerce.date().optional()
17357
- });
17358
17382
  HealthCheckPayloadSchema = external_exports.object({
17359
17383
  __healthCheck: external_exports.literal(true),
17360
- correlationId: external_exports.string()
17384
+ correlationId: external_exports.string(),
17385
+ /**
17386
+ * The run id the caller is about to create, when the probe is being used to
17387
+ * prepare a cross-deployment `start()`.
17388
+ *
17389
+ * The responder runs inside the target deployment, so it can derive that
17390
+ * run's public key locally from its own key material and return it in the
17391
+ * probe response. That lets the caller seal the workflow arguments without
17392
+ * a separate key lookup. Absent for probes issued for other reasons (CLI
17393
+ * health command, dashboard), in which case no key is returned.
17394
+ */
17395
+ runId: external_exports.string().optional()
17361
17396
  });
17362
17397
  QueuePayloadSchema = external_exports.union([
17363
- WorkflowInvokePayloadSchema,
17364
- StepInvokePayloadSchema,
17365
- HealthCheckPayloadSchema
17398
+ HealthCheckPayloadSchema,
17399
+ WorkflowInvokePayloadSchema
17366
17400
  ]);
17367
17401
  }
17368
17402
  });
17369
17403
 
17404
+ // ../world/dist/hooks.js
17405
+ var HookResumeContextSchema, HookSchema;
17406
+ var init_hooks = __esm({
17407
+ "../world/dist/hooks.js"() {
17408
+ "use strict";
17409
+ init_zod();
17410
+ init_queue();
17411
+ init_serialization();
17412
+ HookResumeContextSchema = external_exports.object({
17413
+ deploymentId: external_exports.string(),
17414
+ workflowName: external_exports.string(),
17415
+ // Named `runSpecVersion` to distinguish it from the hook's own `specVersion`.
17416
+ runSpecVersion: external_exports.number().optional(),
17417
+ workflowCoreVersion: external_exports.string().optional(),
17418
+ traceCarrier: TraceCarrierSchema.optional(),
17419
+ // The run's published X25519 public key (base64), mirrored from the run
17420
+ // entity. Lets a resume seal (`encp`) its payload to the run without reading
17421
+ // the run or fetching its symmetric key. Absent on runs created before
17422
+ // sealed envelopes and on projects with encryption disabled, where the
17423
+ // resume falls back to the symmetric per-run key.
17424
+ encryptionPublicKey: external_exports.string().optional()
17425
+ });
17426
+ HookSchema = external_exports.object({
17427
+ runId: external_exports.string(),
17428
+ hookId: external_exports.string(),
17429
+ token: external_exports.string(),
17430
+ ownerId: external_exports.string(),
17431
+ projectId: external_exports.string(),
17432
+ environment: external_exports.string(),
17433
+ metadata: SerializedDataSchema.optional(),
17434
+ createdAt: external_exports.coerce.date(),
17435
+ // Optional in database for backwards compatibility, defaults to 1 (legacy) when reading
17436
+ specVersion: external_exports.number().optional(),
17437
+ isWebhook: external_exports.boolean().optional(),
17438
+ isSystem: external_exports.boolean().optional(),
17439
+ // Present when the server stored it (new hooks) or synthesized it from the
17440
+ // run (old hooks). Absent only against an old server, where the resume path
17441
+ // falls back to `runs.get`.
17442
+ resumeContext: HookResumeContextSchema.optional()
17443
+ });
17444
+ }
17445
+ });
17446
+
17370
17447
  // ../world/dist/recovery.js
17371
17448
  var init_recovery = __esm({
17372
17449
  "../world/dist/recovery.js"() {
@@ -17625,14 +17702,17 @@ async function importKey(raw, usages = [
17625
17702
  usages
17626
17703
  );
17627
17704
  }
17628
- async function encrypt(key, data) {
17705
+ async function encrypt(key, data, aad) {
17629
17706
  const nonce = globalThis.crypto.getRandomValues(new Uint8Array(NONCE_LENGTH));
17630
17707
  let ciphertext;
17631
17708
  try {
17632
17709
  ciphertext = await globalThis.crypto.subtle.encrypt({
17633
17710
  name: "AES-GCM",
17634
17711
  iv: nonce,
17635
- tagLength: TAG_LENGTH
17712
+ tagLength: TAG_LENGTH,
17713
+ ...aad ? {
17714
+ additionalData: aad
17715
+ } : {}
17636
17716
  }, key, data);
17637
17717
  } catch (cause) {
17638
17718
  throw new RuntimeDecryptionError(`AES-256-GCM encryption failed: ${cause instanceof Error ? cause.message : String(cause)}`, {
@@ -17648,7 +17728,7 @@ async function encrypt(key, data) {
17648
17728
  result.set(new Uint8Array(ciphertext), NONCE_LENGTH);
17649
17729
  return result;
17650
17730
  }
17651
- async function decrypt(key, data) {
17731
+ async function decrypt(key, data, aad) {
17652
17732
  const minLength = NONCE_LENGTH + TAG_LENGTH / 8;
17653
17733
  if (data.byteLength < minLength) {
17654
17734
  throw new RuntimeDecryptionError(`Encrypted data too short: expected at least ${minLength} bytes, got ${data.byteLength}`, {
@@ -17665,7 +17745,10 @@ async function decrypt(key, data) {
17665
17745
  plaintext = await globalThis.crypto.subtle.decrypt({
17666
17746
  name: "AES-GCM",
17667
17747
  iv: nonce,
17668
- tagLength: TAG_LENGTH
17748
+ tagLength: TAG_LENGTH,
17749
+ ...aad ? {
17750
+ additionalData: aad
17751
+ } : {}
17669
17752
  }, key, ciphertext);
17670
17753
  } catch (cause) {
17671
17754
  const causeMsg = cause instanceof Error ? cause.message : String(cause);
@@ -17679,13 +17762,14 @@ async function decrypt(key, data) {
17679
17762
  }
17680
17763
  return new Uint8Array(plaintext);
17681
17764
  }
17682
- var NONCE_LENGTH, TAG_LENGTH, KEY_LENGTH;
17765
+ var NONCE_LENGTH, TAG_LENGTH, TAG_BYTES, KEY_LENGTH;
17683
17766
  var init_encryption = __esm({
17684
17767
  "../core/dist/encryption.js"() {
17685
17768
  "use strict";
17686
17769
  init_dist2();
17687
17770
  NONCE_LENGTH = 12;
17688
17771
  TAG_LENGTH = 128;
17772
+ TAG_BYTES = TAG_LENGTH / 8;
17689
17773
  KEY_LENGTH = 32;
17690
17774
  __name(importKey, "importKey");
17691
17775
  __name(encrypt, "encrypt");
@@ -17693,139 +17777,707 @@ var init_encryption = __esm({
17693
17777
  }
17694
17778
  });
17695
17779
 
17696
- // ../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/constants.js
17697
- var UNDEFINED, HOLE, NAN, POSITIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_ZERO, SPARSE, MAX_ARRAY_LEN, MAX_ARRAY_INDEX;
17698
- var init_constants = __esm({
17699
- "../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/constants.js"() {
17700
- "use strict";
17701
- UNDEFINED = -1;
17702
- HOLE = -2;
17703
- NAN = -3;
17704
- POSITIVE_INFINITY = -4;
17705
- NEGATIVE_INFINITY = -5;
17706
- NEGATIVE_ZERO = -6;
17707
- SPARSE = -7;
17708
- MAX_ARRAY_LEN = 2 ** 32 - 1;
17709
- MAX_ARRAY_INDEX = MAX_ARRAY_LEN - 1;
17780
+ // ../core/dist/sealed-box.js
17781
+ function assertKeyMaterialLength(runKeyMaterial) {
17782
+ if (runKeyMaterial.byteLength !== CONTENT_KEY_LENGTH) {
17783
+ throw new WorkflowRuntimeError(`Run key material must be exactly ${CONTENT_KEY_LENGTH} bytes, got ${runKeyMaterial.byteLength}`);
17710
17784
  }
17711
- });
17712
-
17713
- // ../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/utils.js
17714
- function is_primitive(thing) {
17715
- return thing === null || typeof thing !== "object" && typeof thing !== "function";
17716
17785
  }
17717
- function is_plain_object(thing) {
17718
- const proto = Object.getPrototypeOf(thing);
17719
- return proto === Object.prototype || proto === null || Object.getPrototypeOf(proto) === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names;
17786
+ function assertPublicKeyLength(publicKey, label) {
17787
+ if (publicKey.byteLength !== X25519_KEY_LENGTH) {
17788
+ throw new WorkflowRuntimeError(`${label} must be exactly ${X25519_KEY_LENGTH} bytes, got ${publicKey.byteLength}`);
17789
+ }
17720
17790
  }
17721
- function get_type(thing) {
17722
- return Object.prototype.toString.call(thing).slice(8, -1);
17791
+ async function deriveRunKeyPair(runKeyMaterial) {
17792
+ assertKeyMaterialLength(runKeyMaterial);
17793
+ const hkdfKey = await globalThis.crypto.subtle.importKey("raw", runKeyMaterial, "HKDF", false, [
17794
+ "deriveBits"
17795
+ ]);
17796
+ const scalarBits = await globalThis.crypto.subtle.deriveBits({
17797
+ name: "HKDF",
17798
+ hash: "SHA-256",
17799
+ salt: new Uint8Array(32),
17800
+ info: infoEncoder.encode(SCALAR_INFO)
17801
+ }, hkdfKey, X25519_KEY_LENGTH * 8);
17802
+ const scalar = new Uint8Array(scalarBits);
17803
+ const publicKey = await derivePublicKeyFromScalar(scalar);
17804
+ return {
17805
+ scalar,
17806
+ publicKey
17807
+ };
17723
17808
  }
17724
- function get_escaped_char(char) {
17725
- switch (char) {
17726
- case '"':
17727
- return '\\"';
17728
- case "<":
17729
- return "\\u003C";
17730
- case "\\":
17731
- return "\\\\";
17732
- case "\n":
17733
- return "\\n";
17734
- case "\r":
17735
- return "\\r";
17736
- case " ":
17737
- return "\\t";
17738
- case "\b":
17739
- return "\\b";
17740
- case "\f":
17741
- return "\\f";
17742
- case "\u2028":
17743
- return "\\u2028";
17744
- case "\u2029":
17745
- return "\\u2029";
17746
- default:
17747
- return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
17809
+ async function derivePublicKeyFromScalar(scalar) {
17810
+ const privateKey = await importScalar(
17811
+ scalar,
17812
+ /* extractable */
17813
+ true
17814
+ );
17815
+ const jwk = await globalThis.crypto.subtle.exportKey("jwk", privateKey);
17816
+ if (!jwk.x) {
17817
+ throw new WorkflowRuntimeError('X25519 JWK export did not include a public key component ("x")');
17818
+ }
17819
+ const publicKey = base64UrlToBytes(jwk.x);
17820
+ if (publicKey.byteLength !== X25519_KEY_LENGTH) {
17821
+ throw new WorkflowRuntimeError(`X25519 JWK export produced a ${publicKey.byteLength}-byte public key, expected ${X25519_KEY_LENGTH}`);
17822
+ }
17823
+ return publicKey;
17824
+ }
17825
+ async function importScalar(scalar, extractable) {
17826
+ const pkcs8 = new Uint8Array(PKCS8_X25519_PREFIX.length + scalar.byteLength);
17827
+ pkcs8.set(PKCS8_X25519_PREFIX, 0);
17828
+ pkcs8.set(scalar, PKCS8_X25519_PREFIX.length);
17829
+ return globalThis.crypto.subtle.importKey("pkcs8", pkcs8, {
17830
+ name: "X25519"
17831
+ }, extractable, [
17832
+ "deriveBits"
17833
+ ]);
17834
+ }
17835
+ function importPublicKey(publicKey) {
17836
+ return globalThis.crypto.subtle.importKey(
17837
+ "raw",
17838
+ publicKey,
17839
+ {
17840
+ name: "X25519"
17841
+ },
17842
+ /* extractable */
17843
+ true,
17844
+ // Public keys carry no usages for X25519 — the private key does the
17845
+ // deriving; the public key is only ever an argument to it.
17846
+ []
17847
+ );
17848
+ }
17849
+ function bytesToBase64(bytes) {
17850
+ let out = "";
17851
+ for (let i = 0; i < bytes.length; i += 3) {
17852
+ const b0 = bytes[i];
17853
+ const b1 = i + 1 < bytes.length ? bytes[i + 1] : 0;
17854
+ const b2 = i + 2 < bytes.length ? bytes[i + 2] : 0;
17855
+ out += BASE64_CHARS[b0 >> 2 & 63];
17856
+ out += BASE64_CHARS[(b0 & 3) << 4 | b1 >> 4 & 15];
17857
+ out += i + 1 < bytes.length ? BASE64_CHARS[(b1 & 15) << 2 | b2 >> 6 & 3] : "=";
17858
+ out += i + 2 < bytes.length ? BASE64_CHARS[b2 & 63] : "=";
17748
17859
  }
17860
+ return out;
17749
17861
  }
17750
- function stringify_string(str) {
17751
- let result = "";
17752
- let last_pos = 0;
17753
- const len = str.length;
17754
- for (let i = 0; i < len; i += 1) {
17755
- const char = str[i];
17756
- const replacement = get_escaped_char(char);
17757
- if (replacement) {
17758
- result += str.slice(last_pos, i) + replacement;
17759
- last_pos = i + 1;
17862
+ function base64ToBytes(value) {
17863
+ let end = value.length;
17864
+ while (end > 0 && value[end - 1] === "=") end--;
17865
+ const body = value.slice(0, end);
17866
+ if (body.includes("=")) return void 0;
17867
+ if (body.length % 4 === 1) return void 0;
17868
+ if (end !== value.length && value.length % 4 !== 0) return void 0;
17869
+ let accumulator = 0;
17870
+ let bitCount = 0;
17871
+ const bytes = [];
17872
+ for (let i = 0; i < body.length; i++) {
17873
+ const index = BASE64_CHARS.indexOf(body[i]);
17874
+ if (index === -1) return void 0;
17875
+ accumulator = accumulator << 6 | index;
17876
+ bitCount += 6;
17877
+ if (bitCount >= 8) {
17878
+ bitCount -= 8;
17879
+ bytes.push(accumulator >> bitCount & 255);
17760
17880
  }
17761
17881
  }
17762
- return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
17882
+ if (bitCount > 0 && (accumulator & (1 << bitCount) - 1) !== 0) {
17883
+ return void 0;
17884
+ }
17885
+ return new Uint8Array(bytes);
17886
+ }
17887
+ function base64UrlToBytes(value) {
17888
+ let accumulator = 0;
17889
+ let bitCount = 0;
17890
+ const bytes = [];
17891
+ for (let i = 0; i < value.length; i++) {
17892
+ const char = value[i];
17893
+ if (char === "=") break;
17894
+ const index = BASE64URL_CHARS.indexOf(char);
17895
+ if (index === -1) {
17896
+ throw new WorkflowRuntimeError(`Invalid base64url character "${char}" in X25519 JWK key component`);
17897
+ }
17898
+ accumulator = accumulator << 6 | index;
17899
+ bitCount += 6;
17900
+ if (bitCount >= 8) {
17901
+ bitCount -= 8;
17902
+ bytes.push(accumulator >> bitCount & 255);
17903
+ }
17904
+ }
17905
+ return new Uint8Array(bytes);
17763
17906
  }
17764
- function enumerable_symbols(object2) {
17765
- return Object.getOwnPropertySymbols(object2).filter((symbol2) => Object.getOwnPropertyDescriptor(object2, symbol2).enumerable);
17907
+ async function deriveContentKey(sharedSecret, ephemeralPublicKey, recipientPublicKey, usages) {
17908
+ const label = infoEncoder.encode(CONTENT_KEY_INFO);
17909
+ const info = new Uint8Array(label.length + ephemeralPublicKey.length + recipientPublicKey.length);
17910
+ info.set(label, 0);
17911
+ info.set(ephemeralPublicKey, label.length);
17912
+ info.set(recipientPublicKey, label.length + ephemeralPublicKey.length);
17913
+ const hkdfKey = await globalThis.crypto.subtle.importKey("raw", sharedSecret, "HKDF", false, [
17914
+ "deriveBits"
17915
+ ]);
17916
+ const contentKeyBits = await globalThis.crypto.subtle.deriveBits({
17917
+ name: "HKDF",
17918
+ hash: "SHA-256",
17919
+ salt: new Uint8Array(32),
17920
+ info
17921
+ }, hkdfKey, CONTENT_KEY_LENGTH * 8);
17922
+ return globalThis.crypto.subtle.importKey(
17923
+ "raw",
17924
+ new Uint8Array(contentKeyBits),
17925
+ "AES-GCM",
17926
+ false,
17927
+ // `KeyUsage` is a DOM-lib type that is not in scope under `es2022`; the
17928
+ // parameter type is a strict subset of it, so this cast is sound.
17929
+ usages
17930
+ );
17766
17931
  }
17767
- function stringify_key(key) {
17768
- return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]";
17932
+ async function encapsulate(recipientPublicKey) {
17933
+ assertPublicKeyLength(recipientPublicKey, "Recipient public key");
17934
+ let recipientKey;
17935
+ try {
17936
+ recipientKey = await importPublicKey(recipientPublicKey);
17937
+ } catch (cause) {
17938
+ throw new WorkflowRuntimeError(`Invalid X25519 recipient public key: ${cause instanceof Error ? cause.message : String(cause)}`, {
17939
+ cause
17940
+ });
17941
+ }
17942
+ const ephemeral = await globalThis.crypto.subtle.generateKey(
17943
+ {
17944
+ name: "X25519"
17945
+ },
17946
+ /* extractable */
17947
+ true,
17948
+ [
17949
+ "deriveBits"
17950
+ ]
17951
+ );
17952
+ const ephemeralPublicKey = new Uint8Array(await globalThis.crypto.subtle.exportKey("raw", ephemeral.publicKey));
17953
+ let sharedSecretBits;
17954
+ try {
17955
+ sharedSecretBits = await globalThis.crypto.subtle.deriveBits({
17956
+ name: "X25519",
17957
+ public: recipientKey
17958
+ }, ephemeral.privateKey, X25519_KEY_LENGTH * 8);
17959
+ } catch (cause) {
17960
+ throw new WorkflowRuntimeError("X25519 key agreement failed: the recipient public key is not a valid curve point (low-order point or corrupted key material)", {
17961
+ cause
17962
+ });
17963
+ }
17964
+ const contentKey = await deriveContentKey(new Uint8Array(sharedSecretBits), ephemeralPublicKey, recipientPublicKey, [
17965
+ "encrypt"
17966
+ ]);
17967
+ return {
17968
+ ephemeralPublicKey,
17969
+ contentKey
17970
+ };
17769
17971
  }
17770
- function is_valid_array_index(n) {
17771
- if (!Number.isInteger(n)) return false;
17772
- if (n < 0) return false;
17773
- if (n > MAX_ARRAY_INDEX) return false;
17774
- return true;
17972
+ async function decapsulate(keyPair, ephemeralPublicKey) {
17973
+ if (ephemeralPublicKey.byteLength !== X25519_KEY_LENGTH) {
17974
+ throw new RuntimeDecryptionError(`Sealed payload has a malformed ephemeral public key: expected ${X25519_KEY_LENGTH} bytes, got ${ephemeralPublicKey.byteLength}`, {
17975
+ context: {
17976
+ operation: "decrypt",
17977
+ byteLength: ephemeralPublicKey.byteLength
17978
+ }
17979
+ });
17980
+ }
17981
+ let sharedSecretBits;
17982
+ try {
17983
+ const [privateKey, senderKey] = await Promise.all([
17984
+ importScalar(
17985
+ keyPair.scalar,
17986
+ /* extractable */
17987
+ false
17988
+ ),
17989
+ importPublicKey(ephemeralPublicKey)
17990
+ ]);
17991
+ sharedSecretBits = await globalThis.crypto.subtle.deriveBits({
17992
+ name: "X25519",
17993
+ public: senderKey
17994
+ }, privateKey, X25519_KEY_LENGTH * 8);
17995
+ } catch (cause) {
17996
+ throw new RuntimeDecryptionError(`X25519 key agreement failed while opening a sealed payload: ${cause instanceof Error ? cause.message : String(cause)}`, {
17997
+ cause,
17998
+ context: {
17999
+ operation: "decrypt",
18000
+ byteLength: ephemeralPublicKey.byteLength
18001
+ }
18002
+ });
18003
+ }
18004
+ return deriveContentKey(new Uint8Array(sharedSecretBits), ephemeralPublicKey, keyPair.publicKey, [
18005
+ "decrypt"
18006
+ ]);
17775
18007
  }
17776
- function is_valid_array_len(n) {
17777
- if (!Number.isInteger(n)) return false;
17778
- if (n < 0) return false;
17779
- if (n > MAX_ARRAY_LEN) return false;
17780
- return true;
18008
+ async function seal(recipientPublicKey, data, aad) {
18009
+ const { ephemeralPublicKey, contentKey } = await encapsulate(recipientPublicKey);
18010
+ const encrypted = await encrypt(contentKey, data, aad);
18011
+ const result = new Uint8Array(ephemeralPublicKey.byteLength + encrypted.byteLength);
18012
+ result.set(ephemeralPublicKey, 0);
18013
+ result.set(encrypted, ephemeralPublicKey.byteLength);
18014
+ return result;
17781
18015
  }
17782
- function is_valid_array_index_string(s) {
17783
- if (s.length === 0) return false;
17784
- if (s.length > 1 && s.charCodeAt(0) === 48) return false;
17785
- for (let i = 0; i < s.length; i++) {
17786
- const c = s.charCodeAt(i);
17787
- if (c < 48 || c > 57) return false;
18016
+ async function open(keyPair, sealed, aad) {
18017
+ const minLength = X25519_KEY_LENGTH + NONCE_LENGTH + TAG_BYTES;
18018
+ if (sealed.byteLength < minLength) {
18019
+ throw new RuntimeDecryptionError(`Sealed payload too short: expected at least ${minLength} bytes, got ${sealed.byteLength}`, {
18020
+ context: {
18021
+ operation: "decrypt",
18022
+ byteLength: sealed.byteLength
18023
+ }
18024
+ });
17788
18025
  }
17789
- return is_valid_array_index(+s);
18026
+ const ephemeralPublicKey = sealed.subarray(0, X25519_KEY_LENGTH);
18027
+ const encrypted = sealed.subarray(X25519_KEY_LENGTH);
18028
+ const contentKey = await decapsulate(keyPair, ephemeralPublicKey);
18029
+ return decrypt(contentKey, encrypted, aad);
17790
18030
  }
17791
- function valid_array_indices(array2) {
17792
- const keys = Object.keys(array2);
17793
- for (var i = keys.length - 1; i >= 0; i--) {
17794
- if (is_valid_array_index_string(keys[i])) {
17795
- break;
18031
+ function createSealSession(recipientPublicKey, aad) {
18032
+ let encapsulation;
18033
+ return {
18034
+ async seal(data) {
18035
+ encapsulation ??= encapsulate(recipientPublicKey);
18036
+ const { ephemeralPublicKey, contentKey } = await encapsulation;
18037
+ const encrypted = await encrypt(contentKey, data, aad);
18038
+ const result = new Uint8Array(ephemeralPublicKey.byteLength + encrypted.byteLength);
18039
+ result.set(ephemeralPublicKey, 0);
18040
+ result.set(encrypted, ephemeralPublicKey.byteLength);
18041
+ return result;
17796
18042
  }
17797
- }
17798
- keys.length = i + 1;
17799
- return keys;
18043
+ };
17800
18044
  }
17801
- var DevalueError, object_proto_names, is_identifier;
17802
- var init_utils = __esm({
17803
- "../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/utils.js"() {
17804
- "use strict";
17805
- init_constants();
17806
- DevalueError = class extends Error {
17807
- static {
17808
- __name(this, "DevalueError");
18045
+ function createOpenSession(keyPair, aad) {
18046
+ let cachedSender;
18047
+ let cachedKey;
18048
+ return {
18049
+ async open(sealed) {
18050
+ const minLength = X25519_KEY_LENGTH + NONCE_LENGTH + TAG_BYTES;
18051
+ if (sealed.byteLength < minLength) {
18052
+ throw new RuntimeDecryptionError(`Sealed payload too short: expected at least ${minLength} bytes, got ${sealed.byteLength}`, {
18053
+ context: {
18054
+ operation: "decrypt",
18055
+ byteLength: sealed.byteLength
18056
+ }
18057
+ });
17809
18058
  }
17810
- /**
17811
- * @param {string} message
17812
- * @param {string[]} keys
17813
- * @param {any} [value] - The value that failed to be serialized
17814
- * @param {any} [root] - The root value being serialized
17815
- */
17816
- constructor(message, keys, value, root) {
17817
- super(message);
17818
- this.name = "DevalueError";
17819
- this.path = keys.join("");
17820
- this.value = value;
17821
- this.root = root;
18059
+ const ephemeralPublicKey = sealed.subarray(0, X25519_KEY_LENGTH);
18060
+ const encrypted = sealed.subarray(X25519_KEY_LENGTH);
18061
+ const sender = keyCacheId(ephemeralPublicKey);
18062
+ if (sender !== cachedSender || !cachedKey) {
18063
+ cachedSender = sender;
18064
+ cachedKey = decapsulate(keyPair, ephemeralPublicKey);
17822
18065
  }
17823
- };
17824
- __name(is_primitive, "is_primitive");
17825
- object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
17826
- __name(is_plain_object, "is_plain_object");
17827
- __name(get_type, "get_type");
17828
- __name(get_escaped_char, "get_escaped_char");
18066
+ let contentKey;
18067
+ try {
18068
+ contentKey = await cachedKey;
18069
+ } catch (error48) {
18070
+ cachedSender = void 0;
18071
+ cachedKey = void 0;
18072
+ throw error48;
18073
+ }
18074
+ return decrypt(contentKey, encrypted, aad);
18075
+ }
18076
+ };
18077
+ }
18078
+ function keyCacheId(publicKey) {
18079
+ let id = "";
18080
+ for (let i = 0; i < publicKey.length; i++) {
18081
+ id += publicKey[i].toString(16).padStart(2, "0");
18082
+ }
18083
+ return id;
18084
+ }
18085
+ function decodeRunPublicKey(value) {
18086
+ if (!value) return void 0;
18087
+ const bytes = base64ToBytes(value);
18088
+ if (!bytes || bytes.byteLength !== X25519_KEY_LENGTH) return void 0;
18089
+ return bytes;
18090
+ }
18091
+ var X25519_KEY_LENGTH, CONTENT_KEY_LENGTH, SCALAR_INFO, CONTENT_KEY_INFO, PKCS8_X25519_PREFIX, infoEncoder, BASE64_CHARS, BASE64URL_CHARS;
18092
+ var init_sealed_box = __esm({
18093
+ "../core/dist/sealed-box.js"() {
18094
+ "use strict";
18095
+ init_dist2();
18096
+ init_encryption();
18097
+ X25519_KEY_LENGTH = 32;
18098
+ CONTENT_KEY_LENGTH = 32;
18099
+ SCALAR_INFO = "workflow/encp/x25519/v1";
18100
+ CONTENT_KEY_INFO = "workflow/encp/aes256gcm/v1";
18101
+ PKCS8_X25519_PREFIX = new Uint8Array([
18102
+ 48,
18103
+ 46,
18104
+ 2,
18105
+ 1,
18106
+ 0,
18107
+ 48,
18108
+ 5,
18109
+ 6,
18110
+ 3,
18111
+ 43,
18112
+ 101,
18113
+ 110,
18114
+ 4,
18115
+ 34,
18116
+ 4,
18117
+ 32
18118
+ ]);
18119
+ infoEncoder = new TextEncoder();
18120
+ __name(assertKeyMaterialLength, "assertKeyMaterialLength");
18121
+ __name(assertPublicKeyLength, "assertPublicKeyLength");
18122
+ __name(deriveRunKeyPair, "deriveRunKeyPair");
18123
+ __name(derivePublicKeyFromScalar, "derivePublicKeyFromScalar");
18124
+ __name(importScalar, "importScalar");
18125
+ __name(importPublicKey, "importPublicKey");
18126
+ BASE64_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
18127
+ BASE64URL_CHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_";
18128
+ __name(bytesToBase64, "bytesToBase64");
18129
+ __name(base64ToBytes, "base64ToBytes");
18130
+ __name(base64UrlToBytes, "base64UrlToBytes");
18131
+ __name(deriveContentKey, "deriveContentKey");
18132
+ __name(encapsulate, "encapsulate");
18133
+ __name(decapsulate, "decapsulate");
18134
+ __name(seal, "seal");
18135
+ __name(open, "open");
18136
+ __name(createSealSession, "createSealSession");
18137
+ __name(createOpenSession, "createOpenSession");
18138
+ __name(keyCacheId, "keyCacheId");
18139
+ __name(decodeRunPublicKey, "decodeRunPublicKey");
18140
+ }
18141
+ });
18142
+
18143
+ // ../core/dist/serialization/types.js
18144
+ function isFormatPrefix(value) {
18145
+ return value.length === 4 && /^[a-z0-9]{4}$/.test(value);
18146
+ }
18147
+ var SerializationFormat;
18148
+ var init_types = __esm({
18149
+ "../core/dist/serialization/types.js"() {
18150
+ "use strict";
18151
+ __name(isFormatPrefix, "isFormatPrefix");
18152
+ SerializationFormat = {
18153
+ /** devalue stringify/parse with TextEncoder/TextDecoder */
18154
+ DEVALUE_V1: "devl",
18155
+ /** Encrypted payload (inner payload has its own format prefix) */
18156
+ ENCRYPTED: "encr",
18157
+ /**
18158
+ * Sealed payload — asymmetrically encrypted to a run's X25519 public key
18159
+ * (inner payload has its own format prefix).
18160
+ *
18161
+ * Used for *cross-run* writes (hook payloads, forwarded stream frames),
18162
+ * where the writer holds only the recipient run's public key and therefore
18163
+ * cannot decrypt. A run's own payloads continue to use {@link ENCRYPTED}.
18164
+ * See `sealed-box.ts` for the construction.
18165
+ */
18166
+ SEALED: "encp",
18167
+ /** Gzip-compressed payload (inner payload has its own format prefix) */
18168
+ GZIP: "gzip",
18169
+ /** Zstandard-compressed payload (inner payload has its own format prefix) */
18170
+ ZSTD: "zstd"
18171
+ };
18172
+ }
18173
+ });
18174
+
18175
+ // ../core/dist/serialization/format.js
18176
+ function encodeWithFormatPrefix(format, payload) {
18177
+ if (!(payload instanceof Uint8Array)) {
18178
+ return payload;
18179
+ }
18180
+ const prefixBytes = formatEncoder.encode(format);
18181
+ const result = new Uint8Array(FORMAT_PREFIX_LENGTH + payload.length);
18182
+ result.set(prefixBytes, 0);
18183
+ result.set(payload, FORMAT_PREFIX_LENGTH);
18184
+ return result;
18185
+ }
18186
+ function peekFormatPrefix(data) {
18187
+ if (!(data instanceof Uint8Array) || data.length < FORMAT_PREFIX_LENGTH) {
18188
+ return null;
18189
+ }
18190
+ const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
18191
+ const str = formatDecoder.decode(prefixBytes);
18192
+ return isFormatPrefix(str) ? str : null;
18193
+ }
18194
+ function decodeFormatPrefix(data) {
18195
+ if (!(data instanceof Uint8Array)) {
18196
+ return {
18197
+ format: SerializationFormat.DEVALUE_V1,
18198
+ payload: new TextEncoder().encode(JSON.stringify(data))
18199
+ };
18200
+ }
18201
+ if (data.length < FORMAT_PREFIX_LENGTH) {
18202
+ throw new Error(`Data too short to contain format prefix: expected at least ${FORMAT_PREFIX_LENGTH} bytes, got ${data.length}`);
18203
+ }
18204
+ const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
18205
+ const str = formatDecoder.decode(prefixBytes);
18206
+ if (!isFormatPrefix(str)) {
18207
+ throw new Error(`Invalid format prefix: "${str}". Must be 4 characters of [a-z0-9].`);
18208
+ }
18209
+ const payload = data.subarray(FORMAT_PREFIX_LENGTH);
18210
+ return {
18211
+ format: str,
18212
+ payload
18213
+ };
18214
+ }
18215
+ var FORMAT_PREFIX_LENGTH, formatEncoder, formatDecoder;
18216
+ var init_format = __esm({
18217
+ "../core/dist/serialization/format.js"() {
18218
+ "use strict";
18219
+ init_types();
18220
+ FORMAT_PREFIX_LENGTH = 4;
18221
+ formatEncoder = new TextEncoder();
18222
+ formatDecoder = new TextDecoder();
18223
+ __name(encodeWithFormatPrefix, "encodeWithFormatPrefix");
18224
+ __name(peekFormatPrefix, "peekFormatPrefix");
18225
+ __name(decodeFormatPrefix, "decodeFormatPrefix");
18226
+ }
18227
+ });
18228
+
18229
+ // ../core/dist/serialization/encryption.js
18230
+ function sealTo(recipientPublicKey, aad) {
18231
+ return {
18232
+ [SEAL_TARGET_BRAND]: true,
18233
+ recipientPublicKey,
18234
+ aad
18235
+ };
18236
+ }
18237
+ function runPayloadKeys(aes, keyPair, aad) {
18238
+ return {
18239
+ [RUN_KEYS_BRAND]: true,
18240
+ aes,
18241
+ keyPair,
18242
+ aad
18243
+ };
18244
+ }
18245
+ async function deriveRunPayloadKeys(runKeyMaterial) {
18246
+ const [aes, keyPair] = await Promise.all([
18247
+ importKey(runKeyMaterial),
18248
+ deriveRunKeyPair(runKeyMaterial)
18249
+ ]);
18250
+ return runPayloadKeys(aes, keyPair);
18251
+ }
18252
+ function isSealTarget(value) {
18253
+ return typeof value === "object" && value !== null && value[SEAL_TARGET_BRAND] === true;
18254
+ }
18255
+ function isRunPayloadKeys(value) {
18256
+ return typeof value === "object" && value !== null && value[RUN_KEYS_BRAND] === true;
18257
+ }
18258
+ function aesKeyOf(key) {
18259
+ if (!key) return void 0;
18260
+ if (isRunPayloadKeys(key)) return key.aes;
18261
+ if (isSealTarget(key)) return void 0;
18262
+ return key;
18263
+ }
18264
+ async function resolveEncryptionKey(key) {
18265
+ return typeof key === "function" ? key() : key;
18266
+ }
18267
+ async function encrypt2(data, key) {
18268
+ if (!key || !(data instanceof Uint8Array)) return data;
18269
+ if (isSealTarget(key)) {
18270
+ const sealed = await seal(key.recipientPublicKey, data, key.aad);
18271
+ return encodeWithFormatPrefix(SerializationFormat.SEALED, sealed);
18272
+ }
18273
+ const aesKey = isRunPayloadKeys(key) ? key.aes : key;
18274
+ const encrypted = await encrypt(aesKey, data);
18275
+ return encodeWithFormatPrefix(SerializationFormat.ENCRYPTED, encrypted);
18276
+ }
18277
+ async function openSealedEnvelope(data, key) {
18278
+ if (!isRunPayloadKeys(key)) {
18279
+ throw new RuntimeDecryptionError("Sealed data encountered but no run keypair is available. Opening a sealed payload requires the run's own encryption key material; a symmetric key or a seal-only target cannot decrypt it.", {
18280
+ context: {
18281
+ operation: "decrypt",
18282
+ byteLength: data.byteLength,
18283
+ formatPrefix: "encp"
18284
+ }
18285
+ });
18286
+ }
18287
+ const { payload } = decodeFormatPrefix(data);
18288
+ try {
18289
+ return await open(key.keyPair, payload, key.aad);
18290
+ } catch (error48) {
18291
+ if (RuntimeDecryptionError.is(error48) && error48.context) {
18292
+ error48.context.formatPrefix = SerializationFormat.SEALED;
18293
+ }
18294
+ throw error48;
18295
+ }
18296
+ }
18297
+ async function decrypt2(data, key) {
18298
+ if (!(data instanceof Uint8Array)) return data;
18299
+ const format = peekFormatPrefix(data);
18300
+ if (format === SerializationFormat.SEALED) {
18301
+ return openSealedEnvelope(data, key);
18302
+ }
18303
+ if (format !== SerializationFormat.ENCRYPTED) return data;
18304
+ const aesKey = aesKeyOf(key);
18305
+ if (!aesKey) {
18306
+ throw new RuntimeDecryptionError("Encrypted data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.", {
18307
+ context: {
18308
+ operation: "decrypt",
18309
+ byteLength: data.byteLength,
18310
+ formatPrefix: "encr"
18311
+ }
18312
+ });
18313
+ }
18314
+ const { payload } = decodeFormatPrefix(data);
18315
+ try {
18316
+ return await decrypt(aesKey, payload);
18317
+ } catch (error48) {
18318
+ if (RuntimeDecryptionError.is(error48) && error48.context) {
18319
+ error48.context.formatPrefix = format;
18320
+ }
18321
+ throw error48;
18322
+ }
18323
+ }
18324
+ var SEAL_TARGET_BRAND, RUN_KEYS_BRAND;
18325
+ var init_encryption2 = __esm({
18326
+ "../core/dist/serialization/encryption.js"() {
18327
+ "use strict";
18328
+ init_dist2();
18329
+ init_encryption();
18330
+ init_sealed_box();
18331
+ init_format();
18332
+ init_types();
18333
+ SEAL_TARGET_BRAND = /* @__PURE__ */ Symbol.for("workflow.serialization.sealTarget");
18334
+ RUN_KEYS_BRAND = /* @__PURE__ */ Symbol.for("workflow.serialization.runKeys");
18335
+ __name(sealTo, "sealTo");
18336
+ __name(runPayloadKeys, "runPayloadKeys");
18337
+ __name(deriveRunPayloadKeys, "deriveRunPayloadKeys");
18338
+ __name(isSealTarget, "isSealTarget");
18339
+ __name(isRunPayloadKeys, "isRunPayloadKeys");
18340
+ __name(aesKeyOf, "aesKeyOf");
18341
+ __name(resolveEncryptionKey, "resolveEncryptionKey");
18342
+ __name(encrypt2, "encrypt");
18343
+ __name(openSealedEnvelope, "openSealedEnvelope");
18344
+ __name(decrypt2, "decrypt");
18345
+ }
18346
+ });
18347
+
18348
+ // ../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/constants.js
18349
+ var UNDEFINED, HOLE, NAN, POSITIVE_INFINITY, NEGATIVE_INFINITY, NEGATIVE_ZERO, SPARSE, MAX_ARRAY_LEN, MAX_ARRAY_INDEX;
18350
+ var init_constants = __esm({
18351
+ "../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/constants.js"() {
18352
+ "use strict";
18353
+ UNDEFINED = -1;
18354
+ HOLE = -2;
18355
+ NAN = -3;
18356
+ POSITIVE_INFINITY = -4;
18357
+ NEGATIVE_INFINITY = -5;
18358
+ NEGATIVE_ZERO = -6;
18359
+ SPARSE = -7;
18360
+ MAX_ARRAY_LEN = 2 ** 32 - 1;
18361
+ MAX_ARRAY_INDEX = MAX_ARRAY_LEN - 1;
18362
+ }
18363
+ });
18364
+
18365
+ // ../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/utils.js
18366
+ function is_primitive(thing) {
18367
+ return thing === null || typeof thing !== "object" && typeof thing !== "function";
18368
+ }
18369
+ function is_plain_object(thing) {
18370
+ const proto = Object.getPrototypeOf(thing);
18371
+ return proto === Object.prototype || proto === null || Object.getPrototypeOf(proto) === null || Object.getOwnPropertyNames(proto).sort().join("\0") === object_proto_names;
18372
+ }
18373
+ function get_type(thing) {
18374
+ return Object.prototype.toString.call(thing).slice(8, -1);
18375
+ }
18376
+ function get_escaped_char(char) {
18377
+ switch (char) {
18378
+ case '"':
18379
+ return '\\"';
18380
+ case "<":
18381
+ return "\\u003C";
18382
+ case "\\":
18383
+ return "\\\\";
18384
+ case "\n":
18385
+ return "\\n";
18386
+ case "\r":
18387
+ return "\\r";
18388
+ case " ":
18389
+ return "\\t";
18390
+ case "\b":
18391
+ return "\\b";
18392
+ case "\f":
18393
+ return "\\f";
18394
+ case "\u2028":
18395
+ return "\\u2028";
18396
+ case "\u2029":
18397
+ return "\\u2029";
18398
+ default:
18399
+ return char < " " ? `\\u${char.charCodeAt(0).toString(16).padStart(4, "0")}` : "";
18400
+ }
18401
+ }
18402
+ function stringify_string(str) {
18403
+ let result = "";
18404
+ let last_pos = 0;
18405
+ const len = str.length;
18406
+ for (let i = 0; i < len; i += 1) {
18407
+ const char = str[i];
18408
+ const replacement = get_escaped_char(char);
18409
+ if (replacement) {
18410
+ result += str.slice(last_pos, i) + replacement;
18411
+ last_pos = i + 1;
18412
+ }
18413
+ }
18414
+ return `"${last_pos === 0 ? str : result + str.slice(last_pos)}"`;
18415
+ }
18416
+ function enumerable_symbols(object2) {
18417
+ return Object.getOwnPropertySymbols(object2).filter((symbol2) => Object.getOwnPropertyDescriptor(object2, symbol2).enumerable);
18418
+ }
18419
+ function stringify_key(key) {
18420
+ return is_identifier.test(key) ? "." + key : "[" + JSON.stringify(key) + "]";
18421
+ }
18422
+ function is_valid_array_index(n) {
18423
+ if (!Number.isInteger(n)) return false;
18424
+ if (n < 0) return false;
18425
+ if (n > MAX_ARRAY_INDEX) return false;
18426
+ return true;
18427
+ }
18428
+ function is_valid_array_len(n) {
18429
+ if (!Number.isInteger(n)) return false;
18430
+ if (n < 0) return false;
18431
+ if (n > MAX_ARRAY_LEN) return false;
18432
+ return true;
18433
+ }
18434
+ function is_valid_array_index_string(s) {
18435
+ if (s.length === 0) return false;
18436
+ if (s.length > 1 && s.charCodeAt(0) === 48) return false;
18437
+ for (let i = 0; i < s.length; i++) {
18438
+ const c = s.charCodeAt(i);
18439
+ if (c < 48 || c > 57) return false;
18440
+ }
18441
+ return is_valid_array_index(+s);
18442
+ }
18443
+ function valid_array_indices(array2) {
18444
+ const keys = Object.keys(array2);
18445
+ for (var i = keys.length - 1; i >= 0; i--) {
18446
+ if (is_valid_array_index_string(keys[i])) {
18447
+ break;
18448
+ }
18449
+ }
18450
+ keys.length = i + 1;
18451
+ return keys;
18452
+ }
18453
+ var DevalueError, object_proto_names, is_identifier;
18454
+ var init_utils = __esm({
18455
+ "../../node_modules/.pnpm/devalue@5.8.1/node_modules/devalue/src/utils.js"() {
18456
+ "use strict";
18457
+ init_constants();
18458
+ DevalueError = class extends Error {
18459
+ static {
18460
+ __name(this, "DevalueError");
18461
+ }
18462
+ /**
18463
+ * @param {string} message
18464
+ * @param {string[]} keys
18465
+ * @param {any} [value] - The value that failed to be serialized
18466
+ * @param {any} [root] - The root value being serialized
18467
+ */
18468
+ constructor(message, keys, value, root) {
18469
+ super(message);
18470
+ this.name = "DevalueError";
18471
+ this.path = keys.join("");
18472
+ this.value = value;
18473
+ this.root = root;
18474
+ }
18475
+ };
18476
+ __name(is_primitive, "is_primitive");
18477
+ object_proto_names = /* @__PURE__ */ Object.getOwnPropertyNames(Object.prototype).sort().join("\0");
18478
+ __name(is_plain_object, "is_plain_object");
18479
+ __name(get_type, "get_type");
18480
+ __name(get_escaped_char, "get_escaped_char");
17829
18481
  __name(stringify_string, "stringify_string");
17830
18482
  __name(enumerable_symbols, "enumerable_symbols");
17831
18483
  is_identifier = /^[a-zA-Z_$][a-zA-Z_$0-9]*$/;
@@ -18323,6 +18975,29 @@ var init_devalue = __esm({
18323
18975
  }
18324
18976
  });
18325
18977
 
18978
+ // ../core/dist/symbols.js
18979
+ var STABLE_ULID, STREAM_NAME_SYMBOL, STREAM_TYPE_SYMBOL, STREAM_FRAMING_SYMBOL, STREAM_SERVER_RUN_ID_SYMBOL, STREAM_SERVER_DEPLOYMENT_ID_SYMBOL, STREAM_SERVER_PUBLIC_KEY_SYMBOL, STREAM_DRAIN_SYMBOL, BODY_INIT_SYMBOL, WEBHOOK_RESPONSE_WRITABLE, WORKFLOW_CLASS_REGISTRY, ABORT_STREAM_NAME, ABORT_HOOK_TOKEN, ABORT_LISTENER_ATTACHED, ABORT_READER_CANCEL;
18980
+ var init_symbols = __esm({
18981
+ "../core/dist/symbols.js"() {
18982
+ "use strict";
18983
+ STABLE_ULID = /* @__PURE__ */ Symbol.for("WORKFLOW_STABLE_ULID");
18984
+ STREAM_NAME_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_NAME");
18985
+ STREAM_TYPE_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_TYPE");
18986
+ STREAM_FRAMING_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
18987
+ STREAM_SERVER_RUN_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
18988
+ STREAM_SERVER_DEPLOYMENT_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID");
18989
+ STREAM_SERVER_PUBLIC_KEY_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_PUBLIC_KEY");
18990
+ STREAM_DRAIN_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_DRAIN");
18991
+ BODY_INIT_SYMBOL = /* @__PURE__ */ Symbol.for("BODY_INIT");
18992
+ WEBHOOK_RESPONSE_WRITABLE = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
18993
+ WORKFLOW_CLASS_REGISTRY = /* @__PURE__ */ Symbol.for("workflow-class-registry");
18994
+ ABORT_STREAM_NAME = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_STREAM_NAME");
18995
+ ABORT_HOOK_TOKEN = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_HOOK_TOKEN");
18996
+ ABORT_LISTENER_ATTACHED = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_LISTENER_ATTACHED");
18997
+ ABORT_READER_CANCEL = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
18998
+ }
18999
+ });
19000
+
18326
19001
  // ../core/dist/flushable-stream.js
18327
19002
  function createFlushableState() {
18328
19003
  const state = {
@@ -18365,6 +19040,14 @@ function isReadableUnlockedNotClosed(readable) {
18365
19040
  }
18366
19041
  return true;
18367
19042
  }
19043
+ function resolveAfterDrain(state) {
19044
+ const barrier = state.drainBarrier;
19045
+ if (!barrier) {
19046
+ state.resolve();
19047
+ return;
19048
+ }
19049
+ barrier().then(() => state.resolve(), (err) => state.reject(err));
19050
+ }
18368
19051
  function pollWritableLock(writable, state) {
18369
19052
  if (state.writablePollingInterval !== void 0) {
18370
19053
  return;
@@ -18377,9 +19060,9 @@ function pollWritableLock(writable, state) {
18377
19060
  }
18378
19061
  if (isWritableUnlockedNotClosed(writable) && state.pendingOps === 0) {
18379
19062
  state.doneResolved = true;
18380
- state.resolve();
18381
19063
  clearInterval(intervalId);
18382
19064
  state.writablePollingInterval = void 0;
19065
+ resolveAfterDrain(state);
18383
19066
  }
18384
19067
  }, getLockPollIntervalMs());
18385
19068
  state.writablePollingInterval = intervalId;
@@ -18396,14 +19079,21 @@ function pollReadableLock(readable, state) {
18396
19079
  }
18397
19080
  if (isReadableUnlockedNotClosed(readable) && state.pendingOps === 0) {
18398
19081
  state.doneResolved = true;
18399
- state.resolve();
18400
19082
  clearInterval(intervalId);
18401
19083
  state.readablePollingInterval = void 0;
19084
+ resolveAfterDrain(state);
18402
19085
  }
18403
19086
  }, getLockPollIntervalMs());
18404
19087
  state.readablePollingInterval = intervalId;
18405
19088
  }
18406
- async function flushablePipe(source, sink, state) {
19089
+ function flushablePipe(source, sink, state) {
19090
+ const drain = sink[STREAM_DRAIN_SYMBOL];
19091
+ if (typeof drain === "function") {
19092
+ state.drainBarrier = drain;
19093
+ }
19094
+ return flushablePipePerChunk(source, sink, state);
19095
+ }
19096
+ async function flushablePipePerChunk(source, sink, state) {
18407
19097
  const reader = source.getReader();
18408
19098
  const writer = sink.getWriter();
18409
19099
  let cancelReason;
@@ -18440,6 +19130,10 @@ async function flushablePipe(source, sink, state) {
18440
19130
  } catch (err) {
18441
19131
  state.streamEnded = true;
18442
19132
  cancelReason = err;
19133
+ if (state.drainBarrier) {
19134
+ await state.drainBarrier().catch(() => {
19135
+ });
19136
+ }
18443
19137
  if (!state.doneResolved) {
18444
19138
  state.doneResolved = true;
18445
19139
  state.reject(err);
@@ -18452,13 +19146,34 @@ async function flushablePipe(source, sink, state) {
18452
19146
  writer.releaseLock();
18453
19147
  }
18454
19148
  }
18455
- var LOCK_POLL_INTERVAL_MS, getLockPollIntervalMs;
19149
+ var MAX_INFLIGHT_CHUNKS, getMaxInflightChunks, MAX_CHUNKS_PER_BATCH, getMaxChunksPerBatch, MAX_BYTES_PER_BATCH, getMaxBytesPerBatch, MAX_BUFFERED_BYTES, getMaxBufferedBytes, LOCK_POLL_INTERVAL_MS, getLockPollIntervalMs;
18456
19150
  var init_flushable_stream = __esm({
18457
19151
  "../core/dist/flushable-stream.js"() {
18458
19152
  "use strict";
18459
19153
  init_dist2();
18460
19154
  init_dist();
18461
19155
  init_dist4();
19156
+ init_symbols();
19157
+ MAX_INFLIGHT_CHUNKS = 1e3;
19158
+ getMaxInflightChunks = /* @__PURE__ */ __name(() => envNumber("WORKFLOW_STREAM_MAX_INFLIGHT_CHUNKS", MAX_INFLIGHT_CHUNKS, {
19159
+ integer: true,
19160
+ min: 1
19161
+ }), "getMaxInflightChunks");
19162
+ MAX_CHUNKS_PER_BATCH = 1e3;
19163
+ getMaxChunksPerBatch = /* @__PURE__ */ __name(() => envNumber("WORKFLOW_STREAM_MAX_CHUNKS_PER_BATCH", MAX_CHUNKS_PER_BATCH, {
19164
+ integer: true,
19165
+ min: 1
19166
+ }), "getMaxChunksPerBatch");
19167
+ MAX_BYTES_PER_BATCH = 1024 * 1024;
19168
+ getMaxBytesPerBatch = /* @__PURE__ */ __name(() => envNumber("WORKFLOW_STREAM_MAX_BYTES_PER_BATCH", MAX_BYTES_PER_BATCH, {
19169
+ integer: true,
19170
+ min: 1
19171
+ }), "getMaxBytesPerBatch");
19172
+ MAX_BUFFERED_BYTES = 8 * 1024 * 1024;
19173
+ getMaxBufferedBytes = /* @__PURE__ */ __name(() => envNumber("WORKFLOW_STREAM_MAX_BUFFERED_BYTES", MAX_BUFFERED_BYTES, {
19174
+ integer: true,
19175
+ min: 1
19176
+ }), "getMaxBufferedBytes");
18462
19177
  LOCK_POLL_INTERVAL_MS = 10;
18463
19178
  getLockPollIntervalMs = /* @__PURE__ */ __name(() => envNumber("WORKFLOW_LOCK_POLL_INTERVAL_MS", LOCK_POLL_INTERVAL_MS, {
18464
19179
  integer: true,
@@ -18467,9 +19182,11 @@ var init_flushable_stream = __esm({
18467
19182
  __name(createFlushableState, "createFlushableState");
18468
19183
  __name(isWritableUnlockedNotClosed, "isWritableUnlockedNotClosed");
18469
19184
  __name(isReadableUnlockedNotClosed, "isReadableUnlockedNotClosed");
19185
+ __name(resolveAfterDrain, "resolveAfterDrain");
18470
19186
  __name(pollWritableLock, "pollWritableLock");
18471
19187
  __name(pollReadableLock, "pollReadableLock");
18472
19188
  __name(flushablePipe, "flushablePipe");
19189
+ __name(flushablePipePerChunk, "flushablePipePerChunk");
18473
19190
  }
18474
19191
  });
18475
19192
 
@@ -18580,42 +19297,21 @@ async function getWorldLazy() {
18580
19297
  }
18581
19298
  const getWorldFn = g[GetWorldFnKey];
18582
19299
  if (getWorldFn) {
18583
- const world = await getWorldFn();
18584
- assertWorldSupportsRuntimeProtocol(world);
18585
- return world;
18586
- }
18587
- throw new Error("Workflow world runtime was not initialized. Import from the host workflow entrypoints (`workflow`, `workflow/api`, or `workflow/runtime`) so @workflow/core/runtime/world-init can register getWorld before getWorldLazy() is used.");
18588
- }
18589
- var WorldCacheKey, WorldCachePromiseKey, GetWorldFnKey;
18590
- var init_get_world_lazy = __esm({
18591
- "../core/dist/runtime/get-world-lazy.js"() {
18592
- "use strict";
18593
- init_world_compatibility();
18594
- WorldCacheKey = /* @__PURE__ */ Symbol.for("@workflow/world//cache");
18595
- WorldCachePromiseKey = /* @__PURE__ */ Symbol.for("@workflow/world//cachePromise");
18596
- GetWorldFnKey = /* @__PURE__ */ Symbol.for("@workflow/world//getWorldFn");
18597
- __name(getWorldLazy, "getWorldLazy");
18598
- }
18599
- });
18600
-
18601
- // ../core/dist/symbols.js
18602
- var STABLE_ULID, STREAM_NAME_SYMBOL, STREAM_TYPE_SYMBOL, STREAM_FRAMING_SYMBOL, STREAM_SERVER_RUN_ID_SYMBOL, STREAM_SERVER_DEPLOYMENT_ID_SYMBOL, BODY_INIT_SYMBOL, WEBHOOK_RESPONSE_WRITABLE, WORKFLOW_CLASS_REGISTRY, ABORT_STREAM_NAME, ABORT_HOOK_TOKEN, ABORT_LISTENER_ATTACHED, ABORT_READER_CANCEL;
18603
- var init_symbols = __esm({
18604
- "../core/dist/symbols.js"() {
18605
- "use strict";
18606
- STABLE_ULID = /* @__PURE__ */ Symbol.for("WORKFLOW_STABLE_ULID");
18607
- STREAM_NAME_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_NAME");
18608
- STREAM_TYPE_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_TYPE");
18609
- STREAM_FRAMING_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_FRAMING");
18610
- STREAM_SERVER_RUN_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_RUN_ID");
18611
- STREAM_SERVER_DEPLOYMENT_ID_SYMBOL = /* @__PURE__ */ Symbol.for("WORKFLOW_STREAM_SERVER_DEPLOYMENT_ID");
18612
- BODY_INIT_SYMBOL = /* @__PURE__ */ Symbol.for("BODY_INIT");
18613
- WEBHOOK_RESPONSE_WRITABLE = /* @__PURE__ */ Symbol.for("WEBHOOK_RESPONSE_WRITABLE");
18614
- WORKFLOW_CLASS_REGISTRY = /* @__PURE__ */ Symbol.for("workflow-class-registry");
18615
- ABORT_STREAM_NAME = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_STREAM_NAME");
18616
- ABORT_HOOK_TOKEN = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_HOOK_TOKEN");
18617
- ABORT_LISTENER_ATTACHED = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_LISTENER_ATTACHED");
18618
- ABORT_READER_CANCEL = /* @__PURE__ */ Symbol.for("WORKFLOW_ABORT_READER_CANCEL");
19300
+ const world = await getWorldFn();
19301
+ assertWorldSupportsRuntimeProtocol(world);
19302
+ return world;
19303
+ }
19304
+ throw new Error("Workflow world runtime was not initialized. Import from the host workflow entrypoints (`workflow`, `workflow/api`, or `workflow/runtime`) so @workflow/core/runtime/world-init can register getWorld before getWorldLazy() is used.");
19305
+ }
19306
+ var WorldCacheKey, WorldCachePromiseKey, GetWorldFnKey;
19307
+ var init_get_world_lazy = __esm({
19308
+ "../core/dist/runtime/get-world-lazy.js"() {
19309
+ "use strict";
19310
+ init_world_compatibility();
19311
+ WorldCacheKey = /* @__PURE__ */ Symbol.for("@workflow/world//cache");
19312
+ WorldCachePromiseKey = /* @__PURE__ */ Symbol.for("@workflow/world//cachePromise");
19313
+ GetWorldFnKey = /* @__PURE__ */ Symbol.for("@workflow/world//getWorldFn");
19314
+ __name(getWorldLazy, "getWorldLazy");
18619
19315
  }
18620
19316
  });
18621
19317
 
@@ -19086,28 +19782,6 @@ var init_step_function = __esm({
19086
19782
  }
19087
19783
  });
19088
19784
 
19089
- // ../core/dist/serialization/types.js
19090
- function isFormatPrefix(value) {
19091
- return value.length === 4 && /^[a-z0-9]{4}$/.test(value);
19092
- }
19093
- var SerializationFormat;
19094
- var init_types = __esm({
19095
- "../core/dist/serialization/types.js"() {
19096
- "use strict";
19097
- __name(isFormatPrefix, "isFormatPrefix");
19098
- SerializationFormat = {
19099
- /** devalue stringify/parse with TextEncoder/TextDecoder */
19100
- DEVALUE_V1: "devl",
19101
- /** Encrypted payload (inner payload has its own format prefix) */
19102
- ENCRYPTED: "encr",
19103
- /** Gzip-compressed payload (inner payload has its own format prefix) */
19104
- GZIP: "gzip",
19105
- /** Zstandard-compressed payload (inner payload has its own format prefix) */
19106
- ZSTD: "zstd"
19107
- };
19108
- }
19109
- });
19110
-
19111
19785
  // ../core/dist/serialization/codec-devalue.js
19112
19786
  function getReducersForMode(mode, global2 = globalThis, extraReducers) {
19113
19787
  let base;
@@ -19207,60 +19881,6 @@ var init_codec_devalue = __esm({
19207
19881
  }
19208
19882
  });
19209
19883
 
19210
- // ../core/dist/serialization/format.js
19211
- function encodeWithFormatPrefix(format, payload) {
19212
- if (!(payload instanceof Uint8Array)) {
19213
- return payload;
19214
- }
19215
- const prefixBytes = formatEncoder.encode(format);
19216
- const result = new Uint8Array(FORMAT_PREFIX_LENGTH + payload.length);
19217
- result.set(prefixBytes, 0);
19218
- result.set(payload, FORMAT_PREFIX_LENGTH);
19219
- return result;
19220
- }
19221
- function peekFormatPrefix(data) {
19222
- if (!(data instanceof Uint8Array) || data.length < FORMAT_PREFIX_LENGTH) {
19223
- return null;
19224
- }
19225
- const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
19226
- const str = formatDecoder.decode(prefixBytes);
19227
- return isFormatPrefix(str) ? str : null;
19228
- }
19229
- function decodeFormatPrefix(data) {
19230
- if (!(data instanceof Uint8Array)) {
19231
- return {
19232
- format: SerializationFormat.DEVALUE_V1,
19233
- payload: new TextEncoder().encode(JSON.stringify(data))
19234
- };
19235
- }
19236
- if (data.length < FORMAT_PREFIX_LENGTH) {
19237
- throw new Error(`Data too short to contain format prefix: expected at least ${FORMAT_PREFIX_LENGTH} bytes, got ${data.length}`);
19238
- }
19239
- const prefixBytes = data.subarray(0, FORMAT_PREFIX_LENGTH);
19240
- const str = formatDecoder.decode(prefixBytes);
19241
- if (!isFormatPrefix(str)) {
19242
- throw new Error(`Invalid format prefix: "${str}". Must be 4 characters of [a-z0-9].`);
19243
- }
19244
- const payload = data.subarray(FORMAT_PREFIX_LENGTH);
19245
- return {
19246
- format: str,
19247
- payload
19248
- };
19249
- }
19250
- var FORMAT_PREFIX_LENGTH, formatEncoder, formatDecoder;
19251
- var init_format = __esm({
19252
- "../core/dist/serialization/format.js"() {
19253
- "use strict";
19254
- init_types();
19255
- FORMAT_PREFIX_LENGTH = 4;
19256
- formatEncoder = new TextEncoder();
19257
- formatDecoder = new TextDecoder();
19258
- __name(encodeWithFormatPrefix, "encodeWithFormatPrefix");
19259
- __name(peekFormatPrefix, "peekFormatPrefix");
19260
- __name(decodeFormatPrefix, "decodeFormatPrefix");
19261
- }
19262
- });
19263
-
19264
19884
  // ../core/dist/serialization/compression.js
19265
19885
  function isCompressionDisabledByEnv() {
19266
19886
  try {
@@ -19420,51 +20040,6 @@ var init_compression = __esm({
19420
20040
  }
19421
20041
  });
19422
20042
 
19423
- // ../core/dist/serialization/encryption.js
19424
- async function resolveEncryptionKey(key) {
19425
- return typeof key === "function" ? key() : key;
19426
- }
19427
- async function encrypt2(data, key) {
19428
- if (!key || !(data instanceof Uint8Array)) return data;
19429
- const encrypted = await encrypt(key, data);
19430
- return encodeWithFormatPrefix(SerializationFormat.ENCRYPTED, encrypted);
19431
- }
19432
- async function decrypt2(data, key) {
19433
- if (!(data instanceof Uint8Array)) return data;
19434
- const format = peekFormatPrefix(data);
19435
- if (format === SerializationFormat.ENCRYPTED && !key) {
19436
- throw new RuntimeDecryptionError("Encrypted data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.", {
19437
- context: {
19438
- operation: "decrypt",
19439
- byteLength: data.byteLength,
19440
- formatPrefix: "encr"
19441
- }
19442
- });
19443
- }
19444
- if (format !== SerializationFormat.ENCRYPTED) return data;
19445
- const { payload } = decodeFormatPrefix(data);
19446
- try {
19447
- return await decrypt(key, payload);
19448
- } catch (error48) {
19449
- if (RuntimeDecryptionError.is(error48) && error48.context) {
19450
- error48.context.formatPrefix = format;
19451
- }
19452
- throw error48;
19453
- }
19454
- }
19455
- var init_encryption2 = __esm({
19456
- "../core/dist/serialization/encryption.js"() {
19457
- "use strict";
19458
- init_dist2();
19459
- init_encryption();
19460
- init_format();
19461
- init_types();
19462
- __name(resolveEncryptionKey, "resolveEncryptionKey");
19463
- __name(encrypt2, "encrypt");
19464
- __name(decrypt2, "decrypt");
19465
- }
19466
- });
19467
-
19468
20043
  // ../errors/dist/internal-chalk.js
19469
20044
  var colorEnabled, sgr, chalk, internal_chalk_default;
19470
20045
  var init_internal_chalk = __esm({
@@ -19477,7 +20052,7 @@ var init_internal_chalk = __esm({
19477
20052
  if (p.env.NO_COLOR) return false;
19478
20053
  return Boolean(p.stdout?.isTTY);
19479
20054
  })();
19480
- sgr = /* @__PURE__ */ __name((open, close) => (s) => colorEnabled ? `\x1B[${open}m${s}\x1B[${close}m` : s, "sgr");
20055
+ sgr = /* @__PURE__ */ __name((open2, close) => (s) => colorEnabled ? `\x1B[${open2}m${s}\x1B[${close}m` : s, "sgr");
19481
20056
  chalk = {
19482
20057
  bold: sgr(1, 22),
19483
20058
  dim: sgr(2, 22),
@@ -22392,6 +22967,7 @@ var init_abort_controller = __esm({
22392
22967
  "use strict";
22393
22968
  init_dist2();
22394
22969
  init_events_consumer();
22970
+ init_private();
22395
22971
  init_serialization2();
22396
22972
  init_symbols();
22397
22973
  init_util2();
@@ -24472,6 +25048,15 @@ var init_capabilities = __esm({
24472
25048
  {
24473
25049
  format: SerializationFormat.ZSTD,
24474
25050
  minVersion: "5.0.0-beta.18"
25051
+ },
25052
+ // TODO(release): verify this matches the actual version that ships sealed-box
25053
+ // encryption. If a "Version Packages (beta)" PR merges before this change,
25054
+ // bump to the next beta. Unlike the entries above, a wrong cutoff here is
25055
+ // not a correctness hazard: producers gate `encp` on the target run carrying
25056
+ // an `encryptionPublicKey`, not on this table (see History above).
25057
+ {
25058
+ format: SerializationFormat.SEALED,
25059
+ minVersion: "5.0.0-beta.37"
24475
25060
  }
24476
25061
  ];
24477
25062
  CAPABILITY_VERSION_TABLE = [
@@ -24492,7 +25077,7 @@ var version2;
24492
25077
  var init_version = __esm({
24493
25078
  "../core/dist/version.js"() {
24494
25079
  "use strict";
24495
- version2 = "5.0.0-beta.35";
25080
+ version2 = "5.0.0-beta.37";
24496
25081
  }
24497
25082
  });
24498
25083
 
@@ -24578,18 +25163,24 @@ function parseHealthCheckResponse(chunks) {
24578
25163
  if (typeof r.workflowCoreVersion === "string") {
24579
25164
  parsed.workflowCoreVersion = r.workflowCoreVersion;
24580
25165
  }
25166
+ if (typeof r.encryptionPublicKey === "string") {
25167
+ parsed.encryptionPublicKey = r.encryptionPublicKey;
25168
+ }
24581
25169
  return parsed;
24582
25170
  }
24583
- async function healthCheck(world, endpoint, options) {
25171
+ async function healthCheck(world, options) {
24584
25172
  const timeout = options?.timeout ?? DEFAULT_HEALTH_CHECK_TIMEOUT;
24585
25173
  const correlationId = world.createRunId?.() ?? generateId();
24586
25174
  const streamName = getHealthCheckStreamName(correlationId);
24587
- const queueName = `${getQueueTopicPrefix(endpoint, resolveQueueNamespace(options?.namespace))}health_check`;
25175
+ const queueName = `${getQueueTopicPrefix("workflow", resolveQueueNamespace(options?.namespace))}health_check`;
24588
25176
  const startTime = Date.now();
24589
25177
  try {
24590
25178
  await world.queue(queueName, {
24591
25179
  __healthCheck: true,
24592
- correlationId
25180
+ correlationId,
25181
+ ...options?.runId ? {
25182
+ runId: options.runId
25183
+ } : {}
24593
25184
  }, {
24594
25185
  // Use JSON transport so the health check works against both
24595
25186
  // old (JSON-only) and new (dual) deployments.
@@ -24640,8 +25231,9 @@ var init_helpers = __esm({
24640
25231
  init_dist2();
24641
25232
  init_dist4();
24642
25233
  init_node();
24643
- init_encryption();
24644
25234
  init_logger();
25235
+ init_sealed_box();
25236
+ init_encryption2();
24645
25237
  init_semantic_conventions();
24646
25238
  init_telemetry();
24647
25239
  init_version();
@@ -25833,18 +26425,53 @@ __export(resume_hook_exports, {
25833
26425
  resumeHook: () => resumeHook,
25834
26426
  resumeWebhook: () => resumeWebhook
25835
26427
  });
26428
+ function resumeContextFromRun(run2) {
26429
+ const coreVersion = run2.executionContext?.workflowCoreVersion;
26430
+ const traceCarrier = run2.executionContext?.traceCarrier;
26431
+ return {
26432
+ deploymentId: run2.deploymentId,
26433
+ workflowName: run2.workflowName,
26434
+ runSpecVersion: run2.specVersion,
26435
+ workflowCoreVersion: typeof coreVersion === "string" ? coreVersion : void 0,
26436
+ traceCarrier: traceCarrier && typeof traceCarrier === "object" ? traceCarrier : void 0,
26437
+ encryptionPublicKey: run2.encryptionPublicKey
26438
+ };
26439
+ }
26440
+ async function resolveHookResumeInfo(hook) {
26441
+ if (hook.resumeContext) {
26442
+ return {
26443
+ resumeContext: hook.resumeContext,
26444
+ source: "hook"
26445
+ };
26446
+ }
26447
+ const run2 = await (await getWorldLazy()).runs.get(hook.runId);
26448
+ return {
26449
+ resumeContext: resumeContextFromRun(run2),
26450
+ source: "run_fallback",
26451
+ run: run2
26452
+ };
26453
+ }
26454
+ async function resolveHookEncryptionKey(hook, info) {
26455
+ const world = await getWorldLazy();
26456
+ const rawKey = info.run ? await world.getEncryptionKeyForRun?.(info.run) : await world.getEncryptionKeyForRun?.(hook.runId, {
26457
+ deploymentId: info.resumeContext.deploymentId
26458
+ });
26459
+ return rawKey ? await importKey(rawKey) : void 0;
26460
+ }
25836
26461
  async function getHookByTokenWithKey(token) {
25837
26462
  const world = await getWorldLazy();
25838
26463
  const hook = await world.hooks.getByToken(token);
25839
- const run2 = await world.runs.get(hook.runId);
25840
- const rawKey = await world.getEncryptionKeyForRun?.(run2);
25841
- const encryptionKey = rawKey ? await importKey(rawKey) : void 0;
26464
+ let encryptionKey;
25842
26465
  if (typeof hook.metadata !== "undefined") {
26466
+ const info = await resolveHookResumeInfo(hook);
26467
+ const rawKey = info.run ? await world.getEncryptionKeyForRun?.(info.run) : await world.getEncryptionKeyForRun?.(hook.runId, {
26468
+ deploymentId: info.resumeContext.deploymentId
26469
+ });
26470
+ encryptionKey = rawKey ? await deriveRunPayloadKeys(rawKey) : void 0;
25843
26471
  hook.metadata = await hydrateStepArguments(hook.metadata, hook.runId, encryptionKey);
25844
26472
  }
25845
26473
  return {
25846
26474
  hook,
25847
- run: run2,
25848
26475
  encryptionKey
25849
26476
  };
25850
26477
  }
@@ -25857,38 +26484,38 @@ async function resumeHook(tokenOrHook, payload, encryptionKeyOverride) {
25857
26484
  return trace("hook.resume", async (span) => {
25858
26485
  const world = await getWorldLazy();
25859
26486
  try {
25860
- let hook;
25861
- let workflowRun;
25862
- let encryptionKey;
25863
- if (typeof tokenOrHook === "string") {
25864
- const result = await getHookByTokenWithKey(tokenOrHook);
25865
- hook = result.hook;
25866
- workflowRun = result.run;
25867
- encryptionKey = encryptionKeyOverride ?? result.encryptionKey;
25868
- } else {
25869
- hook = tokenOrHook;
25870
- workflowRun = await world.runs.get(hook.runId);
25871
- if (encryptionKeyOverride) {
25872
- encryptionKey = encryptionKeyOverride;
25873
- } else {
25874
- const rawKey = await world.getEncryptionKeyForRun?.(workflowRun);
25875
- encryptionKey = rawKey ? await importKey(rawKey) : void 0;
25876
- }
25877
- }
26487
+ const hook = typeof tokenOrHook === "string" ? await world.hooks.getByToken(tokenOrHook) : tokenOrHook;
26488
+ const info = await resolveHookResumeInfo(hook);
26489
+ const { resumeContext } = info;
25878
26490
  span?.setAttributes({
25879
26491
  ...HookToken(hook.token),
25880
26492
  ...HookId(hook.hookId),
25881
- ...WorkflowRunId(hook.runId)
26493
+ ...WorkflowRunId(hook.runId),
26494
+ "workflow.hook.resume_context_source": info.source
25882
26495
  });
25883
- const rawVersion = workflowRun.executionContext?.workflowCoreVersion;
25884
- const capabilities = getRunCapabilities(typeof rawVersion === "string" ? rawVersion : void 0);
25885
- if (!capabilities.supportedFormats.has(SerializationFormat.ENCRYPTED)) {
25886
- encryptionKey = void 0;
26496
+ if (info.run && isTerminalWorkflowRunStatus(info.run.status)) {
26497
+ throw new HookNotFoundError(hook.token);
26498
+ }
26499
+ const capabilities = getRunCapabilities(resumeContext.workflowCoreVersion);
26500
+ let payloadKey;
26501
+ const runPublicKey = encryptionKeyOverride ? (
26502
+ // hydrate hook metadata), so sealing would add an ECDH for no
26503
+ // saved round trip. Reuse what it resolved.
26504
+ void 0
26505
+ ) : decodeRunPublicKey(resumeContext.encryptionPublicKey);
26506
+ if (runPublicKey) {
26507
+ payloadKey = sealTo(runPublicKey);
26508
+ } else {
26509
+ let encryptionKey = encryptionKeyOverride ?? await resolveHookEncryptionKey(hook, info);
26510
+ if (!capabilities.supportedFormats.has(SerializationFormat.ENCRYPTED)) {
26511
+ encryptionKey = void 0;
26512
+ }
26513
+ payloadKey = encryptionKey;
25887
26514
  }
25888
- const compression = (workflowRun.specVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION && capabilities.supportedFormats.has(SerializationFormat.GZIP);
26515
+ const compression = (resumeContext.runSpecVersion ?? 0) >= SPEC_VERSION_SUPPORTS_COMPRESSION && capabilities.supportedFormats.has(SerializationFormat.GZIP);
25889
26516
  const ops = [];
25890
26517
  const v1Compat = isLegacySpecVersion(hook.specVersion);
25891
- const dehydratedPayload = await dehydrateStepReturnValue(payload, hook.runId, encryptionKey, ops, globalThis, v1Compat, capabilities.framedByteStreams, compression);
26518
+ const dehydratedPayload = await dehydrateStepReturnValue(payload, hook.runId, payloadKey, ops, globalThis, v1Compat, capabilities.framedByteStreams, compression);
25892
26519
  safeWaitUntil(Promise.all(ops), (err) => {
25893
26520
  if (err === void 0) return;
25894
26521
  runtimeLogger.warn("Background flush of hook payload ops failed", {
@@ -25897,33 +26524,40 @@ async function resumeHook(tokenOrHook, payload, encryptionKeyOverride) {
25897
26524
  error: err instanceof Error ? err.message : String(err)
25898
26525
  });
25899
26526
  });
25900
- await world.events.create(hook.runId, {
25901
- eventType: "hook_received",
25902
- specVersion: SPEC_VERSION_CURRENT,
25903
- correlationId: hook.hookId,
25904
- eventData: {
25905
- ...v1Compat ? {} : {
25906
- token: hook.token
25907
- },
25908
- payload: dehydratedPayload
26527
+ try {
26528
+ await world.events.create(hook.runId, {
26529
+ eventType: "hook_received",
26530
+ specVersion: SPEC_VERSION_CURRENT,
26531
+ correlationId: hook.hookId,
26532
+ eventData: {
26533
+ ...v1Compat ? {} : {
26534
+ token: hook.token
26535
+ },
26536
+ payload: dehydratedPayload
26537
+ }
26538
+ }, {
26539
+ v1Compat
26540
+ });
26541
+ } catch (err) {
26542
+ if (HookNotFoundError.is(err) || EntityConflictError.is(err) || RunExpiredError.is(err)) {
26543
+ throw new HookNotFoundError(hook.token);
25909
26544
  }
25910
- }, {
25911
- v1Compat
25912
- });
26545
+ throw err;
26546
+ }
25913
26547
  span?.setAttributes({
25914
- ...WorkflowName(workflowRun.workflowName)
26548
+ ...WorkflowName(resumeContext.workflowName)
25915
26549
  });
25916
- const originLink = await linkToTraceCarrier(workflowRun.executionContext?.traceCarrier);
26550
+ const originLink = await linkToTraceCarrier(resumeContext.traceCarrier);
25917
26551
  if (originLink) {
25918
26552
  span?.addLink?.(originLink);
25919
26553
  }
25920
- await world.queue(getWorkflowQueueName(workflowRun.workflowName), {
26554
+ await world.queue(getWorkflowQueueName(resumeContext.workflowName), {
25921
26555
  runId: hook.runId,
25922
- // attach the trace carrier from the workflow run
25923
- traceCarrier: workflowRun.executionContext?.traceCarrier ?? void 0
26556
+ // attach the trace carrier from the run's resume context
26557
+ traceCarrier: resumeContext.traceCarrier ?? void 0
25924
26558
  }, {
25925
- deploymentId: workflowRun.deploymentId,
25926
- specVersion: workflowRun.specVersion ?? SPEC_VERSION_LEGACY
26559
+ deploymentId: resumeContext.deploymentId,
26560
+ specVersion: resumeContext.runSpecVersion ?? SPEC_VERSION_LEGACY
25927
26561
  });
25928
26562
  return hook;
25929
26563
  } catch (err) {
@@ -25984,6 +26618,8 @@ var init_resume_hook = __esm({
25984
26618
  init_capabilities();
25985
26619
  init_encryption();
25986
26620
  init_logger();
26621
+ init_sealed_box();
26622
+ init_encryption2();
25987
26623
  init_serialization2();
25988
26624
  init_symbols();
25989
26625
  init_semantic_conventions();
@@ -25991,6 +26627,9 @@ var init_resume_hook = __esm({
25991
26627
  init_get_world_lazy();
25992
26628
  init_helpers();
25993
26629
  init_wait_until();
26630
+ __name(resumeContextFromRun, "resumeContextFromRun");
26631
+ __name(resolveHookResumeInfo, "resolveHookResumeInfo");
26632
+ __name(resolveHookEncryptionKey, "resolveHookEncryptionKey");
25994
26633
  __name(getHookByTokenWithKey, "getHookByTokenWithKey");
25995
26634
  __name(getHookByToken, "getHookByToken");
25996
26635
  __name(resumeHook, "resumeHook");
@@ -26043,19 +26682,24 @@ function getSerializeStream(reducers, cryptoKey) {
26043
26682
  resolved: false,
26044
26683
  key: void 0
26045
26684
  };
26685
+ let sealSession;
26046
26686
  const stream = new TransformStream({
26047
26687
  async transform(chunk, controller) {
26048
26688
  try {
26049
26689
  if (!keyState.resolved) {
26050
26690
  keyState.key = await resolveEncryptionKey(cryptoKey);
26051
26691
  keyState.resolved = true;
26692
+ if (isSealTarget(keyState.key)) {
26693
+ sealSession = createSealSession(keyState.key.recipientPublicKey, keyState.key.aad);
26694
+ }
26052
26695
  }
26053
26696
  const serialized = stringify(chunk, reducers);
26054
26697
  const payload = encoder2.encode(serialized);
26055
26698
  let prefixed = encodeWithFormatPrefix(SerializationFormat.DEVALUE_V1, payload);
26056
- if (keyState.key) {
26057
- const encrypted = await encrypt(keyState.key, prefixed);
26058
- prefixed = encodeWithFormatPrefix(SerializationFormat.ENCRYPTED, encrypted);
26699
+ if (sealSession) {
26700
+ prefixed = encodeWithFormatPrefix(SerializationFormat.SEALED, await sealSession.seal(prefixed));
26701
+ } else if (keyState.key) {
26702
+ prefixed = await encrypt2(prefixed, keyState.key);
26059
26703
  }
26060
26704
  const frame2 = new Uint8Array(FRAME_HEADER_SIZE + prefixed.length);
26061
26705
  new DataView(frame2.buffer).setUint32(0, prefixed.length, false);
@@ -26083,6 +26727,7 @@ function getDeserializeStream(revivers, cryptoKey) {
26083
26727
  resolved: false,
26084
26728
  key: void 0
26085
26729
  };
26730
+ let openSession;
26086
26731
  function appendToBuffer(data) {
26087
26732
  const newBuffer = new Uint8Array(buffer2.length + data.length);
26088
26733
  newBuffer.set(buffer2, 0);
@@ -26094,6 +26739,9 @@ function getDeserializeStream(revivers, cryptoKey) {
26094
26739
  if (!keyState.resolved) {
26095
26740
  keyState.key = await resolveEncryptionKey(cryptoKey);
26096
26741
  keyState.resolved = true;
26742
+ if (isRunPayloadKeys(keyState.key)) {
26743
+ openSession = createOpenSession(keyState.key.keyPair, keyState.key.aad);
26744
+ }
26097
26745
  }
26098
26746
  while (buffer2.length >= FRAME_HEADER_SIZE) {
26099
26747
  const frameLength = new DataView(buffer2.buffer, buffer2.byteOffset, buffer2.byteLength).getUint32(0, false);
@@ -26103,20 +26751,22 @@ function getDeserializeStream(revivers, cryptoKey) {
26103
26751
  const frameData = buffer2.slice(FRAME_HEADER_SIZE, FRAME_HEADER_SIZE + frameLength);
26104
26752
  buffer2 = buffer2.slice(FRAME_HEADER_SIZE + frameLength);
26105
26753
  let { format, payload } = decodeFormatPrefix(frameData);
26106
- if (format === SerializationFormat.ENCRYPTED) {
26107
- if (!keyState.key) {
26108
- controller.error(new RuntimeDecryptionError("Encrypted stream data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.", {
26754
+ if (format === SerializationFormat.ENCRYPTED || format === SerializationFormat.SEALED) {
26755
+ const sealed = format === SerializationFormat.SEALED;
26756
+ const usable = sealed ? isRunPayloadKeys(keyState.key) : aesKeyOf(keyState.key) !== void 0;
26757
+ if (!usable) {
26758
+ controller.error(new RuntimeDecryptionError(sealed ? "Sealed stream data encountered but no run keypair is available. Opening a sealed frame requires the run's own encryption key material." : "Encrypted stream data encountered but no encryption key is available. Encryption is not configured or no key was provided for this run.", {
26109
26759
  context: {
26110
26760
  operation: "decrypt",
26111
26761
  byteLength: payload.byteLength,
26112
- formatPrefix: "encr"
26762
+ formatPrefix: sealed ? "encp" : "encr"
26113
26763
  }
26114
26764
  }));
26115
26765
  return;
26116
26766
  }
26117
26767
  let decrypted;
26118
26768
  try {
26119
- decrypted = await decrypt(keyState.key, payload);
26769
+ decrypted = sealed ? await openSession.open(decodeFormatPrefix(frameData).payload) : await decrypt2(frameData, keyState.key);
26120
26770
  } catch (error48) {
26121
26771
  if (RuntimeDecryptionError.is(error48) && error48.context) {
26122
26772
  error48.context.formatPrefix = format;
@@ -26544,6 +27194,10 @@ function getExternalReducers(global2 = globalThis, ops, runId, cryptoKey, framed
26544
27194
  name: existingName,
26545
27195
  runId: existingRunId
26546
27196
  };
27197
+ const existingPublicKey = value[STREAM_SERVER_PUBLIC_KEY_SYMBOL];
27198
+ if (typeof existingPublicKey === "string") {
27199
+ descriptor.encryptionPublicKey = existingPublicKey;
27200
+ }
26547
27201
  const existingDeploymentId = value[STREAM_SERVER_DEPLOYMENT_ID_SYMBOL];
26548
27202
  if (typeof existingDeploymentId === "string") {
26549
27203
  descriptor.deploymentId = existingDeploymentId;
@@ -26609,6 +27263,10 @@ function getWorkflowReducers(global2 = globalThis) {
26609
27263
  if (typeof foreignDeploymentId === "string") {
26610
27264
  s.deploymentId = foreignDeploymentId;
26611
27265
  }
27266
+ const foreignPublicKey = value[STREAM_SERVER_PUBLIC_KEY_SYMBOL];
27267
+ if (typeof foreignPublicKey === "string") {
27268
+ s.encryptionPublicKey = foreignPublicKey;
27269
+ }
26612
27270
  return s;
26613
27271
  }, "WritableStream"),
26614
27272
  // AbortController/AbortSignal in workflow context — just read symbols (handles).
@@ -26681,6 +27339,10 @@ function getStepReducers(global2 = globalThis, ops, runId, cryptoKey, framedByte
26681
27339
  name
26682
27340
  };
26683
27341
  if (typeof foreignRunId === "string") s.runId = foreignRunId;
27342
+ const foreignPublicKey = value[STREAM_SERVER_PUBLIC_KEY_SYMBOL];
27343
+ if (typeof foreignPublicKey === "string") {
27344
+ s.encryptionPublicKey = foreignPublicKey;
27345
+ }
26684
27346
  const foreignDeploymentId = value[STREAM_SERVER_DEPLOYMENT_ID_SYMBOL];
26685
27347
  if (typeof foreignDeploymentId === "string") {
26686
27348
  s.deploymentId = foreignDeploymentId;
@@ -26833,7 +27495,9 @@ function getCommonRevivers2(global2 = globalThis) {
26833
27495
  ...getCommonRevivers(global2)
26834
27496
  };
26835
27497
  }
26836
- async function getForwardedWritableEncryptionKey(runId, deploymentId) {
27498
+ async function getForwardedWritableEncryptionKey(runId, deploymentId, encryptionPublicKey) {
27499
+ const ownerPublicKey = decodeRunPublicKey(encryptionPublicKey);
27500
+ if (ownerPublicKey) return sealTo(ownerPublicKey);
26837
27501
  const world = await getWorldLazy();
26838
27502
  if (!world.getEncryptionKeyForRun) return void 0;
26839
27503
  const rawKey = deploymentId ? await world.getEncryptionKeyForRun(runId, {
@@ -26906,7 +27570,7 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey) {
26906
27570
  }, "ReadableStream"),
26907
27571
  WritableStream: /* @__PURE__ */ __name((value) => {
26908
27572
  const targetRunId = typeof value.runId === "string" ? value.runId : runId;
26909
- const targetKey = targetRunId === runId ? cryptoKey : getForwardedWritableEncryptionKey(targetRunId, value.deploymentId);
27573
+ const targetKey = targetRunId === runId ? cryptoKey : getForwardedWritableEncryptionKey(targetRunId, value.deploymentId, value.encryptionPublicKey);
26910
27574
  const serialize3 = getSerializeStream(getExternalReducers(global2, ops, targetRunId, targetKey), targetKey);
26911
27575
  const serverWritable = new WorkflowServerWritableStream(targetRunId, value.name);
26912
27576
  const state = createFlushableState();
@@ -26928,6 +27592,12 @@ function getExternalRevivers(global2 = globalThis, ops, runId, cryptoKey) {
26928
27592
  writable: false
26929
27593
  });
26930
27594
  }
27595
+ if (typeof value.encryptionPublicKey === "string") {
27596
+ Object.defineProperty(serialize3.writable, STREAM_SERVER_PUBLIC_KEY_SYMBOL, {
27597
+ value: value.encryptionPublicKey,
27598
+ writable: false
27599
+ });
27600
+ }
26931
27601
  return serialize3.writable;
26932
27602
  }, "WritableStream"),
26933
27603
  AbortController: /* @__PURE__ */ __name((value) => reviveAbortController(value, ops, runId), "AbortController"),
@@ -27065,7 +27735,7 @@ function getStepRevivers(global2 = globalThis, ops, runId, cryptoKey, deployment
27065
27735
  WritableStream: /* @__PURE__ */ __name((value) => {
27066
27736
  const targetRunId = typeof value.runId === "string" ? value.runId : runId;
27067
27737
  const targetDeploymentId = typeof value.deploymentId === "string" ? value.deploymentId : targetRunId === runId ? deploymentId : void 0;
27068
- const targetKey = targetRunId === runId ? cryptoKey : getForwardedWritableEncryptionKey(targetRunId, targetDeploymentId);
27738
+ const targetKey = targetRunId === runId ? cryptoKey : getForwardedWritableEncryptionKey(targetRunId, targetDeploymentId, value.encryptionPublicKey);
27069
27739
  const serialize3 = getSerializeStream(getStepReducers(global2, ops, targetRunId, targetKey), targetKey);
27070
27740
  const serverWritable = new WorkflowServerWritableStream(targetRunId, value.name);
27071
27741
  const state = createFlushableState();
@@ -27087,15 +27757,24 @@ function getStepRevivers(global2 = globalThis, ops, runId, cryptoKey, deployment
27087
27757
  writable: false
27088
27758
  });
27089
27759
  }
27760
+ if (typeof value.encryptionPublicKey !== "string" && targetRunId === runId && isRunPayloadKeys(cryptoKey)) {
27761
+ Object.defineProperty(serialize3.writable, STREAM_SERVER_PUBLIC_KEY_SYMBOL, {
27762
+ value: bytesToBase64(cryptoKey.keyPair.publicKey),
27763
+ writable: false
27764
+ });
27765
+ }
27766
+ if (typeof value.encryptionPublicKey === "string") {
27767
+ Object.defineProperty(serialize3.writable, STREAM_SERVER_PUBLIC_KEY_SYMBOL, {
27768
+ value: value.encryptionPublicKey,
27769
+ writable: false
27770
+ });
27771
+ }
27090
27772
  return serialize3.writable;
27091
27773
  }, "WritableStream"),
27092
27774
  AbortController: /* @__PURE__ */ __name((value) => reviveAbortController(value, ops, runId), "AbortController"),
27093
27775
  AbortSignal: /* @__PURE__ */ __name((value) => reviveAbortSignal(value, ops, runId), "AbortSignal")
27094
27776
  };
27095
27777
  }
27096
- async function maybeDecrypt(data, key) {
27097
- return decrypt2(data, key);
27098
- }
27099
27778
  async function dehydrateWorkflowArguments(value, runId, key, ops = [], global2 = globalThis, v1Compat = false, framedByteStreams = false, compression = false) {
27100
27779
  if (v1Compat) {
27101
27780
  const str = stringify(value, getExternalReducers(global2, ops, runId, key, framedByteStreams));
@@ -27196,7 +27875,7 @@ async function dehydrateStepReturnValue(value, runId, key, ops = [], global2 = g
27196
27875
  }
27197
27876
  async function hydrateRunError(value, runId, key, ops = [], global2 = globalThis, extraRevivers = {}) {
27198
27877
  const compressionStats = {};
27199
- const decrypted = await decompress(await maybeDecrypt(value, key), compressionStats);
27878
+ const decrypted = await decompress(await decrypt2(value, key), compressionStats);
27200
27879
  await recordCompression(compressionStats, "deserialize");
27201
27880
  if (!(decrypted instanceof Uint8Array)) {
27202
27881
  return unflatten(decrypted, {
@@ -27232,7 +27911,7 @@ function getStreamAndRequestRevivers(allRevivers) {
27232
27911
  }
27233
27912
  return extra;
27234
27913
  }
27235
- var defaultUlid, FRAME_HEADER_SIZE, MAX_FRAME_SIZE, WorkflowServerReadableStream, FRAMED_STREAM_MAX_RECONNECTS, getFramedStreamMaxReconnects, FRAMED_STREAM_MAX_TOTAL_RECONNECTS, getFramedStreamMaxTotalReconnects, STREAM_FLUSH_INTERVAL_MS, getStreamFlushIntervalMs, WorkflowServerWritableStream, STREAM_AND_REQUEST_KEYS;
27914
+ var defaultUlid, FRAME_HEADER_SIZE, MAX_FRAME_SIZE, WorkflowServerReadableStream, FRAMED_STREAM_MAX_RECONNECTS, getFramedStreamMaxReconnects, FRAMED_STREAM_MAX_TOTAL_RECONNECTS, getFramedStreamMaxTotalReconnects, STREAM_FLUSH_INTERVAL_MS, getEnvStreamFlushIntervalMs, WorkflowServerWritableStream, STREAM_AND_REQUEST_KEYS;
27236
27915
  var init_serialization2 = __esm({
27237
27916
  "../core/dist/serialization.js"() {
27238
27917
  "use strict";
@@ -27240,10 +27919,12 @@ var init_serialization2 = __esm({
27240
27919
  init_dist4();
27241
27920
  init_devalue();
27242
27921
  init_node();
27922
+ init_sealed_box();
27243
27923
  init_encryption();
27244
27924
  init_flushable_stream();
27245
27925
  init_private();
27246
27926
  init_get_world_lazy();
27927
+ init_sealed_box();
27247
27928
  init_client();
27248
27929
  init_compression();
27249
27930
  init_encryption2();
@@ -27342,10 +28023,13 @@ var init_serialization2 = __esm({
27342
28023
  min: 1
27343
28024
  }), "getFramedStreamMaxTotalReconnects");
27344
28025
  __name(createReconnectingFramedStream, "createReconnectingFramedStream");
27345
- STREAM_FLUSH_INTERVAL_MS = 10;
27346
- getStreamFlushIntervalMs = /* @__PURE__ */ __name(() => envNumber("WORKFLOW_STREAM_FLUSH_INTERVAL_MS", STREAM_FLUSH_INTERVAL_MS, {
27347
- integer: true
27348
- }), "getStreamFlushIntervalMs");
28026
+ STREAM_FLUSH_INTERVAL_MS = 0;
28027
+ getEnvStreamFlushIntervalMs = /* @__PURE__ */ __name(() => {
28028
+ const value = envNumber("WORKFLOW_STREAM_FLUSH_INTERVAL_MS", Number.NaN, {
28029
+ integer: true
28030
+ });
28031
+ return Number.isNaN(value) ? void 0 : value;
28032
+ }, "getEnvStreamFlushIntervalMs");
27349
28033
  __name(recordStreamWriteFlush, "recordStreamWriteFlush");
27350
28034
  __name(recordStreamClose, "recordStreamClose");
27351
28035
  WorkflowServerWritableStream = class extends WritableStream {
@@ -27380,99 +28064,192 @@ var init_serialization2 = __esm({
27380
28064
  }
27381
28065
  }, "ensureRunReady");
27382
28066
  let buffer2 = [];
28067
+ let bufferBytes = 0;
28068
+ let inFlightChunks = 0;
28069
+ let inFlightBytes = 0;
27383
28070
  let flushTimer = null;
27384
- let flushPromise = null;
27385
- let resolvedFlushIntervalMs;
27386
- let batchStartAt;
27387
- const flush = /* @__PURE__ */ __name(async () => {
27388
- if (flushTimer) {
27389
- clearTimeout(flushTimer);
27390
- flushTimer = null;
27391
- }
27392
- if (buffer2.length === 0) return;
28071
+ let inFlight = null;
28072
+ let sinkError;
28073
+ let resolvedFlushIntervalMs = getEnvStreamFlushIntervalMs();
28074
+ let flushIntervalResolution = null;
28075
+ const maxChunksPerRequest = getMaxChunksPerBatch();
28076
+ const maxBytesPerRequest = getMaxBytesPerBatch();
28077
+ const maxBufferedChunks = getMaxInflightChunks();
28078
+ const maxBufferedBytes = getMaxBufferedBytes();
28079
+ let bufferT0;
28080
+ let capacityWaiters = [];
28081
+ let drainWaiters = [];
28082
+ const rejectWaiters = /* @__PURE__ */ __name((err) => {
28083
+ const all = [
28084
+ ...capacityWaiters,
28085
+ ...drainWaiters
28086
+ ];
28087
+ capacityWaiters = [];
28088
+ drainWaiters = [];
28089
+ for (const w of all) w.reject(err);
28090
+ }, "rejectWaiters");
28091
+ const takeGroup = /* @__PURE__ */ __name(() => {
28092
+ let count2 = 0;
28093
+ let bytes = 0;
28094
+ for (const chunk of buffer2) {
28095
+ if (count2 >= maxChunksPerRequest) break;
28096
+ if (count2 > 0 && bytes + chunk.byteLength > maxBytesPerRequest) break;
28097
+ count2++;
28098
+ bytes += chunk.byteLength;
28099
+ }
28100
+ const group = buffer2.slice(0, count2);
28101
+ buffer2 = buffer2.slice(count2);
28102
+ bufferBytes -= bytes;
28103
+ return {
28104
+ group,
28105
+ bytes
28106
+ };
28107
+ }, "takeGroup");
28108
+ const sendGroup = /* @__PURE__ */ __name(async (group, bytes, groupT0) => {
27393
28109
  await ensureRunReady();
27394
- const chunksToFlush = buffer2.slice();
27395
- const batchStart = batchStartAt;
27396
- batchStartAt = void 0;
27397
- const dispatchAt = Date.now();
27398
28110
  const world = await worldPromise;
27399
- if (resolvedFlushIntervalMs === void 0) {
27400
- resolvedFlushIntervalMs = world.streamFlushIntervalMs ?? getStreamFlushIntervalMs();
28111
+ const dispatchAt = Date.now();
28112
+ if (typeof world.streams.writeMulti === "function" && group.length > 1) {
28113
+ await world.streams.writeMulti(runId, name, group);
28114
+ } else {
28115
+ for (const chunk of group) {
28116
+ await world.streams.write(runId, name, chunk);
28117
+ }
27401
28118
  }
27402
- const rpcStartAt = Date.now();
27403
- try {
27404
- if (typeof world.streams.writeMulti === "function" && chunksToFlush.length > 1) {
27405
- await world.streams.writeMulti(runId, name, chunksToFlush);
27406
- } else {
27407
- for (const chunk of chunksToFlush) {
27408
- await world.streams.write(runId, name, chunk);
27409
- }
28119
+ if (groupT0 !== void 0) {
28120
+ recordStreamWriteFlush(groupT0, dispatchAt, runId, name, group.length, bytes, Date.now() - dispatchAt);
28121
+ }
28122
+ }, "sendGroup");
28123
+ const dispatchLoop = /* @__PURE__ */ __name(async () => {
28124
+ while (buffer2.length > 0) {
28125
+ if (flushTimer) {
28126
+ clearTimeout(flushTimer);
28127
+ flushTimer = null;
27410
28128
  }
27411
- } catch (error48) {
27412
- if (batchStart !== void 0) {
27413
- batchStartAt = batchStartAt === void 0 ? batchStart : Math.min(batchStartAt, batchStart);
28129
+ const groupT0 = bufferT0;
28130
+ const groupTakenAt = Date.now();
28131
+ const { group, bytes } = takeGroup();
28132
+ inFlightChunks = group.length;
28133
+ inFlightBytes = bytes;
28134
+ bufferT0 = buffer2.length > 0 ? groupTakenAt : void 0;
28135
+ try {
28136
+ await sendGroup(group, bytes, groupT0);
28137
+ inFlightChunks = 0;
28138
+ inFlightBytes = 0;
28139
+ } catch (error48) {
28140
+ buffer2 = group.concat(buffer2);
28141
+ bufferBytes += bytes;
28142
+ inFlightChunks = 0;
28143
+ inFlightBytes = 0;
28144
+ bufferT0 = groupT0 !== void 0 && bufferT0 !== void 0 ? Math.min(groupT0, bufferT0) : groupT0 ?? bufferT0;
28145
+ throw error48;
27414
28146
  }
27415
- throw error48;
28147
+ const relieved = capacityWaiters;
28148
+ capacityWaiters = [];
28149
+ for (const w of relieved) w.resolve();
28150
+ }
28151
+ }, "dispatchLoop");
28152
+ const startDispatch = /* @__PURE__ */ __name(() => {
28153
+ if (inFlight || sinkError !== void 0 || buffer2.length === 0) return;
28154
+ inFlight = dispatchLoop().then(() => {
28155
+ inFlight = null;
28156
+ if (buffer2.length > 0) {
28157
+ startDispatch();
28158
+ return;
28159
+ }
28160
+ const settled = drainWaiters;
28161
+ drainWaiters = [];
28162
+ for (const w of settled) w.resolve();
28163
+ }, (error48) => {
28164
+ inFlight = null;
28165
+ sinkError ??= error48;
28166
+ rejectWaiters(sinkError);
28167
+ });
28168
+ }, "startDispatch");
28169
+ const scheduleGroupCommit = /* @__PURE__ */ __name(() => {
28170
+ if (flushTimer || inFlight) return;
28171
+ if (resolvedFlushIntervalMs === void 0) {
28172
+ flushIntervalResolution ??= Promise.resolve(worldPromise).then((world) => {
28173
+ resolvedFlushIntervalMs = world.streamFlushIntervalMs ?? STREAM_FLUSH_INTERVAL_MS;
28174
+ }, () => {
28175
+ resolvedFlushIntervalMs = STREAM_FLUSH_INTERVAL_MS;
28176
+ }).then(() => {
28177
+ if (buffer2.length > 0) scheduleGroupCommit();
28178
+ });
28179
+ return;
27416
28180
  }
27417
- if (batchStart !== void 0) {
27418
- recordStreamWriteFlush(batchStart, dispatchAt, runId, name, chunksToFlush.length, chunksToFlush.reduce((sum, c) => sum + c.byteLength, 0), Date.now() - rpcStartAt);
28181
+ if (resolvedFlushIntervalMs <= 0) {
28182
+ startDispatch();
28183
+ return;
27419
28184
  }
27420
- buffer2 = [];
27421
- }, "flush");
27422
- let flushWaiters = [];
27423
- const scheduleFlush = /* @__PURE__ */ __name(() => {
27424
- if (flushTimer) return;
27425
28185
  flushTimer = setTimeout(() => {
27426
28186
  flushTimer = null;
27427
- const currentWaiters = flushWaiters;
27428
- flushWaiters = [];
27429
- flushPromise = flush().then(() => {
27430
- for (const w of currentWaiters) w.resolve();
27431
- }, (err) => {
27432
- for (const w of currentWaiters) w.reject(err);
27433
- });
27434
- }, resolvedFlushIntervalMs ?? getStreamFlushIntervalMs());
27435
- }, "scheduleFlush");
27436
- super({
27437
- async write(chunk) {
27438
- if (batchStartAt === void 0) batchStartAt = Date.now();
27439
- if (flushPromise) {
27440
- await flushPromise;
27441
- flushPromise = null;
27442
- }
27443
- buffer2.push(chunk);
27444
- scheduleFlush();
28187
+ startDispatch();
28188
+ }, resolvedFlushIntervalMs);
28189
+ }, "scheduleGroupCommit");
28190
+ const drain = /* @__PURE__ */ __name(async () => {
28191
+ while (true) {
28192
+ if (sinkError !== void 0) throw sinkError;
28193
+ if (buffer2.length === 0 && !inFlight) return;
28194
+ startDispatch();
27445
28195
  await new Promise((resolve, reject) => {
27446
- flushWaiters.push({
28196
+ drainWaiters.push({
27447
28197
  resolve,
27448
28198
  reject
27449
28199
  });
27450
28200
  });
28201
+ }
28202
+ }, "drain");
28203
+ super({
28204
+ async write(chunk) {
28205
+ if (sinkError !== void 0) throw sinkError;
28206
+ if (bufferT0 === void 0) bufferT0 = Date.now();
28207
+ buffer2.push(chunk);
28208
+ bufferBytes += chunk.byteLength;
28209
+ if (buffer2.length >= maxChunksPerRequest || bufferBytes >= maxBytesPerRequest) {
28210
+ startDispatch();
28211
+ } else {
28212
+ scheduleGroupCommit();
28213
+ }
28214
+ while (sinkError === void 0 && (buffer2.length + inFlightChunks >= maxBufferedChunks || bufferBytes + inFlightBytes >= maxBufferedBytes)) {
28215
+ startDispatch();
28216
+ await new Promise((resolve, reject) => {
28217
+ capacityWaiters.push({
28218
+ resolve,
28219
+ reject
28220
+ });
28221
+ });
28222
+ }
28223
+ if (sinkError !== void 0) throw sinkError;
27451
28224
  },
27452
28225
  async close() {
27453
- if (flushPromise) {
27454
- await flushPromise;
27455
- flushPromise = null;
27456
- }
27457
- await flush();
28226
+ await drain();
27458
28227
  await ensureRunReady();
27459
28228
  const world = await worldPromise;
27460
28229
  const closeStart = Date.now();
27461
28230
  await world.streams.close(runId, name);
27462
28231
  recordStreamClose(closeStart, runId, name);
27463
28232
  },
27464
- abort(reason) {
28233
+ async abort(reason) {
28234
+ try {
28235
+ await drain();
28236
+ } catch {
28237
+ }
27465
28238
  if (flushTimer) {
27466
28239
  clearTimeout(flushTimer);
27467
28240
  flushTimer = null;
27468
28241
  }
27469
28242
  buffer2 = [];
27470
- const waiters = flushWaiters;
27471
- flushWaiters = [];
27472
- const abortError = reason ?? new Error("Stream aborted");
27473
- for (const w of waiters) w.reject(abortError);
28243
+ bufferBytes = 0;
28244
+ sinkError ??= reason ?? new Error("Stream aborted");
28245
+ rejectWaiters(sinkError);
27474
28246
  }
27475
28247
  });
28248
+ Object.defineProperty(this, STREAM_DRAIN_SYMBOL, {
28249
+ value: drain,
28250
+ enumerable: false,
28251
+ writable: false
28252
+ });
27476
28253
  }
27477
28254
  };
27478
28255
  __name(getAllBaseReducers, "getAllBaseReducers");
@@ -27491,7 +28268,6 @@ var init_serialization2 = __esm({
27491
28268
  __name(getForwardedWritableEncryptionKey, "getForwardedWritableEncryptionKey");
27492
28269
  __name(getExternalRevivers, "getExternalRevivers");
27493
28270
  __name(getStepRevivers, "getStepRevivers");
27494
- __name(maybeDecrypt, "maybeDecrypt");
27495
28271
  __name(dehydrateWorkflowArguments, "dehydrateWorkflowArguments");
27496
28272
  __name(hydrateWorkflowReturnValue, "hydrateWorkflowReturnValue");
27497
28273
  __name(dehydrateStepArguments, "dehydrateStepArguments");
@@ -27609,7 +28385,7 @@ __builtin_set_attributes.maxRetries = INTERNAL_ATTRIBUTES_MAX_ATTEMPTS - 1;
27609
28385
  init_dist2();
27610
28386
  init_dist3();
27611
28387
  init_dist4();
27612
- init_encryption();
28388
+ init_encryption2();
27613
28389
  init_serialization2();
27614
28390
  init_util2();
27615
28391
  init_get_world_lazy();
@@ -27617,7 +28393,7 @@ init_get_world_lazy();
27617
28393
  // ../core/dist/runtime/runs.js
27618
28394
  init_dist2();
27619
28395
  init_dist4();
27620
- init_encryption();
28396
+ init_encryption2();
27621
28397
  init_serialization2();
27622
28398
  init_helpers();
27623
28399
 
@@ -27695,6 +28471,7 @@ __name(isRetryableWorldError, "isRetryableWorldError");
27695
28471
  // ../core/dist/runtime/start.js
27696
28472
  init_encryption();
27697
28473
  init_logger();
28474
+ init_sealed_box();
27698
28475
  init_serialization2();
27699
28476
  init_context_storage();
27700
28477
  init_semantic_conventions();
@@ -27758,8 +28535,10 @@ async function start(workflow, argsOrOptions, options) {
27758
28535
  deploymentId = currentDeploymentId;
27759
28536
  }
27760
28537
  }
28538
+ const runId = `wrun_${world.createRunId ? world.createRunId(opts) : ulid3()}`;
27761
28539
  let framedByteStreams;
27762
28540
  let targetSupportsCompression;
28541
+ let probedRunPublicKey;
27763
28542
  if (deploymentId === currentDeploymentId) {
27764
28543
  framedByteStreams = true;
27765
28544
  targetSupportsCompression = true;
@@ -27767,17 +28546,18 @@ async function start(workflow, argsOrOptions, options) {
27767
28546
  framedByteStreams = false;
27768
28547
  targetSupportsCompression = false;
27769
28548
  } else {
27770
- const probe = await healthCheck(world, "workflow", {
28549
+ const probe = await healthCheck(world, {
27771
28550
  deploymentId,
28551
+ runId,
27772
28552
  timeout: CROSS_DEPLOYMENT_CAPABILITY_PROBE_TIMEOUT_MS,
27773
28553
  namespace: opts.namespace
27774
28554
  }).catch(() => void 0);
28555
+ probedRunPublicKey = probe?.encryptionPublicKey;
27775
28556
  const capabilities = getRunCapabilities(probe?.workflowCoreVersion);
27776
28557
  framedByteStreams = capabilities.framedByteStreams;
27777
28558
  targetSupportsCompression = capabilities.supportedFormats.has(SerializationFormat.GZIP);
27778
28559
  }
27779
28560
  const ops = [];
27780
- const runId = `wrun_${world.createRunId ? world.createRunId(opts) : ulid3()}`;
27781
28561
  const traceCarrier = await serializeTraceCarrier();
27782
28562
  const specVersion = opts.specVersion ?? world.specVersion;
27783
28563
  const v1Compat = isLegacySpecVersion(specVersion);
@@ -27814,11 +28594,20 @@ async function start(workflow, argsOrOptions, options) {
27814
28594
  if (opts.replayedFromRunId !== void 0 && !workflowRunIdSchema.safeParse(opts.replayedFromRunId).success) {
27815
28595
  throw new WorkflowRuntimeError(`replayedFromRunId must be a run ID (wrun_<ulid>); received ${JSON.stringify(String(opts.replayedFromRunId).slice(0, 64))}.`);
27816
28596
  }
27817
- const rawKey = await world.getEncryptionKeyForRun?.(runId, {
27818
- ...opts,
27819
- deploymentId
27820
- });
27821
- const encryptionKey = rawKey ? await importKey(rawKey) : void 0;
28597
+ const probedPublicKey = decodeRunPublicKey(probedRunPublicKey);
28598
+ let encryptionKey;
28599
+ let encryptionPublicKey;
28600
+ if (probedPublicKey) {
28601
+ encryptionKey = sealTo(probedPublicKey);
28602
+ encryptionPublicKey = probedRunPublicKey;
28603
+ } else {
28604
+ const rawKey = await world.getEncryptionKeyForRun?.(runId, {
28605
+ ...opts,
28606
+ deploymentId
28607
+ });
28608
+ encryptionKey = rawKey ? await importKey(rawKey) : void 0;
28609
+ encryptionPublicKey = rawKey ? bytesToBase64((await deriveRunKeyPair(rawKey)).publicKey) : void 0;
28610
+ }
27822
28611
  const compression = targetSupportsCompression && specVersion >= SPEC_VERSION_SUPPORTS_COMPRESSION;
27823
28612
  const workflowArguments = await dehydrateWorkflowArguments(args, runId, encryptionKey, ops, globalThis, v1Compat, framedByteStreams, compression);
27824
28613
  const executionContext = {
@@ -27840,6 +28629,9 @@ async function start(workflow, argsOrOptions, options) {
27840
28629
  workflowName,
27841
28630
  input: workflowArguments,
27842
28631
  executionContext,
28632
+ ...encryptionPublicKey ? {
28633
+ encryptionPublicKey
28634
+ } : {},
27843
28635
  ...attributeSeed
27844
28636
  }
27845
28637
  }, {
@@ -27855,6 +28647,9 @@ async function start(workflow, argsOrOptions, options) {
27855
28647
  workflowName,
27856
28648
  specVersion,
27857
28649
  executionContext,
28650
+ ...encryptionPublicKey ? {
28651
+ encryptionPublicKey
28652
+ } : {},
27858
28653
  ...attributeSeed
27859
28654
  }
27860
28655
  } : {}
@@ -27921,7 +28716,7 @@ __name(start, "start");
27921
28716
  value: "start",
27922
28717
  configurable: true
27923
28718
  });
27924
- })(start, "step//@workflow/core/runtime/start@5.0.0-beta.35//start");
28719
+ })(start, "step//@workflow/core/runtime/start@5.0.0-beta.37//start");
27925
28720
 
27926
28721
  // ../core/dist/runtime/runs.js
27927
28722
  async function wakeUpRun(world, runId, options) {
@@ -28065,7 +28860,7 @@ var Run = class _Run {
28065
28860
  const world = await this.#lazyWorldPromise;
28066
28861
  const run2 = await world.runs.get(this.runId);
28067
28862
  const rawKey = await world.getEncryptionKeyForRun?.(run2);
28068
- return rawKey ? await importKey(rawKey) : void 0;
28863
+ return rawKey ? await deriveRunPayloadKeys(rawKey) : void 0;
28069
28864
  })();
28070
28865
  }
28071
28866
  return this.#encryptionKeyPromise;
@@ -28257,7 +29052,7 @@ var Run = class _Run {
28257
29052
  value: "wakeUp",
28258
29053
  configurable: true
28259
29054
  });
28260
- })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#wakeUp");
29055
+ })(Run.prototype["wakeUp"], "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#wakeUp");
28261
29056
  (function(__wf_fn, __wf_id) {
28262
29057
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28263
29058
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28266,7 +29061,7 @@ var Run = class _Run {
28266
29061
  value: "cancel",
28267
29062
  configurable: true
28268
29063
  });
28269
- })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#cancel");
29064
+ })(Run.prototype["cancel"], "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#cancel");
28270
29065
  (function(__wf_fn, __wf_id) {
28271
29066
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28272
29067
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28275,7 +29070,7 @@ var Run = class _Run {
28275
29070
  value: "getReadable",
28276
29071
  configurable: true
28277
29072
  });
28278
- })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#getReadable");
29073
+ })(Run.prototype["getReadable"], "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#getReadable");
28279
29074
  (function(__wf_fn, __wf_id) {
28280
29075
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28281
29076
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28284,7 +29079,7 @@ var Run = class _Run {
28284
29079
  value: "exists",
28285
29080
  configurable: true
28286
29081
  });
28287
- })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#exists");
29082
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "exists").get, "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#exists");
28288
29083
  (function(__wf_fn, __wf_id) {
28289
29084
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28290
29085
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28293,7 +29088,7 @@ var Run = class _Run {
28293
29088
  value: "status",
28294
29089
  configurable: true
28295
29090
  });
28296
- })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#status");
29091
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "status").get, "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#status");
28297
29092
  (function(__wf_fn, __wf_id) {
28298
29093
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28299
29094
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28302,7 +29097,7 @@ var Run = class _Run {
28302
29097
  value: "returnValue",
28303
29098
  configurable: true
28304
29099
  });
28305
- })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#returnValue");
29100
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "returnValue").get, "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#returnValue");
28306
29101
  (function(__wf_fn, __wf_id) {
28307
29102
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28308
29103
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28311,7 +29106,7 @@ var Run = class _Run {
28311
29106
  value: "workflowName",
28312
29107
  configurable: true
28313
29108
  });
28314
- })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#workflowName");
29109
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "workflowName").get, "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#workflowName");
28315
29110
  (function(__wf_fn, __wf_id) {
28316
29111
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28317
29112
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28320,7 +29115,7 @@ var Run = class _Run {
28320
29115
  value: "createdAt",
28321
29116
  configurable: true
28322
29117
  });
28323
- })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#createdAt");
29118
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "createdAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#createdAt");
28324
29119
  (function(__wf_fn, __wf_id) {
28325
29120
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28326
29121
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28329,7 +29124,7 @@ var Run = class _Run {
28329
29124
  value: "startedAt",
28330
29125
  configurable: true
28331
29126
  });
28332
- })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#startedAt");
29127
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "startedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#startedAt");
28333
29128
  (function(__wf_fn, __wf_id) {
28334
29129
  var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28335
29130
  __wf_reg.set(__wf_id, __wf_fn);
@@ -28338,7 +29133,7 @@ var Run = class _Run {
28338
29133
  value: "completedAt",
28339
29134
  configurable: true
28340
29135
  });
28341
- })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.35//Run#completedAt");
29136
+ })(Object.getOwnPropertyDescriptor(Run.prototype, "completedAt").get, "step//@workflow/core/runtime/run@5.0.0-beta.37//Run#completedAt");
28342
29137
  (function(__wf_cls, __wf_id) {
28343
29138
  var __wf_sym = /* @__PURE__ */ Symbol.for("workflow-class-registry"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
28344
29139
  __wf_reg.set(__wf_id, __wf_cls);
@@ -28348,7 +29143,7 @@ var Run = class _Run {
28348
29143
  enumerable: false,
28349
29144
  configurable: false
28350
29145
  });
28351
- })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.35//Run");
29146
+ })(Run, "class//@workflow/core/runtime/run@5.0.0-beta.37//Run");
28352
29147
 
28353
29148
  // ../workflow/dist/stdlib.js
28354
29149
  async function fetch2(...args) {
@@ -28390,6 +29185,26 @@ async function addTenWorkflow(input) {
28390
29185
  __name(addTenWorkflow, "addTenWorkflow");
28391
29186
  addTenWorkflow.workflowId = "workflow//./workflows/addition//addTenWorkflow";
28392
29187
 
29188
+ // workflows/event-limit.ts
29189
+ async function tick(i) {
29190
+ return i;
29191
+ }
29192
+ __name(tick, "tick");
29193
+ (function(__wf_fn, __wf_id) {
29194
+ var __wf_sym = /* @__PURE__ */ Symbol.for("@workflow/core//registeredSteps"), __wf_reg = globalThis[__wf_sym] || (globalThis[__wf_sym] = /* @__PURE__ */ new Map());
29195
+ __wf_reg.set(__wf_id, __wf_fn);
29196
+ __wf_fn.stepId = __wf_id;
29197
+ Object.defineProperty(__wf_fn, "name", {
29198
+ value: "tick",
29199
+ configurable: true
29200
+ });
29201
+ })(tick, "step//./workflows/event-limit//tick");
29202
+ async function runawayWorkflow() {
29203
+ throw new Error("You attempted to execute workflow runawayWorkflow function directly. To start a workflow, use start(runawayWorkflow) from workflow/api");
29204
+ }
29205
+ __name(runawayWorkflow, "runawayWorkflow");
29206
+ runawayWorkflow.workflowId = "workflow//./workflows/event-limit//runawayWorkflow";
29207
+
28393
29208
  // ../core/dist/index.js
28394
29209
  init_dist2();
28395
29210
 
@@ -28592,6 +29407,7 @@ init_context_storage();
28592
29407
 
28593
29408
  // ../core/dist/step/writable-stream.js
28594
29409
  init_flushable_stream();
29410
+ init_sealed_box();
28595
29411
  init_serialization2();
28596
29412
  init_symbols();
28597
29413
  init_util2();