@swirls/looms 0.17.0 → 0.18.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (45) hide show
  1. package/CHANGELOG.md +15 -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/agent/effects.d.ts +266 -266
  7. package/dist/client/client.d.ts +1 -0
  8. package/dist/client/client.js +10 -4
  9. package/dist/cloudflare/durable-object.d.ts +5 -1
  10. package/dist/cloudflare/durable-object.js +2 -0
  11. package/dist/cloudflare/queue-consumer.js +11 -3
  12. package/dist/core/effects.d.ts +1 -1
  13. package/dist/core/module.d.ts +1 -0
  14. package/dist/core/run-context.d.ts +6 -2
  15. package/dist/core/sqlite-store.js +6 -0
  16. package/dist/core/store.js +5 -0
  17. package/dist/core/worker-callback.d.ts +5 -2
  18. package/dist/debugger/app/assets/{index-Br9tGbPI.js → index-BjZn1DuJ.js} +2 -2
  19. package/dist/debugger/app/assets/{routes-CZ0buqO7.js → routes-B90xnBF1.js} +2 -2
  20. package/dist/debugger/app/index.html +1 -1
  21. package/dist/runtime/effect-admission.d.ts +8 -3
  22. package/dist/runtime/effect-admission.js +23 -4
  23. package/dist/runtime/index.d.ts +2 -0
  24. package/dist/runtime/index.js +2 -0
  25. package/dist/runtime/local-effect-executor.d.ts +8 -2
  26. package/dist/runtime/local-effect-executor.js +21 -8
  27. package/dist/runtime/looms.d.ts +6 -0
  28. package/dist/runtime/looms.js +2 -0
  29. package/dist/runtime/observer.d.ts +15 -0
  30. package/dist/runtime/run-secrets.d.ts +132 -0
  31. package/dist/runtime/run-secrets.js +154 -0
  32. package/dist/runtime/runtime.js +27 -25
  33. package/dist/runtime/secret-sealer.d.ts +24 -0
  34. package/dist/runtime/secret-sealer.js +120 -0
  35. package/dist/runtime/server/routes/runs.js +2 -1
  36. package/dist/runtime/types.d.ts +20 -7
  37. package/dist/runtime/wake-engine.d.ts +2 -0
  38. package/dist/runtime/wake-engine.js +23 -9
  39. package/dist/runtime/worker-callbacks.d.ts +4 -2
  40. package/dist/runtime/worker-callbacks.js +15 -2
  41. package/dist/runtime/worker-effect-dispatch.d.ts +1 -2
  42. package/dist/runtime/worker-effect-dispatch.js +0 -1
  43. package/dist/schedule/module.d.ts +36 -36
  44. package/dist/workflow/module.d.ts +32 -32
  45. package/package.json +1 -1
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Looms debugger</title>
7
- <script type="module" crossorigin src="./assets/index-Br9tGbPI.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-BjZn1DuJ.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
9
9
  <link rel="stylesheet" crossorigin href="./assets/index-CO5gIvV8.css">
10
10
  </head>
@@ -9,8 +9,11 @@ export type AdmissionDecision = {
9
9
  readonly nonRetryable: boolean;
10
10
  readonly retryAfterMs?: number;
11
11
  };
12
+ /** Recorded on an attempt that could not be given its secrets. It names no cause on purpose. */
13
+ export declare const SECRETS_UNAVAILABLE_ERROR = "secrets are unavailable for this attempt";
12
14
  export type AdmitOrFailResult = {
13
15
  readonly _tag: 'admit';
16
+ readonly secrets: SecretContext;
14
17
  } | {
15
18
  readonly _tag: 'reject';
16
19
  readonly event: EventEnvelope;
@@ -29,8 +32,9 @@ export declare function runEffectAdmission(registry: ComposedRegistry, item: Out
29
32
  readonly trace: TraceContext | null;
30
33
  }): Effect.Effect<AdmissionDecision>;
31
34
  /**
32
- * Gate an attempt, then turn a reject into the durable failure/retry event both the local
33
- * executor and the wake engine append. Call sites only append the event (and notify observer).
35
+ * Get the attempt's secrets and gate it, then turn a reject into the durable failure/retry event
36
+ * both the local executor and the wake engine append. Call sites only append the event (and
37
+ * notify observer). An attempt whose secrets cannot be produced is rejected and may be retried.
34
38
  */
35
39
  export declare function admitOrFailAttempt(input: {
36
40
  readonly registry: ComposedRegistry;
@@ -39,7 +43,8 @@ export declare function admitOrFailAttempt(input: {
39
43
  readonly attempt: number;
40
44
  readonly now: number;
41
45
  readonly attributes: RunAttributes;
42
- readonly secrets: SecretContext;
46
+ /** Produces this attempt's secrets. */
47
+ readonly secrets: Effect.Effect<SecretContext, Error>;
43
48
  readonly trace: TraceContext | null;
44
49
  readonly retry: RetryPolicy | undefined;
45
50
  }): Effect.Effect<AdmitOrFailResult>;
@@ -1,6 +1,8 @@
1
1
  import { Effect } from 'effect';
2
2
  import { isPrimitiveEffect, readEffectFailure, } from '@swirls/looms/core';
3
3
  import { planAttemptFailure } from './retry-policy.js';
4
+ /** Recorded on an attempt that could not be given its secrets. It names no cause on purpose. */
5
+ export const SECRETS_UNAVAILABLE_ERROR = 'secrets are unavailable for this attempt';
4
6
  /**
5
7
  * Run every composed admission hook before a local attempt or a worker dispatch.
6
8
  * A `failEffect` (or other thrown/failed cause) becomes a reject decision.
@@ -32,13 +34,30 @@ export function runEffectAdmission(registry, item, context) {
32
34
  }));
33
35
  }
34
36
  /**
35
- * Gate an attempt, then turn a reject into the durable failure/retry event both the local
36
- * executor and the wake engine append. Call sites only append the event (and notify observer).
37
+ * Get the attempt's secrets and gate it, then turn a reject into the durable failure/retry event
38
+ * both the local executor and the wake engine append. Call sites only append the event (and
39
+ * notify observer). An attempt whose secrets cannot be produced is rejected and may be retried.
37
40
  */
38
41
  export function admitOrFailAttempt(input) {
39
- return runEffectAdmission(input.registry, input.item, input).pipe(Effect.map((decision) => {
42
+ // The runtime's own effects (complete, spawn, wait, ...) have no handler to receive secrets, so
43
+ // the provider is not asked about them.
44
+ const attemptSecrets = isPrimitiveEffect(input.item.effect)
45
+ ? Effect.succeed({})
46
+ : input.secrets;
47
+ const decide = attemptSecrets.pipe(Effect.matchEffect({
48
+ onFailure: () => {
49
+ const decision = {
50
+ _tag: 'reject',
51
+ error: SECRETS_UNAVAILABLE_ERROR,
52
+ nonRetryable: false,
53
+ };
54
+ return Effect.succeed({ decision, secrets: {} });
55
+ },
56
+ onSuccess: (issued) => runEffectAdmission(input.registry, input.item, { ...input, secrets: issued }).pipe(Effect.map((decision) => ({ decision, secrets: issued }))),
57
+ }));
58
+ return decide.pipe(Effect.map(({ decision, secrets }) => {
40
59
  if (decision._tag === 'admit') {
41
- return { _tag: 'admit' };
60
+ return { _tag: 'admit', secrets };
42
61
  }
43
62
  const failure = planAttemptFailure({
44
63
  runId: input.runId,
@@ -6,3 +6,5 @@ export { serveHttp, createFetchHandler, isLoomsApiPath, describeRoute, type Fetc
6
6
  export { filesystemBlobStore } from './filesystem-blob-store';
7
7
  export { createEventStreamResponse, type EventStreamOptions } from './sse';
8
8
  export { notifyObserver, type RuntimeObservation, type RuntimeObserver } from './observer';
9
+ export { SecretProviderError, type AttemptSecrets, type SecretAttempt, type SecretChild, type SecretProvider, type SecretRun, type SecretSealer, } from './run-secrets';
10
+ export { secretSealer, SecretSealError, type SecretSealerOptions } from './secret-sealer';
@@ -6,3 +6,5 @@ export { serveHttp, createFetchHandler, isLoomsApiPath, describeRoute, ACTOR_HEA
6
6
  export { filesystemBlobStore } from './filesystem-blob-store.js';
7
7
  export { createEventStreamResponse } from './sse.js';
8
8
  export { notifyObserver } from './observer.js';
9
+ export { SecretProviderError, } from './run-secrets.js';
10
+ export { secretSealer, SecretSealError } from './secret-sealer.js';
@@ -3,6 +3,7 @@ import { type ComposedRegistry, type EventEnvelope, type DefinitionResolver, typ
3
3
  import type { RuntimeObserver } from './observer';
4
4
  import type { RuntimeRepository } from './repository';
5
5
  import type { RunExecutionContext } from './run-execution-context';
6
+ import type { SecretAttempt, SecretChild } from './run-secrets';
6
7
  export interface LocalEffectExecutorOptions {
7
8
  readonly registry: ComposedRegistry;
8
9
  readonly services: ManagedRuntime.ManagedRuntime<Context.Service.Any, never>;
@@ -13,11 +14,16 @@ export interface LocalEffectExecutorOptions {
13
14
  readonly observe: (event: Parameters<RuntimeObserver['observe']>[0]) => void;
14
15
  readonly launcher: RunLauncher;
15
16
  }
16
- /** Run-level values every effect sees. Runs the effects launch inherit them unless the launch overrides them. */
17
+ /**
18
+ * Run-level values every effect sees. Runs the effects launch inherit the attributes and trace
19
+ * unless the launch overrides them. Secrets are never inherited: a launched run is supplied with
20
+ * what the launch passes, or else with what the secret provider decides.
21
+ */
17
22
  export interface RunContext {
18
23
  readonly correlationId: string;
19
24
  readonly attributes: RunAttributes;
20
- readonly secrets: SecretContext;
25
+ readonly secretsFor: (attempt: SecretAttempt) => Effect.Effect<SecretContext, Error>;
26
+ readonly secretsForChild: (child: SecretChild) => Effect.Effect<SecretContext, Error>;
21
27
  readonly trace: TraceContext | null;
22
28
  }
23
29
  export interface ExecuteLocalEffectsInput {
@@ -34,17 +34,25 @@ function launcherFor(launcher, runId, context, item, launched) {
34
34
  return {
35
35
  launch: (args) => {
36
36
  const targetRunId = args.runId ?? createRunId();
37
- return launcher
38
- .launch({
37
+ const attributes = args.attributes ?? context.attributes;
38
+ const supplied = args.secrets === undefined
39
+ ? context.secretsForChild({
40
+ runId: targetRunId,
41
+ relation: 'launch',
42
+ kind: args.kind,
43
+ definitionName: args.definitionName,
44
+ attributes,
45
+ })
46
+ : Effect.succeed(args.secrets);
47
+ return supplied.pipe(Effect.flatMap((secrets) => launcher.launch({
39
48
  ...args,
40
49
  runId: targetRunId,
41
50
  launchedBy,
42
51
  correlationId: context.correlationId,
43
- attributes: args.attributes ?? context.attributes,
44
- secrets: args.secrets ?? context.secrets,
52
+ attributes,
53
+ secrets,
45
54
  trace: args.trace ?? context.trace ?? undefined,
46
- })
47
- .pipe(Effect.tap(() => Effect.sync(() => {
55
+ })), Effect.tap(() => Effect.sync(() => {
48
56
  launched.push(createEvent(runId, {
49
57
  type: 'runtime.run.launched',
50
58
  payload: runLaunchedPayload(args, targetRunId, item.effectId),
@@ -96,7 +104,12 @@ export function executeLocalEffects(options, input) {
96
104
  attempt: attemptNumber,
97
105
  now: input.now,
98
106
  attributes: input.context.attributes,
99
- secrets: input.context.secrets,
107
+ secrets: input.context.secretsFor({
108
+ effectId: item.effectId,
109
+ attempt: attemptNumber,
110
+ type: item.effect.type,
111
+ threadId: item.threadId,
112
+ }),
100
113
  trace: input.context.trace,
101
114
  retry,
102
115
  });
@@ -134,7 +147,7 @@ export function executeLocalEffects(options, input) {
134
147
  threadId: item.threadId,
135
148
  causingEventId: item.causingEventId,
136
149
  attributes: input.context.attributes,
137
- secrets: input.context.secrets,
150
+ secrets: admission.secrets,
138
151
  trace: input.context.trace,
139
152
  signal: controller.signal,
140
153
  heartbeat: () => Promise.resolve(),
@@ -1,5 +1,6 @@
1
1
  import { type AnyRuntimeModule, type DebuggerHost, type DefinitionInput, type DefinitionRef, type DefinitionResolver, type EventEnvelope, type EventInput, type BlobStore, type EventStore, type EventStoreTrimCoverage, type JsonValue, type SnapshotStore, type ProjectionDefinition, type HasRequiredAttributes, type ReplayStep, type RunAttributeFields, type RunAttributesOption, type RunLauncher, type RunState } from '@swirls/looms/core';
2
2
  import type { RuntimeObserver } from './observer';
3
+ import type { SecretProvider, SecretSealer } from './run-secrets';
3
4
  import { type EffectWorker, type LoomsRuntime, type RunSignalOptions, type RunOperationalStatus, type StartRunArgs, type WakeScheduler, type WorkerCallbackInput, type WorkerCallbackResult } from './runtime';
4
5
  import { type Authorize, type RunningServer } from './server';
5
6
  export interface CreateLoomsOptions<Fields extends RunAttributeFields = RunAttributeFields> {
@@ -51,6 +52,10 @@ export interface CreateLoomsOptions<Fields extends RunAttributeFields = RunAttri
51
52
  readonly maxInFlightWorkerEffects?: number;
52
53
  /** Failure-isolated runtime observation sink. */
53
54
  readonly observer?: RuntimeObserver;
55
+ /** Decides what a run holds and what each attempt receives. See `CreateRuntimeOptions`. */
56
+ readonly secretProvider?: SecretProvider;
57
+ /** Encrypts what a run holds before it is stored. See `secretSealer`. */
58
+ readonly secretSealer?: SecretSealer;
54
59
  /**
55
60
  * Authorizes HTTP API requests. Without it, run reads and writes are open while worker callback
56
61
  * and operations routes return 503; `bearerAuth({ worker, operations })` enables them.
@@ -125,6 +130,7 @@ export interface Looms<Fields extends RunAttributeFields = RunAttributeFields> {
125
130
  /** Start a new run that continues where a finished run ended. */
126
131
  fork(sourceRunId: string, options?: {
127
132
  runId?: string;
133
+ secrets?: StartRunArgs['secrets'];
128
134
  }): Promise<StartResult>;
129
135
  workerCallback(runId: string, input: WorkerCallbackInput): Promise<WorkerCallbackResult>;
130
136
  fetch(req: Request): Promise<Response | null>;
@@ -57,6 +57,8 @@ export function createLooms(options = {}) {
57
57
  observer: options.observer,
58
58
  definitionResolver: options.definitionResolver,
59
59
  attributes: options.attributes,
60
+ secretProvider: options.secretProvider,
61
+ secretSealer: options.secretSealer,
60
62
  });
61
63
  if (options.rescanTimers !== false) {
62
64
  yield* runtime.rescanTimers.pipe(Effect.provideService(EventStoreTag, store), Effect.tapError(Effect.logError), Effect.ignore);
@@ -38,6 +38,21 @@ export type RuntimeObservation = {
38
38
  readonly effectId: string;
39
39
  readonly attempt: number;
40
40
  readonly detail?: string;
41
+ } | {
42
+ /** An attempt was given secrets. `names` are their names, never their values. */
43
+ readonly type: 'secrets.issued';
44
+ readonly runId: string;
45
+ readonly at: number;
46
+ readonly effectId: string;
47
+ readonly attempt: number;
48
+ readonly names: ReadonlyArray<string>;
49
+ } | {
50
+ /** A secret provider or sealer failed. `detail` is the message of the error it threw. */
51
+ readonly type: 'secrets.failed';
52
+ readonly runId: string;
53
+ readonly at: number;
54
+ readonly step: 'provision' | 'forAttempt' | 'forChild' | 'revoke' | 'seal' | 'open';
55
+ readonly detail?: string;
41
56
  };
42
57
  export interface RuntimeObserver {
43
58
  observe(event: RuntimeObservation): void | Promise<void>;
@@ -0,0 +1,132 @@
1
+ import { Effect } from 'effect';
2
+ import { type EventStore, type RunAttributes, type RunState, type SecretContext } from '@swirls/looms/core';
3
+ import { type RuntimeObserver } from './observer';
4
+ /** The run a secret provider is asked about. Everything here is safe to log. */
5
+ export interface SecretRun {
6
+ readonly runId: string;
7
+ readonly kind: string | null;
8
+ readonly definitionName: string | null;
9
+ readonly definitionVersion: string | null;
10
+ readonly attributes: RunAttributes;
11
+ readonly correlationId: string | null;
12
+ /** The run that launched this one, when an effect did. */
13
+ readonly launchedByRunId: string | null;
14
+ }
15
+ /** One attempt of one effect. */
16
+ export interface SecretAttempt {
17
+ readonly effectId: string;
18
+ readonly attempt: number;
19
+ /** The effect's type, such as `agent.model`. */
20
+ readonly type: string;
21
+ readonly threadId: string;
22
+ }
23
+ /** A run that `run` is about to start. */
24
+ export interface SecretChild {
25
+ readonly runId: string;
26
+ /** `launch`: an effect of `run` started it. `fork`: it continues `run`, which has finished. */
27
+ readonly relation: 'launch' | 'fork';
28
+ readonly kind: string | null;
29
+ readonly definitionName: string | null;
30
+ readonly attributes: RunAttributes;
31
+ }
32
+ /** What one attempt receives, and optionally what the run holds from now on. */
33
+ export interface AttemptSecrets {
34
+ /** What the attempt's handler sees as `ctx.secrets`. */
35
+ readonly secrets: SecretContext;
36
+ /**
37
+ * Replaces what the run holds. Leave it out to keep what is held. Use it to store a credential
38
+ * the provider just fetched or refreshed, so the next attempt does not fetch it again.
39
+ */
40
+ readonly hold?: SecretContext;
41
+ }
42
+ type ProviderResult<A> = A | Promise<A> | Effect.Effect<A, Error>;
43
+ /**
44
+ * Decides what a run holds and what each attempt receives. Every method is optional, and a
45
+ * runtime with no provider holds the secrets a start supplies and hands them to every attempt.
46
+ *
47
+ * Looms stores what the run holds beside the log, never in an event, snapshot, or HTTP response,
48
+ * and deletes it when the run finishes. What an attempt receives is never stored.
49
+ *
50
+ * A method may be called more than once for the same run or attempt (a start is retried, a worker
51
+ * asks twice), so each must be safe to repeat. Errors a method throws are reported to the
52
+ * observer and never written to the log, but keep secret values out of their messages anyway.
53
+ */
54
+ export interface SecretProvider {
55
+ /**
56
+ * What the run holds, decided when it starts. `supplied` is what the start passed as `secrets`.
57
+ * Not called again once the run holds something.
58
+ */
59
+ readonly provision?: (input: {
60
+ readonly run: SecretRun;
61
+ readonly supplied: SecretContext;
62
+ }) => ProviderResult<SecretContext>;
63
+ /**
64
+ * What one attempt receives, decided each time an attempt is about to get its secrets. `held`
65
+ * is what the run holds now. Return the held secrets narrowed to this attempt, and never the
66
+ * held secrets themselves when they are worth more than one attempt. A failure fails the
67
+ * attempt under the effect's retry policy.
68
+ */
69
+ readonly forAttempt?: (input: {
70
+ readonly run: SecretRun;
71
+ readonly held: SecretContext;
72
+ readonly attempt: SecretAttempt;
73
+ }) => ProviderResult<AttemptSecrets>;
74
+ /**
75
+ * What a run started by this one is supplied with, which that run's `provision` then sees.
76
+ * Without this a child run is supplied with nothing unless the launch passes `secrets`.
77
+ */
78
+ readonly forChild?: (input: {
79
+ readonly run: SecretRun;
80
+ readonly held: SecretContext;
81
+ readonly child: SecretChild;
82
+ }) => ProviderResult<SecretContext>;
83
+ /**
84
+ * Called once the run has finished, before Looms deletes what it holds. A failure is reported
85
+ * and the held secrets are deleted regardless, so anything held must also expire by itself.
86
+ */
87
+ readonly revoke?: (input: {
88
+ readonly run: SecretRun;
89
+ readonly held: SecretContext;
90
+ }) => ProviderResult<void>;
91
+ }
92
+ /**
93
+ * Encrypts what a run holds before it is stored. `runId` must be bound into the result, so one
94
+ * run's stored secrets cannot be opened as another's.
95
+ */
96
+ export interface SecretSealer {
97
+ readonly seal: (runId: string, secrets: SecretContext) => Effect.Effect<string, Error>;
98
+ readonly open: (runId: string, sealed: string) => Effect.Effect<SecretContext, Error>;
99
+ }
100
+ export type SecretStep = 'provision' | 'forAttempt' | 'forChild' | 'revoke' | 'seal' | 'open';
101
+ declare const SecretProviderError_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 & {
102
+ readonly _tag: "SecretProviderError";
103
+ } & Readonly<A>;
104
+ /** A secret provider or sealer failed. The message never includes secret values. */
105
+ export declare class SecretProviderError extends SecretProviderError_base<{
106
+ readonly runId: string;
107
+ readonly step: SecretStep;
108
+ readonly message: string;
109
+ readonly cause: unknown;
110
+ }> {
111
+ constructor(runId: string, step: SecretStep, cause: unknown);
112
+ }
113
+ /** The one key a sealed record is stored under. A held secret cannot use this name. */
114
+ export declare const SEALED_SECRETS_KEY = "looms.sealed";
115
+ export interface RunSecretsOptions {
116
+ readonly provider?: SecretProvider;
117
+ readonly sealer?: SecretSealer;
118
+ readonly observer?: RuntimeObserver;
119
+ }
120
+ export interface RunSecrets {
121
+ /** Stores what a new run holds. A retried start changes nothing once the run holds something. */
122
+ readonly provision: (store: EventStore, runId: string, state: RunState, supplied: SecretContext | undefined) => Effect.Effect<void, Error>;
123
+ /** What one attempt receives. Fails when the provider or the store does. */
124
+ readonly forAttempt: (store: EventStore, runId: string, state: RunState, attempt: SecretAttempt) => Effect.Effect<SecretContext, Error>;
125
+ /** What a run started by this one is supplied with. */
126
+ readonly forChild: (store: EventStore, runId: string, state: RunState, child: SecretChild) => Effect.Effect<SecretContext, Error>;
127
+ /** Revokes and deletes what a finished run holds. Never fails. */
128
+ readonly release: (store: EventStore, runId: string, state: RunState) => Effect.Effect<void>;
129
+ }
130
+ export declare function secretRun(runId: string, state: RunState): SecretRun;
131
+ export declare function createRunSecrets(options?: RunSecretsOptions): RunSecrets;
132
+ export {};
@@ -0,0 +1,154 @@
1
+ import { Clock, Data, Effect } from 'effect';
2
+ import { hasEntries, isRunTerminal, sameStringRecord, } from '@swirls/looms/core';
3
+ import { RuntimeExecutionError, SecretContextConflictError } from './errors.js';
4
+ import { notifyObserver } from './observer.js';
5
+ /** A secret provider or sealer failed. The message never includes secret values. */
6
+ export class SecretProviderError extends Data.TaggedError('SecretProviderError') {
7
+ constructor(runId, step, cause) {
8
+ super({ runId, step, cause, message: `Secrets for run "${runId}" failed at ${step}` });
9
+ this.name = 'SecretProviderError';
10
+ }
11
+ }
12
+ /** The one key a sealed record is stored under. A held secret cannot use this name. */
13
+ export const SEALED_SECRETS_KEY = 'looms.sealed';
14
+ const NO_STORE = 'This event store cannot persist a secret context';
15
+ export function secretRun(runId, state) {
16
+ const start = state.startIdentity;
17
+ return {
18
+ runId,
19
+ kind: start?.kind ?? null,
20
+ definitionName: start?.definitionName ?? null,
21
+ definitionVersion: start?.definitionVersion ?? null,
22
+ attributes: state.attributes,
23
+ correlationId: start?.correlationId ?? null,
24
+ launchedByRunId: start?.launchedBy?.runId ?? null,
25
+ };
26
+ }
27
+ function asEffect(result) {
28
+ return Effect.isEffect(result) ? result : Effect.succeed(result);
29
+ }
30
+ function call(runId, step, make) {
31
+ // A provider may throw, reject, or fail an Effect. All three become one error.
32
+ return Effect.tryPromise({
33
+ try: () => Promise.resolve().then(make),
34
+ catch: (cause) => new SecretProviderError(runId, step, cause),
35
+ }).pipe(Effect.flatMap((result) => asEffect(result).pipe(Effect.mapError((cause) => new SecretProviderError(runId, step, cause)))));
36
+ }
37
+ function describe(error) {
38
+ if (!(error instanceof SecretProviderError)) {
39
+ return error.message;
40
+ }
41
+ return error.cause instanceof Error ? error.cause.message : String(error.cause);
42
+ }
43
+ export function createRunSecrets(options = {}) {
44
+ const { provider, sealer } = options;
45
+ const reportFailure = (runId, step, error) => Clock.currentTimeMillis.pipe(Effect.map((at) => notifyObserver(options.observer, {
46
+ type: 'secrets.failed',
47
+ runId,
48
+ at,
49
+ step,
50
+ detail: describe(error),
51
+ })));
52
+ const open = (runId, stored) => {
53
+ const sealed = stored[SEALED_SECRETS_KEY];
54
+ if (sealed === undefined) {
55
+ // Stored before sealing was turned on.
56
+ return Effect.succeed(stored);
57
+ }
58
+ if (!sealer) {
59
+ return Effect.fail(new SecretProviderError(runId, 'open', new Error('The stored secrets are sealed and this runtime has no secretSealer')));
60
+ }
61
+ return sealer
62
+ .open(runId, sealed)
63
+ .pipe(Effect.mapError((cause) => new SecretProviderError(runId, 'open', cause)));
64
+ };
65
+ const held = (store, runId) => store.runSecrets
66
+ ? store.runSecrets.get(runId).pipe(Effect.flatMap((stored) => open(runId, stored)))
67
+ : Effect.succeed({});
68
+ const hold = (store, runId, next) => {
69
+ const stored = store.runSecrets;
70
+ if (!stored) {
71
+ return hasEntries(next) ? Effect.fail(new RuntimeExecutionError(NO_STORE)) : Effect.void;
72
+ }
73
+ if (!hasEntries(next)) {
74
+ return stored.delete(runId);
75
+ }
76
+ if (Object.hasOwn(next, SEALED_SECRETS_KEY)) {
77
+ return Effect.fail(new RuntimeExecutionError(`A secret cannot be named "${SEALED_SECRETS_KEY}"`));
78
+ }
79
+ if (!sealer) {
80
+ return stored.put(runId, next);
81
+ }
82
+ return sealer.seal(runId, next).pipe(Effect.mapError((cause) => new SecretProviderError(runId, 'seal', cause)), Effect.flatMap((sealed) => stored.put(runId, { [SEALED_SECRETS_KEY]: sealed })));
83
+ };
84
+ /** Without a provider that provisions, a run holds what its start supplied, written once. */
85
+ const holdSupplied = (store, runId, current, supplied) => {
86
+ if (supplied === undefined || sameStringRecord(current, supplied)) {
87
+ return Effect.void;
88
+ }
89
+ return hasEntries(current)
90
+ ? Effect.fail(new SecretContextConflictError(runId))
91
+ : hold(store, runId, supplied);
92
+ };
93
+ const provision = (store, runId, state, supplied) => {
94
+ const requested = supplied ?? {};
95
+ // A finished run holds nothing, and a retried start must not put anything back.
96
+ if (isRunTerminal(state)) {
97
+ return Effect.void;
98
+ }
99
+ if (!store.runSecrets && hasEntries(requested)) {
100
+ return Effect.fail(new RuntimeExecutionError(NO_STORE));
101
+ }
102
+ const decide = provider?.provision;
103
+ return held(store, runId).pipe(Effect.flatMap((current) => {
104
+ if (!decide) {
105
+ return holdSupplied(store, runId, current, supplied);
106
+ }
107
+ if (hasEntries(current)) {
108
+ return Effect.void;
109
+ }
110
+ return call(runId, 'provision', () => decide({ run: secretRun(runId, state), supplied: requested })).pipe(Effect.tapError((error) => reportFailure(runId, 'provision', error)), Effect.flatMap((next) => hold(store, runId, next)));
111
+ }));
112
+ };
113
+ const issued = (runId, attempt, secrets) => hasEntries(secrets)
114
+ ? Clock.currentTimeMillis.pipe(Effect.map((at) => notifyObserver(options.observer, {
115
+ type: 'secrets.issued',
116
+ runId,
117
+ at,
118
+ effectId: attempt.effectId,
119
+ attempt: attempt.attempt,
120
+ names: Object.keys(secrets).toSorted(),
121
+ })))
122
+ : Effect.void;
123
+ const forAttempt = (store, runId, state, attempt) => {
124
+ const decide = provider?.forAttempt;
125
+ const current = held(store, runId);
126
+ const decided = decide
127
+ ? current.pipe(Effect.flatMap((holding) => call(runId, 'forAttempt', () => decide({ run: secretRun(runId, state), held: holding, attempt })).pipe(Effect.flatMap((result) => {
128
+ const replace = result.hold !== undefined && !sameStringRecord(result.hold, holding);
129
+ const stored = replace ? hold(store, runId, result.hold ?? {}) : Effect.void;
130
+ return stored.pipe(Effect.as(result.secrets));
131
+ }))))
132
+ : current;
133
+ return decided.pipe(Effect.tap((secrets) => issued(runId, attempt, secrets)), Effect.tapError((error) => reportFailure(runId, 'forAttempt', error)));
134
+ };
135
+ const forChild = (store, runId, state, child) => {
136
+ const decide = provider?.forChild;
137
+ if (!decide) {
138
+ return Effect.succeed({});
139
+ }
140
+ return held(store, runId).pipe(Effect.flatMap((current) => call(runId, 'forChild', () => decide({ run: secretRun(runId, state), held: current, child }))), Effect.tapError((error) => reportFailure(runId, 'forChild', error)));
141
+ };
142
+ const release = (store, runId, state) => {
143
+ const stored = store.runSecrets;
144
+ if (!stored) {
145
+ return Effect.void;
146
+ }
147
+ const decide = provider?.revoke;
148
+ const revoke = (raw) => decide
149
+ ? open(runId, raw).pipe(Effect.flatMap((current) => call(runId, 'revoke', () => decide({ run: secretRun(runId, state), held: current }))), Effect.catch((error) => reportFailure(runId, 'revoke', error)))
150
+ : Effect.void;
151
+ return stored.get(runId).pipe(Effect.flatMap((raw) => hasEntries(raw) ? revoke(raw).pipe(Effect.andThen(stored.delete(runId))) : Effect.void), Effect.catch((error) => reportFailure(runId, 'revoke', error).pipe(Effect.andThen(Effect.logWarning(`[looms] could not delete the secrets held by run ${runId}`)))));
152
+ };
153
+ return { provision, forAttempt, forChild, release };
154
+ }
@@ -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
  },