@swirls/looms 0.5.2 → 0.6.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 (39) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/agent/definitions.d.ts +0 -12
  3. package/dist/agent/effects.js +0 -24
  4. package/dist/agent/module.d.ts +507 -507
  5. package/dist/agent/projections.d.ts +5 -0
  6. package/dist/agent/projections.js +5 -0
  7. package/dist/approval/effects.d.ts +26 -26
  8. package/dist/client/client.d.ts +2 -0
  9. package/dist/client/client.js +13 -1
  10. package/dist/client/index.d.ts +1 -1
  11. package/dist/client/index.js +1 -1
  12. package/dist/cloudflare/queue-consumer.js +6 -1
  13. package/dist/core/blob-store.js +5 -1
  14. package/dist/core/definition-resolver.d.ts +16 -0
  15. package/dist/core/definition-resolver.js +23 -0
  16. package/dist/core/definition-version.d.ts +3 -0
  17. package/dist/core/definition-version.js +5 -0
  18. package/dist/core/effects.js +1 -1
  19. package/dist/core/module.d.ts +12 -3
  20. package/dist/core/module.js +18 -3
  21. package/dist/debugger/app/assets/{index-C31SnCuN.js → index-CUO1xyYW.js} +2 -2
  22. package/dist/debugger/app/assets/{routes-DPA3O5AF.js → routes-lt_6J025.js} +12 -12
  23. package/dist/debugger/app/index.html +1 -1
  24. package/dist/react/store.d.ts +1 -1
  25. package/dist/react/store.js +2 -1
  26. package/dist/runtime/cancellation.js +21 -0
  27. package/dist/runtime/dispatch-effect.js +4 -1
  28. package/dist/runtime/filesystem-blob-store.js +17 -8
  29. package/dist/runtime/repository.js +2 -1
  30. package/dist/runtime/server/routes/runs.js +6 -11
  31. package/dist/runtime/sse.d.ts +3 -1
  32. package/dist/runtime/sse.js +5 -2
  33. package/dist/runtime/types.d.ts +2 -1
  34. package/dist/runtime/wake-engine.js +16 -11
  35. package/dist/runtime/worker-effect-dispatch.d.ts +3 -1
  36. package/dist/runtime/worker-effect-dispatch.js +14 -5
  37. package/dist/testing/corpus-module.js +11 -2
  38. package/dist/workflow/threads.js +5 -8
  39. 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-C31SnCuN.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-CUO1xyYW.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
9
9
  <link rel="stylesheet" crossorigin href="./assets/index-B7GdT1UA.css">
10
10
  </head>
@@ -1,4 +1,4 @@
1
- import type { SubscriptionSocketConstructor } from '@swirls/looms/client';
1
+ import { type SubscriptionSocketConstructor } from '@swirls/looms/client';
2
2
  import { type AnyEventEnvelope, type EventInput, type ProjectionDefinition, type RegisteredEvent, type SubscriptionTransport } from '@swirls/looms/core';
3
3
  import { type LiveFoldDefinition } from './derived';
4
4
  import { type CoalesceOption } from './notify';
@@ -1,4 +1,5 @@
1
1
  import { Data, Effect, Fiber, Option, Predicate, Schema } from 'effect';
2
+ import { absoluteHttpBase } from '@swirls/looms/client';
2
3
  import { decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
3
4
  import { EventIndex, ProjectionCache } from './derived.js';
4
5
  import { materializeEvents } from './materialize.js';
@@ -276,7 +277,7 @@ export function createLoomsStore(options) {
276
277
  }
277
278
  let url;
278
279
  try {
279
- const http = new URL(liveUrl());
280
+ const http = new URL(liveUrl(), absoluteHttpBase(endpoint));
280
281
  http.protocol = http.protocol === 'https:' ? 'wss:' : 'ws:';
281
282
  url = http.toString();
282
283
  }
@@ -101,6 +101,27 @@ export function createCancellation(options) {
101
101
  idempotencyKey: `signal:child-close:${current.state.rootThreadId ?? runId}`,
102
102
  });
103
103
  }
104
+ // A prior wait-close may have recorded close.requested then failed mid-cancel.
105
+ // Keep cancelling remaining wait children on later cancel attempts.
106
+ const retryChildIds = rootCancel && current.state.childCloseSent
107
+ ? current.state.launchedRuns
108
+ .filter((child) => child.close === 'wait')
109
+ .map((child) => child.runId)
110
+ : [];
111
+ if (retryChildIds.length > 0) {
112
+ return Effect.succeed({
113
+ events: [],
114
+ value: {
115
+ plan: {
116
+ events: [],
117
+ threadIds: new Set(),
118
+ workerCancellations: [],
119
+ },
120
+ now,
121
+ childRunIds: retryChildIds,
122
+ },
123
+ });
124
+ }
104
125
  const plan = planCancellation({
105
126
  runId,
106
127
  seq: current.seq,
@@ -125,7 +125,10 @@ export function dispatchEffect(registry, services, definitions, launcher, effect
125
125
  };
126
126
  if (registry.middleware && registry.middleware.length > 0) {
127
127
  const pipeline = registry.middleware.reduceRight((next, mw) => (e, c) => mw(e, c, next), baseDispatch);
128
- return pipeline(effect, ctx);
128
+ // Middleware may call `failEffect` (or otherwise fail) before `next`. Catch those the same
129
+ // way handler failures are caught inside `baseDispatch`, so a deliberate gate becomes
130
+ // `runtime.effect.failed` instead of failing the wake.
131
+ return pipeline(effect, ctx).pipe(Effect.catch((err) => Effect.succeed([failedAttempt(ctx.effectId, currentThreadId, err)])));
129
132
  }
130
133
  return baseDispatch(effect, ctx);
131
134
  }
@@ -1,4 +1,5 @@
1
- import { mkdir, readdir, readFile, rm, stat, writeFile } from 'node:fs/promises';
1
+ import { mkdir, readdir, readFile, rename, rm, stat, writeFile } from 'node:fs/promises';
2
+ import { join } from 'node:path';
2
3
  import { Data, Effect, Predicate } from 'effect';
3
4
  import { blobStoreFromBytes, BlobStoreError } from '@swirls/looms/core';
4
5
  class MissingBlobFile extends Data.TaggedError('MissingBlobFile') {
@@ -13,13 +14,21 @@ export function filesystemBlobStore(directory) {
13
14
  function filesystemBlobBytes(directory) {
14
15
  return {
15
16
  read: (key) => readOptional(`${directory}/${key}`, key),
16
- write: (key, body) => Effect.tryPromise({
17
- try: () => mkdir(`${directory}/${folderOf(key)}`, { recursive: true }),
18
- catch: (cause) => new BlobStoreError(`Unable to create a directory for blob key ${key}`, cause),
19
- }).pipe(Effect.andThen(Effect.tryPromise({
20
- try: () => writeFile(`${directory}/${key}`, body),
21
- catch: (cause) => new BlobStoreError(`Unable to write blob key ${key}`, cause),
22
- }))),
17
+ write: (key, body) => {
18
+ const folder = `${directory}/${folderOf(key)}`;
19
+ const target = `${directory}/${key}`;
20
+ const temp = join(folder, `.${key.slice(key.lastIndexOf('/') + 1)}.${process.pid}.tmp`);
21
+ return Effect.tryPromise({
22
+ try: () => mkdir(folder, { recursive: true }),
23
+ catch: (cause) => new BlobStoreError(`Unable to create a directory for blob key ${key}`, cause),
24
+ }).pipe(Effect.andThen(Effect.tryPromise({
25
+ try: () => writeFile(temp, body),
26
+ catch: (cause) => new BlobStoreError(`Unable to write blob key ${key}`, cause),
27
+ })), Effect.andThen(Effect.tryPromise({
28
+ try: () => rename(temp, target),
29
+ catch: (cause) => new BlobStoreError(`Unable to finalize blob key ${key}`, cause),
30
+ })));
31
+ },
23
32
  remove: (key) => Effect.tryPromise({
24
33
  try: () => rm(`${directory}/${key}`, { force: true }),
25
34
  catch: (cause) => new BlobStoreError(`Unable to delete blob key ${key}`, cause),
@@ -1,5 +1,5 @@
1
1
  import { Clock, Data, Effect, Option } from 'effect';
2
- import { advanceCursor, assignSequences, createCoalescingAppender, emptyCursor, EventStoreTrimmedError, hashRunState, primePinnedDefinitions, summarizeRun, trimEventStoreSafely, } from '@swirls/looms/core';
2
+ import { advanceCursor, assignSequences, createCoalescingAppender, emptyCursor, EventStoreTrimmedError, hashRunState, primePinnedDefinitions, primePinnedDefinitionsFromState, summarizeRun, trimEventStoreSafely, } from '@swirls/looms/core';
3
3
  import { RuntimeExecutionError } from './errors.js';
4
4
  import { stripSeq } from './helpers.js';
5
5
  import { notifyObserver } from './observer.js';
@@ -129,6 +129,7 @@ export function createRuntimeRepository(options) {
129
129
  seq: snap.value.cursor,
130
130
  durableSinceSnapshot: 0,
131
131
  };
132
+ yield* primePinnedDefinitionsFromState(definitionResolver, snap.value.state);
132
133
  }
133
134
  else {
134
135
  observe({
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema } from 'effect';
2
- import { createRunId, EventStoreTag, JsonValueSchema, RunAttributesSchema, readTraceHeaders, SecretContextSchema, stringifyJson, } from '@swirls/looms/core';
2
+ import { createRunId, EventStoreTag, JsonValueSchema, RunAttributesSchema, readTraceHeaders, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
3
3
  import { createEventStreamResponse } from '../../sse.js';
4
4
  import { acceptsEventStream, EventInputBodySchema, extractIdempotencyKey, provideStore, readIntegerQuery, readJson, readOptionalJson, RequestQueryError, } from '../http.js';
5
5
  import { route } from '../route-table.js';
@@ -35,17 +35,11 @@ function wantsEventStream(req, url) {
35
35
  return live === 'true' || live === '1' || acceptsEventStream(req);
36
36
  }
37
37
  function readEventStreamFromSeq(req, url) {
38
- const lastEventId = req.headers.get('last-event-id');
39
- if (lastEventId !== null && lastEventId.trim() !== '') {
40
- const value = Number(lastEventId);
41
- if (!Number.isSafeInteger(value) || value < 0) {
42
- return Effect.fail(new RequestQueryError({
43
- message: 'Last-Event-ID must be a non-negative integer',
44
- }));
45
- }
46
- return Effect.succeed(value + 1);
38
+ const parsed = subscriptionFromSeq(url, req.headers.get('last-event-id'));
39
+ if (!parsed.ok) {
40
+ return Effect.fail(new RequestQueryError({ message: parsed.message }));
47
41
  }
48
- return readIntegerQuery(url, 'fromSeq', { minimum: 1 }).pipe(Effect.map((fromSeq) => fromSeq ?? 1));
42
+ return Effect.succeed(parsed.fromSeq);
49
43
  }
50
44
  function streamStartRun(req, runtime, store, args) {
51
45
  return createEventStreamResponse({
@@ -161,6 +155,7 @@ export function runRoutes({ runtime, store }) {
161
155
  store,
162
156
  runId: params.runId,
163
157
  fromSeq: yield* readEventStreamFromSeq(req, url),
158
+ filter: subscriptionFilter(url),
164
159
  });
165
160
  }
166
161
  const fromSeq = (yield* readIntegerQuery(url, 'fromSeq', { minimum: 1 })) ?? undefined;
@@ -1,10 +1,12 @@
1
1
  import { Effect } from 'effect';
2
- import { type EventStore } from '@swirls/looms/core';
2
+ import { type EventStore, type SubscriptionFilter } from '@swirls/looms/core';
3
3
  export interface EventStreamOptions {
4
4
  signal: AbortSignal;
5
5
  store: EventStore;
6
6
  runId: string;
7
7
  fromSeq?: number;
8
+ /** When set, only matching events are written to the stream. Defaults to all events. */
9
+ filter?: SubscriptionFilter;
8
10
  heartbeatMs?: number;
9
11
  onStart?: (write: (text: string) => void, close: () => void) => void | Promise<void> | Effect.Effect<void>;
10
12
  request?: Request;
@@ -1,5 +1,5 @@
1
1
  import { Effect, Fiber, Schedule, Stream } from 'effect';
2
- import { encodeLoomsEvent, encodeSubscriptionFrame, } from '@swirls/looms/core';
2
+ import { encodeLoomsEvent, encodeSubscriptionFrame, eventMatchesSubscription, } from '@swirls/looms/core';
3
3
  import { readSubscriptionBounds } from './subscription.js';
4
4
  function disableBunSocketTimeout(request) {
5
5
  if (!request) {
@@ -22,7 +22,7 @@ function disableBunSocketTimeout(request) {
22
22
  * Handles heartbeats, fiber cancellation on disconnect, event encoding, and optional lifecycle hooks.
23
23
  */
24
24
  export function createEventStreamResponse(options) {
25
- const { signal, store, runId, fromSeq = 1, heartbeatMs = 3_000, onStart, request } = options;
25
+ const { signal, store, runId, fromSeq = 1, filter = { threadId: null, includeEphemeral: true }, heartbeatMs = 3_000, onStart, request, } = options;
26
26
  disableBunSocketTimeout(request);
27
27
  let closed = false;
28
28
  let heartbeatFiber;
@@ -86,6 +86,9 @@ export function createEventStreamResponse(options) {
86
86
  tail: bounds.tail,
87
87
  })}\n\n`);
88
88
  yield* store.subscribe(runId, { fromSeq }).pipe(Stream.tap((event) => Effect.sync(() => {
89
+ if (!eventMatchesSubscription(event, filter)) {
90
+ return;
91
+ }
89
92
  write(`id: ${event.seq}\ndata: ${encodeSubscriptionFrame({
90
93
  type: 'batch',
91
94
  batch: [encodeLoomsEvent(event)],
@@ -95,7 +95,8 @@ export interface EffectWorker {
95
95
  * arrived, so the attempt waits for its schedule-to-start timeout or an operator. With
96
96
  * `'acknowledged'` a rejection means the transport refused it, so the attempt fails under the
97
97
  * retry policy. A transport can still lose an accepted message, so every effect such a worker
98
- * claims must set `retry.scheduleToStartTimeoutMs`.
98
+ * claims must set `retry.scheduleToStartTimeoutMs`, and either `startToCloseTimeoutMs` or
99
+ * `heartbeatTimeoutMs` so a lost terminal callback cannot leave the attempt running forever.
99
100
  */
100
101
  readonly dispatchSemantics?: 'unacknowledged' | 'acknowledged';
101
102
  }
@@ -21,17 +21,22 @@ export function createWakeEngine(options) {
21
21
  const closeLaunchedRuns = (store, runId, cursor) => Effect.gen(function* () {
22
22
  let next = cursor;
23
23
  const state = next.state;
24
- if (isRunTerminal(state) && !state.childCloseSent && state.launchedRuns.length > 0) {
25
- const requested = createEvent(runId, {
26
- type: 'runtime.child.close.requested',
27
- payload: { policy: 'terminate' },
28
- threadId: state.rootThreadId,
29
- origin: { type: 'system' },
30
- idempotencyKey: `child-close:${runId}`,
31
- });
32
- const appended = yield* appendObserved(store, runId, stripSeq([requested]));
33
- next = yield* applyAppend(store, runId, next, stripSeq([requested]), appended);
34
- yield* Effect.forEach(state.launchedRuns, (child) => options.launcher().cancel(child.runId), {
24
+ if (isRunTerminal(state) && state.launchedRuns.length > 0) {
25
+ // Record close.requested once so closeWaiting / terminate policy is durable, then cancel
26
+ // every remaining child. Retries keep cancelling while launchedRuns is non-empty even after
27
+ // childCloseSent, so a partial cancel failure cannot orphan the rest.
28
+ if (!state.childCloseSent) {
29
+ const requested = createEvent(runId, {
30
+ type: 'runtime.child.close.requested',
31
+ payload: { policy: 'terminate' },
32
+ threadId: state.rootThreadId,
33
+ origin: { type: 'system' },
34
+ idempotencyKey: `child-close:${runId}`,
35
+ });
36
+ const appended = yield* appendObserved(store, runId, stripSeq([requested]));
37
+ next = yield* applyAppend(store, runId, next, stripSeq([requested]), appended);
38
+ }
39
+ yield* Effect.forEach(next.state.launchedRuns, (child) => options.launcher().cancel(child.runId), {
35
40
  concurrency: 1,
36
41
  discard: true,
37
42
  });
@@ -40,6 +40,8 @@ export declare function planWorkerEffects(input: {
40
40
  export declare function dispatchWorkerEffect(runId: string, plan: WorkerEffectDispatchPlan, worker: EffectWorker | undefined, now: number): Effect.Effect<EventEnvelope>;
41
41
  /**
42
42
  * An acknowledged transport can lose a message it accepted, for example to a dead-letter queue.
43
- * Only a schedule-to-start timeout notices, so every effect such a worker claims needs one.
43
+ * schedule-to-start covers a message that never starts. After `started` is acked, only
44
+ * start-to-close or a heartbeat timeout notices a lost terminal callback, so every claimed
45
+ * effect needs one of those as well.
44
46
  */
45
47
  export declare function assertWorkerDeadlines(registry: ComposedRegistry, worker: EffectWorker | undefined): void;
@@ -167,17 +167,26 @@ export function dispatchWorkerEffect(runId, plan, worker, now) {
167
167
  }
168
168
  /**
169
169
  * An acknowledged transport can lose a message it accepted, for example to a dead-letter queue.
170
- * Only a schedule-to-start timeout notices, so every effect such a worker claims needs one.
170
+ * schedule-to-start covers a message that never starts. After `started` is acked, only
171
+ * start-to-close or a heartbeat timeout notices a lost terminal callback, so every claimed
172
+ * effect needs one of those as well.
171
173
  */
172
174
  export function assertWorkerDeadlines(registry, worker) {
173
175
  if (worker?.dispatchSemantics !== 'acknowledged') {
174
176
  return;
175
177
  }
176
- const missing = [...registry.effects.values()]
177
- .filter((definition) => claimsType(worker, definition) && !definition.retry?.scheduleToStartTimeoutMs)
178
+ const claimed = [...registry.effects.values()].filter((definition) => claimsType(worker, definition));
179
+ const missingStart = claimed
180
+ .filter((definition) => !definition.retry?.scheduleToStartTimeoutMs)
178
181
  .map((definition) => definition.type);
179
- if (missing.length > 0) {
180
- throw new Error(`An acknowledged worker claims effects without retry.scheduleToStartTimeoutMs: ${missing.join(', ')}`);
182
+ if (missingStart.length > 0) {
183
+ throw new Error(`An acknowledged worker claims effects without retry.scheduleToStartTimeoutMs: ${missingStart.join(', ')}`);
184
+ }
185
+ const missingClose = claimed
186
+ .filter((definition) => !definition.retry?.startToCloseTimeoutMs && !definition.retry?.heartbeatTimeoutMs)
187
+ .map((definition) => definition.type);
188
+ if (missingClose.length > 0) {
189
+ throw new Error(`An acknowledged worker claims effects without retry.startToCloseTimeoutMs or retry.heartbeatTimeoutMs: ${missingClose.join(', ')}`);
181
190
  }
182
191
  }
183
192
  function claimsType(worker, definition) {
@@ -19,12 +19,21 @@ const decodeCheckoutInput = Schema.decodeUnknownOption(CheckoutInputSchema);
19
19
  export function corpusModule(options) {
20
20
  const charge = defineEffect({
21
21
  type: corpusChargeV1,
22
- retry: { maxAttempts: 3, backoffMs: 1, scheduleToStartTimeoutMs: 60_000 },
22
+ retry: {
23
+ maxAttempts: 3,
24
+ backoffMs: 1,
25
+ scheduleToStartTimeoutMs: 60_000,
26
+ startToCloseTimeoutMs: 60_000,
27
+ },
23
28
  execute: options?.charge,
24
29
  });
25
30
  const chargeV2 = defineEffect({
26
31
  type: corpusChargeV2,
27
- retry: { maxAttempts: 1, scheduleToStartTimeoutMs: 60_000 },
32
+ retry: {
33
+ maxAttempts: 1,
34
+ scheduleToStartTimeoutMs: 60_000,
35
+ startToCloseTimeoutMs: 60_000,
36
+ },
28
37
  execute: options?.charge,
29
38
  });
30
39
  return defineRuntimeModule({
@@ -218,23 +218,20 @@ function unsettledChildren(state, nodeId, threadId, runId) {
218
218
  }
219
219
  /**
220
220
  * Drops a node's pending work and cancels the children it leaves running. `settled` is the child
221
- * whose result is finishing the node, which must not be cancelled. A `wait` child run stays
222
- * pending until it settles, so the node does not finish ahead of that cancellation.
221
+ * whose result is finishing the node, which must not be cancelled. Wait-policy child runs are
222
+ * cancelled here too; run-level `childClose: 'wait'` is enforced by the runtime's launched-run
223
+ * bookkeeping, not by leaving stale entries in workflow pending state.
223
224
  */
224
225
  function withoutPendingWork(state, nodeId, threadId, runId, settled = null) {
225
226
  const children = unsettledChildren(state, nodeId, threadId, runId);
226
227
  const cancels = children
227
228
  .map((child) => child.target)
228
229
  .filter((target) => target !== settled && !state.pendingCancels.includes(target));
229
- const keptSpawns = new Set(children
230
- .filter((child) => child.execution === 'run' && child.close === 'wait' && child.target !== settled)
231
- .map((child) => child.key));
232
- const keepMap = children.some((child) => child.execution === 'run' && child.close === 'wait' && child.target !== settled);
233
230
  return {
234
231
  ...state,
235
232
  pendingCancels: cancels.length === 0 ? state.pendingCancels : [...state.pendingCancels, ...cancels],
236
- pendingSpawns: state.pendingSpawns.filter((item) => item.nodeId !== nodeId || keptSpawns.has(item.childThreadId)),
237
- pendingMaps: state.pendingMaps.filter((item) => item.nodeId !== nodeId || keepMap),
233
+ pendingSpawns: state.pendingSpawns.filter((item) => item.nodeId !== nodeId),
234
+ pendingMaps: state.pendingMaps.filter((item) => item.nodeId !== nodeId),
238
235
  pendingSleeps: state.pendingSleeps.filter((item) => item.nodeId !== nodeId),
239
236
  pendingEffects: state.pendingEffects.filter((item) => item.nodeId !== nodeId),
240
237
  };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@swirls/looms",
3
- "version": "0.5.2",
3
+ "version": "0.6.0",
4
4
  "description": "Pluggable event-sourced runtime for durable agents and workflows",
5
5
  "homepage": "https://github.com/ByteSliceHQ/looms#readme",
6
6
  "bugs": {