@swirls/looms 0.8.0 → 0.10.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 (94) hide show
  1. package/CHANGELOG.md +12 -0
  2. package/dist/actor/routing.js +2 -1
  3. package/dist/agent/debugger/agent-chat.js +6 -5
  4. package/dist/agent/debugger/index.js +2 -1
  5. package/dist/agent/module.d.ts +799 -593
  6. package/dist/agent/module.js +31 -0
  7. package/dist/agent/scope.js +1 -0
  8. package/dist/agent/signals.d.ts +108 -15
  9. package/dist/agent/signals.js +70 -47
  10. package/dist/approval/debugger/approvals-view.js +1 -1
  11. package/dist/approval/index.d.ts +1 -0
  12. package/dist/approval/index.js +1 -0
  13. package/dist/approval/module.d.ts +42 -1
  14. package/dist/approval/module.js +53 -0
  15. package/dist/approval/scope.js +1 -0
  16. package/dist/approval/signals.d.ts +19 -13
  17. package/dist/approval/signals.js +25 -45
  18. package/dist/approval/steps.d.ts +11 -0
  19. package/dist/approval/steps.js +39 -0
  20. package/dist/cli/commands.js +87 -16
  21. package/dist/client/client.d.ts +211 -0
  22. package/dist/client/client.js +18 -1
  23. package/dist/core/index.d.ts +1 -0
  24. package/dist/core/index.js +1 -0
  25. package/dist/core/module-scope.d.ts +50 -5
  26. package/dist/core/module-scope.js +22 -2
  27. package/dist/core/module.d.ts +29 -2
  28. package/dist/core/projection.d.ts +1 -0
  29. package/dist/core/published.d.ts +59 -1
  30. package/dist/core/published.js +97 -1
  31. package/dist/core/signals.d.ts +56 -0
  32. package/dist/core/signals.js +93 -0
  33. package/dist/core/validate-event.d.ts +12 -1
  34. package/dist/core/validate-event.js +34 -11
  35. package/dist/debugger/app/assets/index-CO5gIvV8.css +2 -0
  36. package/dist/debugger/app/assets/{index-CMRl_aWQ.js → index-D-2Q7ecG.js} +2 -2
  37. package/dist/debugger/app/assets/routes-lvmllT60.js +47 -0
  38. package/dist/debugger/app/index.html +2 -2
  39. package/dist/debugger/index.d.ts +1 -1
  40. package/dist/debugger/index.js +1 -1
  41. package/dist/debugger/lib/cn.d.ts +1 -1
  42. package/dist/debugger/lib/cn.js +12 -1
  43. package/dist/debugger/plugin.d.ts +11 -1
  44. package/dist/debugger/plugin.js +41 -0
  45. package/dist/debugger/shell/debugger-shell.js +1 -1
  46. package/dist/debugger/shell/form-fields.d.ts +17 -0
  47. package/dist/debugger/shell/form-fields.js +38 -0
  48. package/dist/debugger/shell/run-action.d.ts +6 -0
  49. package/dist/debugger/shell/run-action.js +15 -0
  50. package/dist/debugger/shell/run-controls.js +3 -55
  51. package/dist/debugger/shell/schema-form.d.ts +10 -1
  52. package/dist/debugger/shell/schema-form.js +108 -10
  53. package/dist/debugger/shell/signal-form.d.ts +18 -0
  54. package/dist/debugger/shell/signal-form.js +185 -0
  55. package/dist/debugger/shell/start-form.js +2 -32
  56. package/dist/debugger/shell/use-debounced-preview.d.ts +22 -0
  57. package/dist/debugger/shell/use-debounced-preview.js +68 -0
  58. package/dist/evaluator/index.d.ts +1 -1
  59. package/dist/evaluator/index.js +1 -1
  60. package/dist/evaluator/module.d.ts +8 -1
  61. package/dist/evaluator/module.js +33 -0
  62. package/dist/evaluator/scope.js +1 -0
  63. package/dist/projectors/event-log-ops.d.ts +68 -0
  64. package/dist/projectors/event-log-ops.js +79 -0
  65. package/dist/projectors/event-log.d.ts +4 -68
  66. package/dist/projectors/event-log.js +4 -79
  67. package/dist/projectors/replica/migrations.d.ts +4 -6
  68. package/dist/projectors/replica/migrations.js +18 -1
  69. package/dist/projectors/replica/sqlite-bun.d.ts +5 -0
  70. package/dist/projectors/replica/sqlite-bun.js +39 -0
  71. package/dist/projectors/replica/sqlite-migrations.d.ts +5 -0
  72. package/dist/projectors/replica/sqlite-migrations.js +99 -0
  73. package/dist/projectors/replica/sqlite.d.ts +95 -0
  74. package/dist/projectors/replica/sqlite.js +517 -0
  75. package/dist/runtime/server/routes/definitions.d.ts +1 -1
  76. package/dist/runtime/server/routes/definitions.js +58 -2
  77. package/dist/runtime/server/routes/runs.js +25 -1
  78. package/dist/schedule/module.d.ts +117 -1
  79. package/dist/schedule/module.js +30 -0
  80. package/dist/schedule/scope.js +1 -0
  81. package/dist/schedule/signals.d.ts +59 -7
  82. package/dist/schedule/signals.js +35 -17
  83. package/dist/testing/corpus-module.d.ts +1 -1
  84. package/dist/testing/index.js +2 -1
  85. package/dist/testing/module-examples.d.ts +6 -0
  86. package/dist/testing/module-examples.js +66 -0
  87. package/dist/workflow/module.d.ts +3 -1
  88. package/dist/workflow/module.js +13 -0
  89. package/dist/workflow/scope.js +1 -0
  90. package/package.json +17 -1
  91. package/dist/debugger/app/assets/index-B7GdT1UA.css +0 -2
  92. package/dist/debugger/app/assets/routes-CfXxKG45.js +0 -47
  93. /package/dist/evaluator/{signals.d.ts → steps.d.ts} +0 -0
  94. /package/dist/evaluator/{signals.js → steps.js} +0 -0
@@ -0,0 +1,185 @@
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ import { useEffect, useMemo, useState } from 'react';
3
+ import { cleanUndefined, } from '@swirls/looms/core';
4
+ import { useRunStore, useThreadTree } from '@swirls/looms/react';
5
+ import { JsonTree } from '../components/json-tree.js';
6
+ import { useDebugger } from '../context.js';
7
+ import { errorMessage, shortId } from '../lib/cn.js';
8
+ import { Button } from '../ui/button.js';
9
+ import { Command, CommandEmpty, CommandGroup, CommandInput, CommandItem, CommandList, } from '../ui/command.js';
10
+ import { Kbd } from '../ui/panel.js';
11
+ import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select.js';
12
+ import { Tabs, TabsContent, TabsList, TabsTrigger } from '../ui/tabs.js';
13
+ import { Field, InputFields } from './form-fields.js';
14
+ import { useRunAction } from './run-action.js';
15
+ import { initialValues, inputForm, parseFormInput, } from './schema-form.js';
16
+ import { useDebouncedPreview } from './use-debounced-preview.js';
17
+ function flattenThreads(root) {
18
+ if (!root) {
19
+ return [];
20
+ }
21
+ const rows = [];
22
+ const walk = (node) => {
23
+ rows.push(node);
24
+ for (const child of node.children) {
25
+ walk(child);
26
+ }
27
+ };
28
+ walk(root);
29
+ return rows;
30
+ }
31
+ export function useSignalCatalog() {
32
+ const { client } = useDebugger();
33
+ const [signals, setSignals] = useState([]);
34
+ const [events, setEvents] = useState([]);
35
+ const [error, setError] = useState(null);
36
+ useEffect(() => {
37
+ Promise.all([client.listSignals(), client.listEvents()])
38
+ .then(([signalCatalog, eventCatalog]) => {
39
+ setSignals(signalCatalog.signals);
40
+ setEvents(eventCatalog.events);
41
+ setError(null);
42
+ })
43
+ .catch((cause) => setError(errorMessage(cause)));
44
+ }, [client]);
45
+ return { signals, events, error };
46
+ }
47
+ function signalKey(signal) {
48
+ return `${signal.namespace}.${signal.name}`;
49
+ }
50
+ function PreviewPanel({ pending, error, events, }) {
51
+ if (error && !events) {
52
+ return (_jsx("p", { className: "text-status-failed text-[11px]", title: error, children: error }));
53
+ }
54
+ if (!events) {
55
+ return (_jsx("p", { className: "text-muted-foreground text-[11px]", children: pending ? 'Previewing…' : 'Preview will appear here.' }));
56
+ }
57
+ if (events.length === 0) {
58
+ return _jsx("p", { className: "text-muted-foreground text-[11px]", children: "No events built." });
59
+ }
60
+ return (_jsxs("div", { className: "grid gap-1", children: [pending ? _jsx("p", { className: "text-muted-foreground text-[11px]", children: "Updating\u2026" }) : null, error ? (_jsx("p", { className: "text-status-failed text-[11px]", title: error, children: error })) : null, _jsx("div", { className: pending
61
+ ? 'border-border bg-card max-h-48 overflow-auto rounded-md border p-2 opacity-60'
62
+ : 'border-border bg-card max-h-48 overflow-auto rounded-md border p-2', children: _jsx(JsonTree, { value: events, defaultExpandDepth: 2 }) })] }));
63
+ }
64
+ function ThreadSelect({ rootThreadId, threads, value, onChange, }) {
65
+ const resolved = value || rootThreadId;
66
+ return (_jsx(Field, { label: "Thread", hint: "defaults to root", children: _jsxs(Select, { value: resolved ?? '', onValueChange: onChange, children: [_jsx(SelectTrigger, { className: "w-full font-mono text-xs", children: _jsx(SelectValue, { placeholder: rootThreadId ? shortId(rootThreadId) : 'thread id' }) }), _jsx(SelectContent, { children: threads.map((thread) => (_jsx(SelectItem, { value: thread.threadId, description: thread.definitionName, children: shortId(thread.threadId) }, thread.threadId))) })] }) }));
67
+ }
68
+ function ExecutorFooter({ pending, canSend, error, sent, }) {
69
+ return (_jsxs("div", { className: "flex items-center gap-2", children: [error ? (_jsx("p", { className: "text-status-failed min-w-0 flex-1 truncate text-[11px]", title: error, children: error })) : sent ? (_jsx("p", { className: "text-status-completed flex-1 text-[11px]", children: "Signal sent" })) : (_jsxs("p", { className: "text-muted-foreground flex flex-1 items-center gap-1 text-[11px]", children: [_jsx(Kbd, { children: "\u2318" }), _jsx(Kbd, { children: "\u21B5" })] })), _jsx(Button, { type: "submit", size: "sm", disabled: pending || !canSend, children: "Send signal" })] }));
70
+ }
71
+ function SignalExecutor({ runId, rootThreadId, selectionKey, parsed, inputKey, preview, send, picker, inputLabel, form, values, onValuesChange, showInput, emptyInputHint, }) {
72
+ const store = useRunStore(runId);
73
+ const tree = useThreadTree(store);
74
+ const threads = useMemo(() => flattenThreads(tree.root), [tree.root]);
75
+ const [threadId, setThreadId] = useState('');
76
+ const resolvedThreadId = threadId || rootThreadId;
77
+ const { run, pending, error, setError } = useRunAction();
78
+ const [sent, setSent] = useState(false);
79
+ const previewRun = useDebouncedPreview({
80
+ enabled: selectionKey.length > 0 && parsed.ok,
81
+ key: `${inputKey}:${resolvedThreadId ?? ''}`,
82
+ resetKey: selectionKey,
83
+ run: () => {
84
+ if (!parsed.ok) {
85
+ return Promise.reject(new Error(parsed.error));
86
+ }
87
+ return preview(parsed.value, resolvedThreadId);
88
+ },
89
+ });
90
+ useEffect(() => {
91
+ setSent(false);
92
+ setError(null);
93
+ }, [selectionKey, setError]);
94
+ const parseError = parsed.ok ? null : parsed.error;
95
+ const previewError = parseError ?? previewRun.error;
96
+ const canSend = parsed.ok && selectionKey.length > 0;
97
+ function submit() {
98
+ if (!parsed.ok || !canSend) {
99
+ return;
100
+ }
101
+ setSent(false);
102
+ setError(null);
103
+ run(() => send(parsed.value, resolvedThreadId), () => setSent(true));
104
+ }
105
+ return (_jsxs("form", { className: "grid gap-3", onSubmit: (event) => {
106
+ event.preventDefault();
107
+ submit();
108
+ }, onKeyDown: (event) => {
109
+ if (event.key === 'Enter' && (event.metaKey || event.ctrlKey)) {
110
+ event.preventDefault();
111
+ submit();
112
+ }
113
+ }, children: [picker, _jsx(ThreadSelect, { rootThreadId: rootThreadId, threads: threads, value: threadId, onChange: setThreadId }), showInput ? (_jsxs("div", { className: "grid gap-2", children: [_jsx("p", { className: "text-muted-foreground text-[11px] font-medium", children: inputLabel }), _jsx(InputFields, { form: form, values: values, onChange: onValuesChange })] })) : selectionKey ? (_jsx("p", { className: "text-muted-foreground text-xs", children: "No input" })) : (_jsx("p", { className: "text-muted-foreground text-xs", children: emptyInputHint })), _jsxs("section", { className: "grid gap-1.5", children: [_jsx("p", { className: "text-muted-foreground text-[11px] font-medium", children: "Preview" }), _jsx(PreviewPanel, { pending: previewRun.pending, error: previewError, events: parseError ? null : previewRun.events })] }), _jsx(ExecutorFooter, { pending: pending, canSend: canSend, error: error, sent: sent })] }));
114
+ }
115
+ function SignalTab({ runId, rootThreadId, signals, }) {
116
+ const { client } = useDebugger();
117
+ const [selectedKey, setSelectedKey] = useState(null);
118
+ const selected = signals.find((signal) => signalKey(signal) === selectedKey);
119
+ const form = useMemo(() => (selected?.inputSchema ? inputForm(selected.inputSchema) : { kind: 'json' }), [selected]);
120
+ const [values, setValues] = useState(() => initialValues(form));
121
+ useEffect(() => {
122
+ setValues(initialValues(form));
123
+ }, [selected, form]);
124
+ const parsed = !selected
125
+ ? { ok: false, error: 'Choose a signal' }
126
+ : selected.inputSchema
127
+ ? parseFormInput(form, values)
128
+ : { ok: true, value: undefined };
129
+ const namespaces = useMemo(() => [...new Set(signals.map((signal) => signal.namespace))], [signals]);
130
+ const selectionKey = selected ? signalKey(selected) : '';
131
+ return (_jsx(SignalExecutor, { runId: runId, rootThreadId: rootThreadId, selectionKey: selectionKey, parsed: parsed, inputKey: `${selectionKey}:${JSON.stringify(values)}`, preview: (input, threadId) => {
132
+ if (!selected) {
133
+ return Promise.reject(new Error('Choose a signal'));
134
+ }
135
+ return client
136
+ .previewSignal(selected.namespace, selected.name, { input, threadId })
137
+ .then((result) => result.events);
138
+ }, send: (input, threadId) => {
139
+ if (!selected) {
140
+ return Promise.reject(new Error('Choose a signal'));
141
+ }
142
+ return client
143
+ .sendSignal(runId, selected.namespace, selected.name, { input, threadId })
144
+ .then(() => undefined);
145
+ }, picker: _jsxs(Command, { className: "border-border rounded-lg border", children: [_jsx(CommandInput, { placeholder: "Search signals\u2026" }), _jsxs(CommandList, { className: "max-h-40", children: [_jsx(CommandEmpty, { children: "No signals found." }), namespaces.map((namespace) => (_jsx(CommandGroup, { heading: namespace, children: signals
146
+ .filter((signal) => signal.namespace === namespace)
147
+ .map((signal) => {
148
+ const key = signalKey(signal);
149
+ return (_jsx(CommandItem, { value: `${signal.namespace} ${signal.name} ${signal.description ?? ''}`, "data-selected": key === selectedKey, onSelect: () => setSelectedKey(key), children: _jsxs("div", { className: "flex min-w-0 flex-col gap-0.5", children: [_jsx("span", { className: "font-medium", children: signal.name }), signal.description ? (_jsx("span", { className: "text-muted-foreground line-clamp-1 text-[11px]", children: signal.description })) : null] }) }, key));
150
+ }) }, namespace)))] })] }), inputLabel: "Input", form: form, values: values, onValuesChange: setValues, showInput: Boolean(selected?.inputSchema), emptyInputHint: "Choose a signal to configure input." }));
151
+ }
152
+ function AdvancedTab({ runId, rootThreadId, events: catalog, }) {
153
+ const { client } = useDebugger();
154
+ const [eventType, setEventType] = useState('');
155
+ const selectedEvent = catalog.find((event) => event.type === eventType);
156
+ const form = useMemo(() => inputForm(selectedEvent?.payloadSchema), [selectedEvent?.payloadSchema]);
157
+ const [values, setValues] = useState(() => initialValues(form));
158
+ useEffect(() => {
159
+ setValues(initialValues(form));
160
+ }, [eventType, form]);
161
+ const parsed = eventType
162
+ ? parseFormInput(form, values)
163
+ : { ok: false, error: 'Choose an event' };
164
+ return (_jsx(SignalExecutor, { runId: runId, rootThreadId: rootThreadId, selectionKey: eventType, parsed: parsed, inputKey: `${eventType}:${JSON.stringify(values)}`, preview: (input, threadId) => client
165
+ .previewEvents([
166
+ {
167
+ type: eventType,
168
+ payload: input ?? null,
169
+ threadId,
170
+ },
171
+ ])
172
+ .then((result) => result.events), send: (input, threadId) => client
173
+ .signal(runId, [
174
+ {
175
+ type: eventType,
176
+ payload: cleanUndefined(input ?? null),
177
+ threadId,
178
+ },
179
+ ])
180
+ .then(() => undefined), picker: _jsx(Field, { label: "Event type", children: _jsxs(Select, { value: eventType, onValueChange: setEventType, children: [_jsx(SelectTrigger, { className: "w-full font-mono text-xs", children: _jsx(SelectValue, { placeholder: "module.event" }) }), _jsx(SelectContent, { children: catalog.map((event) => (_jsx(SelectItem, { value: event.type, children: event.type }, event.type))) })] }) }), inputLabel: "Payload", form: form, values: values, onValuesChange: setValues, showInput: eventType.length > 0, emptyInputHint: "Choose an event type." }));
181
+ }
182
+ export function SignalForm({ runId, rootThreadId }) {
183
+ const { signals, events, error } = useSignalCatalog();
184
+ return (_jsxs("div", { className: "grid gap-3", children: [_jsxs("div", { children: [_jsx("p", { className: "text-[13px] font-medium", children: "Send a signal" }), _jsx("p", { className: "text-muted-foreground text-xs", children: "Append an event to this run's log." })] }), error ? (_jsx("p", { className: "text-status-failed text-[11px]", title: error, children: error })) : null, _jsxs(Tabs, { defaultValue: "signal", children: [_jsxs(TabsList, { children: [_jsx(TabsTrigger, { value: "signal", children: "Signal" }), _jsx(TabsTrigger, { value: "advanced", children: "Advanced" })] }), _jsx(TabsContent, { value: "signal", className: "mt-3", children: _jsx(SignalTab, { runId: runId, rootThreadId: rootThreadId, signals: signals }) }), _jsx(TabsContent, { value: "advanced", className: "mt-3", children: _jsx(AdvancedTab, { runId: runId, rootThreadId: rootThreadId, events: events }) })] })] }));
185
+ }
@@ -6,11 +6,9 @@ import { useRunEvents, useRunStore, useRunSummary, useThreadTree } from '@swirls
6
6
  import { JsonTree } from '../components/json-tree.js';
7
7
  import { StatusBadge } from '../components/status-dot.js';
8
8
  import { Button } from '../ui/button.js';
9
- import { Checkbox } from '../ui/checkbox.js';
10
- import { Input } from '../ui/input.js';
11
9
  import { ScrollArea } from '../ui/scroll-area.js';
12
- import { Textarea } from '../ui/textarea.js';
13
- import { formInput, initialValues, inputForm, } from './schema-form.js';
10
+ import { InputFields } from './form-fields.js';
11
+ import { formInput, initialValues, inputForm } from './schema-form.js';
14
12
  import { useStartRun } from './use-start-run.js';
15
13
  function RunResult({ runId }) {
16
14
  const store = useRunStore(runId);
@@ -24,34 +22,6 @@ function RunResult({ runId }) {
24
22
  const failure = failed && isJsonObject(failed.payload) ? failed.payload.error : undefined;
25
23
  return (_jsxs("div", { className: "space-y-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsx("span", { className: "text-muted-foreground text-xs", children: "Status" }), _jsx(StatusBadge, { status: summary.status })] }), output !== undefined ? (_jsxs("section", { className: "border-border bg-card rounded-lg border p-3", children: [_jsx("h3", { className: "text-muted-foreground mb-1.5 text-[11px] font-medium", children: "Output" }), _jsx(JsonTree, { value: output, defaultExpandDepth: 2 })] })) : null, isJsonString(failure) ? (_jsx("p", { className: "text-status-failed bg-status-failed/10 rounded-md px-3 py-2 text-xs", children: failure })) : null] }));
26
24
  }
27
- function FieldInput({ field, value, onChange, }) {
28
- switch (field.type) {
29
- case 'boolean':
30
- return (_jsx(Checkbox, { checked: value === 'true', onCheckedChange: (checked) => onChange(String(checked === true)) }));
31
- case 'number':
32
- return (_jsx(Input, { type: "number", className: "h-8 font-mono text-xs", value: value, onChange: (event) => onChange(event.target.value) }));
33
- case 'string':
34
- return (_jsx(Input, { className: "h-8 text-[13px]", value: value, onChange: (event) => onChange(event.target.value) }));
35
- default: {
36
- const exhaustive = field.type;
37
- return exhaustive;
38
- }
39
- }
40
- }
41
- function InputFields({ form, values, onChange, }) {
42
- switch (form.kind) {
43
- case 'text':
44
- return (_jsx(Textarea, { className: "max-h-64 min-h-20", value: values.source, onChange: (event) => onChange({ ...values, source: event.target.value }), "aria-label": "Input" }));
45
- case 'fields':
46
- return form.fields.map((field) => (_jsxs("label", { className: field.type === 'boolean' ? 'flex items-center gap-2 text-xs' : 'grid gap-1.5 text-xs', children: [_jsx("span", { className: "text-foreground font-medium", children: field.label }), _jsx(FieldInput, { field: field, value: values.fields[field.name] ?? '', onChange: (value) => onChange({ ...values, fields: { ...values.fields, [field.name]: value } }) })] }, field.name)));
47
- case 'json':
48
- return (_jsx(Textarea, { className: "max-h-80 min-h-28 font-mono text-xs", value: values.source, onChange: (event) => onChange({ ...values, source: event.target.value }), "aria-label": "JSON input", spellCheck: false }));
49
- default: {
50
- const exhaustive = form;
51
- return exhaustive;
52
- }
53
- }
54
- }
55
25
  /** Starts a run from a form built from the definition's input schema, then shows its result. */
56
26
  export function StartForm(context) {
57
27
  const form = inputForm(context.definition.inputSchema);
@@ -0,0 +1,22 @@
1
+ import type { JsonValue } from '@swirls/looms/core';
2
+ export type PreviewEvents = readonly {
3
+ readonly type: string;
4
+ readonly payload: JsonValue;
5
+ }[];
6
+ /**
7
+ * Debounced preview with a generation token so a slow stale response cannot overwrite a newer
8
+ * one or clear pending while a later request is still in flight.
9
+ *
10
+ * Input changes (`key`) keep the last successful preview visible until the next result arrives.
11
+ * Selection changes (`resetKey`) clear immediately so a previous signal/event never flashes.
12
+ */
13
+ export declare function useDebouncedPreview({ enabled, key, resetKey, run, }: {
14
+ enabled: boolean;
15
+ key: string;
16
+ resetKey: string;
17
+ run: () => Promise<PreviewEvents>;
18
+ }): {
19
+ events: PreviewEvents | null;
20
+ error: string | null;
21
+ pending: boolean;
22
+ };
@@ -0,0 +1,68 @@
1
+ import { useEffect, useRef, useState } from 'react';
2
+ import { errorMessage } from '../lib/cn.js';
3
+ /** Short trailing debounce so typing stays smooth without feeling laggy. */
4
+ const PREVIEW_MS = 100;
5
+ /**
6
+ * Debounced preview with a generation token so a slow stale response cannot overwrite a newer
7
+ * one or clear pending while a later request is still in flight.
8
+ *
9
+ * Input changes (`key`) keep the last successful preview visible until the next result arrives.
10
+ * Selection changes (`resetKey`) clear immediately so a previous signal/event never flashes.
11
+ */
12
+ export function useDebouncedPreview({ enabled, key, resetKey, run, }) {
13
+ const [events, setEvents] = useState(null);
14
+ const [error, setError] = useState(null);
15
+ const [pending, setPending] = useState(false);
16
+ const generation = useRef(0);
17
+ const runRef = useRef(run);
18
+ runRef.current = run;
19
+ useEffect(() => {
20
+ generation.current += 1;
21
+ setEvents(null);
22
+ setError(null);
23
+ setPending(false);
24
+ }, [resetKey]);
25
+ useEffect(() => {
26
+ if (!enabled) {
27
+ generation.current += 1;
28
+ setEvents(null);
29
+ setError(null);
30
+ setPending(false);
31
+ return undefined;
32
+ }
33
+ const current = ++generation.current;
34
+ // oxlint-disable-next-line effecttsgo/global-timers -- React preview debounce uses DOM timers.
35
+ const timer = setTimeout(() => {
36
+ if (generation.current !== current) {
37
+ return;
38
+ }
39
+ setPending(true);
40
+ runRef
41
+ .current()
42
+ .then((next) => {
43
+ if (generation.current !== current) {
44
+ return;
45
+ }
46
+ setEvents(next);
47
+ setError(null);
48
+ })
49
+ .catch((cause) => {
50
+ if (generation.current !== current) {
51
+ return;
52
+ }
53
+ setEvents(null);
54
+ setError(errorMessage(cause));
55
+ })
56
+ .finally(() => {
57
+ if (generation.current === current) {
58
+ setPending(false);
59
+ }
60
+ });
61
+ }, PREVIEW_MS);
62
+ return () => {
63
+ clearTimeout(timer);
64
+ generation.current += 1;
65
+ };
66
+ }, [enabled, key]);
67
+ return { events, error, pending };
68
+ }
@@ -7,5 +7,5 @@ export * from './evaluator';
7
7
  export * from './effects';
8
8
  export * from './threads';
9
9
  export * from './projections';
10
- export * from './signals';
10
+ export * from './steps';
11
11
  export * from './module';
@@ -7,5 +7,5 @@ export * from './evaluator.js';
7
7
  export * from './effects.js';
8
8
  export * from './threads.js';
9
9
  export * from './projections.js';
10
- export * from './signals.js';
10
+ export * from './steps.js';
11
11
  export * from './module.js';
@@ -1,5 +1,6 @@
1
1
  import type { EvaluatorDefinition } from './definitions';
2
2
  import { EvaluatorTag, type StubEvaluatorPolicy } from './evaluator';
3
+ import { evaluate } from './steps';
3
4
  import type { EvaluatorAdapter } from './types';
4
5
  export interface EvaluatorModuleOptions {
5
6
  readonly definitions?: readonly EvaluatorDefinition[];
@@ -380,7 +381,9 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
380
381
  } | undefined;
381
382
  }[];
382
383
  }>;
383
- }, import("effect/Context").Service.Any> & {
384
+ }, import("effect/Context").Service.Any, {}, {
385
+ evaluate: typeof evaluate;
386
+ }> & {
384
387
  readonly effects: {
385
388
  evaluate: import("@swirls/looms/core").LocalEffectDefinition<{
386
389
  readonly evaluationId: string;
@@ -729,4 +732,8 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
729
732
  }[];
730
733
  }>;
731
734
  };
735
+ readonly signals: {};
736
+ readonly steps: {
737
+ evaluate: typeof evaluate;
738
+ };
732
739
  };
@@ -5,6 +5,7 @@ import { evaluateEffect } from './effects.js';
5
5
  import { evaluatorFromAdapter, EvaluatorTag, StubEvaluatorLive, } from './evaluator.js';
6
6
  import { evaluations } from './projections.js';
7
7
  import { evaluatorModule } from './scope.js';
8
+ import { evaluate } from './steps.js';
8
9
  import { evaluatorThread } from './threads.js';
9
10
  export function evaluator(options = {}) {
10
11
  const listed = options.definitions ?? [];
@@ -21,6 +22,38 @@ export function evaluator(options = {}) {
21
22
  projections: {
22
23
  evaluations,
23
24
  },
25
+ steps: { evaluate },
26
+ examples: [
27
+ {
28
+ name: 'an evaluated answer lands in the list',
29
+ events: [
30
+ evaluatorModule.input('evaluated', {
31
+ evaluationId: 'ev_1',
32
+ definitionName: 'risk',
33
+ answers: {
34
+ ok: { type: 'boolean', value: true, probability: 0.9 },
35
+ },
36
+ route: 'approve',
37
+ reason: 'model',
38
+ }),
39
+ ],
40
+ projections: {
41
+ evaluations: {
42
+ items: [
43
+ {
44
+ evaluationId: 'ev_1',
45
+ definitionName: 'risk',
46
+ answers: {
47
+ ok: { type: 'boolean', value: true, probability: 0.9 },
48
+ },
49
+ route: 'approve',
50
+ reason: 'model',
51
+ },
52
+ ],
53
+ },
54
+ },
55
+ },
56
+ ],
24
57
  services: () => Layer.merge(evaluatorLayer, EvaluatorDefinitionsLive(definitions)),
25
58
  bindHost(host) {
26
59
  definitions.useResolver(host.definitionResolver);
@@ -3,5 +3,6 @@ import { evaluatorCatalog } from './events.js';
3
3
  export const evaluatorModule = createModuleScope({
4
4
  namespace: 'evaluator',
5
5
  protocolVersion: '1.0.0',
6
+ description: 'Typed questions that branch a run.',
6
7
  events: evaluatorCatalog,
7
8
  });
@@ -0,0 +1,68 @@
1
+ import { type EventEnvelope, type EventOrigin, type JsonValue, type RunStatus } from '@swirls/looms/core';
2
+ export interface EventLogEntry {
3
+ readonly runId: string;
4
+ readonly seq: number;
5
+ readonly eventId: string;
6
+ readonly ts: number;
7
+ readonly type: string;
8
+ readonly payload: JsonValue;
9
+ readonly threadId: string | null;
10
+ readonly parentThreadId: string | null;
11
+ readonly causationId: string | null;
12
+ readonly correlationId: string | null;
13
+ readonly effectId: string | null;
14
+ readonly origin: EventOrigin;
15
+ readonly idempotencyKey: string | null;
16
+ }
17
+ export interface RunLogRow {
18
+ readonly runId: string;
19
+ readonly status: RunStatus;
20
+ readonly kind: string | null;
21
+ readonly definitionName: string | null;
22
+ readonly definitionVersion: string | null;
23
+ readonly rootThreadId: string | null;
24
+ readonly parentRunId: string | null;
25
+ readonly launchedByEffectId: string | null;
26
+ readonly correlationId: string | null;
27
+ readonly attributes: {
28
+ readonly [key: string]: string;
29
+ };
30
+ readonly tenant: string | null;
31
+ readonly project: string | null;
32
+ readonly org: string | null;
33
+ readonly startedAt: number | null;
34
+ readonly updatedAt: number;
35
+ readonly completedAt: number | null;
36
+ }
37
+ export type EventLogOp = {
38
+ readonly type: 'insert';
39
+ readonly entry: EventLogEntry;
40
+ } | {
41
+ readonly type: 'start';
42
+ readonly runId: string;
43
+ readonly kind: string | null;
44
+ readonly definitionName: string | null;
45
+ readonly definitionVersion: string | null;
46
+ readonly rootThreadId: string | null;
47
+ readonly parentRunId: string | null;
48
+ readonly launchedByEffectId: string | null;
49
+ readonly correlationId: string | null;
50
+ readonly attributes: {
51
+ readonly [key: string]: string;
52
+ };
53
+ readonly tenant: string | null;
54
+ readonly project: string | null;
55
+ readonly org: string | null;
56
+ readonly at: number;
57
+ } | {
58
+ readonly type: 'finish';
59
+ readonly runId: string;
60
+ readonly status: 'completed' | 'failed' | 'cancelled';
61
+ readonly at: number;
62
+ } | {
63
+ readonly type: 'touch';
64
+ readonly runId: string;
65
+ readonly at: number;
66
+ };
67
+ /** Fold one durable event into event-row and run-summary operations. Ephemeral events produce nothing. */
68
+ export declare function eventLogOps(event: EventEnvelope): readonly EventLogOp[];
@@ -0,0 +1,79 @@
1
+ import { Option, Predicate, Schema } from 'effect';
2
+ import { completedRunStatus, isJsonObject, readRunLaunchSource, } from '@swirls/looms/core';
3
+ const decodeAttributes = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.String));
4
+ /** Fold one durable event into event-row and run-summary operations. Ephemeral events produce nothing. */
5
+ export function eventLogOps(event) {
6
+ if (event.ephemeral) {
7
+ return [];
8
+ }
9
+ const entry = {
10
+ runId: event.runId,
11
+ seq: event.seq,
12
+ eventId: event.id,
13
+ ts: event.ts,
14
+ type: event.type,
15
+ payload: event.payload,
16
+ threadId: event.threadId,
17
+ parentThreadId: event.parentThreadId ?? null,
18
+ causationId: event.causationId ?? null,
19
+ correlationId: event.correlationId ?? null,
20
+ effectId: event.effectId ?? null,
21
+ origin: event.origin,
22
+ idempotencyKey: event.idempotencyKey ?? null,
23
+ };
24
+ const payload = isJsonObject(event.payload) ? event.payload : {};
25
+ switch (event.type) {
26
+ case 'runtime.run.started':
27
+ return [{ type: 'insert', entry }, startOp(event, payload)];
28
+ case 'runtime.run.completed':
29
+ return [
30
+ { type: 'insert', entry },
31
+ {
32
+ type: 'finish',
33
+ runId: event.runId,
34
+ status: completedRunStatus(event.payload),
35
+ at: event.ts,
36
+ },
37
+ ];
38
+ case 'runtime.run.cancelled':
39
+ return [
40
+ { type: 'insert', entry },
41
+ { type: 'finish', runId: event.runId, status: 'cancelled', at: event.ts },
42
+ ];
43
+ default:
44
+ return [
45
+ { type: 'insert', entry },
46
+ { type: 'touch', runId: event.runId, at: event.ts },
47
+ ];
48
+ }
49
+ }
50
+ function startOp(event, payload) {
51
+ const launchedBy = readRunLaunchSource(payload.launchedBy === undefined ? undefined : payload.launchedBy);
52
+ const attributes = readAttributes(payload.attributes);
53
+ return {
54
+ type: 'start',
55
+ runId: event.runId,
56
+ kind: readString(payload, 'kind'),
57
+ definitionName: readString(payload, 'definitionName'),
58
+ definitionVersion: readString(payload, 'definitionVersion'),
59
+ rootThreadId: readString(payload, 'rootThreadId'),
60
+ parentRunId: launchedBy?.runId ?? null,
61
+ launchedByEffectId: launchedBy?.effectId ?? null,
62
+ correlationId: event.correlationId ?? null,
63
+ attributes,
64
+ tenant: attributes.tenant ?? null,
65
+ project: attributes.project ?? null,
66
+ org: attributes.org ?? null,
67
+ at: event.ts,
68
+ };
69
+ }
70
+ function readString(payload, key) {
71
+ const value = payload[key];
72
+ return Predicate.isString(value) ? value : null;
73
+ }
74
+ function readAttributes(value) {
75
+ if (value === undefined) {
76
+ return {};
77
+ }
78
+ return Option.getOrElse(decodeAttributes(value), () => ({}));
79
+ }
@@ -1,73 +1,10 @@
1
1
  import { type Sql, type TransactionSql } from 'postgres';
2
- import { type EventEnvelope, type EventOrigin, type EventStore, type JsonValue, type RunStatus } from '@swirls/looms/core';
2
+ import { type EventEnvelope, type EventStore } from '@swirls/looms/core';
3
+ import { eventLogOps, type EventLogEntry, type EventLogOp, type RunLogRow } from './event-log-ops';
3
4
  import type { Projector } from './projector';
4
5
  import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations';
5
- export { POSTGRES_EVENT_LOG_SCHEMA_SQL };
6
- export interface EventLogEntry {
7
- readonly runId: string;
8
- readonly seq: number;
9
- readonly eventId: string;
10
- readonly ts: number;
11
- readonly type: string;
12
- readonly payload: JsonValue;
13
- readonly threadId: string | null;
14
- readonly parentThreadId: string | null;
15
- readonly causationId: string | null;
16
- readonly correlationId: string | null;
17
- readonly effectId: string | null;
18
- readonly origin: EventOrigin;
19
- readonly idempotencyKey: string | null;
20
- }
21
- export interface RunLogRow {
22
- readonly runId: string;
23
- readonly status: RunStatus;
24
- readonly kind: string | null;
25
- readonly definitionName: string | null;
26
- readonly definitionVersion: string | null;
27
- readonly rootThreadId: string | null;
28
- readonly parentRunId: string | null;
29
- readonly launchedByEffectId: string | null;
30
- readonly correlationId: string | null;
31
- readonly attributes: {
32
- readonly [key: string]: string;
33
- };
34
- readonly tenant: string | null;
35
- readonly project: string | null;
36
- readonly org: string | null;
37
- readonly startedAt: number | null;
38
- readonly updatedAt: number;
39
- readonly completedAt: number | null;
40
- }
41
- export type EventLogOp = {
42
- readonly type: 'insert';
43
- readonly entry: EventLogEntry;
44
- } | {
45
- readonly type: 'start';
46
- readonly runId: string;
47
- readonly kind: string | null;
48
- readonly definitionName: string | null;
49
- readonly definitionVersion: string | null;
50
- readonly rootThreadId: string | null;
51
- readonly parentRunId: string | null;
52
- readonly launchedByEffectId: string | null;
53
- readonly correlationId: string | null;
54
- readonly attributes: {
55
- readonly [key: string]: string;
56
- };
57
- readonly tenant: string | null;
58
- readonly project: string | null;
59
- readonly org: string | null;
60
- readonly at: number;
61
- } | {
62
- readonly type: 'finish';
63
- readonly runId: string;
64
- readonly status: 'completed' | 'failed' | 'cancelled';
65
- readonly at: number;
66
- } | {
67
- readonly type: 'touch';
68
- readonly runId: string;
69
- readonly at: number;
70
- };
6
+ export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
7
+ export type { EventLogEntry, EventLogOp, RunLogRow };
71
8
  export interface EventLogProjector extends Projector {
72
9
  /** Replays the source log into this sink. Safe to repeat; do not run it beside live delivery. */
73
10
  rebuild(source: EventStore, options?: {
@@ -79,7 +16,6 @@ export interface MemoryEventLog extends EventLogProjector {
79
16
  events(runId: string): readonly EventLogEntry[];
80
17
  run(runId: string): RunLogRow | null;
81
18
  }
82
- export declare function eventLogOps(event: EventEnvelope): readonly EventLogOp[];
83
19
  export declare function memoryEventLog(): MemoryEventLog;
84
20
  export declare function postgresEventLog(options: {
85
21
  url: string;