@swirls/looms 0.9.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 (82) hide show
  1. package/CHANGELOG.md +6 -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 +2 -2
  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/runtime/server/routes/definitions.d.ts +1 -1
  64. package/dist/runtime/server/routes/definitions.js +58 -2
  65. package/dist/runtime/server/routes/runs.js +25 -1
  66. package/dist/schedule/module.d.ts +117 -1
  67. package/dist/schedule/module.js +30 -0
  68. package/dist/schedule/scope.js +1 -0
  69. package/dist/schedule/signals.d.ts +59 -7
  70. package/dist/schedule/signals.js +35 -17
  71. package/dist/testing/corpus-module.d.ts +1 -1
  72. package/dist/testing/index.js +2 -1
  73. package/dist/testing/module-examples.d.ts +6 -0
  74. package/dist/testing/module-examples.js +66 -0
  75. package/dist/workflow/module.d.ts +3 -1
  76. package/dist/workflow/module.js +13 -0
  77. package/dist/workflow/scope.js +1 -0
  78. package/package.json +1 -1
  79. package/dist/debugger/app/assets/index-B7GdT1UA.css +0 -2
  80. package/dist/debugger/app/assets/routes-CfXxKG45.js +0 -47
  81. /package/dist/evaluator/{signals.d.ts → steps.d.ts} +0 -0
  82. /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
  });
@@ -1,3 +1,3 @@
1
- import type { RouteOptions } from '../http';
1
+ import { type RouteOptions } from '../http';
2
2
  import { type Route } from '../route-table';
3
3
  export declare function definitionRoutes({ runtime }: RouteOptions): readonly Route[];
@@ -1,6 +1,14 @@
1
- import { Effect } from 'effect';
2
- import { publishDefinition, publishEffects } from '@swirls/looms/core';
1
+ import { Effect, Schema } from 'effect';
2
+ import { findSignal, JsonValueSchema, publishDefinition, publishEffects, publishEvents, publishModules, publishSignals, runSignal, validateEventInput, } from '@swirls/looms/core';
3
+ import { EventInputBodySchema, readJson } from '../http.js';
3
4
  import { route } from '../route-table.js';
5
+ const PreviewSignalBodySchema = Schema.Struct({
6
+ input: Schema.optional(JsonValueSchema),
7
+ threadId: Schema.optional(Schema.String),
8
+ });
9
+ const PreviewEventsBodySchema = Schema.Struct({
10
+ events: Schema.Array(EventInputBodySchema),
11
+ });
4
12
  export function definitionRoutes({ runtime }) {
5
13
  return [
6
14
  route({
@@ -12,6 +20,7 @@ export function definitionRoutes({ runtime }) {
12
20
  const catalog = {
13
21
  definitions: runtime.registry.definitions.map(publishDefinition),
14
22
  projections: [...runtime.registry.projections.keys()],
23
+ modules: publishModules(runtime.registry.modules),
15
24
  };
16
25
  return Effect.succeed(Response.json(catalog));
17
26
  },
@@ -23,5 +32,52 @@ export function definitionRoutes({ runtime }) {
23
32
  access: 'read',
24
33
  handle: () => Effect.succeed(Response.json({ effects: publishEffects(runtime.registry.effects.values()) })),
25
34
  }),
35
+ route({
36
+ method: 'GET',
37
+ path: '/definitions/signals',
38
+ name: 'definitions.signals',
39
+ access: 'read',
40
+ handle: () => Effect.succeed(Response.json({ signals: publishSignals(runtime.registry.modules) })),
41
+ }),
42
+ route({
43
+ method: 'GET',
44
+ path: '/definitions/events',
45
+ name: 'definitions.events',
46
+ access: 'read',
47
+ handle: () => Effect.succeed(Response.json({ events: publishEvents(runtime.registry.modules) })),
48
+ }),
49
+ route({
50
+ method: 'POST',
51
+ path: '/definitions/signals/:namespace/:name/preview',
52
+ name: 'definitions.signals.preview',
53
+ access: 'read',
54
+ handle: ({ req, params }) =>
55
+ // SAFETY: Effect.gen residual R is never here; Schema.decode errors become RequestBodyError via toErrorResponse.
56
+ Effect.gen(function* () {
57
+ const definition = findSignal(runtime.registry.modules, params.namespace, params.name);
58
+ if (!definition) {
59
+ return Response.json({ error: `Unknown signal ${params.namespace}.${params.name}` }, { status: 404 });
60
+ }
61
+ const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(PreviewSignalBodySchema)));
62
+ const events = yield* runSignal(definition, body.input ?? null, body.threadId);
63
+ return Response.json({ events });
64
+ }),
65
+ }),
66
+ route({
67
+ method: 'POST',
68
+ path: '/definitions/events/preview',
69
+ name: 'definitions.events.preview',
70
+ access: 'read',
71
+ handle: ({ req }) =>
72
+ // SAFETY: Effect.gen residual R is never here; validateEventInput failures are already in the Error channel.
73
+ Effect.gen(function* () {
74
+ const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(PreviewEventsBodySchema)));
75
+ const events = [];
76
+ for (const input of body.events) {
77
+ events.push(yield* validateEventInput(runtime.registry.catalogs, input));
78
+ }
79
+ return Response.json({ events });
80
+ }),
81
+ }),
26
82
  ];
27
83
  }
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema } from 'effect';
2
- import { createRunId, EventStoreTag, JsonValueSchema, RunAttributesSchema, readTraceHeaders, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
2
+ import { createRunId, EventStoreTag, findSignal, JsonValueSchema, RunAttributesSchema, readTraceHeaders, runSignal, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
3
3
  import { createEventStreamResponse } from '../../sse.js';
4
4
  import { acceptsEventStream, EventInputBodySchema, extractIdempotencyKey, provideStore, readIntegerQuery, readJson, readOptionalJson, RequestQueryError, } from '../http.js';
5
5
  import { route } from '../route-table.js';
@@ -21,6 +21,11 @@ const SignalBodySchema = Schema.Struct({
21
21
  threadId: Schema.optional(Schema.NullOr(Schema.String)),
22
22
  idempotencyKey: Schema.optional(Schema.String),
23
23
  });
24
+ const NamedSignalBodySchema = Schema.Struct({
25
+ input: Schema.optional(JsonValueSchema),
26
+ threadId: Schema.optional(Schema.String),
27
+ idempotencyKey: Schema.optional(Schema.String),
28
+ });
24
29
  const CancelBodySchema = Schema.Struct({
25
30
  threadId: Schema.optional(Schema.String),
26
31
  });
@@ -194,6 +199,25 @@ export function runRoutes({ runtime, store }) {
194
199
  return Response.json({ runId: params.runId, state });
195
200
  }),
196
201
  }),
202
+ route({
203
+ method: 'POST',
204
+ path: '/runs/:runId/signals/:namespace/:name',
205
+ name: 'runs.signal.named',
206
+ access: 'write',
207
+ handle: ({ req, params }) =>
208
+ // SAFETY: Effect.gen residual R is never here; decode/run errors map to Error via route handlers.
209
+ Effect.gen(function* () {
210
+ const definition = findSignal(runtime.registry.modules, params.namespace, params.name);
211
+ if (!definition) {
212
+ return Response.json({ error: `Unknown signal ${params.namespace}.${params.name}` }, { status: 404 });
213
+ }
214
+ const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(NamedSignalBodySchema)));
215
+ const events = yield* runSignal(definition, body.input ?? null, body.threadId);
216
+ const idempotencyKey = extractIdempotencyKey(req, body.idempotencyKey);
217
+ const state = yield* provideStore(runtime.signal(params.runId, events, { idempotencyKey }), store);
218
+ return Response.json({ runId: params.runId, state });
219
+ }),
220
+ }),
197
221
  route({
198
222
  method: 'POST',
199
223
  path: '/runs/:runId/wake',