@swirls/looms 0.25.0 → 0.26.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 (85) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/dist/actor/cell.d.ts +3 -1
  3. package/dist/actor/cell.js +1 -0
  4. package/dist/actor/host.d.ts +3 -1
  5. package/dist/actor/host.js +2 -1
  6. package/dist/actor/routing.d.ts +6 -3
  7. package/dist/actor/routing.js +6 -4
  8. package/dist/agent/agent-session.js +2 -2
  9. package/dist/agent/debugger/agent-chat.js +4 -3
  10. package/dist/agent/definitions.d.ts +3 -1
  11. package/dist/agent/effects.js +5 -3
  12. package/dist/agent/module.d.ts +730 -730
  13. package/dist/approval/steps.d.ts +3 -1
  14. package/dist/approval/steps.js +2 -2
  15. package/dist/client/client.d.ts +7 -1
  16. package/dist/client/client.js +5 -2
  17. package/dist/cloudflare/durable-object.d.ts +3 -1
  18. package/dist/cloudflare/durable-object.js +1 -0
  19. package/dist/cloudflare/queue-consumer.d.ts +3 -1
  20. package/dist/cloudflare/queue-consumer.js +2 -1
  21. package/dist/cloudflare/router.d.ts +3 -1
  22. package/dist/cloudflare/router.js +1 -1
  23. package/dist/core/compose.d.ts +8 -2
  24. package/dist/core/compose.js +6 -3
  25. package/dist/core/effects.d.ts +3 -0
  26. package/dist/core/envelope.d.ts +2 -0
  27. package/dist/core/envelope.js +2 -2
  28. package/dist/core/event-codec.d.ts +4 -3
  29. package/dist/core/event-codec.js +7 -7
  30. package/dist/core/fold.d.ts +3 -0
  31. package/dist/core/fold.js +3 -1
  32. package/dist/core/fork.js +1 -1
  33. package/dist/core/ids.d.ts +70 -5
  34. package/dist/core/ids.js +164 -41
  35. package/dist/core/snapshots.d.ts +2 -0
  36. package/dist/core/snapshots.js +2 -1
  37. package/dist/core/thread.d.ts +8 -0
  38. package/dist/debugger/app/assets/{index-GLtrulmj.js → index-D_FKxPrN.js} +2 -2
  39. package/dist/debugger/app/assets/routes-CkwzFejg.js +47 -0
  40. package/dist/debugger/app/index.html +1 -1
  41. package/dist/debugger/context.d.ts +4 -1
  42. package/dist/debugger/context.js +4 -4
  43. package/dist/debugger/shell/debugger-shell.d.ts +4 -1
  44. package/dist/debugger/shell/debugger-shell.js +2 -2
  45. package/dist/debugger/shell/use-start-run.d.ts +1 -1
  46. package/dist/debugger/shell/use-start-run.js +1 -2
  47. package/dist/evaluator/effects.d.ts +33 -33
  48. package/dist/evaluator/module.d.ts +66 -66
  49. package/dist/evaluator/steps.d.ts +2 -2
  50. package/dist/evaluator/steps.js +3 -3
  51. package/dist/react/react.d.ts +8 -3
  52. package/dist/react/react.js +15 -2
  53. package/dist/react/store.d.ts +5 -1
  54. package/dist/react/store.js +5 -4
  55. package/dist/runtime/cancellation.js +5 -5
  56. package/dist/runtime/deadline-transition-planner.d.ts +1 -0
  57. package/dist/runtime/deadline-transition-planner.js +8 -7
  58. package/dist/runtime/effect-admission.js +1 -0
  59. package/dist/runtime/helpers.d.ts +6 -5
  60. package/dist/runtime/helpers.js +8 -8
  61. package/dist/runtime/local-effect-executor.js +15 -10
  62. package/dist/runtime/looms.d.ts +6 -1
  63. package/dist/runtime/looms.js +4 -1
  64. package/dist/runtime/retry-policy.d.ts +2 -1
  65. package/dist/runtime/retry-policy.js +2 -1
  66. package/dist/runtime/runtime.js +10 -10
  67. package/dist/runtime/server/routes/runs.js +5 -5
  68. package/dist/runtime/types.d.ts +7 -1
  69. package/dist/runtime/wake-engine.js +10 -9
  70. package/dist/runtime/worker-callbacks.js +9 -8
  71. package/dist/runtime/worker-effect-dispatch.d.ts +3 -2
  72. package/dist/runtime/worker-effect-dispatch.js +7 -5
  73. package/dist/schedule/module.d.ts +36 -36
  74. package/dist/swarm/steps.d.ts +3 -3
  75. package/dist/swarm/steps.js +5 -5
  76. package/dist/swarm/tools.d.ts +3 -2
  77. package/dist/swarm/tools.js +13 -13
  78. package/dist/workflow/effects.js +6 -5
  79. package/dist/workflow/graph.d.ts +3 -3
  80. package/dist/workflow/graph.js +5 -5
  81. package/dist/workflow/module.d.ts +8 -2
  82. package/dist/workflow/threads.d.ts +14 -2
  83. package/dist/workflow/threads.js +54 -44
  84. package/package.json +1 -1
  85. package/dist/debugger/app/assets/routes-CECZJJob.js +0 -47
@@ -1,5 +1,5 @@
1
1
  import { Effect, Layer, type Context, type Types } from 'effect';
2
- import { type AnyRuntimeModule, type AppendableEvent, type EventCatalog, type EventEnvelope, type EventInput, type EventOrigin, type EventStore, InvalidEventError, type DefinitionResolveError, type DefinitionResolver, type JsonValue, type OutstandingEffect, type RetryPolicy, type SecretContext, type TraceContext, type RunCursor, type RunState, type SnapshotStore } from '@swirls/looms/core';
2
+ import { type AnyRuntimeModule, type AppendableEvent, type EventEnvelope, type EventInput, type EventOrigin, type EventStore, InvalidEventError, type DefinitionResolveError, type DefinitionResolver, type JsonValue, type OutstandingEffect, type RetryPolicy, type SecretContext, type TraceContext, type RunCursor, type RunState, type SnapshotStore, type LoomsIds, type ComposedRegistry } from '@swirls/looms/core';
3
3
  import type { EffectWorkerTask } from './types';
4
4
  /** What a dispatch carries beyond the effect itself. */
5
5
  export interface WorkerTaskExtras {
@@ -62,10 +62,11 @@ export declare function createEffectFailedEvent(runId: string, item: {
62
62
  effectId: string;
63
63
  causingEventId: string;
64
64
  threadId: string;
65
- }, error: string, options?: {
65
+ }, error: string, options: {
66
66
  readonly nonRetryable?: boolean;
67
+ readonly ids: LoomsIds;
67
68
  }): EventEnvelope;
68
- export declare function materializeEffectOutcome(catalogs: readonly EventCatalog[], runId: string, item: {
69
+ export declare function materializeEffectOutcome({ catalogs, ids }: Pick<ComposedRegistry, 'catalogs' | 'ids'>, runId: string, item: {
69
70
  effectId: string;
70
71
  causingEventId: string;
71
72
  threadId: string;
@@ -74,13 +75,13 @@ export declare function createLiveEvent(runId: string, item: {
74
75
  effectId: string;
75
76
  causingEventId: string;
76
77
  threadId: string;
77
- }, validated: EventInput): AppendableEvent | undefined;
78
+ }, validated: EventInput, ids: LoomsIds): AppendableEvent | undefined;
78
79
  /**
79
80
  * Admit events from an external caller. Runtime protocol events are reserved for the runtime
80
81
  * itself, and external events can never claim an effect outcome or a non-external origin.
81
82
  */
82
83
  export declare function admitExternalEvents(events: readonly EventInput[]): Effect.Effect<EventInput[], InvalidEventError>;
83
- export declare function validateAndCreateEvents(catalogs: readonly EventCatalog[], runId: string, events: readonly EventInput[], defaults: {
84
+ export declare function validateAndCreateEvents({ catalogs, ids }: Pick<ComposedRegistry, 'catalogs' | 'ids'>, runId: string, events: readonly EventInput[], defaults: {
84
85
  origin: EventOrigin;
85
86
  threadId?: string | null;
86
87
  }): Effect.Effect<EventEnvelope[], InvalidEventError>;
@@ -271,7 +271,7 @@ export function waitSatisfiedEvents(state, events) {
271
271
  }
272
272
  return produced;
273
273
  }
274
- export function createEffectFailedEvent(runId, item, error, options = {}) {
274
+ export function createEffectFailedEvent(runId, item, error, options) {
275
275
  const payload = {
276
276
  effectId: item.effectId,
277
277
  error,
@@ -286,9 +286,9 @@ export function createEffectFailedEvent(runId, item, error, options = {}) {
286
286
  effectId: item.effectId,
287
287
  causationId: item.causingEventId,
288
288
  origin: { type: 'system' },
289
- });
289
+ }, { ids: options.ids });
290
290
  }
291
- export function materializeEffectOutcome(catalogs, runId, item, input) {
291
+ export function materializeEffectOutcome({ catalogs, ids }, runId, item, input) {
292
292
  return validateEventInput(catalogs, input).pipe(Effect.map((validated) => createEvent(runId, {
293
293
  ...validated,
294
294
  effectId: validated.effectId ?? item.effectId,
@@ -297,9 +297,9 @@ export function materializeEffectOutcome(catalogs, runId, item, input) {
297
297
  origin: validated.origin ?? { type: 'thread', threadId: item.threadId },
298
298
  id: validated.id,
299
299
  ts: validated.ts,
300
- })), Effect.catchTag('InvalidEventError', (err) => Effect.succeed(createEffectFailedEvent(runId, item, err.message))));
300
+ }, { ids })), Effect.catchTag('InvalidEventError', (err) => Effect.succeed(createEffectFailedEvent(runId, item, err.message, { ids }))));
301
301
  }
302
- export function createLiveEvent(runId, item, validated) {
302
+ export function createLiveEvent(runId, item, validated, ids) {
303
303
  const targetThreadId = validated.threadId ?? item.threadId;
304
304
  const ephemeral = createEvent(runId, {
305
305
  ...validated,
@@ -308,7 +308,7 @@ export function createLiveEvent(runId, item, validated) {
308
308
  threadId: targetThreadId,
309
309
  ephemeral: true,
310
310
  origin: validated.origin ?? { type: 'thread', threadId: item.threadId },
311
- });
311
+ }, { ids });
312
312
  const [liveEvent] = stripSeq([ephemeral]);
313
313
  return liveEvent;
314
314
  }
@@ -329,10 +329,10 @@ export function admitExternalEvents(events) {
329
329
  origin: input.origin?.type === 'external' ? input.origin : { type: 'external' },
330
330
  }));
331
331
  }
332
- export function validateAndCreateEvents(catalogs, runId, events, defaults) {
332
+ export function validateAndCreateEvents({ catalogs, ids }, runId, events, defaults) {
333
333
  return validateEventsEffect(catalogs, events).pipe(Effect.map((validated) => validated.map((input) => createEvent(runId, {
334
334
  ...input,
335
335
  threadId: input.threadId !== undefined ? input.threadId : (defaults.threadId ?? null),
336
336
  origin: input.origin ?? defaults.origin,
337
- }))));
337
+ }, { ids }))));
338
338
  }
@@ -1,5 +1,5 @@
1
1
  import { Effect, Option, Predicate } from 'effect';
2
- import { createEvent, createRunId, DEFAULT_DEFINITION_VERSION, validateEventInput, withdrawnError, } from '@swirls/looms/core';
2
+ import { createEvent, DEFAULT_DEFINITION_VERSION, validateEventInput, withdrawnError, } from '@swirls/looms/core';
3
3
  import { dispatchEffect } from './dispatch-effect.js';
4
4
  import { admitOrFailAttempt } from './effect-admission.js';
5
5
  import { RuntimeExecutionError } from './errors.js';
@@ -23,7 +23,7 @@ function runLaunchedPayload(args, targetRunId, effectId) {
23
23
  * Stamps every launch with the effect that made it, replacing anything the handler passed, and
24
24
  * records a `runtime.run.launched` event for each launch the target accepts.
25
25
  */
26
- function launcherFor(launcher, runId, context, item, launched) {
26
+ function launcherFor(launcher, runId, context, item, launched, ids) {
27
27
  const launchedBy = {
28
28
  runId,
29
29
  threadId: item.threadId,
@@ -33,7 +33,7 @@ function launcherFor(launcher, runId, context, item, launched) {
33
33
  };
34
34
  return {
35
35
  launch: (args) => {
36
- const targetRunId = args.runId ?? createRunId();
36
+ const targetRunId = args.runId ?? ids.create('run');
37
37
  const attributes = args.attributes ?? context.attributes;
38
38
  const supplied = args.secrets === undefined
39
39
  ? context.secretsForChild({
@@ -60,7 +60,7 @@ function launcherFor(launcher, runId, context, item, launched) {
60
60
  causationId: item.causingEventId,
61
61
  correlationId: context.correlationId,
62
62
  origin: { type: 'thread', threadId: item.threadId },
63
- }));
63
+ }, { ids }));
64
64
  })));
65
65
  },
66
66
  status: launcher.status,
@@ -91,7 +91,9 @@ export function executeLocalEffects(options, input) {
91
91
  let failedEffectId;
92
92
  for (const item of group) {
93
93
  if (failedEffectId && item.effect.type === 'runtime.wait') {
94
- produced.push(createEffectFailedEvent(input.runId, item, withdrawnError(failedEffectId)));
94
+ produced.push(createEffectFailedEvent(input.runId, item, withdrawnError(failedEffectId), {
95
+ ids: registry.ids,
96
+ }));
95
97
  continue;
96
98
  }
97
99
  const retry = registry.effects.get(item.effect.type)?.retry;
@@ -131,7 +133,7 @@ export function executeLocalEffects(options, input) {
131
133
  ? Promise.resolve()
132
134
  : runInContext(Effect.gen(function* () {
133
135
  const validated = yield* validateEventInput(registry.catalogs, eventInput);
134
- const liveEvent = createLiveEvent(input.runId, item, validated);
136
+ const liveEvent = createLiveEvent(input.runId, item, validated, registry.ids);
135
137
  if (liveEvent) {
136
138
  yield* liveAppends.push(input.runId, liveEvent);
137
139
  }
@@ -140,7 +142,7 @@ export function executeLocalEffects(options, input) {
140
142
  controller,
141
143
  threadId: item.threadId,
142
144
  });
143
- const dispatched = dispatchEffect(registry, services, definitionResolver, launcherFor(launcher, input.runId, input.context, item, launched), item.effect, {
145
+ const dispatched = dispatchEffect(registry, services, definitionResolver, launcherFor(launcher, input.runId, input.context, item, launched, registry.ids), item.effect, {
144
146
  placement: 'local',
145
147
  effectId: item.effectId,
146
148
  runId: input.runId,
@@ -150,6 +152,7 @@ export function executeLocalEffects(options, input) {
150
152
  secrets: admission.secrets,
151
153
  trace: input.context.trace,
152
154
  signal: controller.signal,
155
+ ids: registry.ids,
153
156
  heartbeat: () => Promise.resolve(),
154
157
  emit: appendLive,
155
158
  }).pipe(Effect.map((outcomes) => ({ _tag: 'completed', outcomes })), Effect.raceFirst(abortion(controller.signal)));
@@ -185,7 +188,8 @@ export function executeLocalEffects(options, input) {
185
188
  threadId: item.threadId,
186
189
  causationId: item.causingEventId,
187
190
  origin: { type: 'system' },
188
- }), planAttemptFailure({
191
+ }, { ids: registry.ids }), planAttemptFailure({
192
+ ids: registry.ids,
189
193
  runId: input.runId,
190
194
  item,
191
195
  attempt: attemptNumber,
@@ -211,7 +215,7 @@ export function executeLocalEffects(options, input) {
211
215
  effectId: item.effectId,
212
216
  causationId: item.causingEventId,
213
217
  origin: { type: 'system' },
214
- }));
218
+ }, { ids: registry.ids }));
215
219
  }
216
220
  for (const outcome of outcomes) {
217
221
  if (outcome.type === 'runtime.effect.failed') {
@@ -220,6 +224,7 @@ export function executeLocalEffects(options, input) {
220
224
  const error = Predicate.isString(payload.error) ? payload.error : 'effect failed';
221
225
  const retryAfterMs = payload.retryAfterMs;
222
226
  const failure = planAttemptFailure({
227
+ ids: registry.ids,
223
228
  runId: input.runId,
224
229
  item,
225
230
  attempt,
@@ -243,7 +248,7 @@ export function executeLocalEffects(options, input) {
243
248
  continue;
244
249
  }
245
250
  }
246
- produced.push(yield* materializeEffectOutcome(registry.catalogs, input.runId, item, outcome));
251
+ produced.push(yield* materializeEffectOutcome(registry, input.runId, item, outcome));
247
252
  }
248
253
  const itemOutcomes = produced.slice(before);
249
254
  if (item.effect.type !== 'runtime.wait' &&
@@ -1,4 +1,4 @@
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';
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, type LoomsIds } from '@swirls/looms/core';
2
2
  import type { RuntimeObserver } from './observer';
3
3
  import type { SecretProvider, SecretSealer } from './run-secrets';
4
4
  import { type EffectWorker, type LoomsRuntime, type RunSignalOptions, type RunOperationalStatus, type StartRunArgs, type WakeScheduler, type WorkerCallbackInput, type WorkerCallbackResult } from './runtime';
@@ -11,6 +11,11 @@ export interface CreateLoomsOptions<Fields extends RunAttributeFields = RunAttri
11
11
  * A start that misses a `required` attribute or sends an undeclared one is rejected.
12
12
  */
13
13
  readonly attributes?: Fields;
14
+ /**
15
+ * The id format for every event, run, thread, and wait. Defaults to `typeIds` (TypeID). See
16
+ * `CreateRuntimeOptions.ids` for the rules a custom format must keep.
17
+ */
18
+ readonly ids?: LoomsIds;
14
19
  /**
15
20
  * Loads a definition that was not registered on a module. Registered definitions are checked
16
21
  * first. A run pins the resolved version on its start event.
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Predicate } from 'effect';
2
- import { EventStoreTag, makeMemoryEventStore, makeMemorySnapshotStore, snapshotStoreOf, withBlobOffload, SnapshotStoreTag, } from '@swirls/looms/core';
2
+ import { EventStoreTag, makeMemoryEventStore, makeMemorySnapshotStore, snapshotStoreOf, withBlobOffload, SnapshotStoreTag, resolveIds, } from '@swirls/looms/core';
3
3
  import { createRuntime, } from './runtime.js';
4
4
  import { createFetchHandler, handlesPath, mountDebugger, serveHttp, } from './server.js';
5
5
  class LoomsInitializationError extends Data.TaggedError('LoomsInitializationError') {
@@ -13,6 +13,8 @@ class LoomsInitializationError extends Data.TaggedError('LoomsInitializationErro
13
13
  }
14
14
  export function createLooms(options = {}) {
15
15
  const modules = options.modules ?? [];
16
+ // Checked here so a format that breaks a rule fails where it is configured.
17
+ const ids = resolveIds(options.ids);
16
18
  const debuggerMount = options.debugger ? mountDebugger(options.debugger) : undefined;
17
19
  let initPromise;
18
20
  let runningServer;
@@ -39,6 +41,7 @@ export function createLooms(options = {}) {
39
41
  }
40
42
  const runtime = createRuntime({
41
43
  modules,
44
+ ids,
42
45
  store,
43
46
  maxWakeIterations: options.maxWakeIterations,
44
47
  livenessLeaseMs: options.livenessLeaseMs,
@@ -1,4 +1,4 @@
1
- import { type EventEnvelope, type EventOrigin, type OutstandingEffect, type RetryPolicy } from '@swirls/looms/core';
1
+ import { type EventEnvelope, type EventOrigin, type OutstandingEffect, type RetryPolicy, type LoomsIds } from '@swirls/looms/core';
2
2
  export declare function retryBackoff(retry: RetryPolicy, attempt: number): number;
3
3
  /** Policy backoff, extended when the failed attempt asked to wait longer. */
4
4
  export declare function retryDelay(retry: RetryPolicy, attempt: number, retryAfterMs?: number): number;
@@ -15,6 +15,7 @@ export declare function planAttemptFailure(input: {
15
15
  readonly now: number;
16
16
  readonly retry: RetryPolicy | undefined;
17
17
  readonly origin: EventOrigin;
18
+ readonly ids: LoomsIds;
18
19
  /** Customer/domain failures must not be retried even when attempts remain. */
19
20
  readonly nonRetryable?: boolean;
20
21
  readonly retryAfterMs?: number;
@@ -20,6 +20,7 @@ export function planAttemptFailure(input) {
20
20
  return {
21
21
  event: createEffectFailedEvent(runId, item, error, {
22
22
  nonRetryable: input.nonRetryable === true,
23
+ ids: input.ids,
23
24
  }),
24
25
  retrying: false,
25
26
  };
@@ -37,6 +38,6 @@ export function planAttemptFailure(input) {
37
38
  threadId: item.threadId,
38
39
  causationId: item.causingEventId,
39
40
  origin: input.origin,
40
- }),
41
+ }, { ids: input.ids }),
41
42
  };
42
43
  }
@@ -1,5 +1,5 @@
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, summarizeRun, } from '@swirls/looms/core';
2
+ import { cachedDefinitionResolver, chainDefinitionResolvers, composeModules, createEvent, 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
5
  import { ForkConflictError, RunNotFinishedError, RunNotFoundError, RunTerminalError, RuntimeExecutionError, StartRunConflictError, } from './errors.js';
@@ -61,7 +61,7 @@ export function createRuntime(options) {
61
61
  if (options.localLauncher && !options.store && !options.launcher) {
62
62
  throw new Error('localLauncher requires options.store');
63
63
  }
64
- const registry = composeModules(options.modules);
64
+ const registry = composeModules(options.modules, { ids: options.ids });
65
65
  const runSecrets = createRunSecrets({
66
66
  provider: options.secretProvider,
67
67
  sealer: options.secretSealer,
@@ -120,7 +120,7 @@ export function createRuntime(options) {
120
120
  if (filteredEvents.length === 0) {
121
121
  return { events: [], value: current.state };
122
122
  }
123
- const batch = yield* validateAndCreateEvents(registry.catalogs, runId, filteredEvents.map((input) => ({
123
+ const batch = yield* validateAndCreateEvents(registry, runId, filteredEvents.map((input) => ({
124
124
  ...input,
125
125
  idempotencyKey: input.idempotencyKey ?? signalKey,
126
126
  })), { origin: { type: 'external' }, threadId: current.state.rootThreadId });
@@ -133,7 +133,7 @@ export function createRuntime(options) {
133
133
  const forWaits = terminal || current.state.closeWaiting
134
134
  ? batch.filter((event) => event.type !== 'runtime.child.settled')
135
135
  : batch;
136
- const satisfiedEvents = waitSatisfiedEvents(folded, forWaits).map((input) => createEvent(runId, input));
136
+ const satisfiedEvents = waitSatisfiedEvents(folded, forWaits).map((input) => createEvent(runId, input, { ids: registry.ids }));
137
137
  return {
138
138
  events: [...batch, ...satisfiedEvents],
139
139
  value: current.state,
@@ -159,7 +159,7 @@ export function createRuntime(options) {
159
159
  }
160
160
  const store = yield* EventStoreTag;
161
161
  observe({ type: 'run.start', runId, at: currentTimeMillis() });
162
- const threadId = args.threadId ?? createThreadId();
162
+ const threadId = args.threadId ?? registry.ids.create('thread');
163
163
  const startedEvents = yield* threadStartedEvents(definitionResolver, {
164
164
  kind: args.kind,
165
165
  definitionName: args.definitionName,
@@ -208,7 +208,7 @@ export function createRuntime(options) {
208
208
  events: [],
209
209
  value: { threadId: rootThreadId, state: existing.state },
210
210
  })))
211
- : validateAndCreateEvents(registry.catalogs, runId, [
211
+ : validateAndCreateEvents(registry, runId, [
212
212
  {
213
213
  type: 'runtime.run.started',
214
214
  payload: startPayload,
@@ -370,7 +370,7 @@ export function createRuntime(options) {
370
370
  threadId: item.threadId,
371
371
  causationId: item.causingEventId,
372
372
  origin: { type: 'external', actorId: 'operator' },
373
- });
373
+ }, { ids: registry.ids });
374
374
  return { events: [retryEvent], value: undefined };
375
375
  }));
376
376
  })).pipe(Effect.andThen(runtime.wake(runId))),
@@ -389,7 +389,7 @@ export function createRuntime(options) {
389
389
  }),
390
390
  recoverDeadlines: Effect.suspend(() => runtime.rescanTimers),
391
391
  startRun: (args) => {
392
- const runId = args.runId ?? createRunId();
392
+ const runId = args.runId ?? registry.ids.create('run');
393
393
  return withRunIngress(runId, commitStart(args, runId)).pipe(Effect.flatMap((started) => runtime.wake(runId).pipe(Effect.map((state) => ({
394
394
  runId,
395
395
  threadId: state.rootThreadId ?? started.threadId,
@@ -397,7 +397,7 @@ export function createRuntime(options) {
397
397
  })))));
398
398
  },
399
399
  launchRun: (args) => {
400
- const runId = args.runId ?? createRunId();
400
+ const runId = args.runId ?? registry.ids.create('run');
401
401
  return withRunIngress(runId, commitStart(args, runId)).pipe(Effect.flatMap((started) => Effect.gen(function* () {
402
402
  if (!isRunTerminal(started.state)) {
403
403
  const now = yield* Clock.currentTimeMillis;
@@ -414,7 +414,7 @@ export function createRuntime(options) {
414
414
  accept: (runId, events, signalOpts) => appendAndWake(runId, events, signalOpts),
415
415
  cancel: cancellation,
416
416
  fork: (sourceRunId, forkOptions) => {
417
- const runId = forkOptions?.runId ?? createRunId();
417
+ const runId = forkOptions?.runId ?? registry.ids.create('run');
418
418
  return withRunIngress(runId, Effect.gen(function* () {
419
419
  const store = yield* EventStoreTag;
420
420
  const source = yield* loadCursor(store, sourceRunId);
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema } from 'effect';
2
- import { createRunId, EventStoreTag, findSignal, JsonValueSchema, RunAttributesSchema, readTraceHeaders, runSignal, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
2
+ import { EventStoreTag, findSignal, JsonValueSchema, RunAttributesSchema, readTraceHeaders, runSignal, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
3
3
  import { createEventStreamResponse } from '../../sse.js';
4
4
  import { acceptsEventStream, EventInputBodySchema, extractIdempotencyKey, prefersAsyncResponse, provideStore, readIntegerQuery, readJson, readOptionalJson, RequestQueryError, } from '../http.js';
5
5
  import { route } from '../route-table.js';
@@ -42,7 +42,7 @@ const ForkBodySchema = Schema.Struct({
42
42
  runId: Schema.optional(Schema.String),
43
43
  secrets: Schema.optional(SecretContextSchema),
44
44
  });
45
- function readStartRunArgs(req) {
45
+ function readStartRunArgs(req, ids) {
46
46
  return Effect.gen(function* () {
47
47
  const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(StartRunBodySchema)));
48
48
  const definitionName = body.definitionName ?? body.name;
@@ -55,7 +55,7 @@ function readStartRunArgs(req) {
55
55
  definitionName,
56
56
  definitionVersion: body.definitionVersion,
57
57
  input: body.input ?? null,
58
- runId: body.runId ?? createRunId(),
58
+ runId: body.runId ?? ids.create('run'),
59
59
  idempotencyKey: extractIdempotencyKey(req, body.idempotencyKey),
60
60
  attributes: body.attributes,
61
61
  secrets: body.secrets,
@@ -134,7 +134,7 @@ export function runRoutes({ runtime, store }) {
134
134
  name: 'runs.start',
135
135
  access: 'write',
136
136
  handle: ({ req, url }) => Effect.gen(function* () {
137
- const args = yield* readStartRunArgs(req);
137
+ const args = yield* readStartRunArgs(req, runtime.registry.ids);
138
138
  if (args instanceof Response) {
139
139
  return args;
140
140
  }
@@ -151,7 +151,7 @@ export function runRoutes({ runtime, store }) {
151
151
  name: 'runs.launch',
152
152
  access: 'write',
153
153
  handle: ({ req }) => Effect.gen(function* () {
154
- const args = yield* readStartRunArgs(req);
154
+ const args = yield* readStartRunArgs(req, runtime.registry.ids);
155
155
  if (args instanceof Response) {
156
156
  return args;
157
157
  }
@@ -1,5 +1,5 @@
1
1
  import type { Effect } from 'effect';
2
- import type { AnyRuntimeModule, ComposedRegistry, DefinitionResolver, EventEnvelope, EventInput, WorkerCallback, WorkerCallbackInput, DefinitionResolveError, WorkerCallbackResult, WorkerSecretsResult, EventStore, EventStoreAppendError, EventStoreError, EventStoreFencedError, EventStoreTag, EventStoreTrimCoverage, RunLauncher, RunLaunchSource, RunAttributeFields, RunAttributes, SecretContext, TraceContext, EventStoreTruncationError, JsonValue, ProjectionDefinition, ReplayStep, RunState, RunSummary, SnapshotStore, SnapshotStoreError } from '@swirls/looms/core';
2
+ import type { AnyRuntimeModule, LoomsIds, ComposedRegistry, DefinitionResolver, EventEnvelope, EventInput, WorkerCallback, WorkerCallbackInput, DefinitionResolveError, WorkerCallbackResult, WorkerSecretsResult, EventStore, EventStoreAppendError, EventStoreError, EventStoreFencedError, EventStoreTag, EventStoreTrimCoverage, RunLauncher, RunLaunchSource, RunAttributeFields, RunAttributes, SecretContext, TraceContext, EventStoreTruncationError, JsonValue, ProjectionDefinition, ReplayStep, RunState, RunSummary, SnapshotStore, SnapshotStoreError } from '@swirls/looms/core';
3
3
  import type { EventStoreTrimmedError } from '@swirls/looms/core';
4
4
  import type { DuplicateEffectDispatchError, MaxWakeIterationsError } from './errors';
5
5
  import type { RuntimeObserver } from './observer';
@@ -8,6 +8,12 @@ import type { WakeScheduler } from './wake-scheduler';
8
8
  export type WakeError = DuplicateEffectDispatchError | MaxWakeIterationsError | EventStoreTruncationError | EventStoreTrimmedError | EventStoreFencedError | EventStoreError | Error;
9
9
  export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
10
10
  readonly modules: TModules;
11
+ /**
12
+ * The id format for every event, run, thread, and wait this runtime names, and what reducers
13
+ * and effect handlers see as `ctx.ids`. Defaults to `typeIds` (TypeID). A custom format must
14
+ * return non-empty ids with no `:`, and its `derive` must be a pure function of its arguments.
15
+ */
16
+ readonly ids?: LoomsIds;
11
17
  /**
12
18
  * Loads a definition that was not registered on a module. Registered definitions are checked
13
19
  * first. Lookups are cached, including misses. Start fails with `UnknownDefinitionError`
@@ -39,7 +39,7 @@ export function createWakeEngine(options) {
39
39
  threadId: state.rootThreadId,
40
40
  origin: { type: 'system' },
41
41
  idempotencyKey: `child-close:${runId}`,
42
- });
42
+ }, { ids: registry.ids });
43
43
  const appended = yield* appendObserved(store, runId, stripSeq([requested]));
44
44
  next = yield* applyAppend(store, runId, next, stripSeq([requested]), appended);
45
45
  }
@@ -141,7 +141,7 @@ export function createWakeEngine(options) {
141
141
  let cursor = yield* loadCursor(store, runId);
142
142
  const closeEvents = childCloseCancellations(cursor.state);
143
143
  if (closeEvents.length > 0) {
144
- const created = closeEvents.map((input) => createEvent(runId, input));
144
+ const created = closeEvents.map((input) => createEvent(runId, input, { ids: registry.ids }));
145
145
  const appended = yield* appendObserved(store, runId, stripSeq(created));
146
146
  cursor = yield* applyAppend(store, runId, cursor, stripSeq(created), appended);
147
147
  }
@@ -150,6 +150,7 @@ export function createWakeEngine(options) {
150
150
  const events = planTerminalCancellationTransitions({
151
151
  runId,
152
152
  state: cursor.state,
153
+ registry,
153
154
  now,
154
155
  });
155
156
  if (events.length > 0) {
@@ -190,13 +191,13 @@ export function createWakeEngine(options) {
190
191
  ...synthesizedThreadFailed(beforeFold, intermediateState, produced),
191
192
  ...cascadedCancellations(intermediateState, produced),
192
193
  ];
193
- const synthesizedEvents = synthesized.map((input) => createEvent(runId, input));
194
+ const synthesizedEvents = synthesized.map((input) => createEvent(runId, input, { ids: registry.ids }));
194
195
  const stateAfterSynth = synthesizedEvents.length > 0
195
196
  ? foldRun(synthesizedEvents, registry, { runId, initial: intermediateState })
196
197
  : intermediateState;
197
198
  const allNewEvents = [...produced, ...synthesizedEvents];
198
199
  const satisfied = waitSatisfiedEvents(stateAfterSynth, allNewEvents);
199
- const satisfiedEvents = satisfied.map((input) => createEvent(runId, input));
200
+ const satisfiedEvents = satisfied.map((input) => createEvent(runId, input, { ids: registry.ids }));
200
201
  const fullBatch = [...allNewEvents, ...satisfiedEvents];
201
202
  const appendResult = yield* appendObserved(store, runId, stripSeq(fullBatch));
202
203
  cursor = yield* applyAppend(store, runId, cursor, stripSeq(fullBatch), appendResult);
@@ -310,7 +311,7 @@ export function createWakeEngine(options) {
310
311
  // them, and its worker asks for the attempt's secrets once it has started.
311
312
  const dispatchEvent = yield* dispatchWorkerEffect(runId, hasEntries(admission.secrets)
312
313
  ? { ...workerPlan, task: { ...workerPlan.task, secrets: admission.secrets } }
313
- : workerPlan, options.worker, now);
314
+ : workerPlan, options.worker, now, { ids: registry.ids });
314
315
  const dispatchAppend = yield* appendObserved(store, runId, stripSeq([dispatchEvent]));
315
316
  cursor = yield* applyAppend(store, runId, cursor, stripSeq([dispatchEvent]), dispatchAppend);
316
317
  }
@@ -358,7 +359,7 @@ export function createWakeEngine(options) {
358
359
  DEFAULT_LOST_ATTEMPT_LIMIT;
359
360
  return execution.attempt >= limit
360
361
  ? [
361
- createEffectFailedEvent(runId, item, `attempt ${execution.attempt} was lost before it finished, and no attempts remain`),
362
+ createEffectFailedEvent(runId, item, `attempt ${execution.attempt} was lost before it finished, and no attempts remain`, { ids: registry.ids }),
362
363
  ]
363
364
  : [];
364
365
  });
@@ -382,7 +383,7 @@ export function createWakeEngine(options) {
382
383
  },
383
384
  threadId: item.threadId,
384
385
  origin: { type: 'system' },
385
- }));
386
+ }, { ids: registry.ids }));
386
387
  for (const item of due) {
387
388
  observe({
388
389
  type: 'effect.attempt',
@@ -491,7 +492,7 @@ export function createWakeEngine(options) {
491
492
  payload: { reason: root.error ?? 'cancelled' },
492
493
  threadId: null,
493
494
  origin: { type: 'system' },
494
- })
495
+ }, { ids: registry.ids })
495
496
  : createEvent(runId, {
496
497
  type: 'runtime.run.completed',
497
498
  payload: {
@@ -500,7 +501,7 @@ export function createWakeEngine(options) {
500
501
  },
501
502
  threadId: null,
502
503
  origin: { type: 'system' },
503
- });
504
+ }, { ids: registry.ids });
504
505
  const appendResult = yield* appendObserved(store, runId, stripSeq([completed]));
505
506
  cursor = yield* applyAppend(store, runId, cursor, stripSeq([completed]), appendResult);
506
507
  }
@@ -13,13 +13,13 @@ function workerDeadline(retry, startedAt, now) {
13
13
  ].filter(Predicate.isNotNull);
14
14
  return deadlines.length > 0 ? Math.min(...deadlines) : null;
15
15
  }
16
- function workerStartedEvent(runId, item, attempt, retry, now) {
16
+ function workerStartedEvent(runId, item, attempt, retry, now, ids) {
17
17
  return createEvent(runId, {
18
18
  type: 'runtime.effect.worker.started',
19
19
  payload: { effectId: item.effectId, attempt, deadlineAt: workerDeadline(retry, now, now) },
20
20
  threadId: item.threadId,
21
21
  origin: WORKER_ORIGIN,
22
- });
22
+ }, { ids });
23
23
  }
24
24
  const STALE = {
25
25
  events: [],
@@ -73,7 +73,7 @@ function planWorkerCallback(input) {
73
73
  switch (callback.kind) {
74
74
  case 'started': {
75
75
  return Effect.succeed(item && (execution.status === 'dispatched' || execution.status === 'dispatch_wait')
76
- ? accepted([workerStartedEvent(runId, item, callback.attempt, retry, now)])
76
+ ? accepted([workerStartedEvent(runId, item, callback.attempt, retry, now, registry.ids)])
77
77
  : STALE);
78
78
  }
79
79
  case 'heartbeat': {
@@ -91,21 +91,21 @@ function planWorkerCallback(input) {
91
91
  const payload = callback.details === undefined ? recorded : { ...recorded, details: callback.details };
92
92
  return Effect.succeed(accepted([
93
93
  ...(implicitStart
94
- ? [workerStartedEvent(runId, item, callback.attempt, retry, now)]
94
+ ? [workerStartedEvent(runId, item, callback.attempt, retry, now, registry.ids)]
95
95
  : []),
96
96
  createEvent(runId, {
97
97
  type: 'runtime.effect.heartbeat',
98
98
  payload,
99
99
  threadId: item.threadId,
100
100
  origin: WORKER_ORIGIN,
101
- }),
101
+ }, { ids: registry.ids }),
102
102
  ], [notice('effect.heartbeat')]));
103
103
  }
104
104
  case 'complete': {
105
105
  if (!item) {
106
106
  return Effect.succeed(STALE);
107
107
  }
108
- return Effect.forEach(callback.events, (event) => materializeEffectOutcome(registry.catalogs, runId, item, event)).pipe(Effect.map((outcomes) => accepted([
108
+ return Effect.forEach(callback.events, (event) => materializeEffectOutcome(registry, runId, item, event)).pipe(Effect.map((outcomes) => accepted([
109
109
  ...outcomes,
110
110
  createEvent(runId, {
111
111
  type: 'runtime.effect.completed',
@@ -114,7 +114,7 @@ function planWorkerCallback(input) {
114
114
  effectId: item.effectId,
115
115
  causationId: item.causingEventId,
116
116
  origin: WORKER_ORIGIN,
117
- }),
117
+ }, { ids: registry.ids }),
118
118
  ])));
119
119
  }
120
120
  case 'fail': {
@@ -122,6 +122,7 @@ function planWorkerCallback(input) {
122
122
  return Effect.succeed(STALE);
123
123
  }
124
124
  const failure = planAttemptFailure({
125
+ ids: registry.ids,
125
126
  runId,
126
127
  item,
127
128
  attempt: callback.attempt,
@@ -153,7 +154,7 @@ function planWorkerCallback(input) {
153
154
  threadId: item?.threadId ?? null,
154
155
  effectId: callback.effectId,
155
156
  origin: WORKER_ORIGIN,
156
- }),
157
+ }, { ids: registry.ids }),
157
158
  ], [notice('effect.cancellation')], true));
158
159
  }
159
160
  default: {
@@ -1,5 +1,5 @@
1
1
  import { Effect } from 'effect';
2
- import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState } from '@swirls/looms/core';
2
+ import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState, type LoomsIds } from '@swirls/looms/core';
3
3
  import type { EffectWorker, EffectWorkerTask } from './types';
4
4
  /** Caps how many times one attempt's unacknowledged dispatch can be deferred before parking as ambiguous. */
5
5
  export declare const DEFAULT_MAX_WORKER_DISPATCH_DEFERRALS = 32;
@@ -44,7 +44,8 @@ export declare function planWorkerEffects(input: {
44
44
  * arrived, so a later `started` from `dispatch_wait` is accepted.
45
45
  * - Missing worker: ambiguous (misconfiguration).
46
46
  */
47
- export declare function dispatchWorkerEffect(runId: string, plan: WorkerEffectDispatchPlan, worker: EffectWorker | undefined, now: number, options?: {
47
+ export declare function dispatchWorkerEffect(runId: string, plan: WorkerEffectDispatchPlan, worker: EffectWorker | undefined, now: number, options: {
48
+ readonly ids: LoomsIds;
48
49
  readonly maxDispatchDeferrals?: number;
49
50
  }): Effect.Effect<EventEnvelope>;
50
51
  /**