@swirls/looms 0.9.0 → 0.11.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 (118) hide show
  1. package/CHANGELOG.md +32 -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 +1 -0
  6. package/dist/actor/routing.js +2 -1
  7. package/dist/agent/debugger/agent-chat.js +6 -5
  8. package/dist/agent/debugger/index.js +2 -1
  9. package/dist/agent/module.d.ts +207 -1
  10. package/dist/agent/module.js +31 -0
  11. package/dist/agent/scope.js +1 -0
  12. package/dist/agent/signals.d.ts +108 -15
  13. package/dist/agent/signals.js +70 -47
  14. package/dist/approval/debugger/approvals-view.js +1 -1
  15. package/dist/approval/index.d.ts +1 -0
  16. package/dist/approval/index.js +1 -0
  17. package/dist/approval/module.d.ts +42 -1
  18. package/dist/approval/module.js +53 -0
  19. package/dist/approval/scope.js +1 -0
  20. package/dist/approval/signals.d.ts +19 -13
  21. package/dist/approval/signals.js +25 -45
  22. package/dist/approval/steps.d.ts +11 -0
  23. package/dist/approval/steps.js +39 -0
  24. package/dist/cli/commands.d.ts +1 -1
  25. package/dist/cli/commands.js +49 -14
  26. package/dist/client/client.d.ts +231 -21
  27. package/dist/client/client.js +20 -2
  28. package/dist/cloudflare/delete-terminal-run-storage.d.ts +39 -0
  29. package/dist/cloudflare/delete-terminal-run-storage.js +98 -0
  30. package/dist/cloudflare/durable-object.d.ts +11 -1
  31. package/dist/cloudflare/durable-object.js +23 -0
  32. package/dist/cloudflare/index.d.ts +1 -0
  33. package/dist/cloudflare/index.js +1 -0
  34. package/dist/core/index.d.ts +1 -0
  35. package/dist/core/index.js +1 -0
  36. package/dist/core/module-scope.d.ts +50 -5
  37. package/dist/core/module-scope.js +22 -2
  38. package/dist/core/module.d.ts +29 -2
  39. package/dist/core/projection.d.ts +1 -0
  40. package/dist/core/published.d.ts +59 -1
  41. package/dist/core/published.js +97 -1
  42. package/dist/core/run-context.d.ts +50 -0
  43. package/dist/core/run-context.js +21 -1
  44. package/dist/core/signals.d.ts +56 -0
  45. package/dist/core/signals.js +93 -0
  46. package/dist/core/validate-event.d.ts +12 -1
  47. package/dist/core/validate-event.js +34 -11
  48. package/dist/debugger/app/assets/index-CO5gIvV8.css +2 -0
  49. package/dist/debugger/app/assets/{index-CMRl_aWQ.js → index-VTotlHcm.js} +2 -2
  50. package/dist/debugger/app/assets/routes-CEdsN9DO.js +47 -0
  51. package/dist/debugger/app/index.html +2 -2
  52. package/dist/debugger/index.d.ts +1 -1
  53. package/dist/debugger/index.js +1 -1
  54. package/dist/debugger/lib/cn.d.ts +1 -1
  55. package/dist/debugger/lib/cn.js +12 -1
  56. package/dist/debugger/plugin.d.ts +11 -1
  57. package/dist/debugger/plugin.js +41 -0
  58. package/dist/debugger/shell/debugger-shell.js +1 -1
  59. package/dist/debugger/shell/form-fields.d.ts +17 -0
  60. package/dist/debugger/shell/form-fields.js +38 -0
  61. package/dist/debugger/shell/run-action.d.ts +6 -0
  62. package/dist/debugger/shell/run-action.js +15 -0
  63. package/dist/debugger/shell/run-controls.js +3 -55
  64. package/dist/debugger/shell/schema-form.d.ts +10 -1
  65. package/dist/debugger/shell/schema-form.js +108 -10
  66. package/dist/debugger/shell/signal-form.d.ts +18 -0
  67. package/dist/debugger/shell/signal-form.js +185 -0
  68. package/dist/debugger/shell/start-form.js +2 -32
  69. package/dist/debugger/shell/use-debounced-preview.d.ts +22 -0
  70. package/dist/debugger/shell/use-debounced-preview.js +68 -0
  71. package/dist/evaluator/index.d.ts +1 -1
  72. package/dist/evaluator/index.js +1 -1
  73. package/dist/evaluator/module.d.ts +8 -1
  74. package/dist/evaluator/module.js +33 -0
  75. package/dist/evaluator/scope.js +1 -0
  76. package/dist/projectors/event-log-ops.d.ts +0 -6
  77. package/dist/projectors/event-log-ops.js +2 -12
  78. package/dist/projectors/event-log.d.ts +10 -5
  79. package/dist/projectors/event-log.js +26 -22
  80. package/dist/projectors/replica/columns.d.ts +41 -0
  81. package/dist/projectors/replica/columns.js +77 -0
  82. package/dist/projectors/replica/drizzle.d.ts +328 -57
  83. package/dist/projectors/replica/drizzle.js +18 -14
  84. package/dist/projectors/replica/migrations.d.ts +25 -5
  85. package/dist/projectors/replica/migrations.js +62 -14
  86. package/dist/projectors/replica/postgres.d.ts +12 -11
  87. package/dist/projectors/replica/postgres.js +12 -26
  88. package/dist/projectors/replica/sqlite-bun.d.ts +3 -1
  89. package/dist/projectors/replica/sqlite-bun.js +6 -2
  90. package/dist/projectors/replica/sqlite-migrations.d.ts +5 -5
  91. package/dist/projectors/replica/sqlite-migrations.js +22 -9
  92. package/dist/projectors/replica/sqlite.d.ts +12 -11
  93. package/dist/projectors/replica/sqlite.js +23 -16
  94. package/dist/runtime/looms.d.ts +27 -36
  95. package/dist/runtime/looms.js +1 -0
  96. package/dist/runtime/runtime.js +7 -1
  97. package/dist/runtime/server/http.js +4 -2
  98. package/dist/runtime/server/routes/definitions.d.ts +1 -1
  99. package/dist/runtime/server/routes/definitions.js +58 -2
  100. package/dist/runtime/server/routes/runs.js +25 -1
  101. package/dist/runtime/types.d.ts +6 -1
  102. package/dist/schedule/module.d.ts +117 -1
  103. package/dist/schedule/module.js +30 -0
  104. package/dist/schedule/scope.js +1 -0
  105. package/dist/schedule/signals.d.ts +59 -7
  106. package/dist/schedule/signals.js +35 -17
  107. package/dist/testing/corpus-module.d.ts +1 -1
  108. package/dist/testing/index.js +2 -1
  109. package/dist/testing/module-examples.d.ts +6 -0
  110. package/dist/testing/module-examples.js +66 -0
  111. package/dist/workflow/module.d.ts +3 -1
  112. package/dist/workflow/module.js +13 -0
  113. package/dist/workflow/scope.js +1 -0
  114. package/package.json +1 -1
  115. package/dist/debugger/app/assets/index-B7GdT1UA.css +0 -2
  116. package/dist/debugger/app/assets/routes-CfXxKG45.js +0 -47
  117. /package/dist/evaluator/{signals.d.ts → steps.d.ts} +0 -0
  118. /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
  });
@@ -27,9 +27,6 @@ export interface RunLogRow {
27
27
  readonly attributes: {
28
28
  readonly [key: string]: string;
29
29
  };
30
- readonly tenant: string | null;
31
- readonly project: string | null;
32
- readonly org: string | null;
33
30
  readonly startedAt: number | null;
34
31
  readonly updatedAt: number;
35
32
  readonly completedAt: number | null;
@@ -50,9 +47,6 @@ export type EventLogOp = {
50
47
  readonly attributes: {
51
48
  readonly [key: string]: string;
52
49
  };
53
- readonly tenant: string | null;
54
- readonly project: string | null;
55
- readonly org: string | null;
56
50
  readonly at: number;
57
51
  } | {
58
52
  readonly type: 'finish';
@@ -1,6 +1,5 @@
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));
1
+ import { Predicate } from 'effect';
2
+ import { completedRunStatus, isJsonObject, readAttributes, readRunLaunchSource, } from '@swirls/looms/core';
4
3
  /** Fold one durable event into event-row and run-summary operations. Ephemeral events produce nothing. */
5
4
  export function eventLogOps(event) {
6
5
  if (event.ephemeral) {
@@ -61,9 +60,6 @@ function startOp(event, payload) {
61
60
  launchedByEffectId: launchedBy?.effectId ?? null,
62
61
  correlationId: event.correlationId ?? null,
63
62
  attributes,
64
- tenant: attributes.tenant ?? null,
65
- project: attributes.project ?? null,
66
- org: attributes.org ?? null,
67
63
  at: event.ts,
68
64
  };
69
65
  }
@@ -71,9 +67,3 @@ function readString(payload, key) {
71
67
  const value = payload[key];
72
68
  return Predicate.isString(value) ? value : null;
73
69
  }
74
- function readAttributes(value) {
75
- if (value === undefined) {
76
- return {};
77
- }
78
- return Option.getOrElse(decodeAttributes(value), () => ({}));
79
- }
@@ -1,7 +1,8 @@
1
1
  import { type Sql, type TransactionSql } from 'postgres';
2
- import { type EventEnvelope, type EventStore } from '@swirls/looms/core';
2
+ import { type EventEnvelope, type EventStore, type RunAttributeFields } from '@swirls/looms/core';
3
3
  import { eventLogOps, type EventLogEntry, type EventLogOp, type RunLogRow } from './event-log-ops';
4
4
  import type { Projector } from './projector';
5
+ import { type ResolvedReplicaColumn } from './replica/columns';
5
6
  import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations';
6
7
  export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
7
8
  export type { EventLogEntry, EventLogOp, RunLogRow };
@@ -17,13 +18,17 @@ export interface MemoryEventLog extends EventLogProjector {
17
18
  run(runId: string): RunLogRow | null;
18
19
  }
19
20
  export declare function memoryEventLog(): MemoryEventLog;
20
- export declare function postgresEventLog(options: {
21
+ export type PostgresEventLogOptions = ({
21
22
  url: string;
22
23
  } | {
23
24
  sql: Sql;
24
- }): EventLogProjector;
25
- export declare function applySqlOps(sql: TransactionSql, ops: readonly EventLogOp[]): Promise<void>;
25
+ }) & {
26
+ /** Declared run attributes. Each one is a `looms_run_index` column. */
27
+ readonly additionalFields?: RunAttributeFields;
28
+ };
29
+ export declare function postgresEventLog(options: PostgresEventLogOptions): EventLogProjector;
30
+ export declare function applySqlOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
26
31
  /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
27
- export declare function applyRunIndexOps(sql: TransactionSql, ops: readonly EventLogOp[]): Promise<void>;
32
+ export declare function applyRunIndexOps(sql: TransactionSql, ops: readonly EventLogOp[], columns?: readonly ResolvedReplicaColumn[]): Promise<void>;
28
33
  /** Insert event envelopes, including ephemeral ones. Durable callers pass events that are already filtered. */
29
34
  export declare function insertRunEvents(sql: TransactionSql, events: readonly EventEnvelope[]): Promise<void>;
@@ -3,7 +3,8 @@ import createPostgresClient, {} from 'postgres';
3
3
  import {} from '@swirls/looms/core';
4
4
  import { eventLogOps } from './event-log-ops.js';
5
5
  import { runProjectorPromise } from './projector.js';
6
- import { POSTGRES_EVENT_LOG_SCHEMA_SQL } from './replica/migrations.js';
6
+ import { columnValues, resolveReplicaColumns } from './replica/columns.js';
7
+ import { applyPostgresMigrations, POSTGRES_EVENT_LOG_SCHEMA_SQL, POSTGRES_SCHEMA_MIGRATIONS_SQL, postgresAttributeMigrations, } from './replica/migrations.js';
7
8
  export { POSTGRES_EVENT_LOG_SCHEMA_SQL, eventLogOps };
8
9
  const terminal = new Set(['completed', 'failed', 'cancelled']);
9
10
  export function memoryEventLog() {
@@ -34,7 +35,7 @@ export function memoryEventLog() {
34
35
  export function postgresEventLog(options) {
35
36
  const created = 'url' in options;
36
37
  const connected = created ? createPostgresClient(options.url) : options.sql;
37
- return createEventLogProjector('postgres-event-log', postgresStore(connected, created));
38
+ return createEventLogProjector('postgres-event-log', postgresStore(connected, created, options.additionalFields));
38
39
  }
39
40
  function createEventLogProjector(name, store) {
40
41
  return {
@@ -108,9 +109,6 @@ function mergeStart(existing, op) {
108
109
  attributes: existing && Object.keys(existing.attributes).length > 0
109
110
  ? existing.attributes
110
111
  : { ...op.attributes },
111
- tenant: existing?.tenant ?? op.tenant,
112
- project: existing?.project ?? op.project,
113
- org: existing?.org ?? op.org,
114
112
  startedAt: existing?.startedAt ?? op.at,
115
113
  updatedAt: Math.max(existing?.updatedAt ?? 0, op.at),
116
114
  completedAt: existing?.completedAt ?? null,
@@ -128,9 +126,6 @@ function mergeFinish(existing, op) {
128
126
  launchedByEffectId: existing?.launchedByEffectId ?? null,
129
127
  correlationId: existing?.correlationId ?? null,
130
128
  attributes: existing?.attributes ?? {},
131
- tenant: existing?.tenant ?? null,
132
- project: existing?.project ?? null,
133
- org: existing?.org ?? null,
134
129
  startedAt: existing?.startedAt ?? null,
135
130
  updatedAt: Math.max(existing?.updatedAt ?? 0, op.at),
136
131
  completedAt: existing?.completedAt ?? op.at,
@@ -139,15 +134,24 @@ function mergeFinish(existing, op) {
139
134
  function utcDate(ms) {
140
135
  return DateTime.toDateUtc(DateTime.makeUnsafe(ms));
141
136
  }
142
- function postgresStore(sql, ownsClient) {
137
+ /** Applied on every init; each statement is idempotent. */
138
+ const POSTGRES_EVENT_LOG_INIT_SQL = [
139
+ POSTGRES_EVENT_LOG_SCHEMA_SQL,
140
+ POSTGRES_SCHEMA_MIGRATIONS_SQL,
141
+ ].join('\n\n');
142
+ function postgresStore(sql, ownsClient, additionalFields) {
143
+ const columns = resolveReplicaColumns(additionalFields);
144
+ const attributeMigrations = postgresAttributeMigrations(additionalFields);
143
145
  return {
144
- init: () => runProjectorPromise('postgres-event-log', () => sql.unsafe(POSTGRES_EVENT_LOG_SCHEMA_SQL)).then(() => undefined),
146
+ init: () => runProjectorPromise('postgres-event-log', () => sql
147
+ .unsafe(POSTGRES_EVENT_LOG_INIT_SQL)
148
+ .then(() => applyPostgresMigrations(sql, attributeMigrations))),
145
149
  apply: (events) => {
146
150
  const ops = events.flatMap(eventLogOps);
147
151
  if (ops.length === 0) {
148
152
  return Promise.resolve();
149
153
  }
150
- return runProjectorPromise('postgres-event-log', () => sql.begin((tx) => applySqlOps(tx, ops))).then(() => undefined);
154
+ return runProjectorPromise('postgres-event-log', () => sql.begin((tx) => applySqlOps(tx, ops, columns))).then(() => undefined);
151
155
  },
152
156
  dispose: () => ownsClient
153
157
  ? runProjectorPromise('postgres-event-log', () => sql.end({ timeout: 5 })).then(() => undefined)
@@ -181,18 +185,18 @@ function runIndexPatches(ops) {
181
185
  }
182
186
  return [...patches.values()];
183
187
  }
184
- export function applySqlOps(sql, ops) {
188
+ export function applySqlOps(sql, ops, columns = []) {
185
189
  const events = ops.flatMap((op) => (op.type === 'insert' ? [envelopeFromEntry(op.entry)] : []));
186
- return Promise.all([insertRunEvents(sql, events), applyRunIndexOps(sql, ops)]).then(() => undefined);
190
+ return Promise.all([insertRunEvents(sql, events), applyRunIndexOps(sql, ops, columns)]).then(() => undefined);
187
191
  }
188
192
  /** Fold run-summary ops. Event rows are written by {@link insertRunEvents}. */
189
- export function applyRunIndexOps(sql, ops) {
193
+ export function applyRunIndexOps(sql, ops, columns = []) {
190
194
  const patches = runIndexPatches(ops);
191
195
  const upserts = patches.filter((patch) => patch.start !== null || patch.finish !== null);
192
196
  const touches = patches.filter((patch) => patch.start === null && patch.finish === null);
193
197
  const statements = [];
194
198
  if (upserts.length > 0) {
195
- statements.push(upsertRuns(sql, upserts));
199
+ statements.push(upsertRuns(sql, upserts, columns));
196
200
  }
197
201
  if (touches.length > 0) {
198
202
  statements.push(touchRuns(sql, touches));
@@ -248,8 +252,9 @@ function insertEventChunk(sql, events) {
248
252
  }
249
253
  // A finish in the batch sets the status; otherwise a finished run keeps its status and a
250
254
  // started run becomes running. Start fields fill only columns that are still empty.
251
- function upsertRuns(sql, patches) {
255
+ function upsertRuns(sql, patches, columns) {
252
256
  const rows = patches.map(({ runId, start, finish, completedAt, updatedAt }) => ({
257
+ ...hostColumnRow(columns, start?.attributes),
253
258
  run_id: runId,
254
259
  status: finish?.status ?? 'running',
255
260
  kind: start?.kind ?? null,
@@ -260,9 +265,6 @@ function upsertRuns(sql, patches) {
260
265
  launched_by_effect_id: start?.launchedByEffectId ?? null,
261
266
  correlation_id: start?.correlationId ?? null,
262
267
  attributes: sql.json(start?.attributes ?? {}),
263
- tenant: start?.tenant ?? null,
264
- project: start?.project ?? null,
265
- org: start?.org ?? null,
266
268
  started_at: start ? utcDate(start.at) : null,
267
269
  updated_at: utcDate(updatedAt),
268
270
  completed_at: completedAt === null ? null : utcDate(completedAt),
@@ -286,14 +288,16 @@ function upsertRuns(sql, patches) {
286
288
  WHEN looms_run_index.attributes = '{}'::jsonb THEN EXCLUDED.attributes
287
289
  ELSE looms_run_index.attributes
288
290
  END,
289
- tenant = COALESCE(looms_run_index.tenant, EXCLUDED.tenant),
290
- project = COALESCE(looms_run_index.project, EXCLUDED.project),
291
- org = COALESCE(looms_run_index.org, EXCLUDED.org),
291
+ ${columns.reduce((set, column) => sql `${set} ${sql(column.name)} = COALESCE(looms_run_index.${sql(column.name)}, EXCLUDED.${sql(column.name)}),`, sql ``)}
292
292
  started_at = COALESCE(looms_run_index.started_at, EXCLUDED.started_at),
293
293
  updated_at = GREATEST(looms_run_index.updated_at, EXCLUDED.updated_at),
294
294
  completed_at = COALESCE(looms_run_index.completed_at, EXCLUDED.completed_at)
295
295
  `.then(() => undefined);
296
296
  }
297
+ function hostColumnRow(columns, attributes) {
298
+ const values = columnValues(columns, attributes);
299
+ return Object.fromEntries(columns.map((column, index) => [column.name, values[index] ?? null]));
300
+ }
297
301
  function touchRuns(sql, patches) {
298
302
  const runIds = patches.map((patch) => patch.runId);
299
303
  const touchedAt = patches.map((patch) => DateTime.formatIso(DateTime.makeUnsafe(patch.updatedAt)));