@swirls/looms 0.24.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 (116) hide show
  1. package/CHANGELOG.md +34 -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/agent/threads.js +4 -1
  14. package/dist/approval/effects.d.ts +26 -26
  15. package/dist/approval/module.d.ts +52 -52
  16. package/dist/approval/steps.d.ts +3 -1
  17. package/dist/approval/steps.js +2 -2
  18. package/dist/client/client.d.ts +7 -1
  19. package/dist/client/client.js +5 -2
  20. package/dist/cloudflare/durable-object.d.ts +3 -1
  21. package/dist/cloudflare/durable-object.js +1 -0
  22. package/dist/cloudflare/queue-consumer.d.ts +3 -1
  23. package/dist/cloudflare/queue-consumer.js +2 -1
  24. package/dist/cloudflare/router.d.ts +3 -1
  25. package/dist/cloudflare/router.js +1 -1
  26. package/dist/core/compose.d.ts +8 -2
  27. package/dist/core/compose.js +6 -3
  28. package/dist/core/effects.d.ts +3 -0
  29. package/dist/core/envelope.d.ts +2 -0
  30. package/dist/core/envelope.js +2 -2
  31. package/dist/core/event-codec.d.ts +4 -3
  32. package/dist/core/event-codec.js +7 -7
  33. package/dist/core/fold.d.ts +3 -0
  34. package/dist/core/fold.js +3 -1
  35. package/dist/core/fork.js +1 -1
  36. package/dist/core/ids.d.ts +70 -5
  37. package/dist/core/ids.js +164 -41
  38. package/dist/core/snapshots.d.ts +2 -0
  39. package/dist/core/snapshots.js +2 -1
  40. package/dist/core/thread.d.ts +8 -0
  41. package/dist/debugger/app/assets/index-D_FKxPrN.js +23 -0
  42. package/dist/debugger/app/assets/routes-CkwzFejg.js +47 -0
  43. package/dist/debugger/app/index.html +1 -1
  44. package/dist/debugger/context.d.ts +4 -1
  45. package/dist/debugger/context.js +4 -4
  46. package/dist/debugger/shell/debugger-shell.d.ts +4 -1
  47. package/dist/debugger/shell/debugger-shell.js +2 -2
  48. package/dist/debugger/shell/use-start-run.d.ts +1 -1
  49. package/dist/debugger/shell/use-start-run.js +1 -2
  50. package/dist/evaluator/steps.d.ts +2 -2
  51. package/dist/evaluator/steps.js +3 -3
  52. package/dist/react/react.d.ts +8 -3
  53. package/dist/react/react.js +15 -2
  54. package/dist/react/store.d.ts +5 -1
  55. package/dist/react/store.js +5 -4
  56. package/dist/runtime/cancellation.js +5 -5
  57. package/dist/runtime/deadline-transition-planner.d.ts +1 -0
  58. package/dist/runtime/deadline-transition-planner.js +8 -7
  59. package/dist/runtime/effect-admission.js +1 -0
  60. package/dist/runtime/helpers.d.ts +6 -5
  61. package/dist/runtime/helpers.js +8 -8
  62. package/dist/runtime/local-effect-executor.js +15 -10
  63. package/dist/runtime/looms.d.ts +6 -1
  64. package/dist/runtime/looms.js +4 -1
  65. package/dist/runtime/retry-policy.d.ts +2 -1
  66. package/dist/runtime/retry-policy.js +2 -1
  67. package/dist/runtime/runtime.js +10 -10
  68. package/dist/runtime/server/routes/runs.js +5 -5
  69. package/dist/runtime/types.d.ts +7 -1
  70. package/dist/runtime/wake-engine.js +10 -9
  71. package/dist/runtime/worker-callbacks.js +9 -8
  72. package/dist/runtime/worker-effect-dispatch.d.ts +3 -2
  73. package/dist/runtime/worker-effect-dispatch.js +7 -5
  74. package/dist/swarm/board.d.ts +292 -0
  75. package/dist/swarm/board.js +123 -0
  76. package/dist/swarm/conformance.d.ts +15 -0
  77. package/dist/swarm/conformance.js +225 -0
  78. package/dist/swarm/definitions.d.ts +94 -0
  79. package/dist/swarm/definitions.js +51 -0
  80. package/dist/swarm/effects.d.ts +4720 -0
  81. package/dist/swarm/effects.js +296 -0
  82. package/dist/swarm/ensure.d.ts +16 -0
  83. package/dist/swarm/ensure.js +24 -0
  84. package/dist/swarm/events.d.ts +240 -0
  85. package/dist/swarm/events.js +49 -0
  86. package/dist/swarm/index.d.ts +15 -0
  87. package/dist/swarm/index.js +15 -0
  88. package/dist/swarm/memory-board.d.ts +10 -0
  89. package/dist/swarm/memory-board.js +344 -0
  90. package/dist/swarm/module.d.ts +9593 -0
  91. package/dist/swarm/module.js +94 -0
  92. package/dist/swarm/projections.d.ts +60 -0
  93. package/dist/swarm/projections.js +102 -0
  94. package/dist/swarm/prompt.d.ts +4 -0
  95. package/dist/swarm/prompt.js +35 -0
  96. package/dist/swarm/scope.d.ts +357 -0
  97. package/dist/swarm/scope.js +8 -0
  98. package/dist/swarm/services.d.ts +29 -0
  99. package/dist/swarm/services.js +40 -0
  100. package/dist/swarm/signals.d.ts +14 -0
  101. package/dist/swarm/signals.js +15 -0
  102. package/dist/swarm/steps.d.ts +15 -0
  103. package/dist/swarm/steps.js +27 -0
  104. package/dist/swarm/threads.d.ts +41 -0
  105. package/dist/swarm/threads.js +244 -0
  106. package/dist/swarm/tools.d.ts +20 -0
  107. package/dist/swarm/tools.js +100 -0
  108. package/dist/workflow/effects.js +6 -5
  109. package/dist/workflow/graph.d.ts +3 -3
  110. package/dist/workflow/graph.js +5 -5
  111. package/dist/workflow/module.d.ts +8 -2
  112. package/dist/workflow/threads.d.ts +14 -2
  113. package/dist/workflow/threads.js +54 -44
  114. package/package.json +7 -2
  115. package/dist/debugger/app/assets/index-CxbIGkpY.js +0 -22
  116. package/dist/debugger/app/assets/routes-Ch30UGik.js +0 -47
@@ -4,7 +4,7 @@
4
4
  <meta charset="UTF-8" />
5
5
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
6
6
  <title>Looms debugger</title>
7
- <script type="module" crossorigin src="./assets/index-CxbIGkpY.js"></script>
7
+ <script type="module" crossorigin src="./assets/index-D_FKxPrN.js"></script>
8
8
  <link rel="modulepreload" crossorigin href="./assets/rolldown-runtime-CbXtAM7H.js">
9
9
  <link rel="stylesheet" crossorigin href="./assets/index-CO5gIvV8.css">
10
10
  </head>
@@ -1,5 +1,6 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import { type LoomsClient } from '@swirls/looms/client';
3
+ import type { LoomsIds } from '@swirls/looms/core';
3
4
  import type { DebuggerPlugin } from './plugin';
4
5
  /** Where to land in a run another view links to. */
5
6
  export interface OpenRunTarget {
@@ -12,8 +13,10 @@ export interface DebuggerContextValue {
12
13
  readonly openRun?: (runId: string, target?: OpenRunTarget) => void;
13
14
  }
14
15
  /** Supplies one Looms host to both the API client and the run stores. */
15
- export declare function DebuggerProvider({ endpoint, plugins, openRun, children, }: {
16
+ export declare function DebuggerProvider({ endpoint, plugins, openRun, ids, children, }: {
16
17
  endpoint?: string;
18
+ /** The id format for runs and messages started here. Match the host's `ids`. */
19
+ ids?: LoomsIds;
17
20
  plugins: readonly DebuggerPlugin[];
18
21
  openRun?: (runId: string, target?: OpenRunTarget) => void;
19
22
  children: ReactNode;
@@ -4,7 +4,7 @@ import { createLoomsClient } from '@swirls/looms/client';
4
4
  import { LoomsProvider } from '@swirls/looms/react';
5
5
  const DebuggerContext = createContext(null);
6
6
  /** Supplies one Looms host to both the API client and the run stores. */
7
- export function DebuggerProvider({ endpoint = '', plugins, openRun, children, }) {
7
+ export function DebuggerProvider({ endpoint = '', plugins, openRun, ids, children, }) {
8
8
  const openRunRef = useRef(openRun);
9
9
  openRunRef.current = openRun;
10
10
  const hasOpenRun = openRun !== undefined;
@@ -12,13 +12,13 @@ export function DebuggerProvider({ endpoint = '', plugins, openRun, children, })
12
12
  openRunRef.current?.(runId, target);
13
13
  }, []);
14
14
  const value = useMemo(() => {
15
- const client = createLoomsClient({ baseUrl: endpoint });
15
+ const client = createLoomsClient({ baseUrl: endpoint, ids });
16
16
  if (!hasOpenRun) {
17
17
  return { client, plugins };
18
18
  }
19
19
  return { client, plugins, openRun: stableOpenRun };
20
- }, [endpoint, plugins, hasOpenRun, stableOpenRun]);
21
- return (_jsx(LoomsProvider, { endpoint: endpoint, children: _jsx(DebuggerContext.Provider, { value: value, children: children }) }));
20
+ }, [endpoint, ids, plugins, hasOpenRun, stableOpenRun]);
21
+ return (_jsx(LoomsProvider, { endpoint: endpoint, ids: ids, children: _jsx(DebuggerContext.Provider, { value: value, children: children }) }));
22
22
  }
23
23
  export function useDebugger() {
24
24
  const value = useContext(DebuggerContext);
@@ -1,3 +1,4 @@
1
+ import type { LoomsIds } from '@swirls/looms/core';
1
2
  import type { DebuggerPlugin } from '../plugin';
2
3
  export interface DebuggerSelection {
3
4
  readonly kind?: string;
@@ -6,10 +7,12 @@ export interface DebuggerSelection {
6
7
  readonly thread?: string;
7
8
  readonly seq?: number;
8
9
  }
9
- export declare function DebuggerShell({ plugins, selection, onSelectionChange, endpoint, }: {
10
+ export declare function DebuggerShell({ plugins, selection, onSelectionChange, endpoint, ids, }: {
10
11
  plugins: readonly DebuggerPlugin[];
11
12
  selection: DebuggerSelection;
12
13
  onSelectionChange: (selection: DebuggerSelection) => void;
13
14
  /** Looms host base URL. Defaults to the page origin. */
14
15
  endpoint?: string;
16
+ /** The id format for runs started here. Match the host's `ids`. Defaults to `typeIds`. */
17
+ ids?: LoomsIds;
15
18
  }): import("react").JSX.Element;
@@ -38,6 +38,6 @@ function DebuggerFrame({ selection, onSelectionChange, }) {
38
38
  run: run.runId,
39
39
  }) }), _jsxs("div", { className: "ml-auto flex min-w-0 items-center gap-2", children: [error ? (_jsx("p", { className: "text-status-failed truncate text-[11px]", title: error, children: error })) : null, selection.run ? (_jsx(RunControls, { runId: selection.run, onForked: (run) => onSelectionChange({ kind, name, run }) })) : null] })] }), _jsxs(ResizablePanelGroup, { id: "looms-debugger-columns", className: "min-h-0 flex-1", defaultLayout: layout.defaultLayout, onLayoutChanged: layout.onLayoutChanged, children: [_jsx(ResizablePanel, { id: "tree", defaultSize: "17%", minSize: "12rem", maxSize: "30%", className: "bg-sidebar", children: _jsx("section", { "aria-label": "Run tree", className: "h-full min-h-0 overflow-hidden", children: selection.run ? (_jsx(RunTreePane, { runId: selection.run, threadId: selection.thread, onSelectThread: (thread) => onSelectionChange({ ...selection, thread, seq: undefined }) })) : (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(PanelHeader, { children: _jsx(PanelTitle, { children: "Run tree" }) }), _jsx(EmptyState, { icon: _jsx(ListTree, {}), title: "No run selected", children: "Threads and child runs appear here once a run starts." })] })) }) }), _jsx(ResizableHandle, {}), _jsx(ResizablePanel, { id: "workspace", defaultSize: "29%", minSize: "16rem", children: _jsx("section", { "aria-label": "Workspace", className: "@container h-full min-h-0 overflow-hidden", children: _jsx(Workspace, { definition: selected, runId: selection.run, onStarted: (run) => onSelectionChange({ kind, name, run }) }) }) }), _jsx(ResizableHandle, {}), _jsx(ResizablePanel, { id: "events", defaultSize: "32%", minSize: "16rem", children: _jsx("section", { "aria-label": "Events", className: "h-full min-h-0 overflow-hidden", children: selection.run ? (_jsx(EventsPane, { runId: selection.run, threadId: selection.thread, seq: selection.seq, onSelectSeq: (seq) => onSelectionChange({ ...selection, seq }), onClearThread: () => onSelectionChange({ ...selection, thread: undefined }) })) : (_jsxs("div", { className: "flex h-full flex-col", children: [_jsx(PanelHeader, { children: _jsx(PanelTitle, { children: "Events" }) }), _jsx(EmptyState, { icon: _jsx(Activity, {}), title: "No events yet", children: "Events stream in live once a run starts." })] })) }) }), _jsx(ResizableHandle, {}), _jsx(ResizablePanel, { id: "projections", defaultSize: "22%", minSize: "14rem", className: "bg-sidebar", children: _jsx("section", { "aria-label": "Projections", className: "h-full min-h-0 overflow-hidden", children: _jsx(ProjectionsPanel, { runId: selection.run, names: catalog.projections }) }) })] })] }));
40
40
  }
41
- export function DebuggerShell({ plugins, selection, onSelectionChange, endpoint, }) {
42
- return (_jsx(DebuggerProvider, { endpoint: endpoint, plugins: plugins, openRun: (runId, target) => onSelectionChange({ run: runId, seq: target?.seq }), children: _jsx(DebuggerFrame, { selection: selection, onSelectionChange: onSelectionChange }) }));
41
+ export function DebuggerShell({ plugins, selection, onSelectionChange, endpoint, ids, }) {
42
+ return (_jsx(DebuggerProvider, { endpoint: endpoint, ids: ids, plugins: plugins, openRun: (runId, target) => onSelectionChange({ run: runId, seq: target?.seq }), children: _jsx(DebuggerFrame, { selection: selection, onSelectionChange: onSelectionChange }) }));
43
43
  }
@@ -1,4 +1,4 @@
1
- import { type JsonValue } from '@swirls/looms/core';
1
+ import type { JsonValue } from '@swirls/looms/core';
2
2
  import type { WorkspaceContext } from '../plugin';
3
3
  export interface StartedRun {
4
4
  readonly runId: string;
@@ -1,5 +1,4 @@
1
1
  import { useState } from 'react';
2
- import { createRunId } from '@swirls/looms/core';
3
2
  import { useDebugger } from '../context.js';
4
3
  import { errorMessage } from '../lib/cn.js';
5
4
  export function useStartRun({ definition, onStarted }) {
@@ -7,7 +6,7 @@ export function useStartRun({ definition, onStarted }) {
7
6
  const [pending, setPending] = useState(false);
8
7
  const [error, setError] = useState(null);
9
8
  function start(input, after) {
10
- const runId = createRunId();
9
+ const runId = client.ids.create('run');
11
10
  setPending(true);
12
11
  setError(null);
13
12
  onStarted(runId);
@@ -1,3 +1,3 @@
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 { EvaluatorDefinition } from './definitions';
3
- export declare function evaluate(definition: EvaluatorDefinition, input: JsonValue): RuntimeEffect[];
3
+ export declare function evaluate(definition: EvaluatorDefinition, input: JsonValue, ids?: LoomsIds): 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 { evaluateEffect } from './effects.js';
3
- export function evaluate(definition, input) {
4
- const evaluationId = createWaitId('evaluator');
3
+ export function evaluate(definition, input, ids = typeIds) {
4
+ const evaluationId = ids.create('wait');
5
5
  return [
6
6
  invoke(evaluateEffect, {
7
7
  evaluationId,
@@ -1,6 +1,6 @@
1
1
  import { type ReactNode } from 'react';
2
2
  import type { SubscriptionSocketConstructor } from '@swirls/looms/client';
3
- import { type AnyEventEnvelope, type ProjectionDefinition, type RegisteredEvent, type RunAttributes, type RunLaunchSource, type RunStatus, type SubscriptionTransport, type ThreadTree } from '@swirls/looms/core';
3
+ import { type AnyEventEnvelope, type LoomsIds, type ProjectionDefinition, type RegisteredEvent, type RunAttributes, type RunLaunchSource, type RunStatus, type SubscriptionTransport, type ThreadTree } from '@swirls/looms/core';
4
4
  import type { EventCache } from './cache';
5
5
  import { defineLiveFold, foldLive, type LiveFoldDefinition } from './derived';
6
6
  import type { StoreObserver } from './observer';
@@ -29,6 +29,8 @@ export interface LoomsProviderProps {
29
29
  * store connects. See `LoomsClientStoreOptions.grant`.
30
30
  */
31
31
  grant?: RunGrantSource;
32
+ /** The id format run stores draw from. See `LoomsClientStoreOptions.ids`. */
33
+ ids?: LoomsIds;
32
34
  }
33
35
  /** What gives a run's current read grant, or undefined when it has none. */
34
36
  export type RunGrantSource = (runId: string) => string | undefined;
@@ -37,6 +39,7 @@ interface StoreReach {
37
39
  readonly fetch?: typeof fetch;
38
40
  readonly webSocket?: SubscriptionSocketConstructor;
39
41
  readonly grant?: RunGrantSource;
42
+ readonly ids?: LoomsIds;
40
43
  }
41
44
  interface ProviderContextValue extends StoreReach {
42
45
  endpoint: string;
@@ -47,7 +50,7 @@ interface ProviderContextValue extends StoreReach {
47
50
  observer?: StoreObserver;
48
51
  }
49
52
  /** Root provider that supplies the Looms host endpoint to run stores. */
50
- export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
53
+ export declare function LoomsProvider({ children, endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant, ids, }: LoomsProviderProps): import("react").FunctionComponentElement<import("react").ProviderProps<ProviderContextValue>>;
51
54
  export interface UseRunStoreOptions {
52
55
  endpoint?: string;
53
56
  reconnectDelayMs?: number;
@@ -62,7 +65,7 @@ export interface UseRunStoreOptions {
62
65
  /**
63
66
  * Everything that decides which store a run gets when there is no provider to supply part of
64
67
  * it. Inside React the provider gives `endpoint`, `coalesce`, `transport`, `retainMs`, `cache`
65
- * `observer`, `fetch`, `webSocket` and `grant`; outside it the caller passes them.
68
+ * `observer`, `fetch`, `webSocket`, `grant` and `ids`; outside it the caller passes them.
66
69
  */
67
70
  export interface RunStoreOptions extends UseRunStoreOptions {
68
71
  /** Makes every HTTP request the store sends. See `LoomsClientStoreOptions.fetch`. */
@@ -71,6 +74,8 @@ export interface RunStoreOptions extends UseRunStoreOptions {
71
74
  webSocket?: SubscriptionSocketConstructor;
72
75
  /** The read grant for a run. See `LoomsClientStoreOptions.grant`. */
73
76
  grant?: RunGrantSource;
77
+ /** The id format the store draws from. See `LoomsClientStoreOptions.ids`. */
78
+ ids?: LoomsIds;
74
79
  /** Keeps the run's durable events on the device. See `indexedDbEventCache`. */
75
80
  cache?: EventCache;
76
81
  /** Told how long the run took to show and how long each commit took. */
@@ -46,6 +46,7 @@ function peekStore(runId, identity) {
46
46
  fetch: identity.fetch,
47
47
  webSocket: identity.webSocket,
48
48
  grant: identity.grant === undefined ? undefined : () => identity.grant?.(runId),
49
+ ids: identity.ids,
49
50
  });
50
51
  const retainMs = Math.max(0, identity.retainMs ?? DEFAULT_RETAIN_MS);
51
52
  registry.set(key, {
@@ -82,8 +83,19 @@ function releaseStore(runId, identity) {
82
83
  }
83
84
  }
84
85
  /** Root provider that supplies the Looms host endpoint to run stores. */
85
- export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant, }) {
86
- const value = useMemo(() => ({ endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant }), [endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant]);
86
+ export function LoomsProvider({ children, endpoint = '', coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant, ids, }) {
87
+ const value = useMemo(() => ({
88
+ endpoint,
89
+ coalesce,
90
+ transport,
91
+ retainMs,
92
+ cache,
93
+ observer,
94
+ fetch,
95
+ webSocket,
96
+ grant,
97
+ ids,
98
+ }), [endpoint, coalesce, transport, retainMs, cache, observer, fetch, webSocket, grant, ids]);
87
99
  return createElement(LoomsContext.Provider, { value, children });
88
100
  }
89
101
  /**
@@ -166,6 +178,7 @@ export function useRunStore(runId, options) {
166
178
  fetch: context.fetch,
167
179
  webSocket: context.webSocket,
168
180
  grant: context.grant,
181
+ ids: context.ids,
169
182
  };
170
183
  const store = peekStore(runId, identity);
171
184
  useEffect(() => {
@@ -1,5 +1,5 @@
1
1
  import { type SubscriptionSocketConstructor } from '@swirls/looms/client';
2
- import { type AnyEventEnvelope, type EventInput, type ProjectionDefinition, type RegisteredEvent, type SubscriptionTransport } from '@swirls/looms/core';
2
+ import { type LoomsIds, type AnyEventEnvelope, type EventInput, type ProjectionDefinition, type RegisteredEvent, type SubscriptionTransport } from '@swirls/looms/core';
3
3
  import type { EventCache } from './cache';
4
4
  import { type LiveFoldDefinition } from './derived';
5
5
  import { type CoalesceOption } from './notify';
@@ -76,6 +76,10 @@ export interface LoomsClientStoreOptions {
76
76
  fromSeq?: number;
77
77
  /** Whether `commit` shows its events before the host confirms them. Defaults to false. */
78
78
  optimistic?: boolean;
79
+ /**
80
+ * The id format for the event ids and idempotency keys of optimistic commits. Match the host's `ids`. Defaults to `typeIds` (TypeID).
81
+ */
82
+ ids?: LoomsIds;
79
83
  /**
80
84
  * Keeps the run's durable events on the device. A store that has followed the run before starts
81
85
  * from them and downloads only what was appended since. Not used together with `fromSeq`.
@@ -1,6 +1,6 @@
1
1
  import { Data, DateTime, Effect, Fiber, Option, Predicate, Schema } from 'effect';
2
2
  import { absoluteHttpBase } from '@swirls/looms/client';
3
- import { createEvent, createEventId, decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
3
+ import { createEvent, resolveIds, decodeLoomsEvent, readSubscriptionData, stringifyJson, } from '@swirls/looms/core';
4
4
  import { EventIndex, ProjectionCache } from './derived.js';
5
5
  import { materializeEvents } from './materialize.js';
6
6
  import { createNotifyScheduler } from './notify.js';
@@ -53,6 +53,7 @@ function eventSourceCtor() {
53
53
  export function createLoomsStore(options) {
54
54
  const endpoint = options.endpoint.replace(/\/$/, '');
55
55
  const fetchFn = options.fetch ?? fetch;
56
+ const ids = resolveIds(options.ids);
56
57
  const reconnectDelayMs = options.reconnectDelayMs ?? 1_000;
57
58
  const coalesce = options.coalesce ?? 'adaptive';
58
59
  const listeners = new Set();
@@ -334,7 +335,7 @@ export function createLoomsStore(options) {
334
335
  }
335
336
  const body = decodedBody.value;
336
337
  const pulledEvents = 'events' in body && Array.isArray(body.events) ? body.events : [];
337
- applyBatch(pulledEvents.map((raw) => decodeLoomsEvent(raw, options.storeId)));
338
+ applyBatch(pulledEvents.map((raw) => decodeLoomsEvent(raw, options.storeId, ids)));
338
339
  return undefined;
339
340
  }).pipe(Effect.catchIf((error) => disposed ||
340
341
  error.message.includes('fetch failed') ||
@@ -603,7 +604,7 @@ export function createLoomsStore(options) {
603
604
  commit: (event, commitOptions) => {
604
605
  const inputs = Array.isArray(event) ? event : [event];
605
606
  const optimistic = commitOptions?.optimistic ?? options.optimistic ?? false;
606
- const key = commitOptions?.idempotencyKey ?? (optimistic ? createEventId() : undefined);
607
+ const key = commitOptions?.idempotencyKey ?? (optimistic ? ids.create('event') : undefined);
607
608
  const startedAt = nowMs();
608
609
  let shown;
609
610
  if (optimistic && key !== undefined && inputs.length > 0) {
@@ -619,7 +620,7 @@ export function createLoomsStore(options) {
619
620
  threadId: input.threadId === undefined ? rootThreadId : input.threadId,
620
621
  origin: input.origin ?? { type: 'external' },
621
622
  idempotencyKey: input.idempotencyKey ?? key,
622
- }, { seq: pendingSeq });
623
+ }, { seq: pendingSeq, ids });
623
624
  }),
624
625
  };
625
626
  pendingCommits.push(shown);
@@ -34,7 +34,7 @@ function planCancellation(input) {
34
34
  effectId: item.effectId,
35
35
  origin: { type: 'system' },
36
36
  idempotencyKey,
37
- }));
37
+ }, { ids: registry.ids }));
38
38
  continue;
39
39
  }
40
40
  const timeoutMs = registry.effects.get(item.effect.type)?.retry?.cancellationTimeoutMs;
@@ -49,7 +49,7 @@ function planCancellation(input) {
49
49
  threadId: item.threadId,
50
50
  origin: { type: 'system' },
51
51
  idempotencyKey,
52
- }));
52
+ }, { ids: registry.ids }));
53
53
  }
54
54
  const threadEvents = [...descendants.toReversed(), targetThreadId]
55
55
  .filter((threadId) => threadId.length > 0)
@@ -61,11 +61,11 @@ function planCancellation(input) {
61
61
  threadId,
62
62
  origin: { type: 'external' },
63
63
  idempotencyKey,
64
- });
64
+ }, { ids: registry.ids });
65
65
  });
66
66
  const batch = [...effectEvents, ...threadEvents];
67
67
  const folded = foldRun(batch, registry, { runId, initial: state });
68
- const satisfied = waitSatisfiedEvents(folded, batch).map((event) => createEvent(runId, event));
68
+ const satisfied = waitSatisfiedEvents(folded, batch).map((event) => createEvent(runId, event, { ids: registry.ids }));
69
69
  return { events: [...batch, ...satisfied], threadIds, workerCancellations };
70
70
  }
71
71
  export function createCancellation(options) {
@@ -86,7 +86,7 @@ export function createCancellation(options) {
86
86
  threadId: current.state.rootThreadId,
87
87
  origin: { type: 'system' },
88
88
  idempotencyKey: `child-close:${current.state.rootThreadId ?? runId}`,
89
- });
89
+ }, { ids: registry.ids });
90
90
  return Effect.succeed({
91
91
  events: [requested],
92
92
  value: {
@@ -22,6 +22,7 @@ export declare function planDeadlineTransitions(input: {
22
22
  export declare function planTerminalCancellationTransitions(input: {
23
23
  readonly runId: string;
24
24
  readonly state: RunState;
25
+ readonly registry: ComposedRegistry;
25
26
  readonly now: number;
26
27
  }): ReadonlyArray<EventEnvelope>;
27
28
  /**
@@ -25,14 +25,14 @@ function planDueTimers(input) {
25
25
  payload: { timerId: record.waitId, waitId: record.waitId },
26
26
  threadId: record.threadId,
27
27
  origin: { type: 'system' },
28
- }),
28
+ }, { ids: input.registry.ids }),
29
29
  ]
30
30
  : []);
31
31
  const stateAfterFired = foldRun(fired, input.registry, {
32
32
  runId: input.runId,
33
33
  initial: input.state,
34
34
  });
35
- const satisfied = waitSatisfiedEvents(stateAfterFired, fired).map((event) => createEvent(input.runId, event));
35
+ const satisfied = waitSatisfiedEvents(stateAfterFired, fired).map((event) => createEvent(input.runId, event, { ids: input.registry.ids }));
36
36
  return {
37
37
  events: [...fired, ...satisfied],
38
38
  timerNotices: due.flatMap((record) => isWaitOnTimer(record.on)
@@ -57,7 +57,7 @@ function planExpiredExecutions(input) {
57
57
  const item = input.state.outstandingEffects.find((candidate) => candidate.effectId === execution.effectId);
58
58
  if (!item) {
59
59
  if (execution.status === 'cancel_requested') {
60
- events.push(cancellationAmbiguous(input.runId, execution.effectId, execution.attempt));
60
+ events.push(cancellationAmbiguous(input.runId, execution.effectId, execution.attempt, input.registry.ids));
61
61
  }
62
62
  continue;
63
63
  }
@@ -74,8 +74,9 @@ function planExpiredExecutions(input) {
74
74
  threadId: item.threadId,
75
75
  causationId: item.causingEventId,
76
76
  origin: { type: 'system' },
77
- }));
77
+ }, { ids: input.registry.ids }));
78
78
  events.push(planAttemptFailure({
79
+ ids: input.registry.ids,
79
80
  runId: input.runId,
80
81
  item,
81
82
  attempt: execution.attempt,
@@ -106,7 +107,7 @@ export function planTerminalCancellationTransitions(input) {
106
107
  .filter((execution) => execution.status === 'cancel_requested' &&
107
108
  execution.deadlineAt !== null &&
108
109
  execution.deadlineAt <= input.now)
109
- .map((execution) => cancellationAmbiguous(input.runId, execution.effectId, execution.attempt));
110
+ .map((execution) => cancellationAmbiguous(input.runId, execution.effectId, execution.attempt, input.registry.ids));
110
111
  }
111
112
  /**
112
113
  * The earliest deadline after `after` that needs a wake. A terminal run only waits on
@@ -134,7 +135,7 @@ export function nextRuntimeDeadline(state, after = Number.NEGATIVE_INFINITY) {
134
135
  const deadlines = [...timers, ...executions, ...deferred];
135
136
  return deadlines.length > 0 ? Math.min(...deadlines) : undefined;
136
137
  }
137
- function cancellationAmbiguous(runId, effectId, attempt) {
138
+ function cancellationAmbiguous(runId, effectId, attempt, ids) {
138
139
  return createEvent(runId, {
139
140
  type: 'runtime.effect.ambiguous',
140
141
  payload: {
@@ -144,5 +145,5 @@ function cancellationAmbiguous(runId, effectId, attempt) {
144
145
  },
145
146
  threadId: null,
146
147
  origin: { type: 'system' },
147
- });
148
+ }, { ids });
148
149
  }
@@ -60,6 +60,7 @@ export function admitOrFailAttempt(input) {
60
60
  return { _tag: 'admit', secrets };
61
61
  }
62
62
  const failure = planAttemptFailure({
63
+ ids: input.registry.ids,
63
64
  runId: input.runId,
64
65
  item: input.item,
65
66
  attempt: input.attempt,
@@ -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.