@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # @swirls/looms
2
2
 
3
+ ## 0.18.1
4
+
5
+ ### Patch Changes
6
+
7
+ - 14bfc23: A wake that reaches `maxWakeIterations` no longer fails and leaves its run with nothing driving
8
+ it. It starts nothing new, waits for the effects it already started, parks, and asks its
9
+ scheduler to wake the run again at once, as the hosting guide describes. A long agent session
10
+ whose workers kept calling tools could reach the limit inside one wake and then sit idle until
11
+ an unrelated request woke it. `MaxWakeIterationsError` is no longer raised and is deprecated.
12
+
13
+ ## 0.18.0
14
+
15
+ ### Minor Changes
16
+
17
+ - e9f8f73: Decide what a run holds and what each attempt receives with a secret provider. Pass `secretProvider` to `createLooms`, `createRuntime`, an actor host, or the Cloudflare Durable Object. `provision` decides what a run holds when it starts, `forAttempt` decides what one attempt receives and can replace what the run holds, `forChild` decides what a launched or forked run is supplied with, and `revoke` is called when the run finishes. A `forAttempt` failure fails the attempt under its retry policy, and a worker that asks for its secrets is told `unavailable`. The observer is told `secrets.issued` and `secrets.failed`.
18
+
19
+ `secretSealer({ key })` encrypts what a run holds before it is stored. Pass it as `secretSealer`.
20
+
21
+ Breaking changes:
22
+
23
+ - What a run holds is deleted when the run finishes.
24
+ - A run launched from an effect, and a fork, no longer inherit the parent's secrets. Pass `secrets` on the launch or the fork, or return them from `forChild`. To keep the old behavior for launches, use `secretProvider: { forChild: ({ held }) => held }`.
25
+ - `RunSecretStore` needs a `delete` method.
26
+ - `EffectAdmissionContext.secrets` and `ctx.secrets` are the attempt's secrets, which differ from what the run holds when a provider has `forAttempt`.
27
+
3
28
  ## 0.17.0
4
29
 
5
30
  ### Minor Changes
@@ -1,5 +1,5 @@
1
1
  import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type EventStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot, type SnapshotStore } from '@swirls/looms/core';
2
- import { type Authorize, type EffectWorker, type LoomsRuntime, type RunSignalOptions, type StartResult, type StartRunArgs, type WakeScheduler, type RuntimeObserver } from '@swirls/looms/runtime';
2
+ import { type Authorize, type EffectWorker, type LoomsRuntime, type RunSignalOptions, type StartResult, type StartRunArgs, type WakeScheduler, type RuntimeObserver, type SecretProvider, type SecretSealer } from '@swirls/looms/runtime';
3
3
  export interface ActorCellOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
4
4
  readonly runId: string;
5
5
  readonly store: EventStore;
@@ -30,6 +30,10 @@ export interface ActorCellOptions<TModules extends readonly AnyRuntimeModule[] =
30
30
  readonly attributes?: RunAttributeFields;
31
31
  /** Told about wakes, appends, snapshots and effect attempts. See `CreateRuntimeOptions`. */
32
32
  readonly observer?: RuntimeObserver;
33
+ /** Decides what a run holds and what each attempt receives. See `CreateRuntimeOptions`. */
34
+ readonly secretProvider?: SecretProvider;
35
+ /** Encrypts what a run holds before it is stored. See `secretSealer`. */
36
+ readonly secretSealer?: SecretSealer;
33
37
  }
34
38
  export interface ActorCell<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
35
39
  readonly runId: string;
@@ -23,6 +23,8 @@ export function createActorCell(options) {
23
23
  trimAfterSnapshot: options.trimAfterSnapshot,
24
24
  attributes: options.attributes,
25
25
  observer: options.observer,
26
+ secretProvider: options.secretProvider,
27
+ secretSealer: options.secretSealer,
26
28
  });
27
29
  const provide = (effect) => Effect.runPromise(Effect.provideService(effect, EventStoreTag, store));
28
30
  const fetchHandler = createFetchHandler({ runtime, store, authorize: options.authorize });
@@ -1,5 +1,5 @@
1
1
  import type { AnyRuntimeModule, DefinitionResolver, EventInput, EventStore, EventStoreTrimCoverage, RunAttributeFields, RunLauncher, RunState, SnapshotStore } from '@swirls/looms/core';
2
- import { type Authorize, type RunSignalOptions, type StartResult, type StartRunArgs, type RuntimeObserver } from '@swirls/looms/runtime';
2
+ import { type Authorize, type RunSignalOptions, type StartResult, type StartRunArgs, type RuntimeObserver, type SecretProvider, type SecretSealer } from '@swirls/looms/runtime';
3
3
  import { type ActorCell } from './cell';
4
4
  export interface LocalActorHostOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
5
5
  readonly createStore: (runId: string) => EventStore | Promise<EventStore>;
@@ -10,6 +10,10 @@ export interface LocalActorHostOptions<TModules extends readonly AnyRuntimeModul
10
10
  readonly attributes?: RunAttributeFields;
11
11
  /** Told about wakes, appends, snapshots and effect attempts. See `CreateRuntimeOptions`. */
12
12
  readonly observer?: RuntimeObserver;
13
+ /** Decides what a run holds and what each attempt receives. See `CreateRuntimeOptions`. */
14
+ readonly secretProvider?: SecretProvider;
15
+ /** Encrypts what a run holds before it is stored. See `secretSealer`. */
16
+ readonly secretSealer?: SecretSealer;
13
17
  readonly snapshotStore?: SnapshotStore;
14
18
  readonly snapshotEvery?: number;
15
19
  readonly maxWakeIterations?: number;
@@ -61,6 +61,8 @@ export function createLocalActorHost(options) {
61
61
  definitionResolver: options.definitionResolver,
62
62
  attributes: options.attributes,
63
63
  observer: options.observer,
64
+ secretProvider: options.secretProvider,
65
+ secretSealer: options.secretSealer,
64
66
  snapshotStore: options.snapshotStore,
65
67
  snapshotEvery: options.snapshotEvery,
66
68
  maxWakeIterations: options.maxWakeIterations,
@@ -1775,6 +1775,7 @@ export declare function createLoomsClient<const Fields extends RunAttributeField
1775
1775
  /** Start a new run that continues where a finished run ended. */
1776
1776
  fork: (sourceRunId: string, forkOptions?: {
1777
1777
  runId?: string;
1778
+ secrets?: SecretContext;
1778
1779
  }) => Promise<{
1779
1780
  readonly runId: string;
1780
1781
  readonly threadId: string;
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Option, Predicate, Schema, Stream } from 'effect';
2
- import { createRunId, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, EventTypeCatalogSchema, JsonValueSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, SignalCatalogSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
2
+ import { createRunId, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, cleanUndefined, EventTypeCatalogSchema, JsonValueSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, SignalCatalogSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
3
3
  import { consumeSseStreamEffect, eventsFromSseData, sseFrames } from './sse.js';
4
4
  class LoomsClientError extends Data.TaggedError('LoomsClientError') {
5
5
  constructor(message, cause) {
@@ -52,7 +52,13 @@ const WorkerCallbackResultSchema = Schema.Struct({
52
52
  });
53
53
  const WorkerSecretsResultSchema = Schema.Union([
54
54
  Schema.Struct({ status: Schema.Literal('accepted'), secrets: SecretContextSchema }),
55
- Schema.Struct({ status: Schema.Union([Schema.Literal('stale'), Schema.Literal('cancelled')]) }),
55
+ Schema.Struct({
56
+ status: Schema.Union([
57
+ Schema.Literal('stale'),
58
+ Schema.Literal('cancelled'),
59
+ Schema.Literal('unavailable'),
60
+ ]),
61
+ }),
56
62
  ]);
57
63
  /** `appended` counts the events the run gained while the wake ran. */
58
64
  const WakeResultSchema = Schema.Struct({
@@ -197,7 +203,7 @@ export function createLoomsClient(options = {}) {
197
203
  body: stringifyJson(body),
198
204
  });
199
205
  };
200
- /** Read the run's secret context. Only the attempt that is currently running gets it. */
206
+ /** Read the secrets for one attempt. Only the attempt that is currently running gets them. */
201
207
  const workerSecrets = (runId, attempt) => request(`${attemptPath(runId, attempt)}/secrets`, WorkerSecretsResultSchema, {
202
208
  method: 'POST',
203
209
  headers: workerHeaders,
@@ -274,7 +280,7 @@ export function createLoomsClient(options = {}) {
274
280
  /** Start a new run that continues where a finished run ended. */
275
281
  fork: (sourceRunId, forkOptions) => request(`/runs/${encodeURIComponent(sourceRunId)}/fork`, StartResultSchema, {
276
282
  method: 'POST',
277
- body: stringifyJson(forkOptions?.runId === undefined ? {} : { runId: forkOptions.runId }),
283
+ body: stringifyJson(cleanUndefined({ runId: forkOptions?.runId, secrets: forkOptions?.secrets })),
278
284
  }),
279
285
  workerCallback,
280
286
  workerSecrets,
@@ -1,7 +1,7 @@
1
1
  import { DurableObject } from 'cloudflare:workers';
2
2
  import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type BlobStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot } from '@swirls/looms/core';
3
3
  import type { Projector } from '@swirls/looms/projectors';
4
- import { type Authorize, type EffectWorker, type RunSignalOptions, type StartResult, type StartRunArgs, type RuntimeObserver } from '@swirls/looms/runtime';
4
+ import { type Authorize, type EffectWorker, type RunSignalOptions, type StartResult, type StartRunArgs, type RuntimeObserver, type SecretProvider, type SecretSealer } from '@swirls/looms/runtime';
5
5
  import { type DeleteTerminalRunStorageOptions } from './delete-terminal-run-storage';
6
6
  export interface LoomsDurableObjectConfig {
7
7
  readonly modules: readonly AnyRuntimeModule[];
@@ -11,6 +11,10 @@ export interface LoomsDurableObjectConfig {
11
11
  readonly attributes?: RunAttributeFields;
12
12
  /** Told about wakes, appends, snapshots and effect attempts. See `CreateRuntimeOptions`. */
13
13
  readonly observer?: RuntimeObserver;
14
+ /** Decides what a run holds and what each attempt receives. See `CreateRuntimeOptions`. */
15
+ readonly secretProvider?: SecretProvider;
16
+ /** Encrypts what a run holds before it is stored. See `secretSealer`. */
17
+ readonly secretSealer?: SecretSealer;
14
18
  readonly projectors?: readonly Projector[];
15
19
  /** Content-addressed store for event and snapshot JSON over the inline byte limits. */
16
20
  readonly blobs?: BlobStore;
@@ -55,6 +55,8 @@ export class LoomsDurableObject extends DurableObject {
55
55
  definitionResolver: config.definitionResolver,
56
56
  attributes: config.attributes,
57
57
  observer: config.observer,
58
+ secretProvider: config.secretProvider,
59
+ secretSealer: config.secretSealer,
58
60
  snapshotEvery: config.snapshotEvery,
59
61
  maxWakeIterations: config.maxWakeIterations,
60
62
  livenessLeaseMs: config.livenessLeaseMs,
@@ -71,10 +71,18 @@ function runAttempt(task, attempt, handler, cancelRequested, options) {
71
71
  if (result.status === 'accepted') {
72
72
  return Effect.succeed(result.secrets);
73
73
  }
74
+ // The host could not produce the secrets this time. The attempt fails under its retry
75
+ // policy, so a later attempt can ask again.
76
+ if (result.status === 'unavailable') {
77
+ return Effect.fail(new QueueTaskError({ message: 'secrets are unavailable for this attempt' }));
78
+ }
74
79
  controller.abort();
75
- return Effect.fail(new CallbackError({ message: `the attempt is ${result.status}` }));
76
- }));
77
- return taskInput(task, options.blobs).pipe(Effect.flatMap((input) => loadSecrets().pipe(Effect.mapError((error) => new QueueTaskError({ message: error.message, nonRetryable: true })), Effect.flatMap((secrets) => {
80
+ return Effect.fail(new QueueTaskError({
81
+ message: `the attempt is ${result.status}`,
82
+ nonRetryable: true,
83
+ }));
84
+ }), Effect.catchTag('CallbackError', (error) => Effect.fail(new QueueTaskError({ message: error.message, nonRetryable: true }))));
85
+ return taskInput(task, options.blobs).pipe(Effect.flatMap((input) => loadSecrets().pipe(Effect.flatMap((secrets) => {
78
86
  const ctx = {
79
87
  placement: 'worker',
80
88
  effectId: task.effectId,
@@ -177,7 +177,7 @@ export interface EffectContextBase {
177
177
  /** Labels safe for every reader of the run. */
178
178
  readonly attributes: RunAttributes;
179
179
  /**
180
- * Bearer material for this run. Never copy it into an emitted event.
180
+ * Bearer material for this attempt. Never copy it into an emitted event.
181
181
  * On a durable worker transport this is loaded before the handler runs (same shape as local).
182
182
  */
183
183
  readonly secrets: SecretContext;
@@ -37,6 +37,7 @@ export interface EffectAdmissionContext {
37
37
  readonly threadId: string;
38
38
  readonly causingEventId: string;
39
39
  readonly attributes: RunAttributes;
40
+ /** The secrets this attempt will receive. */
40
41
  readonly secrets: SecretContext;
41
42
  readonly trace: TraceContext | null;
42
43
  }
@@ -8,8 +8,9 @@ export type RunAttributes = {
8
8
  readonly [key: string]: string;
9
9
  };
10
10
  /**
11
- * Bearer material for a run, such as an attenuated macaroon.
12
- * It is stored beside the log and is never written to an event, snapshot, or HTTP response.
11
+ * Bearer material, such as an attenuated macaroon. For a run it is stored beside the log, and it
12
+ * is never written to an event, snapshot, or HTTP response. For an attempt it is what the
13
+ * attempt's handler receives as `ctx.secrets`.
13
14
  */
14
15
  export type SecretContext = {
15
16
  readonly [key: string]: string;
@@ -67,7 +68,10 @@ export declare const RunAttributesSchema: Schema.$Record<Schema.String, Schema.S
67
68
  export declare const SecretContextSchema: Schema.$Record<Schema.String, Schema.String>;
68
69
  export interface RunSecretStore {
69
70
  readonly get: (runId: string) => Effect.Effect<SecretContext, Error>;
71
+ /** Replaces what is stored for the run. */
70
72
  readonly put: (runId: string, secrets: SecretContext) => Effect.Effect<void, Error>;
73
+ /** Removes what is stored for the run. Deleting a run that has nothing stored succeeds. */
74
+ readonly delete: (runId: string) => Effect.Effect<void, Error>;
71
75
  }
72
76
  export declare function hasEntries(record: {
73
77
  readonly [key: string]: string;
@@ -265,6 +265,12 @@ function createSqliteSecrets(exec) {
265
265
  },
266
266
  catch: (cause) => new EventStoreError(`Failed to store secret context for ${runId}`, cause),
267
267
  }),
268
+ delete: (runId) => Effect.try({
269
+ try: () => {
270
+ exec.run('DELETE FROM looms_run_secrets WHERE run_id = ?', [runId]);
271
+ },
272
+ catch: (cause) => new EventStoreError(`Failed to delete secret context for ${runId}`, cause),
273
+ }),
268
274
  };
269
275
  }
270
276
  function createSqliteEventStore(exec) {
@@ -122,6 +122,11 @@ export const makeMemoryEventStore = Effect.gen(function* () {
122
122
  const runSecrets = {
123
123
  get: (runId) => Ref.get(secrets).pipe(Effect.map((map) => readSecretContext(map.get(runId) ?? {}))),
124
124
  put: (runId, value) => Ref.update(secrets, (map) => new Map(map).set(runId, value)),
125
+ delete: (runId) => Ref.update(secrets, (map) => {
126
+ const next = new Map(map);
127
+ next.delete(runId);
128
+ return next;
129
+ }),
125
130
  };
126
131
  const getOrCreate = (map, runId) => {
127
132
  const existing = map.get(runId);
@@ -32,10 +32,13 @@ export interface WorkerCallbackResult {
32
32
  readonly status: 'accepted' | 'stale' | 'cancelled';
33
33
  readonly cancelRequested: boolean;
34
34
  }
35
- /** The run's secret context, released only to the attempt that is currently running. */
35
+ /**
36
+ * The secrets for one attempt, released only to the attempt that is currently running.
37
+ * `unavailable` means the host could not produce them this time; the attempt can be retried.
38
+ */
36
39
  export type WorkerSecretsResult = {
37
40
  readonly status: 'accepted';
38
41
  readonly secrets: SecretContext;
39
42
  } | {
40
- readonly status: 'stale' | 'cancelled';
43
+ readonly status: 'stale' | 'cancelled' | 'unavailable';
41
44
  };