@swirls/looms 0.25.0 → 0.27.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 (109) hide show
  1. package/CHANGELOG.md +42 -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 +16 -4
  11. package/dist/agent/effects.js +20 -9
  12. package/dist/agent/llm.d.ts +3 -1
  13. package/dist/agent/threads.js +4 -1
  14. package/dist/ai-vercel/messages.d.ts +3 -3
  15. package/dist/ai-vercel/messages.js +23 -6
  16. package/dist/ai-vercel/vercel-llm.js +1 -1
  17. package/dist/approval/steps.d.ts +3 -1
  18. package/dist/approval/steps.js +2 -2
  19. package/dist/client/client.d.ts +7 -1
  20. package/dist/client/client.js +5 -2
  21. package/dist/cloudflare/durable-object.d.ts +3 -1
  22. package/dist/cloudflare/durable-object.js +1 -0
  23. package/dist/cloudflare/queue-consumer.d.ts +3 -1
  24. package/dist/cloudflare/queue-consumer.js +2 -1
  25. package/dist/cloudflare/router.d.ts +3 -1
  26. package/dist/cloudflare/router.js +1 -1
  27. package/dist/core/compose.d.ts +8 -2
  28. package/dist/core/compose.js +6 -3
  29. package/dist/core/effects.d.ts +3 -0
  30. package/dist/core/envelope.d.ts +2 -0
  31. package/dist/core/envelope.js +2 -2
  32. package/dist/core/event-codec.d.ts +4 -3
  33. package/dist/core/event-codec.js +7 -7
  34. package/dist/core/fold.d.ts +3 -0
  35. package/dist/core/fold.js +3 -1
  36. package/dist/core/fork.js +1 -1
  37. package/dist/core/ids.d.ts +70 -5
  38. package/dist/core/ids.js +164 -41
  39. package/dist/core/snapshots.d.ts +2 -0
  40. package/dist/core/snapshots.js +2 -1
  41. package/dist/core/thread.d.ts +8 -0
  42. package/dist/debugger/app/assets/{index-GLtrulmj.js → index-D_FKxPrN.js} +2 -2
  43. package/dist/debugger/app/assets/routes-CkwzFejg.js +47 -0
  44. package/dist/debugger/app/index.html +1 -1
  45. package/dist/debugger/context.d.ts +4 -1
  46. package/dist/debugger/context.js +4 -4
  47. package/dist/debugger/shell/debugger-shell.d.ts +4 -1
  48. package/dist/debugger/shell/debugger-shell.js +2 -2
  49. package/dist/debugger/shell/use-start-run.d.ts +1 -1
  50. package/dist/debugger/shell/use-start-run.js +1 -2
  51. package/dist/evaluator/steps.d.ts +2 -2
  52. package/dist/evaluator/steps.js +3 -3
  53. package/dist/react/react.d.ts +8 -3
  54. package/dist/react/react.js +15 -2
  55. package/dist/react/store.d.ts +5 -1
  56. package/dist/react/store.js +5 -4
  57. package/dist/runtime/cancellation.js +5 -5
  58. package/dist/runtime/deadline-transition-planner.d.ts +1 -0
  59. package/dist/runtime/deadline-transition-planner.js +8 -7
  60. package/dist/runtime/effect-admission.js +1 -0
  61. package/dist/runtime/helpers.d.ts +6 -5
  62. package/dist/runtime/helpers.js +8 -8
  63. package/dist/runtime/local-effect-executor.js +15 -10
  64. package/dist/runtime/looms.d.ts +6 -1
  65. package/dist/runtime/looms.js +4 -1
  66. package/dist/runtime/retry-policy.d.ts +2 -1
  67. package/dist/runtime/retry-policy.js +2 -1
  68. package/dist/runtime/runtime.js +10 -10
  69. package/dist/runtime/server/routes/runs.js +5 -5
  70. package/dist/runtime/types.d.ts +7 -1
  71. package/dist/runtime/wake-engine.js +10 -9
  72. package/dist/runtime/worker-callbacks.js +9 -8
  73. package/dist/runtime/worker-effect-dispatch.d.ts +3 -2
  74. package/dist/runtime/worker-effect-dispatch.js +7 -5
  75. package/dist/swarm/board.d.ts +51 -3
  76. package/dist/swarm/board.js +8 -0
  77. package/dist/swarm/conformance.js +54 -1
  78. package/dist/swarm/definitions.d.ts +15 -0
  79. package/dist/swarm/definitions.js +3 -0
  80. package/dist/swarm/effects.d.ts +1009 -31
  81. package/dist/swarm/effects.js +73 -18
  82. package/dist/swarm/ensure.d.ts +9 -2
  83. package/dist/swarm/ensure.js +2 -1
  84. package/dist/swarm/events.d.ts +51 -0
  85. package/dist/swarm/events.js +10 -0
  86. package/dist/swarm/index.d.ts +1 -0
  87. package/dist/swarm/index.js +1 -0
  88. package/dist/swarm/memory-board.js +18 -2
  89. package/dist/swarm/module.d.ts +2055 -115
  90. package/dist/swarm/module.js +3 -1
  91. package/dist/swarm/prompt.d.ts +5 -0
  92. package/dist/swarm/prompt.js +27 -2
  93. package/dist/swarm/scope.d.ts +80 -0
  94. package/dist/swarm/services.d.ts +2 -2
  95. package/dist/swarm/services.js +5 -2
  96. package/dist/swarm/steps.d.ts +3 -3
  97. package/dist/swarm/steps.js +5 -5
  98. package/dist/swarm/threads.d.ts +4 -0
  99. package/dist/swarm/threads.js +24 -2
  100. package/dist/swarm/tools.d.ts +3 -2
  101. package/dist/swarm/tools.js +25 -18
  102. package/dist/workflow/effects.js +6 -5
  103. package/dist/workflow/graph.d.ts +3 -3
  104. package/dist/workflow/graph.js +5 -5
  105. package/dist/workflow/module.d.ts +8 -2
  106. package/dist/workflow/threads.d.ts +14 -2
  107. package/dist/workflow/threads.js +54 -44
  108. package/package.json +1 -1
  109. package/dist/debugger/app/assets/routes-CECZJJob.js +0 -47
@@ -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 {};
package/dist/core/ids.js CHANGED
@@ -1,63 +1,186 @@
1
- import { DateTime, Predicate } from 'effect';
2
- let counter = 0;
3
- function token() {
4
- counter += 1;
5
- const timestamp = DateTime.toEpochMillis(DateTime.nowUnsafe());
6
- // Synchronous ID factories need process-independent entropy without an Effect runtime.
7
- // oxlint-disable-next-line effecttsgo/crypto-random-uuid
8
- const entropy = globalThis.crypto.randomUUID().replaceAll('-', '');
9
- return `${timestamp.toString(36)}_${counter.toString(36)}_${entropy}`;
1
+ import { sha256 } from '@noble/hashes/sha2.js';
2
+ import { Data, DateTime, Predicate } from 'effect';
3
+ export class InvalidIdFormatError extends Data.TaggedError('InvalidIdFormatError') {
10
4
  }
5
+ const TYPEID_PREFIX = {
6
+ event: 'evt',
7
+ run: 'run',
8
+ thread: 'thr',
9
+ wait: 'wait',
10
+ };
11
+ const CROCKFORD = '0123456789abcdefghjkmnpqrstvwxyz';
12
+ /** The 26-character TypeID suffix for a UUID's 16 bytes: 128 bits, left-padded to 130. */
13
+ export function encodeTypeIdSuffix(uuid) {
14
+ if (uuid.length !== 16) {
15
+ throw new RangeError(`A TypeID suffix encodes 16 bytes, got ${uuid.length}`);
16
+ }
17
+ let value = 0n;
18
+ for (const byte of uuid) {
19
+ value = (value << 8n) | BigInt(byte);
20
+ }
21
+ let suffix = '';
22
+ for (let index = 0; index < 26; index++) {
23
+ suffix = CROCKFORD.charAt(Number(value & 31n)) + suffix;
24
+ value >>= 5n;
25
+ }
26
+ return suffix;
27
+ }
28
+ /** `<prefix>_<suffix>` for a UUID's 16 bytes, per TypeID 0.3. */
29
+ export function typeId(prefix, uuid) {
30
+ return `${prefix}_${encodeTypeIdSuffix(uuid)}`;
31
+ }
32
+ const RANDOM_BYTES = 10;
33
+ let lastTimestamp = -1;
34
+ const lastRandom = new Uint8Array(RANDOM_BYTES);
35
+ /** How many bits of each `lastRandom` byte the UUID carries: 4 + 8 for rand_a, 6 + 56 for rand_b. */
36
+ const RANDOM_MASKS = [0x0f, 0xff, 0x3f, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff];
37
+ function drawRandom() {
38
+ globalThis.crypto.getRandomValues(lastRandom);
39
+ lastRandom[2] = lastRandom[2] & 0x3f;
40
+ // Clear the top bit so a burst within one millisecond has room to count up.
41
+ lastRandom[0] = lastRandom[0] & 0x07;
42
+ }
43
+ /** Add one to the 74 random bits. Returns false when they wrap. */
44
+ function incrementRandom() {
45
+ for (let index = RANDOM_BYTES - 1; index >= 0; index--) {
46
+ lastRandom[index] = (lastRandom[index] + 1) & RANDOM_MASKS[index];
47
+ if (lastRandom[index] !== 0) {
48
+ return true;
49
+ }
50
+ }
51
+ return false;
52
+ }
53
+ /**
54
+ * UUIDv7 bytes (RFC 9562): a 48-bit millisecond timestamp, then random bits. Ids drawn in the same
55
+ * millisecond, or after the clock steps back, increment the previous random bits (section 6.2,
56
+ * method 2), so every id this process draws sorts after the one before it.
57
+ */
58
+ export function uuidV7() {
59
+ const now = DateTime.toEpochMillis(DateTime.nowUnsafe());
60
+ if (now > lastTimestamp) {
61
+ lastTimestamp = now;
62
+ drawRandom();
63
+ }
64
+ else if (!incrementRandom()) {
65
+ lastTimestamp += 1;
66
+ drawRandom();
67
+ }
68
+ const bytes = new Uint8Array(16);
69
+ let timestamp = lastTimestamp;
70
+ for (let index = 5; index >= 0; index--) {
71
+ bytes[index] = timestamp % 256;
72
+ timestamp = Math.floor(timestamp / 256);
73
+ }
74
+ bytes[6] = 0x70 | lastRandom[0];
75
+ bytes[7] = lastRandom[1];
76
+ bytes[8] = 0x80 | lastRandom[2];
77
+ bytes.set(lastRandom.subarray(3), 9);
78
+ return bytes;
79
+ }
80
+ const encoder = new TextEncoder();
81
+ /**
82
+ * UUIDv8 bytes whose 122 free bits are the leading bits of SHA-256 over `kind` and `parts`. Parts
83
+ * are hashed as JSON, so `['a:b', 'c']` and `['a', 'b:c']` differ, and so do `1` and `'1'`.
84
+ */
85
+ function derivedUuid(kind, parts) {
86
+ const bytes = sha256(encoder.encode(`${kind}\n${JSON.stringify(parts)}`)).slice(0, 16);
87
+ bytes[6] = 0x80 | (bytes[6] & 0x0f);
88
+ bytes[8] = 0x80 | (bytes[8] & 0x3f);
89
+ return bytes;
90
+ }
91
+ /**
92
+ * The default id format: [TypeID](https://github.com/jetify-com/typeid) 0.3. Ids are `evt_`,
93
+ * `run_`, `thr_`, or `wait_` followed by 26 characters. Drawn ids carry a UUIDv7 and sort by
94
+ * creation time within a process; derived ids carry a UUIDv8 hashed from their parts.
95
+ */
96
+ export const typeIds = {
97
+ create: (kind) => typeId(TYPEID_PREFIX[kind], uuidV7()),
98
+ derive: (kind, parts) => typeId(TYPEID_PREFIX[kind], derivedUuid(kind, parts)),
99
+ };
100
+ function checkId(id, source) {
101
+ if (!Predicate.isString(id) || id.length === 0) {
102
+ throw new InvalidIdFormatError({
103
+ rule: 'non-empty',
104
+ id,
105
+ message: `Invalid id format: ${source} must return a non-empty string, got ${JSON.stringify(id)}`,
106
+ });
107
+ }
108
+ if (id.includes(':')) {
109
+ throw new InvalidIdFormatError({
110
+ rule: 'no-colon',
111
+ id,
112
+ message: `Invalid id format: ${source} returned ${JSON.stringify(id)}, which contains ":". Ids must not contain ":" because effect ids are "<threadId>:<tag>"`,
113
+ });
114
+ }
115
+ return id;
116
+ }
117
+ const checked = new WeakSet([typeIds]);
118
+ const DRAWN_KINDS = ['event', 'run', 'thread', 'wait'];
119
+ const DERIVED_KINDS = ['run', 'thread'];
120
+ /**
121
+ * The format an `ids` option names, or {@link typeIds} without one. A custom format is tried once
122
+ * for every kind here, and every id it returns later is checked against the same rules; a
123
+ * violation throws {@link InvalidIdFormatError}.
124
+ */
125
+ export function resolveIds(ids) {
126
+ if (ids === undefined) {
127
+ return typeIds;
128
+ }
129
+ if (checked.has(ids)) {
130
+ return ids;
131
+ }
132
+ const resolved = {
133
+ create: (kind) => checkId(ids.create(kind), `ids.create('${kind}')`),
134
+ derive: (kind, parts) => checkId(ids.derive(kind, parts), `ids.derive('${kind}', parts)`),
135
+ };
136
+ for (const kind of DRAWN_KINDS) {
137
+ resolved.create(kind);
138
+ }
139
+ for (const kind of DERIVED_KINDS) {
140
+ resolved.derive(kind, ['looms', 0]);
141
+ }
142
+ checked.add(resolved);
143
+ return resolved;
144
+ }
145
+ /** A fresh event id in the default format. A configured format is `ids.create('event')`. */
11
146
  export function createEventId() {
12
- return `evt_${token()}`;
147
+ return typeIds.create('event');
13
148
  }
149
+ /** A fresh run id in the default format. A configured format is `ids.create('run')`. */
14
150
  export function createRunId() {
15
- return `run_${token()}`;
151
+ return typeIds.create('run');
16
152
  }
153
+ /** A fresh thread id in the default format. A configured format is `ids.create('thread')`. */
17
154
  export function createThreadId() {
18
- return `thr_${token()}`;
19
- }
20
- function fnv1a32(value, seed) {
21
- let hash = seed >>> 0;
22
- for (let index = 0; index < value.length; index++) {
23
- hash ^= value.charCodeAt(index);
24
- hash = Math.imul(hash, 0x01000193);
25
- }
26
- return (hash >>> 0).toString(16).padStart(8, '0');
155
+ return typeIds.create('thread');
27
156
  }
28
- /** A stable `run_` id derived from `parts`, so a retry launches the same child run. */
157
+ /**
158
+ * A stable run id in the default format, so a retry launches the same child run. A configured
159
+ * format is `ctx.ids.derive('run', parts)`.
160
+ */
29
161
  export function deterministicRunId(...parts) {
30
- return `run_${deterministicThreadId(...parts).replaceAll('-', '')}`;
162
+ return typeIds.derive('run', parts);
31
163
  }
32
164
  /**
33
- * A UUID-shaped id derived only from `parts`, so a reducer that replays the same events names the same
34
- * child thread every time.
165
+ * A thread id in the default format derived only from `parts`, so a reducer that replays the same
166
+ * events names the same child thread every time. A configured format is
167
+ * `ctx.ids.derive('thread', parts)`.
35
168
  */
36
169
  export function deterministicThreadId(...parts) {
37
- const source = parts.join(':');
38
- let reversed = '';
39
- for (let index = source.length - 1; index >= 0; index--) {
40
- reversed += source.charAt(index);
41
- }
42
- const hex = [
43
- fnv1a32(source, 0x811c9dc5),
44
- fnv1a32(source, 0x9e3779b9),
45
- fnv1a32(reversed, 0x85ebca6b),
46
- fnv1a32(reversed, 0xc2b2ae35),
47
- ].join('');
48
- return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-5${hex.slice(13, 16)}-${((Number.parseInt(hex.slice(16, 18), 16) & 0x3f) |
49
- 0x80)
50
- .toString(16)
51
- .padStart(2, '0')}${hex.slice(18, 20)}-${hex.slice(20)}`;
170
+ return typeIds.derive('thread', parts);
52
171
  }
172
+ /**
173
+ * A wait id. With `scope` and `tag` it is the composed key `wait_<scope>_<tag>` and draws nothing.
174
+ * Without a tag it draws from the default format; a configured format is `ids.create('wait')`.
175
+ */
53
176
  export function createWaitId(scope, tag) {
54
177
  if (scope !== undefined && tag !== undefined) {
55
178
  return `wait_${scope}_${tag}`;
56
179
  }
57
180
  if (scope !== undefined) {
58
- return `wait_${scope}_${token()}`;
181
+ return `wait_${scope}_${encodeTypeIdSuffix(uuidV7())}`;
59
182
  }
60
- return `wait_${token()}`;
183
+ return typeIds.create('wait');
61
184
  }
62
185
  export function createEffectId(threadId, causingSeqOrTag, index) {
63
186
  if (Predicate.isString(causingSeqOrTag)) {
@@ -1,6 +1,7 @@
1
1
  import { Schema } from 'effect';
2
2
  import { type EventEnvelope } from './envelope';
3
3
  import { type FoldRegistry } from './fold';
4
+ import type { LoomsIds } from './ids';
4
5
  import { type RunState } from './state';
5
6
  import { type JsonValue } from './types';
6
7
  export declare const DEFAULT_SNAPSHOT_EVERY = 200;
@@ -23,6 +24,7 @@ export declare function buildSnapshotEvent(runId: string, events: readonly Event
23
24
  export declare function buildSnapshotMarker(runId: string, cursor: number, stateHash: string, options?: {
24
25
  state?: RunState;
25
26
  maxInlineBytes?: number;
27
+ ids?: LoomsIds;
26
28
  }): EventEnvelope;
27
29
  export declare function foldFromSnapshots(events: readonly EventEnvelope[], registry: FoldRegistry, options?: {
28
30
  runId?: string;
@@ -34,6 +34,7 @@ export function buildSnapshotEvent(runId, events, registry, options) {
34
34
  const last = events[events.length - 1];
35
35
  return buildSnapshotMarker(runId, last?.seq ?? 0, hashRunState(state), {
36
36
  state: options?.includeState ? state : undefined,
37
+ ids: registry.ids,
37
38
  });
38
39
  }
39
40
  /**
@@ -55,7 +56,7 @@ export function buildSnapshotMarker(runId, cursor, stateHash, options) {
55
56
  payload,
56
57
  threadId: null,
57
58
  origin: { type: 'system' },
58
- });
59
+ }, { ids: options?.ids });
59
60
  }
60
61
  export function foldFromSnapshots(events, registry, options) {
61
62
  const runId = options?.runId ?? events[0]?.runId ?? 'unknown';
@@ -1,5 +1,6 @@
1
1
  import type { RuntimeEffect } from './effects';
2
2
  import type { EventEnvelope } from './envelope';
3
+ import type { LoomsIds } from './ids';
3
4
  import type { InferDefinedSchema, InferSchemaOutput, SchemaInput } from './schema';
4
5
  import type { ThreadStatus, JsonValue } from './types';
5
6
  export interface StartContext<TInput = JsonValue> {
@@ -9,11 +10,18 @@ export interface StartContext<TInput = JsonValue> {
9
10
  readonly definitionName: string;
10
11
  readonly definitionVersion: string;
11
12
  readonly input: TInput;
13
+ /** The id format this registry was composed with. */
14
+ readonly ids: LoomsIds;
12
15
  }
13
16
  export interface ThreadContext {
14
17
  readonly runId: string;
15
18
  readonly threadId: string;
16
19
  readonly parentThreadId: string | null;
20
+ /**
21
+ * The id format this registry was composed with. Name a child with `ids.derive`, never
22
+ * `ids.create`: a reducer runs again on every replay.
23
+ */
24
+ readonly ids: LoomsIds;
17
25
  }
18
26
  export interface ThreadDefinition<S = any> {
19
27
  readonly kind: string;