@swirls/looms 0.6.0 → 0.7.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 (75) hide show
  1. package/CHANGELOG.md +24 -0
  2. package/dist/actor/cell.d.ts +1 -1
  3. package/dist/actor/routing.d.ts +5 -1
  4. package/dist/actor/routing.js +14 -3
  5. package/dist/agent/effects.d.ts +20 -2
  6. package/dist/agent/effects.js +2 -0
  7. package/dist/agent/module.d.ts +540 -504
  8. package/dist/approval/effects.d.ts +36 -27
  9. package/dist/approval/effects.js +1 -0
  10. package/dist/approval/module.d.ts +20 -2
  11. package/dist/client/client.d.ts +38 -10
  12. package/dist/client/client.js +2 -1
  13. package/dist/cloudflare/durable-object.d.ts +1 -1
  14. package/dist/cloudflare/index.d.ts +1 -1
  15. package/dist/cloudflare/index.js +1 -1
  16. package/dist/cloudflare/queue-consumer.d.ts +17 -10
  17. package/dist/cloudflare/queue-consumer.js +63 -27
  18. package/dist/cloudflare/queue-message.d.ts +4 -1
  19. package/dist/cloudflare/queue-message.js +4 -1
  20. package/dist/cloudflare/queue-worker.d.ts +7 -3
  21. package/dist/cloudflare/queue-worker.js +7 -2
  22. package/dist/cloudflare/queues.d.ts +1 -1
  23. package/dist/cloudflare/queues.js +1 -1
  24. package/dist/core/compose.d.ts +2 -1
  25. package/dist/core/compose.js +5 -0
  26. package/dist/core/effects.d.ts +84 -39
  27. package/dist/core/effects.js +29 -8
  28. package/dist/core/fold.js +87 -14
  29. package/dist/core/module-scope.d.ts +22 -8
  30. package/dist/core/module-scope.js +3 -0
  31. package/dist/core/module.d.ts +40 -9
  32. package/dist/core/module.js +25 -6
  33. package/dist/core/protocol.d.ts +12 -1
  34. package/dist/core/protocol.js +12 -0
  35. package/dist/core/published.d.ts +52 -0
  36. package/dist/core/published.js +45 -0
  37. package/dist/core/replay.d.ts +4 -2
  38. package/dist/core/state.d.ts +8 -2
  39. package/dist/core/state.js +2 -0
  40. package/dist/debugger/app/assets/{index-CUO1xyYW.js → index-CMRl_aWQ.js} +2 -2
  41. package/dist/debugger/app/assets/routes-CfXxKG45.js +47 -0
  42. package/dist/debugger/app/index.html +1 -1
  43. package/dist/debugger/events/protocol-summarize.js +2 -0
  44. package/dist/evaluator/effects.d.ts +10 -1
  45. package/dist/evaluator/effects.js +1 -0
  46. package/dist/evaluator/module.d.ts +20 -2
  47. package/dist/runtime/cancellation.js +1 -1
  48. package/dist/runtime/dispatch-effect.d.ts +2 -2
  49. package/dist/runtime/dispatch-effect.js +12 -4
  50. package/dist/runtime/effect-admission.d.ts +45 -0
  51. package/dist/runtime/effect-admission.js +70 -0
  52. package/dist/runtime/helpers.d.ts +6 -1
  53. package/dist/runtime/helpers.js +14 -5
  54. package/dist/runtime/index.d.ts +1 -0
  55. package/dist/runtime/index.js +1 -0
  56. package/dist/runtime/local-effect-executor.js +30 -8
  57. package/dist/runtime/retry-policy.js +6 -1
  58. package/dist/runtime/runtime.js +7 -2
  59. package/dist/runtime/server/routes/definitions.js +8 -1
  60. package/dist/runtime/types.d.ts +20 -5
  61. package/dist/runtime/wake-engine.js +20 -0
  62. package/dist/runtime/worker-callbacks.js +2 -2
  63. package/dist/runtime/worker-effect-dispatch.d.ts +35 -9
  64. package/dist/runtime/worker-effect-dispatch.js +105 -26
  65. package/dist/schedule/effects.d.ts +20 -2
  66. package/dist/schedule/effects.js +2 -0
  67. package/dist/schedule/module.d.ts +40 -4
  68. package/dist/testing/corpus-module.d.ts +2 -2
  69. package/dist/testing/corpus-module.js +27 -19
  70. package/dist/testing/index.js +12 -23
  71. package/dist/workflow/effects.d.ts +20 -2
  72. package/dist/workflow/effects.js +2 -0
  73. package/dist/workflow/module.d.ts +40 -4
  74. package/package.json +1 -1
  75. package/dist/debugger/app/assets/routes-lt_6J025.js +0 -47
@@ -3,7 +3,7 @@ import type { CatalogEvent, EventCatalog } from './catalog';
3
3
  import type { EffectDefinition } from './effects';
4
4
  import type { EventEnvelope } from './envelope';
5
5
  import type { FoldRegistry } from './fold';
6
- import type { AnyRuntimeModule, EffectMiddleware, RuntimeModule, RegisteredDefinition, SignalInterruptRule } from './module';
6
+ import type { AnyRuntimeModule, EffectAdmission, EffectMiddleware, RuntimeModule, RegisteredDefinition, SignalInterruptRule } from './module';
7
7
  import type { ProjectionDefinition } from './projection';
8
8
  import { protocolCatalog } from './protocol';
9
9
  import type { ThreadDefinition } from './thread';
@@ -22,6 +22,7 @@ export interface ComposedRegistry extends FoldRegistry {
22
22
  readonly projections: ReadonlyMap<string, ProjectionDefinition>;
23
23
  readonly catalogs: readonly EventCatalog[];
24
24
  readonly middleware: readonly EffectMiddleware[];
25
+ readonly admission: readonly EffectAdmission[];
25
26
  readonly interruptRules: readonly SignalInterruptRule[];
26
27
  }
27
28
  export declare function composeModules(modules: readonly AnyRuntimeModule[]): ComposedRegistry;
@@ -15,6 +15,7 @@ export function composeModules(modules) {
15
15
  const effects = new Map();
16
16
  const projections = new Map();
17
17
  const middleware = [];
18
+ const admission = [];
18
19
  const interruptRules = [];
19
20
  const catalogs = [protocolCatalog];
20
21
  for (const module of modules) {
@@ -81,6 +82,9 @@ export function composeModules(modules) {
81
82
  if (module.middleware) {
82
83
  middleware.push(...module.middleware);
83
84
  }
85
+ if (module.admission) {
86
+ admission.push(...module.admission);
87
+ }
84
88
  if (module.interruptsOnSignal) {
85
89
  interruptRules.push(module.interruptsOnSignal);
86
90
  }
@@ -101,6 +105,7 @@ export function composeModules(modules) {
101
105
  projections,
102
106
  catalogs,
103
107
  middleware,
108
+ admission,
104
109
  interruptRules,
105
110
  };
106
111
  }
@@ -167,7 +167,8 @@ export declare function deferredUntil(effect: RuntimeEffect): number | undefined
167
167
  export declare const WITHDRAWN_ERROR_PREFIX = "withdrawn:";
168
168
  export declare function withdrawnError(siblingEffectId: string): string;
169
169
  export declare function isWithdrawnError(error: string): boolean;
170
- export interface EffectContext {
170
+ /** Shared identity and credentials for an effect attempt. */
171
+ export interface EffectContextBase {
171
172
  readonly effectId: string;
172
173
  readonly runId: string;
173
174
  readonly threadId: string;
@@ -175,23 +176,43 @@ export interface EffectContext {
175
176
  readonly signal: AbortSignal;
176
177
  /** Labels safe for every reader of the run. */
177
178
  readonly attributes: RunAttributes;
178
- /** Bearer material for this run. Never copy it into an emitted event. */
179
+ /**
180
+ * Bearer material for this run. Never copy it into an emitted event.
181
+ * On a durable worker transport this is loaded before the handler runs (same shape as local).
182
+ */
179
183
  readonly secrets: SecretContext;
180
184
  /** The W3C trace context of the caller that started the run, to parent spans the handler starts. */
181
185
  readonly trace: TraceContext | null;
186
+ }
187
+ /**
188
+ * Context for an effect that runs in the host actor cell (for example a Durable Object).
189
+ * `emit` appends live so subscribers see events as they happen.
190
+ */
191
+ export interface LocalEffectContext extends EffectContextBase {
192
+ readonly placement: 'local';
193
+ /** No-op locally; present so local handlers can call the same progress API as workers. */
194
+ heartbeat(details?: JsonValue): Promise<void>;
195
+ /** Appended to the run log immediately. */
182
196
  emit(event: EventInput): Promise<void>;
183
197
  }
184
- export interface ScopedEffectContext<E extends EventInput = EventInput> {
185
- readonly effectId: string;
186
- readonly runId: string;
187
- readonly threadId: string;
188
- readonly causingEventId: string;
189
- readonly signal: AbortSignal;
190
- readonly attributes: RunAttributes;
191
- readonly secrets: SecretContext;
192
- readonly trace: TraceContext | null;
198
+ /**
199
+ * Context for an effect that runs on an external effect worker (for example a Cloudflare Queue consumer).
200
+ * `emit` is buffered until the attempt completes — not a live stream.
201
+ */
202
+ export interface WorkerEffectContext extends EffectContextBase {
203
+ readonly placement: 'worker';
204
+ /** Extends the heartbeat deadline on the host. */
205
+ heartbeat(details?: JsonValue): Promise<void>;
206
+ /** Buffered until `complete`; subscribers do not see the event until then. */
207
+ emit(event: EventInput): Promise<void>;
208
+ }
209
+ /** Either placement's context. Prefer {@link LocalEffectContext} or {@link WorkerEffectContext}. */
210
+ export type EffectContext = LocalEffectContext | WorkerEffectContext;
211
+ export interface ScopedLocalEffectContext<E extends EventInput = EventInput> extends Omit<LocalEffectContext, 'emit'> {
193
212
  emit(event: E): Promise<void>;
194
213
  }
214
+ /** @deprecated Use {@link ScopedLocalEffectContext}. */
215
+ export type ScopedEffectContext<E extends EventInput = EventInput> = ScopedLocalEffectContext<E>;
195
216
  export type EffectInputSchema = SchemaInput;
196
217
  declare const EffectHandlerError_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 & {
197
218
  readonly _tag: "EffectHandlerError";
@@ -226,47 +247,71 @@ export declare function failEffect(options: EffectFailureOptions): Effect.Effect
226
247
  export declare function readEffectFailure(cause: unknown): EffectFailure | null;
227
248
  export type EffectHandlerResult<R = never, E extends EventInput = EventInput, HandlerError = never> = ReadonlyArray<E> | Promise<ReadonlyArray<E>> | Effect.Effect<ReadonlyArray<E>, HandlerError, R>;
228
249
  declare const effectInputType: unique symbol;
229
- export type EffectExecution = 'local' | 'worker';
230
- export interface EffectDefinition<TInput = JsonValue, R = Context.Service.Any, E extends EventInput = EventInput> {
250
+ declare const effectEventType: unique symbol;
251
+ /** Where an effect attempt runs. Declared with `placement` on `m.effect` / {@link defineEffect}. */
252
+ export type EffectPlacement = 'local' | 'worker';
253
+ /** @deprecated Use {@link EffectPlacement}. */
254
+ export type EffectExecution = EffectPlacement;
255
+ interface EffectDefinitionFields<TInput> {
231
256
  readonly type: string;
232
257
  readonly input?: SchemaInput;
233
258
  readonly retry?: RetryPolicy;
234
- /** Forces where the effect runs. When omitted, the runtime decides from `hasHandler` and the configured worker. */
235
- readonly execution?: EffectExecution;
236
- /** Whether `execute` runs a user handler. Without one, the effect can only complete through a worker. */
237
- readonly hasHandler: boolean;
238
259
  /**
239
260
  * The outcome follows from the input alone, like scheduling from state already folded. Forking
240
261
  * a failed run retries the effect that produced the failure, not a deterministic one passing it on.
241
262
  */
242
263
  readonly deterministic?: boolean;
243
264
  readonly [effectInputType]?: (input: TInput) => TInput;
244
- execute(input: JsonValue, ctx: EffectContext): Effect.Effect<ReadonlyArray<E>, InvalidInputError | EffectHandlerError, R>;
245
265
  }
246
266
  /**
247
- * Define an effect. With `execute`, a run's actor cell runs the handler at
248
- * most once while it is alive; if the cell dies mid-execution, the replacement
249
- * actor may re-run it (at-least-once across failover). Keep handlers
250
- * idempotent when they have external side effects.
267
+ * An effect that runs in the host actor cell. Requires `execute`. Live `emit` / local middleware apply.
268
+ */
269
+ export interface LocalEffectDefinition<TInput = JsonValue, R = Context.Service.Any, E extends EventInput = EventInput> extends EffectDefinitionFields<TInput> {
270
+ readonly placement: 'local';
271
+ execute(input: JsonValue, ctx: LocalEffectContext): Effect.Effect<ReadonlyArray<E>, InvalidInputError | EffectHandlerError, R>;
272
+ }
273
+ /**
274
+ * An effect that only an external effect worker completes. Declare it with `placement: 'worker'`
275
+ * and implement the handler via `workerHandlers` (or an equivalent consumer). The host never runs it.
276
+ */
277
+ export interface WorkerEffectDefinition<TInput = JsonValue, E extends EventInput = EventInput> extends EffectDefinitionFields<TInput> {
278
+ readonly placement: 'worker';
279
+ readonly [effectEventType]?: E;
280
+ }
281
+ /**
282
+ * Either placement's definition. `R` is the host services a local handler needs; worker
283
+ * definitions never run on the host, so they contribute none.
284
+ */
285
+ export type EffectDefinition<TInput = JsonValue, R = Context.Service.Any, E extends EventInput = EventInput> = LocalEffectDefinition<TInput, R, E> | WorkerEffectDefinition<TInput, E>;
286
+ export declare function isLocalEffectDefinition(definition: EffectDefinition): definition is LocalEffectDefinition;
287
+ export declare function isWorkerEffectDefinition(definition: EffectDefinition): definition is WorkerEffectDefinition;
288
+ /**
289
+ * `execute` is required for `placement: 'local'` and rejected for `placement: 'worker'`. A worker
290
+ * handler lives with the worker (`workerHandlers`), so the host bundle never imports its
291
+ * dependencies.
292
+ */
293
+ export type PlacementHandler<P extends EffectPlacement, THandler> = P extends 'local' ? {
294
+ readonly execute: THandler;
295
+ } : {
296
+ readonly execute?: 'Worker effects have no execute; implement the handler with workerHandlers';
297
+ };
298
+ /** The definition type `defineEffect` / `m.effect` return for a given placement. */
299
+ export type PlacedEffectDefinition<P extends EffectPlacement, TInput, R, E extends EventInput> = P extends 'local' ? LocalEffectDefinition<TInput, R, E> : WorkerEffectDefinition<TInput, E>;
300
+ interface EffectDefinitionInput<TPlacement extends EffectPlacement, TSchema> {
301
+ readonly type: string;
302
+ readonly placement: TPlacement;
303
+ readonly input?: TSchema;
304
+ readonly retry?: RetryPolicy;
305
+ readonly deterministic?: boolean;
306
+ }
307
+ /**
308
+ * Low-level effect constructor without a module namespace. Inside a module, prefer the scoped
309
+ * `m.effect` / `scope.effect`, which also checks the type prefix and the catalog.
251
310
  *
252
- * Omit `execute` to declare an effect that only an `EffectWorker` completes.
311
+ * `placement: 'local'` runs `execute` in the host actor cell with live `emit`.
312
+ * `placement: 'worker'` has no `execute`; implement it on the worker with `workerHandlers`.
253
313
  */
254
- export declare function defineEffect<TSchema extends SchemaInput, R = never, E extends EventInput = EventInput, HandlerError = never>(def: {
255
- type: string;
256
- input: TSchema;
257
- retry?: RetryPolicy;
258
- execution?: EffectExecution;
259
- deterministic?: boolean;
260
- execute?: (input: InferDefinedSchema<TSchema>, ctx: EffectContext) => EffectHandlerResult<R, E, HandlerError>;
261
- }): EffectDefinition<InferDefinedSchema<TSchema>, R, E>;
262
- export declare function defineEffect<R = never, E extends EventInput = EventInput, HandlerError = never>(def: {
263
- type: string;
264
- input?: undefined;
265
- retry?: RetryPolicy;
266
- execution?: EffectExecution;
267
- deterministic?: boolean;
268
- execute?: (input: JsonValue, ctx: EffectContext) => EffectHandlerResult<R, E, HandlerError>;
269
- }): EffectDefinition<JsonValue, R, E>;
314
+ export declare function defineEffect<const P extends EffectPlacement, TSchema extends SchemaInput | undefined = undefined, R = never, E extends EventInput = EventInput, HandlerError = never>(def: EffectDefinitionInput<P, TSchema> & PlacementHandler<P, (input: InferDefinedSchema<TSchema>, ctx: LocalEffectContext) => EffectHandlerResult<R, E, HandlerError>>): PlacedEffectDefinition<P, InferDefinedSchema<TSchema>, R, E>;
270
315
  export declare function spawn(args: {
271
316
  childThreadId?: string;
272
317
  kind: string;
@@ -137,6 +137,12 @@ export function readEffectFailure(cause) {
137
137
  }
138
138
  return null;
139
139
  }
140
+ export function isLocalEffectDefinition(definition) {
141
+ return definition.placement === 'local';
142
+ }
143
+ export function isWorkerEffectDefinition(definition) {
144
+ return definition.placement === 'worker';
145
+ }
140
146
  function liftHandlerResult(result) {
141
147
  if (Effect.isEffect(result)) {
142
148
  return result.pipe(Effect.mapError((cause) => new EffectHandlerError(cause)));
@@ -157,27 +163,42 @@ function invokeHandler(handler, input, ctx) {
157
163
  return Effect.fail(new EffectHandlerError(cause));
158
164
  }
159
165
  }
160
- export function defineEffect(def) {
166
+ function defineLocalEffect(def) {
161
167
  const schema = def.input;
162
168
  const handler = def.execute;
163
- const noOutput = [];
164
169
  return {
165
170
  type: def.type,
166
171
  input: schema,
167
172
  retry: def.retry,
168
- execution: def.execution,
169
- hasHandler: handler !== undefined,
173
+ placement: 'local',
170
174
  deterministic: def.deterministic,
171
175
  execute: (raw, ctx) => Effect.gen(function* () {
172
176
  const input = schema ? yield* validateInputEffect(schema, raw) : raw;
173
- if (!handler) {
174
- return noOutput;
175
- }
176
- // invokeHandler turns a synchronous throw into EffectHandlerError.
177
177
  return yield* invokeHandler(handler, input, ctx);
178
178
  }),
179
179
  };
180
180
  }
181
+ function defineWorkerEffect(def) {
182
+ return {
183
+ type: def.type,
184
+ input: def.input,
185
+ retry: def.retry,
186
+ placement: 'worker',
187
+ deterministic: def.deterministic,
188
+ };
189
+ }
190
+ export function defineEffect(def) {
191
+ switch (def.placement) {
192
+ case 'local':
193
+ return defineLocalEffect(def);
194
+ case 'worker':
195
+ return defineWorkerEffect(def);
196
+ default: {
197
+ const exhaustive = def;
198
+ return exhaustive;
199
+ }
200
+ }
201
+ }
181
202
  export function spawn(args) {
182
203
  const childThreadId = args.childThreadId ?? '';
183
204
  return {
package/dist/core/fold.js CHANGED
@@ -7,6 +7,7 @@ import { readAttributes } from './run-context.js';
7
7
  import { completedRunStatus, emptyRunState } from './state.js';
8
8
  import { isTerminalStatus } from './thread.js';
9
9
  import { readStoredTrace } from './trace.js';
10
+ import { asJson, isJsonObject } from './types.js';
10
11
  const decodeWaitCondition = Schema.decodeUnknownOption(WaitConditionSchema);
11
12
  function payloadObject(event) {
12
13
  const payload = event.payload;
@@ -248,6 +249,7 @@ function applyProtocol(state, event, registry) {
248
249
  lastHeartbeatAt: null,
249
250
  heartbeatDetails: priorHeartbeatDetails(state, effectId),
250
251
  lastError: null,
252
+ dispatchTry: 0,
251
253
  },
252
254
  },
253
255
  };
@@ -303,6 +305,38 @@ function applyProtocol(state, event, registry) {
303
305
  : null,
304
306
  heartbeatDetails: nextHeartbeatDetails(state, effectId, event, payload),
305
307
  lastError: readString(payload, 'error') ?? null,
308
+ dispatchTry: sameAttempt ? previous.dispatchTry : 0,
309
+ },
310
+ },
311
+ };
312
+ }
313
+ case 'runtime.effect.dispatch.deferred': {
314
+ const effectId = readString(payload, 'effectId');
315
+ const attempt = payload.attempt;
316
+ const retryAt = payload.retryAt;
317
+ const dispatchTry = payload.try;
318
+ if (!effectId ||
319
+ !Predicate.isNumber(attempt) ||
320
+ !Predicate.isNumber(retryAt) ||
321
+ !Predicate.isNumber(dispatchTry)) {
322
+ return state;
323
+ }
324
+ const previous = state.effectExecutions[effectId];
325
+ return {
326
+ ...state,
327
+ effectExecutions: {
328
+ ...state.effectExecutions,
329
+ [effectId]: {
330
+ effectId,
331
+ attempt,
332
+ status: 'dispatch_wait',
333
+ nextAttemptAt: retryAt,
334
+ deadlineAt: retryAt,
335
+ startedAt: null,
336
+ lastHeartbeatAt: null,
337
+ heartbeatDetails: previous?.heartbeatDetails ?? null,
338
+ lastError: readString(payload, 'error') ?? 'worker dispatch deferred',
339
+ dispatchTry,
306
340
  },
307
341
  },
308
342
  };
@@ -332,6 +366,7 @@ function applyProtocol(state, event, registry) {
332
366
  lastHeartbeatAt: null,
333
367
  heartbeatDetails: priorHeartbeatDetails(state, effectId),
334
368
  lastError: readString(payload, 'error') ?? 'effect failed',
369
+ dispatchTry: 0,
335
370
  },
336
371
  },
337
372
  };
@@ -457,26 +492,63 @@ export function stableEffectId(threadId, effect) {
457
492
  }
458
493
  return undefined;
459
494
  }
460
- function mapEffects(threadId, event, effects, completed, existingForThread) {
495
+ function jsonEquals(left, right) {
496
+ if (left === right) {
497
+ return true;
498
+ }
499
+ if (Array.isArray(left) || Array.isArray(right)) {
500
+ return (Array.isArray(left) &&
501
+ Array.isArray(right) &&
502
+ left.length === right.length &&
503
+ left.every((item, index) => jsonEquals(item, right[index] ?? null)));
504
+ }
505
+ if (!isJsonObject(left) || !isJsonObject(right)) {
506
+ return false;
507
+ }
508
+ const leftKeys = Object.keys(left);
509
+ return (leftKeys.length === Object.keys(right).length &&
510
+ leftKeys.every((key) => key in right && jsonEquals(left[key] ?? null, right[key] ?? null)));
511
+ }
512
+ /**
513
+ * An untagged effect that `runtime.effect.completed` just settled with no outcome. The thread
514
+ * re-emitting the same effect from that very event asks nothing new, so it is not re-issued;
515
+ * any later event for the thread gives it a fresh id again.
516
+ */
517
+ function settledWithoutOutcome(state, event) {
518
+ if (event.type !== 'runtime.effect.completed' || !event.effectId) {
519
+ return undefined;
520
+ }
521
+ const item = state.outstandingEffects.find((candidate) => candidate.effectId === event.effectId);
522
+ return item && stableEffectId(item.threadId, item.effect) === undefined ? item : undefined;
523
+ }
524
+ function mapEffects(threadId, event, effects, completed, existingForThread, settled) {
461
525
  const remainingExisting = [...existingForThread];
462
526
  return effects
463
- .map((effect, index) => {
527
+ .flatMap((effect, index) => {
464
528
  const stableId = stableEffectId(threadId, effect);
465
529
  const matchIndex = remainingExisting.findIndex((item) => stableId === undefined ? item.effect.type === effect.type : item.effectId === stableId);
466
530
  const existing = matchIndex >= 0 ? remainingExisting.splice(matchIndex, 1)[0] : undefined;
531
+ if (existing === undefined &&
532
+ stableId === undefined &&
533
+ settled?.threadId === threadId &&
534
+ jsonEquals(asJson(settled.effect), asJson(effect))) {
535
+ return [];
536
+ }
467
537
  const effectId = stableId ?? existing?.effectId ?? createEffectId(threadId, event.seq, index);
468
- return (existing ?? {
469
- effectId,
470
- threadId,
471
- causingSeq: event.seq,
472
- causingEventId: event.id,
473
- effect,
474
- });
538
+ return [
539
+ existing ?? {
540
+ effectId,
541
+ threadId,
542
+ causingSeq: event.seq,
543
+ causingEventId: event.id,
544
+ effect,
545
+ },
546
+ ];
475
547
  })
476
548
  .filter((item) => !completed.includes(item.effectId));
477
549
  }
478
550
  /** Reconcile a thread's outstanding effects with enabled work from `effects()`. */
479
- function reconcileEffects(state, threadId, event, effects) {
551
+ function reconcileEffects(state, threadId, event, effects, settled) {
480
552
  const record = state.threads[threadId];
481
553
  if (record && isTerminalStatus(record.status)) {
482
554
  return {
@@ -486,14 +558,14 @@ function reconcileEffects(state, threadId, event, effects) {
486
558
  }
487
559
  const completed = state.completedEffectIds ?? [];
488
560
  const existingForThread = state.outstandingEffects.filter((item) => item.threadId === threadId);
489
- const mapped = mapEffects(threadId, event, effects, completed, existingForThread);
561
+ const mapped = mapEffects(threadId, event, effects, completed, existingForThread, settled);
490
562
  const otherThreadEffects = state.outstandingEffects.filter((item) => item.threadId !== threadId);
491
563
  return {
492
564
  ...state,
493
565
  outstandingEffects: [...otherThreadEffects, ...mapped],
494
566
  };
495
567
  }
496
- function deliver(state, event, registry) {
568
+ function deliver(state, event, registry, settled) {
497
569
  const threadId = event.threadId ?? (event.origin.type === 'external' ? state.rootThreadId : null);
498
570
  if (!threadId) {
499
571
  return state;
@@ -517,7 +589,7 @@ function deliver(state, event, registry) {
517
589
  const nextState = definition.step(record.state, event, ctx);
518
590
  const enabled = definition.effects(nextState, ctx);
519
591
  let next = putThread(state, { ...record, state: nextState });
520
- next = reconcileEffects(next, threadId, event, enabled);
592
+ next = reconcileEffects(next, threadId, event, enabled, settled);
521
593
  if (definition.forgetsCompletedEffects) {
522
594
  next = forgetCompletedEffects(next, threadId, enabled);
523
595
  }
@@ -570,6 +642,7 @@ export function foldEvent(state, event, registry) {
570
642
  if (event.runId && next.runId !== event.runId) {
571
643
  next = { ...next, runId: event.runId };
572
644
  }
645
+ const settled = settledWithoutOutcome(next, event);
573
646
  if (event.effectId) {
574
647
  next = completeEffect(next, event.effectId);
575
648
  }
@@ -581,7 +654,7 @@ export function foldEvent(state, event, registry) {
581
654
  }
582
655
  next = applyProtocol(next, event, registry);
583
656
  const effectIdsBeforeDeliver = new Set(next.outstandingEffects.map((item) => item.effectId));
584
- next = deliver(next, event, registry);
657
+ next = deliver(next, event, registry, settled);
585
658
  return failUnhandledEffect(next, event, effectIdsBeforeDeliver);
586
659
  }
587
660
  export function foldRun(events, registry, options) {
@@ -1,10 +1,10 @@
1
1
  import type { Layer } from 'effect';
2
2
  import { type CatalogEntries, type EventCatalog, type EventInputOf, type EventsOfCatalog, type InferPayload } from './catalog';
3
3
  import type { EventsOf, ProtocolEvents } from './compose';
4
- import { type EffectDefinition, type EffectExecution, type EffectHandlerResult, type EmitEffect, type RetryPolicy, type RuntimeEffect, type ScopedEffectContext } from './effects';
4
+ import { type EffectDefinition, type EffectHandlerResult, type EffectPlacement, type EmitEffect, type LocalEffectDefinition, type PlacedEffectDefinition, type PlacementHandler, type RetryPolicy, type RuntimeEffect, type ScopedLocalEffectContext } from './effects';
5
5
  import type { EventEnvelope, EventInput } from './envelope';
6
6
  import type { RunLauncherTag } from './launcher';
7
- import { type AnyRuntimeModule, type DefinitionHost, type EffectMiddleware, type RuntimeModule, type DefinitionRef, type RuntimeModuleDependency, type SignalInterruptRule } from './module';
7
+ import { type AnyRuntimeModule, type DefinitionHost, type EffectAdmission, type EffectMiddleware, type RuntimeModule, type DefinitionRef, type RuntimeModuleDependency, type SignalInterruptRule } from './module';
8
8
  import { type ProjectionDefinition } from './projection';
9
9
  import type { InferDefinedSchema, InferSchemaOutput, SchemaInput } from './schema';
10
10
  import { type StartContext, type ThreadContext, type ThreadDefinition } from './thread';
@@ -20,8 +20,16 @@ export type ScopeUniverse<TEvents extends EventCatalog | undefined, TObserves ex
20
20
  export type EffectRequirementsOf<TEffects> = TEffects extends {
21
21
  readonly [key: string]: EffectDefinition<any, any, any>;
22
22
  } ? Exclude<{
23
- [K in keyof TEffects]: TEffects[K] extends EffectDefinition<any, infer R, any> ? R : never;
23
+ [K in keyof TEffects]: TEffects[K] extends LocalEffectDefinition<any, infer R, any> ? R : never;
24
24
  }[keyof TEffects], RunLauncherTag> : never;
25
+ type EffectEventsOf<T> = T extends EffectDefinition<any, any, infer Ev> ? Ev : never;
26
+ /**
27
+ * Marks each effect whose events fall outside the module's catalogs, such as one built with
28
+ * another module's scope or the unscoped `defineEffect`.
29
+ */
30
+ export type ForeignEffectsCheck<FX, TAllowed> = {
31
+ readonly [K in keyof FX as [EffectEventsOf<FX[K]>] extends [TAllowed] ? never : K]: 'Effect events are outside this module catalog; build it with this module scope';
32
+ };
25
33
  export type ModuleServicesConfig<TR> = [TR] extends [never] ? {
26
34
  readonly services?: () => Layer.Layer<any>;
27
35
  } : {
@@ -63,14 +71,18 @@ export interface ModuleScope<TNamespace extends string, U extends EventEnvelope<
63
71
  readonly initialState: InferSchemaOutput<TShape>;
64
72
  reduce(state: NoInfer<InferSchemaOutput<TShape>>, event: U): InferSchemaOutput<TShape>;
65
73
  }): ProjectionDefinition<InferSchemaOutput<TShape>>;
66
- effect<TSchema extends SchemaInput | undefined = undefined, TInput = InferDefinedSchema<TSchema>, R = never, HandlerError = never>(def: {
74
+ /**
75
+ * Declare an effect for this module. `placement: 'local'` runs `execute` in the host actor cell
76
+ * with live `emit`. `placement: 'worker'` has no `execute`; implement it on the worker with
77
+ * `workerHandlers`. The type must start with the module namespace.
78
+ */
79
+ effect<const P extends EffectPlacement, TSchema extends SchemaInput | undefined = undefined, TInput = InferDefinedSchema<TSchema>, R = never, HandlerError = never>(def: {
67
80
  type: `${TNamespace}.${string}`;
81
+ placement: P;
68
82
  input?: TSchema;
69
83
  retry?: RetryPolicy;
70
- execution?: EffectExecution;
71
84
  deterministic?: boolean;
72
- execute?: (input: TInput, ctx: ScopedEffectContext<EventInputOf<U>>) => EffectHandlerResult<R, EventInputOf<U>, HandlerError>;
73
- }): NoInfer<EffectDefinition<TInput, R, EventInputOf<U>>>;
85
+ } & PlacementHandler<P, (input: TInput, ctx: ScopedLocalEffectContext<EventInputOf<U>>) => EffectHandlerResult<R, EventInputOf<U>, HandlerError>>): NoInfer<PlacedEffectDefinition<P, TInput, R, EventInputOf<U>>>;
74
86
  input<K extends keyof (TEvents extends EventCatalog<any, infer E> ? E : never) & string>(key: K, payload: InferPayload<(TEvents extends EventCatalog<any, infer E> ? E : never)[K]>, meta?: Omit<EventInput, 'type' | 'payload'>): Omit<EventInput, 'type' | 'payload'> & {
75
87
  readonly type: `${TNamespace}.${K}`;
76
88
  readonly payload: InferPayload<(TEvents extends EventCatalog<any, infer E> ? E : never)[K]>;
@@ -92,11 +104,12 @@ export declare function defineModule<const N extends string, E extends EventCata
92
104
  } = {}>(options: Omit<DefineModuleOptions<N, ModuleCatalog<N, E>, O>, 'events'> & {
93
105
  readonly events?: E;
94
106
  }, setup: (scope: ModuleScope<N, ScopeUniverse<ModuleCatalog<N, E>, O>, ModuleCatalog<N, E>, O>) => {
95
- readonly effects?: FX;
107
+ readonly effects?: FX & ForeignEffectsCheck<FX, EventInputOf<ScopeUniverse<ModuleCatalog<N, E>, O>>>;
96
108
  readonly threads?: TH;
97
109
  readonly projections?: PR;
98
110
  readonly definitions?: readonly DefinitionRef[];
99
111
  readonly middleware?: readonly EffectMiddleware[];
112
+ readonly admission?: readonly EffectAdmission[];
100
113
  readonly interruptsOnSignal?: SignalInterruptRule;
101
114
  readonly bindHost?: (host: DefinitionHost) => void;
102
115
  } & ModuleServicesConfig<EffectRequirementsOf<FX>>): RuntimeModule<N, Extract<ModuleCatalog<N, E>, EventCatalog>, FX, TH, PR> & {
@@ -104,3 +117,4 @@ export declare function defineModule<const N extends string, E extends EventCata
104
117
  readonly threads: TH;
105
118
  readonly projections: PR;
106
119
  };
120
+ export {};
@@ -72,6 +72,9 @@ export function defineModule(options, setup) {
72
72
  if (members.middleware) {
73
73
  module.middleware = members.middleware;
74
74
  }
75
+ if (members.admission) {
76
+ module.admission = members.admission;
77
+ }
75
78
  if (members.services) {
76
79
  module.services = members.services;
77
80
  }
@@ -1,25 +1,51 @@
1
- import type { Context, Effect, Layer } from 'effect';
1
+ import { Effect, type Context, type Layer } from 'effect';
2
2
  import type { EventCatalog } from './catalog';
3
3
  import type { DefinitionResolver } from './definition-resolver';
4
- import { type EffectContext, type EffectDefinition, type RuntimeEffect } from './effects';
4
+ import { type EffectDefinition, type LocalEffectContext, type LocalEffectDefinition, type RuntimeEffect } from './effects';
5
5
  import type { EventInput } from './envelope';
6
6
  import type { ProjectionDefinition } from './projection';
7
- import type { InferDefinedSchema, SchemaInput } from './schema';
7
+ import type { RunAttributes, SecretContext } from './run-context';
8
+ import { type InferDefinedSchema, type SchemaInput } from './schema';
8
9
  import type { ThreadDefinition } from './thread';
10
+ import type { TraceContext } from './trace';
9
11
  import type { JsonValue } from './types';
10
12
  export { DEFAULT_DEFINITION_VERSION, definitionKey } from './definition-version';
11
- export type NextEffectHandler = (effect: RuntimeEffect, ctx: EffectContext) => Effect.Effect<ReadonlyArray<EventInput>, Error>;
12
- export type EffectMiddleware = (effect: RuntimeEffect, ctx: EffectContext, next: NextEffectHandler) => Effect.Effect<ReadonlyArray<EventInput>, Error>;
13
+ export type NextEffectHandler = (effect: RuntimeEffect, ctx: LocalEffectContext) => Effect.Effect<ReadonlyArray<EventInput>, Error>;
14
+ export type EffectMiddleware = (effect: RuntimeEffect, ctx: LocalEffectContext, next: NextEffectHandler) => Effect.Effect<ReadonlyArray<EventInput>, Error>;
13
15
  /** Continues the middleware chain for the effect `onEffect` already matched. */
14
16
  export type OnEffectNext = () => Effect.Effect<ReadonlyArray<EventInput>, Error>;
15
17
  /**
16
- * Middleware that runs only for one effect definition. The handler receives the effect's
18
+ * Middleware that runs only for one **local** effect definition. The handler receives the effect's
17
19
  * decoded input type and must call `next()` to continue (or `failEffect` to reject the attempt).
18
20
  *
19
- * Middleware wraps local (in-process) effect dispatch only. Effects routed to an `EffectWorker`
20
- * never see it.
21
+ * Middleware wraps local (in-process) effect dispatch only. Worker-placed effects never see it —
22
+ * pass a {@link LocalEffectDefinition} so that is a type error rather than a silent no-op.
23
+ * Prefer {@link EffectAdmission} / {@link onAdmit} for gates that must apply on both paths.
21
24
  */
22
- export declare function onEffect<TInput>(definition: EffectDefinition<TInput>, handler: (input: TInput, ctx: EffectContext, next: OnEffectNext) => Effect.Effect<ReadonlyArray<EventInput>, Error>): EffectMiddleware;
25
+ export declare function onEffect<TInput>(definition: LocalEffectDefinition<TInput>, handler: (input: TInput, ctx: LocalEffectContext, next: OnEffectNext) => Effect.Effect<ReadonlyArray<EventInput>, Error>): EffectMiddleware;
26
+ /**
27
+ * Identity of an effect attempt before it runs locally or is dispatched to a worker.
28
+ * Admission hooks see this on both paths; they cannot call `emit` or `heartbeat`.
29
+ */
30
+ export interface EffectAdmissionContext {
31
+ readonly effectId: string;
32
+ readonly runId: string;
33
+ readonly threadId: string;
34
+ readonly causingEventId: string;
35
+ readonly attributes: RunAttributes;
36
+ readonly secrets: SecretContext;
37
+ readonly trace: TraceContext | null;
38
+ }
39
+ /**
40
+ * Runs in the host before a local attempt starts and before a worker attempt is queued.
41
+ * Fail with `failEffect` to reject the attempt under the retry policy on either path.
42
+ */
43
+ export type EffectAdmission = (effect: RuntimeEffect, ctx: EffectAdmissionContext) => Effect.Effect<void, Error>;
44
+ /**
45
+ * Admission that runs only for one effect definition (local or worker). Prefer this over
46
+ * middleware when the gate must apply to worker-placed effects as well as local ones.
47
+ */
48
+ export declare function onAdmit<TInput>(definition: EffectDefinition<TInput>, handler: (input: TInput, ctx: EffectAdmissionContext) => Effect.Effect<void, Error>): EffectAdmission;
23
49
  /**
24
50
  * Names the threads whose in-process effects an admitted signal event interrupts, so a running
25
51
  * effect (such as a model call) can stop early. The runtime also interrupts each named thread's
@@ -81,6 +107,11 @@ export interface RuntimeModule<TNamespace extends string = string, TEvents exten
81
107
  readonly definitions?: readonly DefinitionRef[];
82
108
  readonly dependencies?: readonly RuntimeModuleDependency[];
83
109
  readonly middleware?: readonly EffectMiddleware[];
110
+ /**
111
+ * Gates that run in the host before every local attempt and before every worker dispatch.
112
+ * Prefer this over middleware for credits, flags, and tenant checks that must cover worker effects.
113
+ */
114
+ readonly admission?: readonly EffectAdmission[];
84
115
  readonly interruptsOnSignal?: SignalInterruptRule;
85
116
  /** Host-side services this module's effect handlers need (an LLM, a definition lookup, a DB pool). */
86
117
  readonly services?: () => Layer.Layer<TServices>;