@swirls/looms 0.17.0 → 0.18.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/dist/actor/cell.d.ts +5 -1
  3. package/dist/actor/cell.js +2 -0
  4. package/dist/actor/host.d.ts +5 -1
  5. package/dist/actor/host.js +2 -0
  6. package/dist/client/client.d.ts +1 -0
  7. package/dist/client/client.js +10 -4
  8. package/dist/cloudflare/durable-object.d.ts +5 -1
  9. package/dist/cloudflare/durable-object.js +2 -0
  10. package/dist/cloudflare/queue-consumer.js +11 -3
  11. package/dist/core/effects.d.ts +1 -1
  12. package/dist/core/module.d.ts +1 -0
  13. package/dist/core/run-context.d.ts +6 -2
  14. package/dist/core/sqlite-store.js +6 -0
  15. package/dist/core/store.js +5 -0
  16. package/dist/core/worker-callback.d.ts +5 -2
  17. package/dist/debugger/app/assets/{index-Br9tGbPI.js → index-BjZn1DuJ.js} +2 -2
  18. package/dist/debugger/app/assets/{routes-CZ0buqO7.js → routes-B90xnBF1.js} +2 -2
  19. package/dist/debugger/app/index.html +1 -1
  20. package/dist/runtime/effect-admission.d.ts +8 -3
  21. package/dist/runtime/effect-admission.js +23 -4
  22. package/dist/runtime/errors.d.ts +4 -0
  23. package/dist/runtime/errors.js +4 -0
  24. package/dist/runtime/index.d.ts +2 -0
  25. package/dist/runtime/index.js +2 -0
  26. package/dist/runtime/local-effect-executor.d.ts +8 -2
  27. package/dist/runtime/local-effect-executor.js +21 -8
  28. package/dist/runtime/looms.d.ts +6 -0
  29. package/dist/runtime/looms.js +2 -0
  30. package/dist/runtime/observer.d.ts +15 -0
  31. package/dist/runtime/run-secrets.d.ts +132 -0
  32. package/dist/runtime/run-secrets.js +154 -0
  33. package/dist/runtime/runtime.js +27 -25
  34. package/dist/runtime/secret-sealer.d.ts +24 -0
  35. package/dist/runtime/secret-sealer.js +120 -0
  36. package/dist/runtime/server/routes/runs.js +2 -1
  37. package/dist/runtime/types.d.ts +26 -7
  38. package/dist/runtime/wake-engine.d.ts +2 -0
  39. package/dist/runtime/wake-engine.js +47 -18
  40. package/dist/runtime/worker-callbacks.d.ts +4 -2
  41. package/dist/runtime/worker-callbacks.js +15 -2
  42. package/dist/runtime/worker-effect-dispatch.d.ts +1 -2
  43. package/dist/runtime/worker-effect-dispatch.js +0 -1
  44. package/dist/workflow/module.d.ts +32 -32
  45. package/package.json +1 -1
@@ -1,13 +1,14 @@
1
1
  import { Clock, Effect, ManagedRuntime, Predicate } from 'effect';
2
- import { cachedDefinitionResolver, chainDefinitionResolvers, composeModules, createEvent, createThreadId, createRunId, DEFAULT_DEFINITION_VERSION, DEFAULT_SNAPSHOT_EVERY, staticDefinitionResolver, descendantThreadIds, EventStoreTag, foldRun, hasEntries, InvalidRunAttributesError, isRunTerminal, runAttributeIssues, unavailableRunLauncher, planFork, project, readTraceContext, replayTo, sameStringRecord, summarizeRun, } from '@swirls/looms/core';
2
+ import { cachedDefinitionResolver, chainDefinitionResolvers, composeModules, createEvent, createThreadId, createRunId, DEFAULT_DEFINITION_VERSION, DEFAULT_SNAPSHOT_EVERY, staticDefinitionResolver, descendantThreadIds, EventStoreTag, foldRun, hasEntries, InvalidRunAttributesError, isRunTerminal, runAttributeIssues, unavailableRunLauncher, planFork, project, readTraceContext, replayTo, summarizeRun, } from '@swirls/looms/core';
3
3
  import { createCancellation } from './cancellation.js';
4
4
  import { nextRuntimeDeadline } from './deadline-transition-planner.js';
5
- import { ForkConflictError, RunNotFinishedError, RunNotFoundError, RunTerminalError, RuntimeExecutionError, SecretContextConflictError, StartRunConflictError, } from './errors.js';
5
+ import { ForkConflictError, RunNotFinishedError, RunNotFoundError, RunTerminalError, RuntimeExecutionError, StartRunConflictError, } from './errors.js';
6
6
  import { admitExternalEvents, moduleServices, resolveSnapshotStore, RunCursorCache, threadStartedEvents, UnknownDefinitionError, validateAndCreateEvents, waitSatisfiedEvents, } from './helpers.js';
7
7
  import { createRunIngress } from './ingress.js';
8
8
  import { notifyObserver } from './observer.js';
9
9
  import { createRuntimeRepository } from './repository.js';
10
10
  import { requestWakeAgain, RunExecutionContexts } from './run-execution-context.js';
11
+ import { createRunSecrets, SEALED_SECRETS_KEY } from './run-secrets.js';
11
12
  import { assertSameDurableStart } from './run-start.js';
12
13
  import { createWakeEngine } from './wake-engine.js';
13
14
  import { createTimeoutScheduler } from './wake-scheduler.js';
@@ -56,31 +57,16 @@ function startedPayload(input) {
56
57
  }
57
58
  return payload;
58
59
  }
59
- function reconcileRunSecrets(store, runId, requested) {
60
- const next = requested ?? {};
61
- return Effect.gen(function* () {
62
- const stored = store.runSecrets;
63
- if (!stored) {
64
- if (hasEntries(next)) {
65
- return yield* new RuntimeExecutionError('This event store cannot persist a secret context');
66
- }
67
- return yield* Effect.void;
68
- }
69
- const current = yield* stored.get(runId);
70
- if (sameStringRecord(current, next) || requested === undefined) {
71
- return yield* Effect.void;
72
- }
73
- if (!hasEntries(current)) {
74
- return yield* stored.put(runId, next);
75
- }
76
- return yield* new SecretContextConflictError(runId);
77
- });
78
- }
79
60
  export function createRuntime(options) {
80
61
  if (options.localLauncher && !options.store && !options.launcher) {
81
62
  throw new Error('localLauncher requires options.store');
82
63
  }
83
64
  const registry = composeModules(options.modules);
65
+ const runSecrets = createRunSecrets({
66
+ provider: options.secretProvider,
67
+ sealer: options.secretSealer,
68
+ observer: options.observer,
69
+ });
84
70
  assertWorkerConfigured(registry, options.worker);
85
71
  assertWorkerClaimsExplicit(registry, options.worker);
86
72
  assertWorkerDeadlines(registry, options.worker);
@@ -214,6 +200,9 @@ export function createRuntime(options) {
214
200
  if (hasEntries(args.secrets ?? {}) && !store.runSecrets) {
215
201
  return yield* new RuntimeExecutionError('This event store cannot persist a secret context');
216
202
  }
203
+ if (Object.hasOwn(args.secrets ?? {}, SEALED_SECRETS_KEY)) {
204
+ return yield* new RuntimeExecutionError(`A secret cannot be named "${SEALED_SECRETS_KEY}"`);
205
+ }
217
206
  const committed = yield* commit(store, runId, (existing) => existing.seq > 0
218
207
  ? assertSameDurableStart(runId, existing.state, requestedIdentity).pipe(Effect.map((rootThreadId) => ({
219
208
  events: [],
@@ -235,12 +224,13 @@ export function createRuntime(options) {
235
224
  },
236
225
  idempotencyKey: args.idempotencyKey ? `start:${args.idempotencyKey}` : undefined,
237
226
  }))));
238
- yield* reconcileRunSecrets(store, runId, args.secrets);
239
227
  if (!committed.append?.deduplicated) {
228
+ yield* runSecrets.provision(store, runId, committed.value.state, args.secrets);
240
229
  return committed.value;
241
230
  }
242
231
  const durable = yield* loadCursor(store, runId);
243
232
  const rootThreadId = yield* assertSameDurableStart(runId, durable.state, requestedIdentity);
233
+ yield* runSecrets.provision(store, runId, durable.state, args.secrets);
244
234
  return { threadId: rootThreadId, state: durable.state };
245
235
  });
246
236
  let scheduler;
@@ -260,6 +250,7 @@ export function createRuntime(options) {
260
250
  definitionResolver,
261
251
  scheduler: () => scheduler,
262
252
  launcher: () => launcher,
253
+ runSecrets,
263
254
  });
264
255
  const workerCallbacks = createWorkerCallbacks({
265
256
  registry,
@@ -267,6 +258,7 @@ export function createRuntime(options) {
267
258
  withRunIngress,
268
259
  observer: options.observer,
269
260
  wake: wakeEngine,
261
+ runSecrets,
270
262
  });
271
263
  const cancellation = createCancellation({
272
264
  registry,
@@ -447,8 +439,18 @@ export function createRuntime(options) {
447
439
  ? Effect.succeed({ events: [], value: undefined })
448
440
  : Effect.fail(new ForkConflictError(runId, sourceRunId));
449
441
  });
450
- const parentSecrets = store.runSecrets ? yield* store.runSecrets.get(sourceRunId) : {};
451
- yield* reconcileRunSecrets(store, runId, hasEntries(parentSecrets) ? parentSecrets : undefined);
442
+ // The source has finished, so it holds nothing. The provider decides what the fork is
443
+ // supplied with; without one the fork starts with no secrets.
444
+ const fork = yield* loadCursor(store, runId);
445
+ const supplied = forkOptions?.secrets ??
446
+ (yield* runSecrets.forChild(store, sourceRunId, source.state, {
447
+ runId,
448
+ relation: 'fork',
449
+ kind: fork.state.startIdentity?.kind ?? null,
450
+ definitionName: fork.state.startIdentity?.definitionName ?? null,
451
+ attributes: fork.state.attributes,
452
+ }));
453
+ yield* runSecrets.provision(store, runId, fork.state, supplied);
452
454
  return plan.rootThreadId;
453
455
  })).pipe(Effect.flatMap((threadId) => runtime.wake(runId).pipe(Effect.map((state) => ({ runId, threadId, state })))));
454
456
  },
@@ -0,0 +1,24 @@
1
+ import type { SecretSealer } from './run-secrets';
2
+ export interface SecretSealerOptions {
3
+ /** The key new records are sealed with. At least 32 characters of high-entropy text. */
4
+ readonly key: string;
5
+ /** Keys that older records may still be sealed with. They open records and never seal them. */
6
+ readonly previousKeys?: ReadonlyArray<string>;
7
+ }
8
+ declare const SecretSealError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
9
+ readonly _tag: "SecretSealError";
10
+ } & Readonly<A>;
11
+ /** A record could not be sealed or opened. The message never includes secret values. */
12
+ export declare class SecretSealError extends SecretSealError_base<{
13
+ readonly message: string;
14
+ }> {
15
+ }
16
+ /**
17
+ * Seals what a run holds with AES-256-GCM, under a key derived from `key`. The run id is
18
+ * authenticated with each record, so a record copied to another run does not open.
19
+ *
20
+ * This protects a copy of the storage that leaves without the key, such as a backup or an
21
+ * export. It does not protect against code that runs in the host, which has the key.
22
+ */
23
+ export declare function secretSealer(options: SecretSealerOptions): SecretSealer;
24
+ export {};
@@ -0,0 +1,120 @@
1
+ import { Data, Effect, Schema } from 'effect';
2
+ import { SecretContextSchema } from '@swirls/looms/core';
3
+ /** A record could not be sealed or opened. The message never includes secret values. */
4
+ export class SecretSealError extends Data.TaggedError('SecretSealError') {
5
+ }
6
+ const MIN_KEY_LENGTH = 32;
7
+ const VERSION = 'v1';
8
+ const encoder = new TextEncoder();
9
+ const decoder = new TextDecoder();
10
+ const SecretsJson = Schema.fromJsonString(SecretContextSchema);
11
+ const decodeSecrets = Schema.decodeUnknownEffect(SecretsJson);
12
+ const encodeSecrets = Schema.encodeSync(SecretsJson);
13
+ const failed = (message) => () => new SecretSealError({ message });
14
+ function bytes(text) {
15
+ const encoded = encoder.encode(text);
16
+ const copy = new Uint8Array(new ArrayBuffer(encoded.length));
17
+ copy.set(encoded);
18
+ return copy;
19
+ }
20
+ function toBase64Url(value) {
21
+ const view = value instanceof Uint8Array ? value : new Uint8Array(value);
22
+ let binary = '';
23
+ for (const byte of view) {
24
+ binary += String.fromCharCode(byte);
25
+ }
26
+ return btoa(binary).replaceAll('+', '-').replaceAll('/', '_').replaceAll('=', '');
27
+ }
28
+ function fromBase64Url(value) {
29
+ if (!/^[A-Za-z0-9_-]+$/.test(value)) {
30
+ return Effect.fail(new SecretSealError({ message: 'The sealed record is malformed' }));
31
+ }
32
+ const binary = atob(value.replaceAll('-', '+').replaceAll('_', '/'));
33
+ const out = new Uint8Array(new ArrayBuffer(binary.length));
34
+ for (let index = 0; index < binary.length; index += 1) {
35
+ out[index] = binary.charCodeAt(index);
36
+ }
37
+ return Effect.succeed(out);
38
+ }
39
+ function hkdf(info) {
40
+ return {
41
+ name: 'HKDF',
42
+ hash: 'SHA-256',
43
+ salt: new Uint8Array(new ArrayBuffer(0)),
44
+ info: bytes(info),
45
+ };
46
+ }
47
+ /** Derives the encryption key and a public id for it, so a record names the key that sealed it. */
48
+ function derive(secret) {
49
+ const fail = failed('The sealing key could not be derived');
50
+ return Effect.gen(function* () {
51
+ const material = yield* Effect.tryPromise({
52
+ try: () => crypto.subtle.importKey('raw', bytes(secret), 'HKDF', false, ['deriveBits', 'deriveKey']),
53
+ catch: fail,
54
+ });
55
+ const id = yield* Effect.tryPromise({
56
+ try: () => crypto.subtle.deriveBits(hkdf('looms/run-secrets/v1/id'), material, 64),
57
+ catch: fail,
58
+ });
59
+ const key = yield* Effect.tryPromise({
60
+ try: () => crypto.subtle.deriveKey(hkdf('looms/run-secrets/v1/key'), material, { name: 'AES-GCM', length: 256 }, false, ['encrypt', 'decrypt']),
61
+ catch: fail,
62
+ });
63
+ return { id: toBase64Url(id), key };
64
+ });
65
+ }
66
+ /**
67
+ * Seals what a run holds with AES-256-GCM, under a key derived from `key`. The run id is
68
+ * authenticated with each record, so a record copied to another run does not open.
69
+ *
70
+ * This protects a copy of the storage that leaves without the key, such as a backup or an
71
+ * export. It does not protect against code that runs in the host, which has the key.
72
+ */
73
+ export function secretSealer(options) {
74
+ const secrets = [options.key, ...(options.previousKeys ?? [])];
75
+ if (secrets.some((secret) => secret.length < MIN_KEY_LENGTH)) {
76
+ throw new Error(`A secret sealing key needs at least ${MIN_KEY_LENGTH} characters`);
77
+ }
78
+ let derived;
79
+ // Derived on first use and kept: deriving is the expensive part of every seal and open.
80
+ const keys = Effect.tryPromise({
81
+ try: () => {
82
+ derived ??= Effect.runPromise(Effect.forEach(secrets, derive));
83
+ return derived;
84
+ },
85
+ catch: failed('The sealing key could not be derived'),
86
+ });
87
+ return {
88
+ seal: (runId, secretContext) => Effect.gen(function* () {
89
+ const [current] = yield* keys;
90
+ if (!current) {
91
+ return yield* new SecretSealError({ message: 'No sealing key' });
92
+ }
93
+ const iv = crypto.getRandomValues(new Uint8Array(new ArrayBuffer(12)));
94
+ const sealed = yield* Effect.tryPromise({
95
+ try: () => crypto.subtle.encrypt({ name: 'AES-GCM', iv, additionalData: bytes(runId) }, current.key, bytes(encodeSecrets(secretContext))),
96
+ catch: failed('The secrets could not be sealed'),
97
+ });
98
+ return [VERSION, current.id, toBase64Url(iv), toBase64Url(sealed)].join('.');
99
+ }),
100
+ open: (runId, sealed) => Effect.gen(function* () {
101
+ const [version, id, iv, body] = sealed.split('.');
102
+ if (version !== VERSION || !id || !iv || !body) {
103
+ return yield* new SecretSealError({ message: 'The sealed record is malformed' });
104
+ }
105
+ const match = (yield* keys).find((candidate) => candidate.id === id);
106
+ if (!match) {
107
+ return yield* new SecretSealError({
108
+ message: 'The sealed record was sealed with a key this runtime does not have',
109
+ });
110
+ }
111
+ const nonce = yield* fromBase64Url(iv);
112
+ const ciphertext = yield* fromBase64Url(body);
113
+ const opened = yield* Effect.tryPromise({
114
+ try: () => crypto.subtle.decrypt({ name: 'AES-GCM', iv: nonce, additionalData: bytes(runId) }, match.key, ciphertext),
115
+ catch: failed('The sealed record does not open for this run with this key'),
116
+ });
117
+ return yield* decodeSecrets(decoder.decode(opened)).pipe(Effect.mapError(failed('The sealed record is malformed')));
118
+ }),
119
+ };
120
+ }
@@ -40,6 +40,7 @@ const CancelBodySchema = Schema.Struct({
40
40
  });
41
41
  const ForkBodySchema = Schema.Struct({
42
42
  runId: Schema.optional(Schema.String),
43
+ secrets: Schema.optional(SecretContextSchema),
43
44
  });
44
45
  function readStartRunArgs(req) {
45
46
  return Effect.gen(function* () {
@@ -294,7 +295,7 @@ export function runRoutes({ runtime, store }) {
294
295
  access: 'write',
295
296
  handle: ({ req, params }) => Effect.gen(function* () {
296
297
  const body = yield* readOptionalJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(ForkBodySchema)));
297
- const result = yield* provideStore(runtime.fork(params.runId, { runId: body.runId }), store);
298
+ const result = yield* provideStore(runtime.fork(params.runId, { runId: body.runId, secrets: body.secrets }), store);
298
299
  return Response.json(result);
299
300
  }),
300
301
  }),
@@ -3,6 +3,7 @@ import type { AnyRuntimeModule, ComposedRegistry, DefinitionResolver, EventEnvel
3
3
  import type { EventStoreTrimmedError } from '@swirls/looms/core';
4
4
  import type { DuplicateEffectDispatchError, MaxWakeIterationsError } from './errors';
5
5
  import type { RuntimeObserver } from './observer';
6
+ import type { SecretProvider, SecretSealer } from './run-secrets';
6
7
  import type { WakeScheduler } from './wake-scheduler';
7
8
  export type WakeError = DuplicateEffectDispatchError | MaxWakeIterationsError | EventStoreTruncationError | EventStoreTrimmedError | EventStoreFencedError | EventStoreError | Error;
8
9
  export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
@@ -20,6 +21,12 @@ export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule
20
21
  * after a crash inside one long wake.
21
22
  */
22
23
  readonly snapshotEvery?: number;
24
+ /**
25
+ * How many times one wake may plan before it hands the run to a new wake. Default 100. A wake
26
+ * that reaches it starts nothing new, waits for the effects it already started, parks, and
27
+ * asks its scheduler to wake the run again at once. It bounds the work one wake does in a
28
+ * single host invocation; it does not stop a run.
29
+ */
23
30
  readonly maxWakeIterations?: number;
24
31
  /**
25
32
  * How far ahead a wake with in-process effects in flight keeps its `WakeScheduler.keepAlive`
@@ -68,6 +75,13 @@ export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule
68
75
  * undeclared one fails with `InvalidRunAttributesError` and writes no events.
69
76
  */
70
77
  readonly attributes?: RunAttributeFields;
78
+ /**
79
+ * Decides what each run holds and what each attempt receives. Without one, a run holds the
80
+ * `secrets` its start supplied and every attempt receives them.
81
+ */
82
+ readonly secretProvider?: SecretProvider;
83
+ /** Encrypts what a run holds before it is stored. See `secretSealer`. */
84
+ readonly secretSealer?: SecretSealer;
71
85
  }
72
86
  export interface EffectWorkerTask {
73
87
  readonly runId: string;
@@ -88,8 +102,8 @@ export interface EffectWorkerTask {
88
102
  /** The attempt's deadlines from the effect's retry policy, when it sets any. */
89
103
  readonly deadlines?: EffectWorkerDeadlines;
90
104
  /**
91
- * Present only on the in-memory dispatch. A transport that persists the task must leave this out
92
- * and let the worker read the secret context through an authenticated callback.
105
+ * This attempt's secrets. Present only on the in-memory dispatch. A transport that persists the
106
+ * task must leave this out and let the worker read them through an authenticated callback.
93
107
  */
94
108
  readonly secrets?: SecretContext;
95
109
  }
@@ -134,8 +148,10 @@ export interface StartRunArgs {
134
148
  /** Immutable labels stored on the start event and the run summary. */
135
149
  attributes?: RunAttributes;
136
150
  /**
137
- * Bearer material stored beside the log. A retry that sends a different context conflicts.
138
- * Omitting it on a retry keeps the context already stored.
151
+ * Bearer material the run holds, stored beside the log and deleted when the run finishes. With
152
+ * a `secretProvider` that has `provision`, this is what `provision` is supplied with. Without
153
+ * one it is stored as given: a retry that sends a different context conflicts, and omitting it
154
+ * on a retry keeps the context already stored.
139
155
  */
140
156
  secrets?: SecretContext;
141
157
  /**
@@ -213,10 +229,12 @@ export interface LoomsRuntime<TModules extends readonly AnyRuntimeModule[] = rea
213
229
  /**
214
230
  * Start a new run that continues where a finished run ended. The fork copies the source's
215
231
  * history up to the point it finished and re-issues the effects outstanding there. Retrying
216
- * with the same `runId` returns the existing fork.
232
+ * with the same `runId` returns the existing fork. The source's secrets were deleted when it
233
+ * finished, so the fork holds `secrets` when given, or else what the secret provider decides.
217
234
  */
218
235
  fork(sourceRunId: string, options?: {
219
236
  runId?: string;
237
+ secrets?: SecretContext;
220
238
  }): Effect.Effect<StartResult, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
221
239
  /**
222
240
  * Applies a worker's report about one effect attempt. A report for another attempt, or one that
@@ -224,8 +242,9 @@ export interface LoomsRuntime<TModules extends readonly AnyRuntimeModule[] = rea
224
242
  */
225
243
  workerCallback(runId: string, input: WorkerCallbackInput): Effect.Effect<WorkerCallbackResult, Error | EventStoreAppendError | EventStoreError, EventStoreTag>;
226
244
  /**
227
- * The run's secret context for a worker attempt that has started and not settled. Any other
228
- * attempt is `stale`, so a redelivered or superseded message never sees the secrets.
245
+ * The secrets for a worker attempt that has started and not settled. Any other attempt is
246
+ * `stale`, so a redelivered or superseded message never sees them. `unavailable` means the
247
+ * secret provider failed this time.
229
248
  */
230
249
  workerSecrets(runId: string, callback: WorkerCallback): Effect.Effect<WorkerSecretsResult, Error | EventStoreTruncationError | EventStoreTrimmedError | EventStoreError, EventStoreTag>;
231
250
  readonly listRuns: Effect.Effect<string[], EventStoreError, EventStoreTag>;
@@ -3,6 +3,7 @@ import { type ComposedRegistry, type DefinitionResolver, type RunLauncher } from
3
3
  import { type RuntimeObserver } from './observer';
4
4
  import type { RuntimeRepository } from './repository';
5
5
  import { type RunExecutionContexts } from './run-execution-context';
6
+ import type { RunSecrets } from './run-secrets';
6
7
  import type { LoomsRuntime, EffectWorker } from './types';
7
8
  import type { WakeScheduler } from './wake-scheduler';
8
9
  export interface WakeEngineOptions {
@@ -19,5 +20,6 @@ export interface WakeEngineOptions {
19
20
  readonly observer?: RuntimeObserver;
20
21
  readonly scheduler: () => WakeScheduler;
21
22
  readonly launcher: () => RunLauncher;
23
+ readonly runSecrets: RunSecrets;
22
24
  }
23
25
  export declare function createWakeEngine(options: WakeEngineOptions): LoomsRuntime['wake'];
@@ -1,9 +1,9 @@
1
1
  import { Clock, Deferred, Effect, Exit, Fiber, Option, Queue, } from 'effect';
2
- import { createEvent, deferredUntil, EventStoreTag, foldRun, isPrimitiveEffect, isRunTerminal, } from '@swirls/looms/core';
2
+ import { createEvent, deferredUntil, EventStoreTag, foldRun, isPrimitiveEffect, hasEntries, isRunTerminal, } from '@swirls/looms/core';
3
3
  import { childCloseCancellations, notifyLaunchingParent } from './child-run.js';
4
4
  import { nextRuntimeDeadline, planDeadlineTransitions, planTerminalCancellationTransitions, } from './deadline-transition-planner.js';
5
5
  import { admitOrFailAttempt } from './effect-admission.js';
6
- import { DuplicateEffectDispatchError, MaxWakeIterationsError, RuntimeExecutionError, } from './errors.js';
6
+ import { DuplicateEffectDispatchError, RuntimeExecutionError } from './errors.js';
7
7
  import { cascadedCancellations, createEffectFailedEvent, groupOutstanding, stripSeq, synthesizedThreadFailed, waitSatisfiedEvents, } from './helpers.js';
8
8
  import { executeLocalEffects } from './local-effect-executor.js';
9
9
  import { notifyObserver } from './observer.js';
@@ -134,7 +134,6 @@ export function createWakeEngine(options) {
134
134
  };
135
135
  return yield* Effect.gen(function* () {
136
136
  const store = yield* EventStoreTag;
137
- const secrets = store.runSecrets ? yield* store.runSecrets.get(runId) : {};
138
137
  const runInContext = Effect.runPromiseWith(yield* Effect.context());
139
138
  executionContext.liveStore = store;
140
139
  let finalState;
@@ -158,6 +157,8 @@ export function createWakeEngine(options) {
158
157
  cursor = yield* applyAppend(store, runId, cursor, stripSeq(events), appended);
159
158
  }
160
159
  cursor = yield* closeLaunchedRuns(store, runId, cursor);
160
+ // A finished run starts no more attempts, so nothing it holds is needed again.
161
+ yield* options.runSecrets.release(store, runId, cursor.state);
161
162
  const nextDeadline = nextRuntimeDeadline(cursor.state, now);
162
163
  if (nextDeadline !== undefined) {
163
164
  yield* options.scheduler().schedule(runId, nextDeadline);
@@ -174,6 +175,8 @@ export function createWakeEngine(options) {
174
175
  const inFlight = new Map();
175
176
  const settled = yield* Queue.unbounded();
176
177
  let guard = 0;
178
+ // Set once this pass has used its iterations: the rest of the work goes to a new wake.
179
+ let yieldToNextWake = false;
177
180
  // Deadlines at or before this instant were handled by the last loop iteration.
178
181
  let plannedAt = Number.NEGATIVE_INFINITY;
179
182
  const foldProduced = (produced) => Effect.gen(function* () {
@@ -210,10 +213,19 @@ export function createWakeEngine(options) {
210
213
  };
211
214
  const dispatchKeyFor = (item) => `${item.effectId}:${attemptFor(item)}`;
212
215
  while (!isRunTerminal(cursor.state)) {
213
- if (guard >= maxWakeIterations) {
214
- return yield* new MaxWakeIterationsError(runId, maxWakeIterations);
216
+ // A pass that has used its iterations starts nothing new. It waits for the effects
217
+ // it already started, then parks and hands the rest to a new wake (see below). A
218
+ // long-lived run (an agent that keeps calling tools while siblings wait) does far
219
+ // more than one pass's worth of work, and failing here would leave it with nothing
220
+ // driving it until some request happened to wake it again.
221
+ const draining = guard >= maxWakeIterations;
222
+ if (draining && inFlight.size === 0) {
223
+ yieldToNextWake = true;
224
+ break;
225
+ }
226
+ if (!draining) {
227
+ guard += 1;
215
228
  }
216
- guard += 1;
217
229
  // A signal (or coalesced join) may have appended events while local effects ran.
218
230
  if (executionContext.wakeAgain) {
219
231
  executionContext.wakeAgain = false;
@@ -223,7 +235,7 @@ export function createWakeEngine(options) {
223
235
  const now = yield* Clock.currentTimeMillis;
224
236
  plannedAt = now;
225
237
  const deadlinePlan = planDeadlineTransitions({ runId, state, registry, now });
226
- if (deadlinePlan.events.length > 0) {
238
+ if (!draining && deadlinePlan.events.length > 0) {
227
239
  for (const notice of deadlinePlan.timerNotices) {
228
240
  observe({
229
241
  type: 'timer.late',
@@ -263,9 +275,8 @@ export function createWakeEngine(options) {
263
275
  worker: options.worker,
264
276
  now,
265
277
  maxInFlightWorkerEffects: options.maxInFlightWorkerEffects,
266
- secrets,
267
278
  });
268
- if (workerPlans.length > 0) {
279
+ if (!draining && workerPlans.length > 0) {
269
280
  for (const workerPlan of workerPlans) {
270
281
  const admission = yield* admitOrFailAttempt({
271
282
  registry,
@@ -274,7 +285,12 @@ export function createWakeEngine(options) {
274
285
  attempt: workerPlan.attempt,
275
286
  now,
276
287
  attributes: state.attributes ?? {},
277
- secrets,
288
+ secrets: options.runSecrets.forAttempt(store, runId, state, {
289
+ effectId: workerPlan.item.effectId,
290
+ attempt: workerPlan.attempt,
291
+ type: workerPlan.item.effect.type,
292
+ threadId: workerPlan.item.threadId,
293
+ }),
278
294
  trace: state.startIdentity?.trace ?? null,
279
295
  retry: workerPlan.retry,
280
296
  });
@@ -290,7 +306,11 @@ export function createWakeEngine(options) {
290
306
  const queuedAppend = yield* appendObserved(store, runId, stripSeq([workerPlan.queuedEvent]));
291
307
  cursor = yield* applyAppend(store, runId, cursor, stripSeq([workerPlan.queuedEvent]), queuedAppend);
292
308
  }
293
- const dispatchEvent = yield* dispatchWorkerEffect(runId, workerPlan, options.worker, now);
309
+ // Only an in-memory transport passes these on. One that persists the task drops
310
+ // them, and its worker asks for the attempt's secrets once it has started.
311
+ const dispatchEvent = yield* dispatchWorkerEffect(runId, hasEntries(admission.secrets)
312
+ ? { ...workerPlan, task: { ...workerPlan.task, secrets: admission.secrets } }
313
+ : workerPlan, options.worker, now);
294
314
  const dispatchAppend = yield* appendObserved(store, runId, stripSeq([dispatchEvent]));
295
315
  cursor = yield* applyAppend(store, runId, cursor, stripSeq([dispatchEvent]), dispatchAppend);
296
316
  }
@@ -342,12 +362,12 @@ export function createWakeEngine(options) {
342
362
  ]
343
363
  : [];
344
364
  });
345
- if (exhausted.length > 0) {
365
+ if (!draining && exhausted.length > 0) {
346
366
  yield* foldProduced(exhausted);
347
367
  continue;
348
368
  }
349
369
  const due = outstanding.filter((item) => !dispatchedEffectIds.has(dispatchKeyFor(item)));
350
- if (due.length > 0) {
370
+ if (!draining && due.length > 0) {
351
371
  const attempts = new Map(due.map((item) => [item.effectId, attemptFor(item)]));
352
372
  for (const item of due) {
353
373
  const key = `${item.effectId}:${attempts.get(item.effectId) ?? 1}`;
@@ -387,11 +407,13 @@ export function createWakeEngine(options) {
387
407
  observe,
388
408
  launcher: options.launcher(),
389
409
  };
410
+ const dispatchState = cursor.state;
390
411
  const runContext = {
391
- correlationId: cursor.state.startIdentity?.correlationId ?? runId,
392
- attributes: cursor.state.attributes ?? {},
393
- secrets,
394
- trace: cursor.state.startIdentity?.trace ?? null,
412
+ correlationId: dispatchState.startIdentity?.correlationId ?? runId,
413
+ attributes: dispatchState.attributes ?? {},
414
+ secretsFor: (attempt) => options.runSecrets.forAttempt(store, runId, dispatchState, attempt),
415
+ secretsForChild: (child) => options.runSecrets.forChild(store, runId, dispatchState, child),
416
+ trace: dispatchState.startIdentity?.trace ?? null,
395
417
  };
396
418
  // One fiber per (thread, causingSeq) group keeps in-group order and frees the
397
419
  // wake loop to plan other threads while a group is still running.
@@ -484,10 +506,17 @@ export function createWakeEngine(options) {
484
506
  }
485
507
  if (isRunTerminal(cursor.state)) {
486
508
  cursor = yield* closeLaunchedRuns(store, runId, cursor);
509
+ // The run finished in this wake. A wake of a run that had already finished does the
510
+ // same above, which covers a host that stopped between the two.
511
+ yield* options.runSecrets.release(store, runId, cursor.state);
487
512
  }
488
513
  // Snapshot on park: the next wake (on any instance) starts from here.
489
514
  cursor = yield* persistSnapshot(store, runId, cursor);
490
- const nextDeadline = nextRuntimeDeadline(cursor.state, plannedAt);
515
+ const runtimeDeadline = nextRuntimeDeadline(cursor.state, plannedAt);
516
+ // Work this pass left for the next wake is due now.
517
+ const nextDeadline = yieldToNextWake
518
+ ? Math.min(runtimeDeadline ?? Number.POSITIVE_INFINITY, yield* Clock.currentTimeMillis)
519
+ : runtimeDeadline;
491
520
  if (nextDeadline !== undefined) {
492
521
  yield* options.scheduler().schedule(runId, nextDeadline);
493
522
  }
@@ -3,6 +3,7 @@ import { EventStoreTag, type ComposedRegistry, type WorkerCallback, type WorkerC
3
3
  import type { RunIngress } from './ingress';
4
4
  import { type RuntimeObserver } from './observer';
5
5
  import type { RuntimeRepository } from './repository';
6
+ import { type RunSecrets } from './run-secrets';
6
7
  import type { LoomsRuntime } from './types';
7
8
  export interface WorkerCallbacksOptions {
8
9
  readonly registry: ComposedRegistry;
@@ -10,17 +11,18 @@ export interface WorkerCallbacksOptions {
10
11
  readonly withRunIngress: RunIngress;
11
12
  readonly observer?: RuntimeObserver;
12
13
  readonly wake: LoomsRuntime['wake'];
14
+ readonly runSecrets: RunSecrets;
13
15
  }
14
16
  export declare function createWorkerCallbacks(options: WorkerCallbacksOptions): {
15
17
  workerCallback: (runId: string, callback: WorkerCallbackInput) => Effect.Effect<WorkerCallbackResult, import("@swirls/looms/core").DefinitionResolveError | import("./errors").DuplicateEffectDispatchError | Error | import("@swirls/looms/core").EventPayloadTooLargeError | import("@swirls/looms/core").EventStoreConflictError | import("@swirls/looms/core").EventStoreError | import("@swirls/looms/core").EventStoreFencedError | import("@swirls/looms/core").EventStoreTrimmedError | import("@swirls/looms/core").EventStoreTruncationError | import("./errors").MaxWakeIterationsError | import("./ingress").RunOverloadedError | import("./errors").RuntimeExecutionError, EventStoreTag>;
16
18
  workerSecrets: (runId: string, callback: WorkerCallback) => Effect.Effect<{
17
19
  status: "stale";
18
- secrets?: undefined;
19
20
  } | {
20
21
  status: "cancelled";
21
- secrets?: undefined;
22
22
  } | {
23
23
  status: "accepted";
24
24
  secrets: import("@swirls/looms/core").SecretContext;
25
+ } | {
26
+ status: "unavailable";
25
27
  }, Error | import("@swirls/looms/core").EventStoreError, EventStoreTag>;
26
28
  };
@@ -3,6 +3,7 @@ import { createEvent, EventStoreTag, isRunTerminal, } from '@swirls/looms/core';
3
3
  import { materializeEffectOutcome } from './helpers.js';
4
4
  import { notifyObserver } from './observer.js';
5
5
  import { planAttemptFailure } from './retry-policy.js';
6
+ import { SecretProviderError } from './run-secrets.js';
6
7
  const WORKER_ORIGIN = { type: 'external', actorId: 'worker' };
7
8
  /** The earliest of the start-to-close cap and the next heartbeat deadline. */
8
9
  function workerDeadline(retry, startedAt, now) {
@@ -190,8 +191,20 @@ export function createWorkerCallbacks(options) {
190
191
  if (execution.status !== 'started' && execution.status !== 'heartbeat') {
191
192
  return { status: 'stale' };
192
193
  }
193
- const secrets = store.runSecrets ? yield* store.runSecrets.get(runId) : {};
194
- return { status: 'accepted', secrets };
194
+ const item = state.outstandingEffects.find((candidate) => candidate.effectId === callback.effectId);
195
+ if (!item) {
196
+ return { status: 'stale' };
197
+ }
198
+ // A provider failure is not a transport failure: the worker fails this attempt and the
199
+ // retry policy decides whether another one asks again.
200
+ return yield* options.runSecrets
201
+ .forAttempt(store, runId, state, {
202
+ effectId: callback.effectId,
203
+ attempt: callback.attempt,
204
+ type: item.effect.type,
205
+ threadId: item.threadId,
206
+ })
207
+ .pipe(Effect.map((secrets) => ({ status: 'accepted', secrets })), Effect.catchIf((error) => error instanceof SecretProviderError, () => Effect.succeed({ status: 'unavailable' })));
195
208
  });
196
209
  return { workerCallback: applyWorkerCallback, workerSecrets };
197
210
  }
@@ -1,5 +1,5 @@
1
1
  import { Effect } from 'effect';
2
- import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState, type SecretContext } from '@swirls/looms/core';
2
+ import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState } from '@swirls/looms/core';
3
3
  import type { EffectWorker, EffectWorkerTask } from './types';
4
4
  /** Caps how many times one attempt's unacknowledged dispatch can be deferred before parking as ambiguous. */
5
5
  export declare const DEFAULT_MAX_WORKER_DISPATCH_DEFERRALS = 32;
@@ -32,7 +32,6 @@ export declare function planWorkerEffects(input: {
32
32
  readonly worker?: EffectWorker;
33
33
  readonly now: number;
34
34
  readonly maxInFlightWorkerEffects?: number;
35
- readonly secrets?: SecretContext;
36
35
  }): ReadonlyArray<WorkerEffectDispatchPlan>;
37
36
  /**
38
37
  * Hand a planned attempt to the worker.
@@ -102,7 +102,6 @@ export function planWorkerEffects(input) {
102
102
  }),
103
103
  task: workerTask(input.runId, item, attempt, {
104
104
  details: existing?.heartbeatDetails,
105
- secrets: input.secrets,
106
105
  attributes: input.state.attributes,
107
106
  trace: input.state.startIdentity?.trace,
108
107
  retry,