@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
@@ -2,8 +2,16 @@ import { defineEventCatalog, } from './catalog.js';
2
2
  import { emit, defineEffect, } from './effects.js';
3
3
  import {} from './module.js';
4
4
  import { defineProjection } from './projection.js';
5
+ import { defineSignal } from './signals.js';
5
6
  import { defineThread, } from './thread.js';
6
- import { asJson } from './types.js';
7
+ import { asJson, cleanUndefined } from './types.js';
8
+ function storeExamples(examples) {
9
+ return examples.map(({ name, events, projections }) => ({
10
+ name,
11
+ events,
12
+ projections: Object.fromEntries(Object.entries(projections).map(([key, state]) => [key, cleanUndefined(state)])),
13
+ }));
14
+ }
7
15
  function buildScopeInput(namespace, key, payload, meta) {
8
16
  return {
9
17
  ...meta,
@@ -12,10 +20,11 @@ function buildScopeInput(namespace, key, payload, meta) {
12
20
  };
13
21
  }
14
22
  export function createModuleScope(options) {
15
- const { namespace, protocolVersion, events, observes, dependencies } = options;
23
+ const { namespace, protocolVersion, description, events, observes, dependencies } = options;
16
24
  const scope = {
17
25
  namespace,
18
26
  protocolVersion,
27
+ description,
19
28
  events,
20
29
  observes,
21
30
  dependencies,
@@ -28,6 +37,9 @@ export function createModuleScope(options) {
28
37
  effect(def) {
29
38
  return defineEffect(def);
30
39
  },
40
+ signal(def) {
41
+ return defineSignal(def);
42
+ },
31
43
  input(key, payload, meta) {
32
44
  return buildScopeInput(namespace, key, payload, meta);
33
45
  },
@@ -59,13 +71,21 @@ export function defineModule(options, setup) {
59
71
  effects: members.effects ?? {},
60
72
  threads: members.threads ?? {},
61
73
  projections: members.projections ?? {},
74
+ signals: members.signals ?? {},
75
+ steps: members.steps ?? {},
62
76
  };
77
+ if (options.description) {
78
+ module.description = options.description;
79
+ }
63
80
  if (options.observes) {
64
81
  module.observes = options.observes;
65
82
  }
66
83
  if (options.dependencies) {
67
84
  module.dependencies = options.dependencies;
68
85
  }
86
+ if (members.examples) {
87
+ module.examples = storeExamples(members.examples);
88
+ }
69
89
  if (members.definitions) {
70
90
  module.definitions = members.definitions;
71
91
  }
@@ -6,6 +6,7 @@ import type { EventInput } from './envelope';
6
6
  import type { ProjectionDefinition } from './projection';
7
7
  import type { RunAttributes, SecretContext } from './run-context';
8
8
  import { type InferDefinedSchema, type SchemaInput } from './schema';
9
+ import type { AnySignalDefinition } from './signals';
9
10
  import type { ThreadDefinition } from './thread';
10
11
  import type { TraceContext } from './trace';
11
12
  import type { JsonValue } from './types';
@@ -84,6 +85,17 @@ export interface RegisteredDefinition {
84
85
  export type DefinitionInput<TDef> = TDef extends {
85
86
  readonly input?: infer S;
86
87
  } ? InferDefinedSchema<S> : JsonValue;
88
+ /**
89
+ * A trace `moduleConformance` folds. Events are catalog inputs in log order. `projections` maps a
90
+ * projection member key to the JSON state the fold must produce. The host does not read examples.
91
+ */
92
+ export interface ModuleExample {
93
+ readonly name: string;
94
+ readonly events: readonly EventInput[];
95
+ readonly projections: {
96
+ readonly [memberKey: string]: JsonValue;
97
+ };
98
+ }
87
99
  export interface RuntimeModule<TNamespace extends string = string, TEvents extends EventCatalog = EventCatalog, TEffects extends {
88
100
  readonly [key: string]: EffectDefinition;
89
101
  } = {
@@ -96,14 +108,25 @@ export interface RuntimeModule<TNamespace extends string = string, TEvents exten
96
108
  readonly [key: string]: ProjectionDefinition;
97
109
  } = {
98
110
  readonly [key: string]: ProjectionDefinition;
99
- }, TServices = Context.Service.Any> {
111
+ }, TServices = Context.Service.Any, TSignals = {}, TSteps = {}> {
100
112
  readonly namespace: TNamespace;
101
113
  readonly protocolVersion: string;
114
+ /** Published on `GET /definitions` so a catalog can name the module. */
115
+ readonly description?: string;
102
116
  readonly events?: TEvents;
103
117
  readonly observes?: readonly EventCatalog[];
104
118
  readonly threads?: TThreads;
105
119
  readonly effects?: TEffects;
106
120
  readonly projections?: TProjections;
121
+ /**
122
+ * Schema-backed event builders for callers outside a run. Callers import them, and the host
123
+ * publishes their input schemas and can run `build` for preview / named send over HTTP.
124
+ */
125
+ readonly signals?: TSignals;
126
+ /** Effect composers for threads and workflow nodes. The host does not run them. */
127
+ readonly steps?: TSteps;
128
+ /** Sample traces. The host ignores them; conformance folds them. */
129
+ readonly examples?: readonly ModuleExample[];
107
130
  readonly definitions?: readonly DefinitionRef[];
108
131
  readonly dependencies?: readonly RuntimeModuleDependency[];
109
132
  readonly middleware?: readonly EffectMiddleware[];
@@ -127,11 +150,15 @@ export declare function defineRuntimeModule<TNamespace extends string, TEvents e
127
150
  readonly [key: string]: ThreadDefinition;
128
151
  }, TProjections extends {
129
152
  readonly [key: string]: ProjectionDefinition;
130
- }, TServices = Context.Service.Any>(module: RuntimeModule<TNamespace, TEvents, TEffects, TThreads, TProjections, TServices>): RuntimeModule<TNamespace, TEvents, TEffects, TThreads, TProjections, TServices>;
153
+ }, TServices = Context.Service.Any, TSignals = {}, TSteps = {}>(module: RuntimeModule<TNamespace, TEvents, TEffects, TThreads, TProjections, TServices, TSignals, TSteps>): RuntimeModule<TNamespace, TEvents, TEffects, TThreads, TProjections, TServices, TSignals, TSteps>;
131
154
  export type AnyRuntimeModule = RuntimeModule<string, EventCatalog, {
132
155
  readonly [name: string]: EffectDefinition<any, any, any>;
133
156
  }, {
134
157
  readonly [kind: string]: ThreadDefinition;
135
158
  }, {
136
159
  readonly [name: string]: ProjectionDefinition;
160
+ }, Context.Service.Any, {
161
+ readonly [name: string]: AnySignalDefinition;
162
+ }, {
163
+ readonly [name: string]: (...args: never[]) => readonly RuntimeEffect[];
137
164
  }>;
@@ -9,6 +9,7 @@ export interface ProjectionDefinition<S = unknown> {
9
9
  initialState: S;
10
10
  reduce(state: S, event: EventEnvelope): S;
11
11
  }
12
+ export type ProjectionStateOf<T> = T extends ProjectionDefinition<infer S> ? S : never;
12
13
  export declare function defineProjection<S = unknown, TEvent extends AnyEventEnvelope = RegisteredEvent>(def: {
13
14
  readonly name: string;
14
15
  readonly shape?: undefined;
@@ -1,6 +1,6 @@
1
1
  import { Schema } from 'effect';
2
2
  import type { EffectPlacement, RetryPolicy } from './effects';
3
- import type { RegisteredDefinition } from './module';
3
+ import type { AnyRuntimeModule, RegisteredDefinition } from './module';
4
4
  import { type SchemaInput } from './schema';
5
5
  import { type RunState } from './state';
6
6
  /** A registered definition as `GET /definitions` publishes it. */
@@ -13,6 +13,13 @@ export declare const PublishedDefinitionSchema: Schema.Struct<{
13
13
  readonly inputSchema: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
14
14
  }>;
15
15
  export type PublishedDefinition = Schema.Schema.Type<typeof PublishedDefinitionSchema>;
16
+ /** A module as `GET /definitions` publishes it. */
17
+ export declare const PublishedModuleSchema: Schema.Struct<{
18
+ readonly namespace: Schema.String;
19
+ readonly protocolVersion: Schema.String;
20
+ readonly description: Schema.optional<Schema.String>;
21
+ }>;
22
+ export type PublishedModule = Schema.Schema.Type<typeof PublishedModuleSchema>;
16
23
  export declare const DefinitionCatalogSchema: Schema.Struct<{
17
24
  readonly definitions: Schema.$Array<Schema.Struct<{
18
25
  readonly kind: Schema.String;
@@ -23,8 +30,15 @@ export declare const DefinitionCatalogSchema: Schema.Struct<{
23
30
  readonly inputSchema: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
24
31
  }>>;
25
32
  readonly projections: Schema.$Array<Schema.String>;
33
+ readonly modules: Schema.withDecodingDefaultKey<Schema.$Array<Schema.Struct<{
34
+ readonly namespace: Schema.String;
35
+ readonly protocolVersion: Schema.String;
36
+ readonly description: Schema.optional<Schema.String>;
37
+ }>>, never>;
26
38
  }>;
27
39
  export type DefinitionCatalog = Schema.Schema.Type<typeof DefinitionCatalogSchema>;
40
+ /** Modules in registration order. */
41
+ export declare function publishModules(modules: readonly AnyRuntimeModule[]): readonly PublishedModule[];
28
42
  export declare function publishDefinition(definition: RegisteredDefinition): PublishedDefinition;
29
43
  /** A declared effect as `GET /definitions/effects` publishes it. */
30
44
  export declare const PublishedEffectSchema: Schema.Struct<{
@@ -75,6 +89,50 @@ interface PublishableEffect {
75
89
  export declare function publishEffect(definition: PublishableEffect): PublishedEffect;
76
90
  /** Declared effects, sorted by type so the catalog is stable. */
77
91
  export declare function publishEffects(effects: Iterable<PublishableEffect>): readonly PublishedEffect[];
92
+ /** A module signal as `GET /definitions/signals` publishes it. */
93
+ export declare const PublishedSignalSchema: Schema.Struct<{
94
+ readonly namespace: Schema.String;
95
+ readonly name: Schema.String;
96
+ readonly description: Schema.optional<Schema.String>;
97
+ /** JSON Schema derived from the signal's `input`. Omitted for no-arg signals. */
98
+ readonly inputSchema: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
99
+ }>;
100
+ export type PublishedSignal = Schema.Schema.Type<typeof PublishedSignalSchema>;
101
+ export declare const SignalCatalogSchema: Schema.Struct<{
102
+ readonly signals: Schema.$Array<Schema.Struct<{
103
+ readonly namespace: Schema.String;
104
+ readonly name: Schema.String;
105
+ readonly description: Schema.optional<Schema.String>;
106
+ /** JSON Schema derived from the signal's `input`. Omitted for no-arg signals. */
107
+ readonly inputSchema: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
108
+ }>>;
109
+ }>;
110
+ export type SignalCatalog = Schema.Schema.Type<typeof SignalCatalogSchema>;
111
+ export declare function publishSignal(namespace: string, name: string, definition: {
112
+ readonly description?: string;
113
+ readonly input?: SchemaInput;
114
+ }): PublishedSignal;
115
+ /** Declared signals across modules, sorted by namespace then name. */
116
+ export declare function publishSignals(modules: readonly AnyRuntimeModule[]): readonly PublishedSignal[];
117
+ /** A catalog event as `GET /definitions/events` publishes it. */
118
+ export declare const PublishedEventSchema: Schema.Struct<{
119
+ readonly type: Schema.String;
120
+ readonly namespace: Schema.String;
121
+ /** JSON Schema for the event payload, when the catalog entry has a runtime schema. */
122
+ readonly payloadSchema: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
123
+ }>;
124
+ export type PublishedEvent = Schema.Schema.Type<typeof PublishedEventSchema>;
125
+ export declare const EventTypeCatalogSchema: Schema.Struct<{
126
+ readonly events: Schema.$Array<Schema.Struct<{
127
+ readonly type: Schema.String;
128
+ readonly namespace: Schema.String;
129
+ /** JSON Schema for the event payload, when the catalog entry has a runtime schema. */
130
+ readonly payloadSchema: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
131
+ }>>;
132
+ }>;
133
+ export type EventTypeCatalog = Schema.Schema.Type<typeof EventTypeCatalogSchema>;
134
+ /** Catalog events across modules, sorted by type. */
135
+ export declare function publishEvents(modules: readonly AnyRuntimeModule[]): readonly PublishedEvent[];
78
136
  /** A run as `GET /runs/summaries` lists it. */
79
137
  export declare const RunSummarySchema: Schema.Struct<{
80
138
  readonly runId: Schema.String;
@@ -1,7 +1,8 @@
1
- import { Effect, Schema } from 'effect';
1
+ import { Effect, Predicate, Schema } from 'effect';
2
2
  import { JsonValueSchema } from './envelope.js';
3
3
  import { RunAttributesSchema } from './run-context.js';
4
4
  import { jsonSchemaOfInput } from './schema.js';
5
+ import { isSignalDefinition } from './signals.js';
5
6
  import { RunStateSchema } from './state.js';
6
7
  /** A registered definition as `GET /definitions` publishes it. */
7
8
  export const PublishedDefinitionSchema = Schema.Struct({
@@ -12,10 +13,25 @@ export const PublishedDefinitionSchema = Schema.Struct({
12
13
  /** JSON Schema derived from the definition's `input`. */
13
14
  inputSchema: Schema.optional(JsonValueSchema),
14
15
  });
16
+ /** A module as `GET /definitions` publishes it. */
17
+ export const PublishedModuleSchema = Schema.Struct({
18
+ namespace: Schema.String,
19
+ protocolVersion: Schema.String,
20
+ description: Schema.optional(Schema.String),
21
+ });
15
22
  export const DefinitionCatalogSchema = Schema.Struct({
16
23
  definitions: Schema.Array(PublishedDefinitionSchema),
17
24
  projections: Schema.Array(Schema.String),
25
+ modules: Schema.Array(PublishedModuleSchema).pipe(Schema.withDecodingDefaultKey(Effect.succeed([]))),
18
26
  });
27
+ /** Modules in registration order. */
28
+ export function publishModules(modules) {
29
+ return modules.map(({ namespace, protocolVersion, description }) => ({
30
+ namespace,
31
+ protocolVersion,
32
+ ...(description ? { description } : undefined),
33
+ }));
34
+ }
19
35
  export function publishDefinition(definition) {
20
36
  return {
21
37
  kind: definition.kind,
@@ -70,6 +86,86 @@ export function publishEffects(effects) {
70
86
  .map(publishEffect)
71
87
  .toSorted((left, right) => left.type.localeCompare(right.type));
72
88
  }
89
+ /** A module signal as `GET /definitions/signals` publishes it. */
90
+ export const PublishedSignalSchema = Schema.Struct({
91
+ namespace: Schema.String,
92
+ name: Schema.String,
93
+ description: Schema.optional(Schema.String),
94
+ /** JSON Schema derived from the signal's `input`. Omitted for no-arg signals. */
95
+ inputSchema: Schema.optional(JsonValueSchema),
96
+ });
97
+ export const SignalCatalogSchema = Schema.Struct({
98
+ signals: Schema.Array(PublishedSignalSchema),
99
+ });
100
+ export function publishSignal(namespace, name, definition) {
101
+ const published = { namespace, name };
102
+ if (definition.description !== undefined) {
103
+ published.description = definition.description;
104
+ }
105
+ const inputSchema = jsonSchemaOfInput(definition.input);
106
+ if (inputSchema !== undefined) {
107
+ published.inputSchema = inputSchema;
108
+ }
109
+ return published;
110
+ }
111
+ /** Declared signals across modules, sorted by namespace then name. */
112
+ export function publishSignals(modules) {
113
+ const signals = [];
114
+ for (const module of modules) {
115
+ for (const [name, candidate] of Object.entries(module.signals ?? {})) {
116
+ if (!isSignalDefinition(candidate)) {
117
+ throw new TypeError(`Module "${module.namespace}" signals.${name} is not a SignalDefinition`);
118
+ }
119
+ signals.push(publishSignal(module.namespace, name, candidate));
120
+ }
121
+ }
122
+ return signals.toSorted((left, right) => left.namespace.localeCompare(right.namespace) || left.name.localeCompare(right.name));
123
+ }
124
+ /** A catalog event as `GET /definitions/events` publishes it. */
125
+ export const PublishedEventSchema = Schema.Struct({
126
+ type: Schema.String,
127
+ namespace: Schema.String,
128
+ /** JSON Schema for the event payload, when the catalog entry has a runtime schema. */
129
+ payloadSchema: Schema.optional(JsonValueSchema),
130
+ });
131
+ export const EventTypeCatalogSchema = Schema.Struct({
132
+ events: Schema.Array(PublishedEventSchema),
133
+ });
134
+ function payloadSchemaOfEntry(entry) {
135
+ if (Predicate.isReadonlyObject(entry) && '~standard' in entry) {
136
+ // SAFETY: CatalogEntry with ~standard is a Standard Schema; jsonSchemaOfInput expects SchemaInput.
137
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
138
+ return jsonSchemaOfInput(entry);
139
+ }
140
+ if (Schema.isSchema(entry)) {
141
+ // SAFETY: Schema.isSchema narrows CatalogEntry to an Effect Schema, which is a valid SchemaInput.
142
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
143
+ return jsonSchemaOfInput(entry);
144
+ }
145
+ return undefined;
146
+ }
147
+ /** Catalog events across modules, sorted by type. */
148
+ export function publishEvents(modules) {
149
+ const events = [];
150
+ for (const module of modules) {
151
+ const catalog = module.events;
152
+ if (!catalog) {
153
+ continue;
154
+ }
155
+ for (const [key, entry] of Object.entries(catalog.entries)) {
156
+ const published = {
157
+ type: `${catalog.namespace}.${key}`,
158
+ namespace: catalog.namespace,
159
+ };
160
+ const payloadSchema = payloadSchemaOfEntry(entry);
161
+ if (payloadSchema !== undefined) {
162
+ published.payloadSchema = payloadSchema;
163
+ }
164
+ events.push(published);
165
+ }
166
+ }
167
+ return events.toSorted((left, right) => left.type.localeCompare(right.type));
168
+ }
73
169
  /** A run as `GET /runs/summaries` lists it. */
74
170
  export const RunSummarySchema = Schema.Struct({
75
171
  runId: Schema.String,
@@ -0,0 +1,56 @@
1
+ import { Effect } from 'effect';
2
+ import type { EventInput } from './envelope';
3
+ import type { AnyRuntimeModule } from './module';
4
+ import { type InferDefinedSchema, type InvalidInputError, type SchemaInput } from './schema';
5
+ import { type JsonValue } from './types';
6
+ declare const signalBrand: unique symbol;
7
+ /** Options for a signal call. `threadId` stamps events that do not already set one. */
8
+ export interface SignalOptions {
9
+ readonly threadId?: string;
10
+ }
11
+ type SignalResult = EventInput | readonly EventInput[];
12
+ /**
13
+ * A named, schema-backed event builder. Callable as `(input, options?) => events`.
14
+ * When `input` is omitted on the definition, the first argument is options: `pause()` or
15
+ * `stopAgentTurn({ threadId })`.
16
+ */
17
+ export type SignalDefinition<TInput = JsonValue | undefined, E extends SignalResult = EventInput> = {
18
+ readonly description?: string;
19
+ readonly input?: SchemaInput;
20
+ readonly [signalBrand]: true;
21
+ } & ([TInput] extends [undefined] ? {
22
+ (options?: SignalOptions): E;
23
+ } : {
24
+ (input: TInput, options?: SignalOptions): E;
25
+ });
26
+ /** Erased signal shape for registries, publishing, and `findSignal`. */
27
+ export type AnySignalDefinition = {
28
+ readonly description?: string;
29
+ readonly input?: SchemaInput;
30
+ readonly [signalBrand]: true;
31
+ (...args: any[]): SignalResult;
32
+ };
33
+ export declare function isSignalDefinition(value: unknown): value is AnySignalDefinition;
34
+ /** Stamp `threadId` onto events that do not already set one. Preserves single vs batch shape. */
35
+ export declare function stampSignalThread(built: SignalResult, threadId: string | undefined): SignalResult;
36
+ interface DefineSignalInput<TSchema, E extends SignalResult> {
37
+ readonly description?: string;
38
+ readonly input?: TSchema;
39
+ readonly build: (input: InferDefinedSchema<TSchema, undefined>) => E;
40
+ }
41
+ /**
42
+ * Low-level signal constructor. Inside a module, prefer `m.signal` / `scope.signal`, which type
43
+ * built events against the module's catalogs. `defineModule` also rejects foreign signals the
44
+ * same way it rejects foreign effects.
45
+ */
46
+ export declare function defineSignal<TSchema extends SchemaInput | undefined = undefined, E extends SignalResult = EventInput>(def: DefineSignalInput<TSchema, E>): SignalDefinition<InferDefinedSchema<TSchema, undefined>, E>;
47
+ /** Look up a signal by module namespace and member key. */
48
+ export declare function findSignal(modules: readonly AnyRuntimeModule[], namespace: string, name: string): AnySignalDefinition | undefined;
49
+ /**
50
+ * Validate `rawInput` against the signal's schema and invoke the callable (which stamps
51
+ * `threadId`). Returns the events that `runtime.signal` would append.
52
+ */
53
+ export declare function runSignal(definition: AnySignalDefinition, rawInput: JsonValue, threadId?: string): Effect.Effect<EventInput[], InvalidInputError>;
54
+ /** Sync form of {@link runSignal}. Throws {@link InvalidInputError} on bad input. */
55
+ export declare function runSignalSync(definition: AnySignalDefinition, rawInput: JsonValue, threadId?: string): EventInput[];
56
+ export {};
@@ -0,0 +1,93 @@
1
+ import { Effect, Predicate } from 'effect';
2
+ import { validateInputEffect, validateInputSync, } from './schema.js';
3
+ import { asJson } from './types.js';
4
+ const signalBrand = Symbol.for('@swirls/looms/core/signal');
5
+ export function isSignalDefinition(value) {
6
+ return Predicate.isFunction(value) && signalBrand in value;
7
+ }
8
+ function stampOne(event, threadId) {
9
+ return threadId !== undefined && event.threadId === undefined ? { ...event, threadId } : event;
10
+ }
11
+ function isEventBatch(built) {
12
+ return Array.isArray(built);
13
+ }
14
+ function asEventList(built) {
15
+ return isEventBatch(built) ? [...built] : [built];
16
+ }
17
+ /** Stamp `threadId` onto events that do not already set one. Preserves single vs batch shape. */
18
+ export function stampSignalThread(built, threadId) {
19
+ if (isEventBatch(built)) {
20
+ return built.map((event) => stampOne(event, threadId));
21
+ }
22
+ return stampOne(built, threadId);
23
+ }
24
+ /**
25
+ * Low-level signal constructor. Inside a module, prefer `m.signal` / `scope.signal`, which type
26
+ * built events against the module's catalogs. `defineModule` also rejects foreign signals the
27
+ * same way it rejects foreign effects.
28
+ */
29
+ export function defineSignal(def) {
30
+ function invoke(input, options) {
31
+ const stamped = stampSignalThread(def.build(input), options?.threadId);
32
+ // SAFETY: stampSignalThread preserves single vs batch; build returns E.
33
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
34
+ return stamped;
35
+ }
36
+ function noInput() {
37
+ // SAFETY: no-schema signals use InferDefinedSchema<undefined, undefined> === undefined.
38
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
39
+ return undefined;
40
+ }
41
+ // SAFETY: the callable matches the SignalDefinition overload for this input schema.
42
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
43
+ const call = (def.input === undefined
44
+ ? (options) => invoke(noInput(), options)
45
+ : (input, options) => invoke(input, options));
46
+ Object.defineProperty(call, signalBrand, { value: true });
47
+ if (def.description !== undefined) {
48
+ Object.defineProperty(call, 'description', { value: def.description });
49
+ }
50
+ if (def.input !== undefined) {
51
+ Object.defineProperty(call, 'input', { value: def.input });
52
+ }
53
+ return call;
54
+ }
55
+ /** Look up a signal by module namespace and member key. */
56
+ export function findSignal(modules, namespace, name) {
57
+ for (const module of modules) {
58
+ if (module.namespace !== namespace) {
59
+ continue;
60
+ }
61
+ const signals = module.signals;
62
+ if (!signals || !Object.hasOwn(signals, name)) {
63
+ return undefined;
64
+ }
65
+ const candidate = signals[name];
66
+ // ModuleSignals guarantees branded callables; index access widens the value.
67
+ return isSignalDefinition(candidate) ? candidate : undefined;
68
+ }
69
+ return undefined;
70
+ }
71
+ /**
72
+ * Validate `rawInput` against the signal's schema and invoke the callable (which stamps
73
+ * `threadId`). Returns the events that `runtime.signal` would append.
74
+ */
75
+ export function runSignal(definition, rawInput, threadId) {
76
+ return Effect.gen(function* () {
77
+ const schema = definition.input;
78
+ const options = { threadId };
79
+ const built = schema
80
+ ? definition(yield* validateInputEffect(schema, rawInput), options)
81
+ : definition(options);
82
+ return asEventList(built);
83
+ });
84
+ }
85
+ /** Sync form of {@link runSignal}. Throws {@link InvalidInputError} on bad input. */
86
+ export function runSignalSync(definition, rawInput, threadId) {
87
+ const schema = definition.input;
88
+ const options = { threadId };
89
+ const built = schema
90
+ ? definition(validateInputSync(schema, asJson(rawInput)), options)
91
+ : definition(options);
92
+ return asEventList(built);
93
+ }
@@ -1,6 +1,6 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import { Effect } from 'effect';
3
- import type { EventCatalog } from './catalog';
3
+ import type { CatalogEntry, EventCatalog } from './catalog';
4
4
  import type { EventInput } from './envelope';
5
5
  declare const InvalidEventError_base: new <A extends Record<string, any> = {}>(args: import("effect/Types").VoidIfEmpty<{ readonly [P in keyof A as P extends "_tag" ? never : P]: A[P]; }>) => import("effect/Cause").YieldableError & {
6
6
  readonly _tag: "InvalidEventError";
@@ -14,6 +14,17 @@ export declare class InvalidEventError extends InvalidEventError_base<{
14
14
  readonly issues: ReadonlyArray<StandardSchemaV1.Issue>;
15
15
  constructor(type: string, text: string, issues?: ReadonlyArray<StandardSchemaV1.Issue>);
16
16
  }
17
+ /** Locate a catalog entry for a fully-qualified event type across the given catalogs. */
18
+ export declare function findCatalogEntry(catalogs: readonly EventCatalog[], type: string): {
19
+ catalog: EventCatalog;
20
+ key: string;
21
+ entry: CatalogEntry;
22
+ } | undefined;
17
23
  export declare function validateEventInput(catalogs: readonly EventCatalog[], input: EventInput): Effect.Effect<EventInput, InvalidEventError>;
24
+ /**
25
+ * Synchronous `validateEventInput`. Throws `InvalidEventError` for a rejected payload, and
26
+ * throws when a catalog schema validates asynchronously.
27
+ */
28
+ export declare function validateEventInputSync(catalogs: readonly EventCatalog[], input: EventInput): EventInput;
18
29
  export declare function validateEventsEffect(catalogs: readonly EventCatalog[], events: readonly EventInput[]): Effect.Effect<EventInput[], InvalidEventError>;
19
30
  export {};
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Predicate, Schema } from 'effect';
2
- import { validateInputEffect } from './schema.js';
2
+ import { InvalidInputError, validateInputEffect, validateInputSync, } from './schema.js';
3
3
  import { cleanUndefined } from './types.js';
4
4
  export class InvalidEventError extends Data.TaggedError('InvalidEventError') {
5
5
  type;
@@ -11,7 +11,8 @@ export class InvalidEventError extends Data.TaggedError('InvalidEventError') {
11
11
  this.issues = issues;
12
12
  }
13
13
  }
14
- function findCatalogAndEntry(catalogs, type) {
14
+ /** Locate a catalog entry for a fully-qualified event type across the given catalogs. */
15
+ export function findCatalogEntry(catalogs, type) {
15
16
  for (const catalog of catalogs) {
16
17
  const prefix = `${catalog.namespace}.`;
17
18
  if (type.startsWith(prefix)) {
@@ -31,21 +32,43 @@ function isStandardSchema(entry) {
31
32
  function isEffectSchema(entry) {
32
33
  return Schema.isSchema(entry);
33
34
  }
35
+ /** The runtime schema behind a catalog entry. `payload<T>()` entries have none. */
36
+ function schemaOf(entry) {
37
+ return isEffectSchema(entry) || isStandardSchema(entry) ? entry : undefined;
38
+ }
39
+ function invalidEvent(type, err) {
40
+ return new InvalidEventError(type, `Invalid payload for event "${type}": ${err.message}`, err.issues);
41
+ }
34
42
  export function validateEventInput(catalogs, input) {
35
- const match = findCatalogAndEntry(catalogs, input.type);
43
+ const match = findCatalogEntry(catalogs, input.type);
36
44
  if (!match) {
37
45
  return Effect.succeed(input);
38
46
  }
39
- const cleanedPayload = cleanUndefined(input.payload);
40
- const validated = isEffectSchema(match.entry)
41
- ? validateInputEffect(match.entry, cleanedPayload)
42
- : isStandardSchema(match.entry)
43
- ? validateInputEffect(match.entry, cleanedPayload)
44
- : Effect.succeed(cleanedPayload);
45
- return validated.pipe(Effect.map((validatedPayload) => ({
47
+ return validateInputEffect(schemaOf(match.entry), cleanUndefined(input.payload)).pipe(Effect.map((validatedPayload) => ({
46
48
  ...input,
47
49
  payload: cleanUndefined(validatedPayload),
48
- })), Effect.mapError((err) => new InvalidEventError(input.type, `Invalid payload for event "${input.type}": ${err.message}`, err.issues)));
50
+ })), Effect.mapError((err) => invalidEvent(input.type, err)));
51
+ }
52
+ /**
53
+ * Synchronous `validateEventInput`. Throws `InvalidEventError` for a rejected payload, and
54
+ * throws when a catalog schema validates asynchronously.
55
+ */
56
+ export function validateEventInputSync(catalogs, input) {
57
+ const match = findCatalogEntry(catalogs, input.type);
58
+ if (!match) {
59
+ return input;
60
+ }
61
+ const schema = schemaOf(match.entry);
62
+ const payload = cleanUndefined(input.payload);
63
+ if (!schema) {
64
+ return { ...input, payload };
65
+ }
66
+ try {
67
+ return { ...input, payload: cleanUndefined(validateInputSync(schema, payload)) };
68
+ }
69
+ catch (err) {
70
+ throw err instanceof InvalidInputError ? invalidEvent(input.type, err) : err;
71
+ }
49
72
  }
50
73
  export function validateEventsEffect(catalogs, events) {
51
74
  return Effect.forEach(events, (event) => validateEventInput(catalogs, event));