@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,4 +1,4 @@
1
- import { type JsonValue, type RuntimeEffect } from '@swirls/looms/core';
1
+ import { type JsonValue, type LoomsIds, type RuntimeEffect } from '@swirls/looms/core';
2
2
  import type { ApprovalAction } from './events';
3
3
  export declare function gate(args: {
4
4
  title: string;
@@ -8,4 +8,6 @@ export declare function gate(args: {
8
8
  schema?: JsonValue;
9
9
  /** Absolute epoch milliseconds. Decision and timer waits race; the first wins. */
10
10
  timeoutAt?: number;
11
+ /** The id format to draw `approvalId` from. Pass `ctx.ids`. Defaults to `typeIds`. */
12
+ ids?: LoomsIds;
11
13
  }): RuntimeEffect[];
@@ -1,7 +1,7 @@
1
- import { createWaitId, invoke, wait } from '@swirls/looms/core';
1
+ import { createWaitId, invoke, typeIds, wait, } from '@swirls/looms/core';
2
2
  import { requestApprovalEffect } from './effects.js';
3
3
  export function gate(args) {
4
- const approvalId = args.approvalId ?? createWaitId('approval');
4
+ const approvalId = args.approvalId ?? (args.ids ?? typeIds).create('wait');
5
5
  const actions = args.actions ?? [
6
6
  { id: 'approve', label: 'Approve', outcome: 'approve' },
7
7
  { id: 'reject', label: 'Reject', outcome: 'reject' },
@@ -1,5 +1,5 @@
1
1
  import { Schema } from 'effect';
2
- import { type DefinitionInput, type DefinitionRef, type EventEnvelope, type EventInput, type HasRequiredAttributes, type JsonValue, type RunAttributeFields, type RunAttributesOption, type RunState, type SecretContext, type SubscriptionTransport, type TraceContext, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerSecretsResult } from '@swirls/looms/core';
2
+ import { type LoomsIds, type DefinitionInput, type DefinitionRef, type EventEnvelope, type EventInput, type HasRequiredAttributes, type JsonValue, type RunAttributeFields, type RunAttributesOption, type RunState, type SecretContext, type SubscriptionTransport, type TraceContext, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerSecretsResult } from '@swirls/looms/core';
3
3
  export interface LoomsClientOptions<Fields extends RunAttributeFields = RunAttributeFields> {
4
4
  baseUrl?: string;
5
5
  fetch?: typeof fetch;
@@ -11,6 +11,10 @@ export interface LoomsClientOptions<Fields extends RunAttributeFields = RunAttri
11
11
  grant?: string;
12
12
  /** Declared run attributes, from `defineRunAttributes`. Types `attributes` on starts. */
13
13
  attributes?: Fields;
14
+ /**
15
+ * The id format for the run id of a `stream` started without one. Match the host's `ids`. Defaults to `typeIds` (TypeID).
16
+ */
17
+ ids?: LoomsIds;
14
18
  }
15
19
  type ClientStartArgs<Fields extends RunAttributeFields> = {
16
20
  kind: string;
@@ -32,6 +36,8 @@ export interface StreamHandle extends AsyncIterable<EventEnvelope> {
32
36
  readonly runId: string;
33
37
  }
34
38
  export declare function createLoomsClient<const Fields extends RunAttributeFields = RunAttributeFields>(options?: LoomsClientOptions<Fields>): {
39
+ /** The id format this client draws from. */
40
+ ids: LoomsIds;
35
41
  /**
36
42
  * Start a run by `{ kind, definitionName }` when you only have names. Answers after the first
37
43
  * wake, so a short run can come back finished.
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Option, Predicate, Schema, Stream } from 'effect';
2
- import { createRunId, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, cleanUndefined, EventTypeCatalogSchema, JsonValueSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, SignalCatalogSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
2
+ import { resolveIds, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, cleanUndefined, EventTypeCatalogSchema, JsonValueSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, SignalCatalogSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
3
3
  import { consumeSseStreamEffect, eventsFromSseData, sseFrames } from './sse.js';
4
4
  class LoomsClientError extends Data.TaggedError('LoomsClientError') {
5
5
  constructor(message, cause) {
@@ -91,6 +91,7 @@ const PreviewEventsResultSchema = Schema.Struct({
91
91
  export function createLoomsClient(options = {}) {
92
92
  const baseUrl = (options.baseUrl ?? '').replace(/\/$/, '');
93
93
  const fetchImpl = options.fetch ?? fetch;
94
+ const ids = resolveIds(options.ids);
94
95
  function request(path, schema, init) {
95
96
  const headers = new Headers(init?.headers);
96
97
  if (!headers.has('content-type')) {
@@ -211,7 +212,7 @@ export function createLoomsClient(options = {}) {
211
212
  });
212
213
  const streamRun = (args) => {
213
214
  const { trace, ...body } = args;
214
- const runId = body.runId ?? createRunId();
215
+ const runId = body.runId ?? ids.create('run');
215
216
  const stream = Stream.unwrap(Effect.tryPromise({
216
217
  try: (signal) => fetchImpl(`${baseUrl}/runs`, {
217
218
  method: 'POST',
@@ -236,6 +237,8 @@ export function createLoomsClient(options = {}) {
236
237
  return Object.assign(Stream.toAsyncIterable(stream), { runId });
237
238
  };
238
239
  return {
240
+ /** The id format this client draws from. */
241
+ ids,
239
242
  /**
240
243
  * Start a run by `{ kind, definitionName }` when you only have names. Answers after the first
241
244
  * wake, so a short run can come back finished.
@@ -1,5 +1,5 @@
1
1
  import { DurableObject } from 'cloudflare:workers';
2
- import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type BlobStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot } from '@swirls/looms/core';
2
+ import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type BlobStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot, type LoomsIds } from '@swirls/looms/core';
3
3
  import type { Projector } from '@swirls/looms/projectors';
4
4
  import { type Authorize, type EffectWorker, type RunSignalOptions, type StartResult, type StartRunArgs, type RuntimeObserver, type SecretProvider, type SecretSealer } from '@swirls/looms/runtime';
5
5
  import { type DeleteTerminalRunStorageOptions } from './delete-terminal-run-storage';
@@ -7,6 +7,8 @@ export interface LoomsDurableObjectConfig {
7
7
  readonly modules: readonly AnyRuntimeModule[];
8
8
  /** Loads definitions that were not registered on a module. See `CreateRuntimeOptions`. */
9
9
  readonly definitionResolver?: DefinitionResolver;
10
+ /** The id format. See `CreateRuntimeOptions.ids`. */
11
+ readonly ids?: LoomsIds;
10
12
  /** Declared run attributes. Pass the same declaration to the replica. */
11
13
  readonly attributes?: RunAttributeFields;
12
14
  /** Told about wakes, appends, snapshots and effect attempts. See `CreateRuntimeOptions`. */
@@ -53,6 +53,7 @@ export class LoomsDurableObject extends DurableObject {
53
53
  scheduler: alarms.scheduler,
54
54
  modules: config.modules,
55
55
  definitionResolver: config.definitionResolver,
56
+ ids: config.ids,
56
57
  attributes: config.attributes,
57
58
  observer: config.observer,
58
59
  secretProvider: config.secretProvider,
@@ -1,5 +1,5 @@
1
1
  import { Effect } from 'effect';
2
- import { type BlobStore, type EventInput, type JsonValue, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerEffectContext, type WorkerEffectDefinition, type WorkerSecretsResult } from '@swirls/looms/core';
2
+ import { type BlobStore, type EventInput, type JsonValue, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerEffectContext, type WorkerEffectDefinition, type WorkerSecretsResult, type LoomsIds } from '@swirls/looms/core';
3
3
  import { type QueueEffectMessage, type QueueMessageLike } from './queue-message';
4
4
  /** The worker half of the Looms HTTP API. `createLoomsClient({ baseUrl, workerCallbackToken })` is one. */
5
5
  export interface WorkerCallbackClient {
@@ -43,6 +43,8 @@ export interface QueueConsumerOptions {
43
43
  readonly callbacks: WorkerCallbackClient;
44
44
  /** Reads inputs the producer offloaded. Use the store the producer writes to. */
45
45
  readonly blobs?: BlobStore;
46
+ /** The id format handlers see as `ctx.ids`. Match the host's `ids`. Defaults to `typeIds`. */
47
+ readonly ids?: LoomsIds;
46
48
  }
47
49
  export interface QueueBatchLike {
48
50
  readonly messages: ReadonlyArray<QueueMessageLike>;
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect } from 'effect';
2
- import { resolveJson, validateInput, } from '@swirls/looms/core';
2
+ import { resolveJson, validateInput, resolveIds, } from '@swirls/looms/core';
3
3
  import { readQueueEffectMessage, } from './queue-message.js';
4
4
  /**
5
5
  * Build a `handlers` map from **worker-placed** effect definitions. Input is validated with each
@@ -93,6 +93,7 @@ function runAttempt(task, attempt, handler, cancelRequested, options) {
93
93
  attributes: task.attributes ?? {},
94
94
  secrets,
95
95
  trace: task.trace ?? null,
96
+ ids: resolveIds(options.ids),
96
97
  heartbeat: (details) => Effect.runPromise(callback(() => options.callbacks.workerCallback(task.runId, details === undefined
97
98
  ? { ...attempt, kind: 'heartbeat' }
98
99
  : { ...attempt, kind: 'heartbeat', details })).pipe(Effect.map((result) => {
@@ -1,4 +1,4 @@
1
- import type { AnyRuntimeModule } from '@swirls/looms/core';
1
+ import type { AnyRuntimeModule, LoomsIds } from '@swirls/looms/core';
2
2
  import { type AuthDecision, type RouteInfo } from '@swirls/looms/runtime';
3
3
  export interface DurableObjectStubLike {
4
4
  fetch(request: Request): Promise<Response>;
@@ -26,4 +26,6 @@ export type RouteAuthorize = (request: Request, route: RouteInfo) => AuthDecisio
26
26
  export declare function routeToDurableObject(namespace: DurableObjectNamespaceLike, req: Request, options?: {
27
27
  readonly modules?: readonly AnyRuntimeModule[] | (() => readonly AnyRuntimeModule[]);
28
28
  readonly authorize?: RouteAuthorize;
29
+ /** The id format for a run started without a `runId`. Match the Durable Object's `ids`. */
30
+ readonly ids?: LoomsIds;
29
31
  }): Promise<Response | null>;
@@ -49,7 +49,7 @@ function forward(namespace, req, options) {
49
49
  if (unsupported) {
50
50
  return Promise.resolve(unsupported);
51
51
  }
52
- return resolveRunTarget(req)
52
+ return resolveRunTarget(req, { ids: options?.ids })
53
53
  .then(({ runId, request }) => namespace.getByName(runId).fetch(request))
54
54
  .catch((error) => {
55
55
  if (error instanceof RunTargetError) {
@@ -3,6 +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 LoomsIds } from './ids';
6
7
  import type { AnyRuntimeModule, EffectAdmission, EffectMiddleware, RuntimeModule, RegisteredDefinition, SignalInterruptRule } from './module';
7
8
  import type { ProjectionDefinition } from './projection';
8
9
  import { protocolCatalog } from './protocol';
@@ -24,9 +25,14 @@ export interface ComposedRegistry extends FoldRegistry {
24
25
  readonly middleware: readonly EffectMiddleware[];
25
26
  readonly admission: readonly EffectAdmission[];
26
27
  readonly interruptRules: readonly SignalInterruptRule[];
28
+ readonly ids: LoomsIds;
27
29
  }
28
- export declare function composeModules(modules: readonly AnyRuntimeModule[]): ComposedRegistry;
29
- export declare function composeModulesEffect(modules: readonly AnyRuntimeModule[]): Effect.Effect<ComposedRegistry, ModuleCompositionError>;
30
+ export interface ComposeModulesOptions {
31
+ /** The id format for everything this registry names. Defaults to `typeIds`. */
32
+ readonly ids?: LoomsIds;
33
+ }
34
+ export declare function composeModules(modules: readonly AnyRuntimeModule[], options?: ComposeModulesOptions): ComposedRegistry;
35
+ export declare function composeModulesEffect(modules: readonly AnyRuntimeModule[], options?: ComposeModulesOptions): Effect.Effect<ComposedRegistry, ModuleCompositionError>;
30
36
  export type ProtocolEvents = CatalogEvent<'runtime', typeof protocolCatalog.entries>;
31
37
  export type ModuleEvents<T> = T extends {
32
38
  readonly events?: infer C;
@@ -1,4 +1,5 @@
1
1
  import { Data, Effect } from 'effect';
2
+ import { resolveIds } from './ids.js';
2
3
  import { DEFAULT_DEFINITION_VERSION, definitionKey } from './module.js';
3
4
  import { protocolCatalog } from './protocol.js';
4
5
  export class ModuleCompositionError extends Data.TaggedError('ModuleCompositionError') {
@@ -7,7 +8,8 @@ export class ModuleCompositionError extends Data.TaggedError('ModuleCompositionE
7
8
  this.name = 'ModuleCompositionError';
8
9
  }
9
10
  }
10
- export function composeModules(modules) {
11
+ export function composeModules(modules, options) {
12
+ const ids = resolveIds(options?.ids);
11
13
  const definitions = [];
12
14
  const definitionKeys = new Set();
13
15
  const namespaces = new Set();
@@ -107,11 +109,12 @@ export function composeModules(modules) {
107
109
  middleware,
108
110
  admission,
109
111
  interruptRules,
112
+ ids,
110
113
  };
111
114
  }
112
- export function composeModulesEffect(modules) {
115
+ export function composeModulesEffect(modules, options) {
113
116
  return Effect.try({
114
- try: () => composeModules(modules),
117
+ try: () => composeModules(modules, options),
115
118
  catch: (cause) => cause instanceof ModuleCompositionError
116
119
  ? cause
117
120
  : new ModuleCompositionError(cause instanceof Error ? cause.message : String(cause)),
@@ -1,5 +1,6 @@
1
1
  import { Effect, Schema, type Context } from 'effect';
2
2
  import { type EventInput } from './envelope';
3
+ import type { LoomsIds } from './ids';
3
4
  import type { RunAttributes, SecretContext } from './run-context';
4
5
  import { type InferDefinedSchema, type InvalidInputError, type SchemaInput } from './schema';
5
6
  import type { TraceContext } from './trace';
@@ -183,6 +184,8 @@ export interface EffectContextBase {
183
184
  readonly secrets: SecretContext;
184
185
  /** The W3C trace context of the caller that started the run, to parent spans the handler starts. */
185
186
  readonly trace: TraceContext | null;
187
+ /** The id format the host was configured with. */
188
+ readonly ids: LoomsIds;
186
189
  }
187
190
  /**
188
191
  * Context for an effect that runs in the host actor cell (for example a Durable Object).
@@ -1,4 +1,5 @@
1
1
  import { Schema } from 'effect';
2
+ import { type LoomsIds } from './ids';
2
3
  import { type JsonValue } from './types';
3
4
  export declare const JsonValueSchema: Schema.Codec<Schema.Json, Schema.Json, never, never>;
4
5
  export declare const EventOriginSchema: Schema.Union<readonly [Schema.Struct<{
@@ -104,5 +105,6 @@ export declare function payloadAsJson(payload: JsonValue): JsonValue;
104
105
  export declare function withAssignedSeq(partial: AppendableEvent, runId: string, seq: number): EventEnvelope;
105
106
  export declare function createEvent<TType extends string, TPayload = JsonValue>(runId: string, input: EventInput<TType, TPayload>, options?: {
106
107
  seq?: number;
108
+ ids?: LoomsIds;
107
109
  }): EventEnvelope<TType, TPayload>;
108
110
  export declare function fromWireEvent(wire: Schema.Schema.Type<typeof EventEnvelopeSchema>): EventEnvelope;
@@ -1,5 +1,5 @@
1
1
  import { DateTime, Schema } from 'effect';
2
- import { createEventId } from './ids.js';
2
+ import { typeIds } from './ids.js';
3
3
  import { cleanUndefined } from './types.js';
4
4
  export const JsonValueSchema = Schema.Json;
5
5
  export const EventOriginSchema = Schema.Union([
@@ -59,7 +59,7 @@ export function createEvent(runId, input, options) {
59
59
  const threadId = input.threadId ?? null;
60
60
  const parentThreadId = input.parentThreadId ?? null;
61
61
  return {
62
- id: input.id ?? createEventId(),
62
+ id: input.id ?? (options?.ids ?? typeIds).create('event'),
63
63
  runId,
64
64
  seq: options?.seq ?? 0,
65
65
  ts: input.ts ?? DateTime.toEpochMillis(DateTime.nowUnsafe()),
@@ -1,10 +1,11 @@
1
1
  import type { AppendableEvent, EventEnvelope } from './envelope';
2
+ import { type LoomsIds } from './ids';
2
3
  import type { JsonValue } from './types';
3
4
  /** JSON-safe event envelope for SSE and pull responses. */
4
5
  export type EncodedLoomsEvent = EventEnvelope;
5
6
  type EventWireInput = JsonValue | Partial<EncodedLoomsEvent>;
6
7
  export declare function encodeLoomsEvent(event: EventEnvelope): EncodedLoomsEvent;
7
- export declare function encodeAppendableEvent(event: AppendableEvent): EncodedLoomsEvent;
8
- export declare function decodeLoomsEvent(raw: EventWireInput, runId: string): EventEnvelope;
9
- export declare function decodeAppendableEvent(raw: EventWireInput, runId: string): AppendableEvent | undefined;
8
+ export declare function encodeAppendableEvent(event: AppendableEvent, ids?: LoomsIds): EncodedLoomsEvent;
9
+ export declare function decodeLoomsEvent(raw: EventWireInput, runId: string, ids?: LoomsIds): EventEnvelope;
10
+ export declare function decodeAppendableEvent(raw: EventWireInput, runId: string, ids?: LoomsIds): AppendableEvent | undefined;
10
11
  export {};
@@ -1,6 +1,6 @@
1
1
  import { DateTime, Predicate, Schema } from 'effect';
2
2
  import { createEvent, payloadAsJson } from './envelope.js';
3
- import { createEventId } from './ids.js';
3
+ import { typeIds } from './ids.js';
4
4
  const decodeJsonValue = Schema.decodeUnknownSync(Schema.Json);
5
5
  export function encodeLoomsEvent(event) {
6
6
  return {
@@ -8,9 +8,9 @@ export function encodeLoomsEvent(event) {
8
8
  payload: payloadAsJson(event.payload),
9
9
  };
10
10
  }
11
- export function encodeAppendableEvent(event) {
11
+ export function encodeAppendableEvent(event, ids = typeIds) {
12
12
  return {
13
- id: event.id ?? createEventId(),
13
+ id: event.id ?? ids.create('event'),
14
14
  runId: event.runId,
15
15
  seq: event.seq ?? 0,
16
16
  ts: event.ts ?? DateTime.toEpochMillis(DateTime.nowUnsafe()),
@@ -42,14 +42,14 @@ function readOrigin(raw) {
42
42
  }
43
43
  return { type: 'system' };
44
44
  }
45
- export function decodeLoomsEvent(raw, runId) {
45
+ export function decodeLoomsEvent(raw, runId, ids = typeIds) {
46
46
  if (!Predicate.isReadonlyObject(raw)) {
47
47
  throw new Error('Invalid event payload: expected object');
48
48
  }
49
49
  if ('type' in raw && Predicate.isString(raw.type)) {
50
50
  const rawPayload = 'payload' in raw ? raw.payload : {};
51
51
  const payload = decodeJsonValue(rawPayload);
52
- const id = 'id' in raw && Predicate.isString(raw.id) ? raw.id : createEventId();
52
+ const id = 'id' in raw && Predicate.isString(raw.id) ? raw.id : ids.create('event');
53
53
  const ts = 'ts' in raw && Predicate.isNumber(raw.ts)
54
54
  ? raw.ts
55
55
  : DateTime.toEpochMillis(DateTime.nowUnsafe());
@@ -82,9 +82,9 @@ export function decodeLoomsEvent(raw, runId) {
82
82
  }
83
83
  throw new Error('Invalid event payload: missing type');
84
84
  }
85
- export function decodeAppendableEvent(raw, runId) {
85
+ export function decodeAppendableEvent(raw, runId, ids = typeIds) {
86
86
  try {
87
- const { seq: _seq, ...rest } = decodeLoomsEvent(raw, runId);
87
+ const { seq: _seq, ...rest } = decodeLoomsEvent(raw, runId, ids);
88
88
  return rest;
89
89
  }
90
90
  catch {
@@ -1,10 +1,13 @@
1
1
  import { Stream, type Effect } from 'effect';
2
2
  import { type RuntimeEffect } from './effects';
3
3
  import type { EventEnvelope } from './envelope';
4
+ import { type LoomsIds } from './ids';
4
5
  import type { RunState } from './state';
5
6
  import { type ThreadDefinition } from './thread';
6
7
  export interface FoldRegistry {
7
8
  readonly threads: ReadonlyMap<string, ThreadDefinition>;
9
+ /** The id format reducers see as `ctx.ids`. Defaults to `typeIds`. */
10
+ readonly ids?: LoomsIds;
8
11
  }
9
12
  /** The id an effect keeps across folds when it names itself by tag, wait id, or child thread. */
10
13
  export declare function stableEffectId(threadId: string, effect: RuntimeEffect): string | undefined;
package/dist/core/fold.js CHANGED
@@ -1,6 +1,6 @@
1
1
  import { Option, Predicate, Schema, Stream } from 'effect';
2
2
  import { isWithdrawnError, WaitConditionSchema } from './effects.js';
3
- import { createEffectId } from './ids.js';
3
+ import { createEffectId, typeIds } from './ids.js';
4
4
  import { readRunLaunchSource } from './launcher.js';
5
5
  import { DEFAULT_DEFINITION_VERSION } from './module.js';
6
6
  import { readAttributes } from './run-context.js';
@@ -174,6 +174,7 @@ function applyProtocol(state, event, registry) {
174
174
  definitionName,
175
175
  definitionVersion,
176
176
  input,
177
+ ids: registry.ids ?? typeIds,
177
178
  })
178
179
  : {},
179
180
  };
@@ -585,6 +586,7 @@ function deliver(state, event, registry, settled) {
585
586
  runId: state.runId,
586
587
  threadId,
587
588
  parentThreadId: record.parentThreadId,
589
+ ids: registry.ids ?? typeIds,
588
590
  };
589
591
  const nextState = definition.step(record.state, event, ctx);
590
592
  const enabled = definition.effects(nextState, ctx);
package/dist/core/fork.js CHANGED
@@ -120,7 +120,7 @@ export function planFork(input) {
120
120
  payload: { sourceRunId, sourceSeq: cut },
121
121
  threadId: null,
122
122
  origin: { type: 'system' },
123
- }, { seq: cut + 1 });
123
+ }, { seq: cut + 1, ids: registry.ids });
124
124
  return Effect.succeed({
125
125
  events: [...prefix.map((event) => copyEvent(event, runId, reissued)), marker],
126
126
  sourceSeq: cut,
@@ -1,13 +1,77 @@
1
+ /** The ids a format draws fresh: one per event, run, thread, or wait. */
2
+ export type DrawnIdKind = 'event' | 'run' | 'thread' | 'wait';
3
+ /** The ids a format derives from parts, so replay names the same child every time. */
4
+ export type DerivedIdKind = 'run' | 'thread';
5
+ export type IdPart = string | number;
6
+ /**
7
+ * How a process names events, runs, threads, and waits. The default is {@link typeIds}.
8
+ *
9
+ * Two rules hold for every id a format returns:
10
+ *
11
+ * - It is a non-empty string.
12
+ * - It contains no `:`. Effect ids are `<threadId>:<tag>`.
13
+ *
14
+ * `derive` must also be a pure function of `kind` and `parts`: reducers call it on every replay
15
+ * and must name the same child each time. Looms cannot check this.
16
+ */
17
+ export interface LoomsIds {
18
+ /** A fresh id that no earlier call returned. */
19
+ create(kind: DrawnIdKind): string;
20
+ /** The same id for the same `kind` and `parts`, on every call, in every process. */
21
+ derive(kind: DerivedIdKind, parts: readonly IdPart[]): string;
22
+ }
23
+ declare const InvalidIdFormatError_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 & {
24
+ readonly _tag: "InvalidIdFormatError";
25
+ } & Readonly<A>;
26
+ export declare class InvalidIdFormatError extends InvalidIdFormatError_base<{
27
+ readonly message: string;
28
+ readonly rule: 'non-empty' | 'no-colon';
29
+ readonly id: unknown;
30
+ }> {
31
+ }
32
+ /** The 26-character TypeID suffix for a UUID's 16 bytes: 128 bits, left-padded to 130. */
33
+ export declare function encodeTypeIdSuffix(uuid: Uint8Array): string;
34
+ /** `<prefix>_<suffix>` for a UUID's 16 bytes, per TypeID 0.3. */
35
+ export declare function typeId(prefix: string, uuid: Uint8Array): string;
36
+ /**
37
+ * UUIDv7 bytes (RFC 9562): a 48-bit millisecond timestamp, then random bits. Ids drawn in the same
38
+ * millisecond, or after the clock steps back, increment the previous random bits (section 6.2,
39
+ * method 2), so every id this process draws sorts after the one before it.
40
+ */
41
+ export declare function uuidV7(): Uint8Array;
42
+ /**
43
+ * The default id format: [TypeID](https://github.com/jetify-com/typeid) 0.3. Ids are `evt_`,
44
+ * `run_`, `thr_`, or `wait_` followed by 26 characters. Drawn ids carry a UUIDv7 and sort by
45
+ * creation time within a process; derived ids carry a UUIDv8 hashed from their parts.
46
+ */
47
+ export declare const typeIds: LoomsIds;
48
+ /**
49
+ * The format an `ids` option names, or {@link typeIds} without one. A custom format is tried once
50
+ * for every kind here, and every id it returns later is checked against the same rules; a
51
+ * violation throws {@link InvalidIdFormatError}.
52
+ */
53
+ export declare function resolveIds(ids?: LoomsIds): LoomsIds;
54
+ /** A fresh event id in the default format. A configured format is `ids.create('event')`. */
1
55
  export declare function createEventId(): string;
56
+ /** A fresh run id in the default format. A configured format is `ids.create('run')`. */
2
57
  export declare function createRunId(): string;
58
+ /** A fresh thread id in the default format. A configured format is `ids.create('thread')`. */
3
59
  export declare function createThreadId(): string;
4
- /** A stable `run_` id derived from `parts`, so a retry launches the same child run. */
5
- export declare function deterministicRunId(...parts: readonly (string | number)[]): string;
6
60
  /**
7
- * A UUID-shaped id derived only from `parts`, so a reducer that replays the same events names the same
8
- * child thread every time.
61
+ * A stable run id in the default format, so a retry launches the same child run. A configured
62
+ * format is `ctx.ids.derive('run', parts)`.
63
+ */
64
+ export declare function deterministicRunId(...parts: readonly IdPart[]): string;
65
+ /**
66
+ * A thread id in the default format derived only from `parts`, so a reducer that replays the same
67
+ * events names the same child thread every time. A configured format is
68
+ * `ctx.ids.derive('thread', parts)`.
69
+ */
70
+ export declare function deterministicThreadId(...parts: readonly IdPart[]): string;
71
+ /**
72
+ * A wait id. With `scope` and `tag` it is the composed key `wait_<scope>_<tag>` and draws nothing.
73
+ * Without a tag it draws from the default format; a configured format is `ids.create('wait')`.
9
74
  */
10
- export declare function deterministicThreadId(...parts: readonly (string | number)[]): string;
11
75
  export declare function createWaitId(scope?: string, tag?: string | number): string;
12
76
  export declare function createEffectId(threadId: string, causingSeqOrTag: number | string, index?: number): string;
13
77
  export declare function parseEffectId(effectId: string): {
@@ -16,3 +80,4 @@ export declare function parseEffectId(effectId: string): {
16
80
  tag?: string;
17
81
  index?: number;
18
82
  } | null;
83
+ export {};