@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
@@ -1,6 +1,6 @@
1
1
  import { Schema } from 'effect';
2
- import { type DefinitionInput, type DefinitionRef, type EventEnvelope, type EventInput, type JsonValue, type RunAttributes, type RunState, type SecretContext, type SubscriptionTransport, type TraceContext, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerSecretsResult } from '@swirls/looms/core';
3
- export interface LoomsClientOptions {
2
+ import { type DefinitionInput, type DefinitionRef, type EventEnvelope, type EventInput, type HasRequiredAttributes, type JsonValue, type RunAttributeFields, type RunAttributesOption, type RunState, type SecretContext, type SubscriptionTransport, type TraceContext, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerSecretsResult } from '@swirls/looms/core';
3
+ export interface LoomsClientOptions<Fields extends RunAttributeFields = RunAttributeFields> {
4
4
  baseUrl?: string;
5
5
  fetch?: typeof fetch;
6
6
  workerCallbackToken?: string;
@@ -9,7 +9,20 @@ export interface LoomsClientOptions {
9
9
  * grant cannot authorize other requests, so it is not sent on them.
10
10
  */
11
11
  grant?: string;
12
+ /** Declared run attributes, from `defineRunAttributes`. Types `attributes` on starts. */
13
+ attributes?: Fields;
12
14
  }
15
+ type ClientStartArgs<Fields extends RunAttributeFields> = {
16
+ kind: string;
17
+ definitionName: string;
18
+ definitionVersion?: string;
19
+ input?: JsonValue;
20
+ runId?: string;
21
+ /** Sent as the W3C `traceparent` and `tracestate` headers. */
22
+ trace?: TraceContext;
23
+ } & RunAttributesOption<Fields>;
24
+ /** `stream`'s arguments after the definition. Options are required when an attribute is. */
25
+ export type ClientStreamArgs<TDef extends DefinitionRef, Fields extends RunAttributeFields = RunAttributeFields> = HasRequiredAttributes<Fields> extends true ? [input: DefinitionInput<TDef> | undefined, options: RunAttributesOption<Fields>] : [input?: DefinitionInput<TDef>, options?: RunAttributesOption<Fields>];
13
26
  export interface StartResult {
14
27
  runId: string;
15
28
  threadId: string;
@@ -18,18 +31,10 @@ export interface StartResult {
18
31
  export interface StreamHandle extends AsyncIterable<EventEnvelope> {
19
32
  readonly runId: string;
20
33
  }
21
- export declare function createLoomsClient(options?: LoomsClientOptions): {
34
+ export declare function createLoomsClient<const Fields extends RunAttributeFields = RunAttributeFields>(options?: LoomsClientOptions<Fields>): {
22
35
  /** Start a run by `{ kind, definitionName }` when you only have names. */
23
- startRun: (args: {
24
- kind: string;
25
- definitionName: string;
26
- definitionVersion?: string;
27
- input?: JsonValue;
28
- runId?: string;
29
- attributes?: RunAttributes;
36
+ startRun: (args: ClientStartArgs<Fields> & {
30
37
  secrets?: SecretContext;
31
- /** Sent as the W3C `traceparent` and `tracestate` headers. */
32
- trace?: TraceContext;
33
38
  }) => Promise<{
34
39
  readonly runId: string;
35
40
  readonly threadId: string;
@@ -906,6 +911,178 @@ export declare function createLoomsClient(options?: LoomsClientOptions): {
906
911
  readonly childCloseSent: boolean;
907
912
  };
908
913
  }>;
914
+ sendSignal: (runId: string, namespace: string, name: string, body?: {
915
+ input?: JsonValue;
916
+ threadId?: string;
917
+ idempotencyKey?: string;
918
+ }) => Promise<{
919
+ readonly runId: string;
920
+ readonly state: {
921
+ readonly runId: string;
922
+ readonly status: "cancelled" | "completed" | "failed" | "running";
923
+ readonly rootThreadId: string | null;
924
+ readonly startIdentity: {
925
+ readonly kind: string;
926
+ readonly definitionName: string;
927
+ readonly definitionVersion: string;
928
+ readonly input: Schema.Json;
929
+ readonly requestedThreadId: string | null;
930
+ readonly idempotencyKey: string | null;
931
+ readonly rootThreadId: string;
932
+ readonly launchedBy: {
933
+ readonly runId: string;
934
+ readonly threadId: string;
935
+ readonly effectId: string;
936
+ readonly causationId: string;
937
+ readonly causationSeq: number;
938
+ } | null;
939
+ readonly correlationId: string | null;
940
+ readonly attributes: {
941
+ readonly [x: string]: string;
942
+ };
943
+ readonly trace: {
944
+ readonly traceparent: string;
945
+ readonly tracestate?: string | undefined;
946
+ } | null;
947
+ } | null;
948
+ readonly attributes: {
949
+ readonly [x: string]: string;
950
+ };
951
+ readonly forkedFrom: {
952
+ readonly runId: string;
953
+ readonly seq: number;
954
+ } | null;
955
+ readonly threads: {
956
+ readonly [x: string]: {
957
+ readonly threadId: string;
958
+ readonly kind: string;
959
+ readonly definitionName: string;
960
+ readonly definitionVersion: string;
961
+ readonly parentThreadId: string | null;
962
+ readonly status: "cancelled" | "completed" | "failed" | "running" | "waiting";
963
+ readonly input: Schema.Json;
964
+ readonly output: Schema.Json;
965
+ readonly error: string | null;
966
+ readonly state: Schema.Json;
967
+ };
968
+ };
969
+ readonly waits: {
970
+ readonly [x: string]: {
971
+ readonly waitId: string;
972
+ readonly threadId: string;
973
+ readonly on: {
974
+ readonly type: string | readonly string[];
975
+ readonly match?: Schema.Json | undefined;
976
+ } | {
977
+ readonly timerAt: number;
978
+ };
979
+ readonly tag?: Schema.Json | undefined;
980
+ };
981
+ };
982
+ readonly outstandingEffects: readonly {
983
+ readonly effectId: string;
984
+ readonly threadId: string;
985
+ readonly causingSeq: number;
986
+ readonly causingEventId: string;
987
+ readonly effect: {
988
+ readonly type: "runtime.spawn";
989
+ readonly childThreadId: string;
990
+ readonly kind: string;
991
+ readonly definitionName: string;
992
+ readonly definitionVersion: string;
993
+ readonly input: Schema.Json;
994
+ } | {
995
+ readonly type: "runtime.wait";
996
+ readonly waitId: string;
997
+ readonly on: {
998
+ readonly type: string | readonly string[];
999
+ readonly match?: Schema.Json | undefined;
1000
+ } | {
1001
+ readonly timerAt: number;
1002
+ };
1003
+ readonly tag?: Schema.Json | undefined;
1004
+ } | {
1005
+ readonly type: "runtime.emit";
1006
+ readonly event: {
1007
+ readonly type: string;
1008
+ readonly payload: Schema.Json;
1009
+ readonly threadId?: string | null | undefined;
1010
+ readonly parentThreadId?: string | null | undefined;
1011
+ readonly causationId?: string | null | undefined;
1012
+ readonly correlationId?: string | null | undefined;
1013
+ readonly effectId?: string | null | undefined;
1014
+ readonly origin?: {
1015
+ readonly type: "thread";
1016
+ readonly threadId: string;
1017
+ } | {
1018
+ readonly type: "external";
1019
+ readonly actorId?: string | undefined;
1020
+ } | {
1021
+ readonly type: "system";
1022
+ } | {
1023
+ readonly type: "run";
1024
+ readonly runId: string;
1025
+ } | undefined;
1026
+ readonly ephemeral?: boolean | undefined;
1027
+ readonly id?: string | undefined;
1028
+ readonly ts?: number | undefined;
1029
+ readonly idempotencyKey?: string | null | undefined;
1030
+ };
1031
+ readonly tag?: string | undefined;
1032
+ } | {
1033
+ readonly type: "runtime.complete";
1034
+ readonly output: Schema.Json;
1035
+ } | {
1036
+ readonly type: "runtime.fail";
1037
+ readonly error: string;
1038
+ } | {
1039
+ readonly type: "runtime.cancel";
1040
+ readonly threadId: string;
1041
+ readonly tag?: string | undefined;
1042
+ } | {
1043
+ readonly type: "runtime.launch";
1044
+ readonly runId: string;
1045
+ readonly kind: string;
1046
+ readonly definitionName: string;
1047
+ readonly definitionVersion: string;
1048
+ readonly input: Schema.Json;
1049
+ readonly close: "terminate" | "wait";
1050
+ readonly tag?: string | undefined;
1051
+ } | {
1052
+ readonly type: "runtime.cancelRun";
1053
+ readonly runId: string;
1054
+ readonly tag?: string | undefined;
1055
+ } | {
1056
+ readonly type: string;
1057
+ readonly input: Schema.Json;
1058
+ readonly tag?: string | undefined;
1059
+ readonly at?: number | undefined;
1060
+ };
1061
+ }[];
1062
+ readonly effectExecutions: {
1063
+ readonly [x: string]: {
1064
+ readonly effectId: string;
1065
+ readonly attempt: number;
1066
+ readonly status: "ambiguous" | "cancel_requested" | "dispatch_wait" | "dispatched" | "heartbeat" | "queued" | "retry_wait" | "running" | "started" | "timed_out";
1067
+ readonly nextAttemptAt: number | null;
1068
+ readonly deadlineAt: number | null;
1069
+ readonly startedAt: number | null;
1070
+ readonly lastHeartbeatAt: number | null;
1071
+ readonly heartbeatDetails: Schema.Json;
1072
+ readonly lastError: string | null;
1073
+ readonly dispatchTry: number;
1074
+ };
1075
+ };
1076
+ readonly completedEffectIds: readonly string[];
1077
+ readonly processedIdempotencyKeys: readonly string[];
1078
+ readonly launchedRuns: readonly {
1079
+ readonly runId: string;
1080
+ readonly close: "terminate" | "wait";
1081
+ }[];
1082
+ readonly closeWaiting: boolean;
1083
+ readonly childCloseSent: boolean;
1084
+ };
1085
+ }>;
909
1086
  wake: (runId: string) => Promise<{
910
1087
  readonly runId: string;
911
1088
  readonly state: {
@@ -1438,6 +1615,11 @@ export declare function createLoomsClient(options?: LoomsClientOptions): {
1438
1615
  readonly inputSchema?: Schema.Json | undefined;
1439
1616
  }[];
1440
1617
  readonly projections: readonly string[];
1618
+ readonly modules: readonly {
1619
+ readonly namespace: string;
1620
+ readonly protocolVersion: string;
1621
+ readonly description?: string | undefined;
1622
+ }[];
1441
1623
  }>;
1442
1624
  listEffects: () => Promise<{
1443
1625
  readonly effects: readonly {
@@ -1457,6 +1639,40 @@ export declare function createLoomsClient(options?: LoomsClientOptions): {
1457
1639
  readonly inputSchema?: Schema.Json | undefined;
1458
1640
  }[];
1459
1641
  }>;
1642
+ listSignals: () => Promise<{
1643
+ readonly signals: readonly {
1644
+ readonly namespace: string;
1645
+ readonly name: string;
1646
+ readonly description?: string | undefined;
1647
+ readonly inputSchema?: Schema.Json | undefined;
1648
+ }[];
1649
+ }>;
1650
+ listEvents: () => Promise<{
1651
+ readonly events: readonly {
1652
+ readonly type: string;
1653
+ readonly namespace: string;
1654
+ readonly payloadSchema?: Schema.Json | undefined;
1655
+ }[];
1656
+ }>;
1657
+ previewSignal: (namespace: string, name: string, body?: {
1658
+ input?: JsonValue;
1659
+ threadId?: string;
1660
+ }) => Promise<{
1661
+ readonly events: readonly {
1662
+ readonly type: string;
1663
+ readonly payload: Schema.Json;
1664
+ readonly threadId?: string | null | undefined;
1665
+ readonly idempotencyKey?: string | null | undefined;
1666
+ }[];
1667
+ }>;
1668
+ previewEvents: (events: ReadonlyArray<EventInput>) => Promise<{
1669
+ readonly events: readonly {
1670
+ readonly type: string;
1671
+ readonly payload: Schema.Json;
1672
+ readonly threadId?: string | null | undefined;
1673
+ readonly idempotencyKey?: string | null | undefined;
1674
+ }[];
1675
+ }>;
1460
1676
  replayTo: (runId: string, seq: number) => Promise<{
1461
1677
  readonly runId: string;
1462
1678
  readonly step: {
@@ -1904,15 +2120,8 @@ export declare function createLoomsClient(options?: LoomsClientOptions): {
1904
2120
  * Subscribe to the run log, then start execution so deltas arrive live.
1905
2121
  * Yields events in store order, including live module events such as `agent.turn.text_delta`.
1906
2122
  */
1907
- streamRun: (args: {
1908
- kind: string;
1909
- definitionName: string;
1910
- definitionVersion?: string;
1911
- input?: JsonValue;
1912
- runId?: string;
1913
- trace?: TraceContext;
1914
- }) => StreamHandle;
1915
- stream: <TDef extends DefinitionRef>(definition: TDef, input?: DefinitionInput<TDef>) => StreamHandle;
2123
+ streamRun: (args: ClientStartArgs<Fields>) => StreamHandle;
2124
+ stream: <TDef extends DefinitionRef>(definition: TDef, ...[input, streamOptions]: ClientStreamArgs<TDef, Fields>) => StreamHandle;
1916
2125
  };
1917
2126
  export type LoomsClient = ReturnType<typeof createLoomsClient>;
1918
2127
  export interface SubscribeEventsOptions {
@@ -1933,3 +2142,4 @@ export interface SubscriptionSocketConstructor {
1933
2142
  }
1934
2143
  /** Resolve a possibly-relative HTTP base so `new URL(path, base)` never throws on `''` or `/app`. */
1935
2144
  export declare function absoluteHttpBase(baseUrl: string): string;
2145
+ export {};
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Option, Predicate, Schema, Stream } from 'effect';
2
- import { createRunId, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
2
+ import { createRunId, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, EventTypeCatalogSchema, JsonValueSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, SignalCatalogSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
3
3
  import { consumeSseStreamEffect, eventsFromSseData, sseFrames } from './sse.js';
4
4
  class LoomsClientError extends Data.TaggedError('LoomsClientError') {
5
5
  constructor(message, cause) {
@@ -73,6 +73,15 @@ const ProjectionResultSchema = Schema.Struct({
73
73
  name: Schema.String,
74
74
  value: Schema.Unknown,
75
75
  });
76
+ const PreviewEventSchema = Schema.Struct({
77
+ type: Schema.String,
78
+ payload: JsonValueSchema,
79
+ threadId: Schema.optional(Schema.NullOr(Schema.String)),
80
+ idempotencyKey: Schema.optional(Schema.NullOr(Schema.String)),
81
+ });
82
+ const PreviewEventsResultSchema = Schema.Struct({
83
+ events: Schema.Array(PreviewEventSchema),
84
+ });
76
85
  export function createLoomsClient(options = {}) {
77
86
  const baseUrl = (options.baseUrl ?? '').replace(/\/$/, '');
78
87
  const fetchImpl = options.fetch ?? fetch;
@@ -239,6 +248,7 @@ export function createLoomsClient(options = {}) {
239
248
  method: 'POST',
240
249
  body: stringifyJson({ events }),
241
250
  }),
251
+ sendSignal: (runId, namespace, name, body = {}) => request(`/runs/${encodeURIComponent(runId)}/signals/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}`, RunResultSchema, { method: 'POST', body: stringifyJson(body) }),
242
252
  wake: (runId) => request(`/runs/${encodeURIComponent(runId)}/wake`, WakeResultSchema, { method: 'POST' }),
243
253
  /** Cancel a thread and its descendants; omit `threadId` to cancel the whole run. */
244
254
  cancel: (runId, threadId) => request(`/runs/${encodeURIComponent(runId)}/cancel`, RunResultSchema, {
@@ -255,6 +265,13 @@ export function createLoomsClient(options = {}) {
255
265
  listRunSummaries: () => request('/runs/summaries', RunSummariesSchema),
256
266
  listDefinitions: () => request('/definitions', DefinitionCatalogSchema),
257
267
  listEffects: () => request('/definitions/effects', EffectCatalogSchema),
268
+ listSignals: () => request('/definitions/signals', SignalCatalogSchema),
269
+ listEvents: () => request('/definitions/events', EventTypeCatalogSchema),
270
+ previewSignal: (namespace, name, body = {}) => request(`/definitions/signals/${encodeURIComponent(namespace)}/${encodeURIComponent(name)}/preview`, PreviewEventsResultSchema, { method: 'POST', body: stringifyJson(body) }),
271
+ previewEvents: (events) => request('/definitions/events/preview', PreviewEventsResultSchema, {
272
+ method: 'POST',
273
+ body: stringifyJson({ events }),
274
+ }),
258
275
  replayTo: (runId, seq) => request(`/runs/${encodeURIComponent(runId)}/replay?seq=${seq}`, ReplayResultSchema),
259
276
  project: (runId, name) => request(`/runs/${encodeURIComponent(runId)}/projections/${encodeURIComponent(name)}`, ProjectionResultSchema),
260
277
  subscribeEvents,
@@ -263,7 +280,8 @@ export function createLoomsClient(options = {}) {
263
280
  * Yields events in store order, including live module events such as `agent.turn.text_delta`.
264
281
  */
265
282
  streamRun,
266
- stream: (definition, input) => streamRun({
283
+ stream: (definition, ...[input, streamOptions]) => streamRun({
284
+ ...streamOptions,
267
285
  kind: definition.kind,
268
286
  definitionName: definition.name,
269
287
  definitionVersion: definition.version,
@@ -0,0 +1,39 @@
1
+ import { type RunState } from '@swirls/looms/core';
2
+ import type { DurableObjectEventStore } from './event-store';
3
+ export interface DeleteTerminalRunStorageOptions {
4
+ /**
5
+ * Projector identities (`name@version`) that must have delivered through the
6
+ * log tail before storage is removed. The store must have projectors attached.
7
+ */
8
+ readonly requireProjectors?: readonly string[];
9
+ }
10
+ declare const RunNotTerminalError_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 & {
11
+ readonly _tag: "RunNotTerminalError";
12
+ } & Readonly<A>;
13
+ export declare class RunNotTerminalError extends RunNotTerminalError_base<{
14
+ readonly runId: string;
15
+ readonly status: string;
16
+ }> {
17
+ }
18
+ declare const ProjectorCoverageError_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 & {
19
+ readonly _tag: "ProjectorCoverageError";
20
+ } & Readonly<A>;
21
+ export declare class ProjectorCoverageError extends ProjectorCoverageError_base<{
22
+ readonly runId: string;
23
+ readonly message: string;
24
+ }> {
25
+ }
26
+ export interface TerminalRunStorageHost {
27
+ readonly deleteAll?: () => Promise<void>;
28
+ readonly deleteAlarm?: () => Promise<void>;
29
+ readonly sql: {
30
+ exec(query: string, ...bindings: readonly unknown[]): Iterable<unknown>;
31
+ };
32
+ }
33
+ /**
34
+ * Deletes this Durable Object's embedded SQLite once the run is terminal and
35
+ * optional projector checkpoints cover the log tail. One run owns the object, so
36
+ * {@link TerminalRunStorageHost.deleteAll} removes the actor copy.
37
+ */
38
+ export declare function deleteTerminalRunStorage(storage: TerminalRunStorageHost, store: DurableObjectEventStore, runId: string, state: RunState, options?: DeleteTerminalRunStorageOptions): Promise<void>;
39
+ export {};
@@ -0,0 +1,98 @@
1
+ import { Data, Effect } from 'effect';
2
+ import { isRunTerminal } from '@swirls/looms/core';
3
+ export class RunNotTerminalError extends Data.TaggedError('RunNotTerminalError') {
4
+ }
5
+ export class ProjectorCoverageError extends Data.TaggedError('ProjectorCoverageError') {
6
+ }
7
+ function parseProjectorIdentity(runId, identity) {
8
+ const at = identity.indexOf('@');
9
+ if (at <= 0 || at === identity.length - 1) {
10
+ return Effect.fail(new ProjectorCoverageError({
11
+ runId,
12
+ message: `Invalid projector identity "${identity}"; expected name@version`,
13
+ }));
14
+ }
15
+ return Effect.succeed({ name: identity.slice(0, at), version: identity.slice(at + 1) });
16
+ }
17
+ function assertProjectorCoverage(store, delivery, runId, requireProjectors) {
18
+ const boundsOf = store.bounds;
19
+ if (!boundsOf) {
20
+ return Effect.fail(new ProjectorCoverageError({
21
+ runId,
22
+ message: 'Event store has no bounds(); cannot verify projector coverage',
23
+ }));
24
+ }
25
+ return Effect.gen(function* () {
26
+ const bounds = yield* boundsOf(runId).pipe(Effect.mapError((cause) => new ProjectorCoverageError({
27
+ runId,
28
+ message: cause.message,
29
+ })));
30
+ const statuses = yield* delivery.status(runId).pipe(Effect.mapError((cause) => new ProjectorCoverageError({
31
+ runId,
32
+ message: cause.message,
33
+ })));
34
+ yield* Effect.forEach(requireProjectors, (identity) => Effect.gen(function* () {
35
+ const { name, version } = yield* parseProjectorIdentity(runId, identity);
36
+ const row = statuses.find((entry) => entry.projector === name && entry.version === version);
37
+ const cursor = row?.cursor ?? null;
38
+ if (cursor === null || cursor < bounds.tail) {
39
+ return yield* new ProjectorCoverageError({
40
+ runId,
41
+ message: `Projector "${identity}" cursor ${cursor ?? 'missing'} is before log tail ${bounds.tail}`,
42
+ });
43
+ }
44
+ return undefined;
45
+ }), { concurrency: 'unbounded' });
46
+ });
47
+ }
48
+ function wipeStorage(storage, runId, delivery) {
49
+ const deleteAll = storage.deleteAll;
50
+ if (deleteAll) {
51
+ return Effect.promise(() => deleteAll());
52
+ }
53
+ return Effect.sync(() => {
54
+ const tables = [
55
+ 'looms_events',
56
+ 'looms_snapshots',
57
+ 'looms_commands',
58
+ 'looms_run_secrets',
59
+ 'looms_run_headers',
60
+ 'looms_streams',
61
+ ];
62
+ if (delivery) {
63
+ tables.unshift('looms_projector_delivery');
64
+ }
65
+ for (const table of tables) {
66
+ void [...storage.sql.exec(`DELETE FROM ${table} WHERE run_id = ?`, runId)];
67
+ }
68
+ });
69
+ }
70
+ /**
71
+ * Deletes this Durable Object's embedded SQLite once the run is terminal and
72
+ * optional projector checkpoints cover the log tail. One run owns the object, so
73
+ * {@link TerminalRunStorageHost.deleteAll} removes the actor copy.
74
+ */
75
+ export function deleteTerminalRunStorage(storage, store, runId, state, options = {}) {
76
+ const delivery = store.projectorDelivery;
77
+ return Effect.runPromise(Effect.gen(function* () {
78
+ if (!isRunTerminal(state)) {
79
+ return yield* new RunNotTerminalError({ runId, status: state.status });
80
+ }
81
+ const required = options.requireProjectors ?? [];
82
+ if (required.length > 0) {
83
+ if (!delivery) {
84
+ return yield* new ProjectorCoverageError({
85
+ runId,
86
+ message: 'requireProjectors needs an event store with projectors attached',
87
+ });
88
+ }
89
+ yield* assertProjectorCoverage(store, delivery, runId, required);
90
+ }
91
+ yield* wipeStorage(storage, runId, delivery);
92
+ const deleteAlarm = storage.deleteAlarm;
93
+ if (deleteAlarm) {
94
+ yield* Effect.promise(() => deleteAlarm());
95
+ }
96
+ return undefined;
97
+ }));
98
+ }
@@ -1,11 +1,14 @@
1
1
  import { DurableObject } from 'cloudflare:workers';
2
- import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type BlobStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunLauncher, type RunState, type RunStatusSnapshot } from '@swirls/looms/core';
2
+ import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type BlobStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot } from '@swirls/looms/core';
3
3
  import type { Projector } from '@swirls/looms/projectors';
4
4
  import { type Authorize, type EffectWorker, type StartResult, type StartRunArgs } from '@swirls/looms/runtime';
5
+ import { type DeleteTerminalRunStorageOptions } from './delete-terminal-run-storage';
5
6
  export interface LoomsDurableObjectConfig {
6
7
  readonly modules: readonly AnyRuntimeModule[];
7
8
  /** Loads definitions that were not registered on a module. See `CreateRuntimeOptions`. */
8
9
  readonly definitionResolver?: DefinitionResolver;
10
+ /** Declared run attributes. Pass the same declaration to the replica. */
11
+ readonly attributes?: RunAttributeFields;
9
12
  readonly projectors?: readonly Projector[];
10
13
  /** Content-addressed store for event and snapshot JSON over the inline byte limits. */
11
14
  readonly blobs?: BlobStore;
@@ -62,6 +65,12 @@ export declare abstract class LoomsDurableObject<Env = unknown> extends DurableO
62
65
  }): Promise<RunState>;
63
66
  cancel(): Promise<void>;
64
67
  getRun(): Promise<RunState>;
68
+ /**
69
+ * Wipes this object's SQLite once the run is terminal and optional projector
70
+ * checkpoints cover the log tail. Clears the cached cell so the next request
71
+ * rebuilds an empty store.
72
+ */
73
+ deleteTerminalRunStorage(options?: DeleteTerminalRunStorageOptions): Promise<void>;
65
74
  /** A rejected alarm is retried by the platform with backoff, so failures just propagate. */
66
75
  alarm(): Promise<void>;
67
76
  }
@@ -80,6 +89,7 @@ export interface DurableObjectRunStub {
80
89
  }): Promise<RunState>;
81
90
  cancel(): Promise<void>;
82
91
  getRun(): Promise<RunState>;
92
+ deleteTerminalRunStorage?(options?: DeleteTerminalRunStorageOptions): Promise<void>;
83
93
  }
84
94
  /**
85
95
  * Launches and reads runs in other Durable Objects. One object per `runId`.
@@ -4,6 +4,7 @@ import { createActorCell } from '@swirls/looms/actor';
4
4
  import { createRemoteRunLauncher, } from '@swirls/looms/core';
5
5
  import { defaultAuthorize, } from '@swirls/looms/runtime';
6
6
  import { durableObjectAlarms } from './alarm-scheduler.js';
7
+ import { deleteTerminalRunStorage, } from './delete-terminal-run-storage.js';
7
8
  import { durableObjectEventStore } from './event-store.js';
8
9
  import { attachSocketFanout, isRunSocketUpgrade, openRunSocket } from './websocket.js';
9
10
  /**
@@ -50,6 +51,7 @@ export class LoomsDurableObject extends DurableObject {
50
51
  scheduler: alarms.scheduler,
51
52
  modules: config.modules,
52
53
  definitionResolver: config.definitionResolver,
54
+ attributes: config.attributes,
53
55
  snapshotEvery: config.snapshotEvery,
54
56
  maxWakeIterations: config.maxWakeIterations,
55
57
  maxPendingRunOperations: config.maxPendingRunOperations,
@@ -118,6 +120,27 @@ export class LoomsDurableObject extends DurableObject {
118
120
  getRun() {
119
121
  return this.getCell().then((cell) => cell.getRun());
120
122
  }
123
+ /**
124
+ * Wipes this object's SQLite once the run is terminal and optional projector
125
+ * checkpoints cover the log tail. Clears the cached cell so the next request
126
+ * rebuilds an empty store.
127
+ */
128
+ deleteTerminalRunStorage(options = {}) {
129
+ return this.getCell().then((cell) => {
130
+ const runId = this.ctx.id.name;
131
+ if (!runId) {
132
+ throw new Error('LoomsDurableObject requires a named Durable Object id (use idFromName / getByName)');
133
+ }
134
+ const store = this.store;
135
+ if (!store) {
136
+ throw new Error('Run storage is not ready');
137
+ }
138
+ return cell.getRun().then((state) => deleteTerminalRunStorage(this.ctx.storage, store, runId, state, options).then(() => {
139
+ this.cellPromise = undefined;
140
+ this.store = undefined;
141
+ }));
142
+ });
143
+ }
121
144
  /** A rejected alarm is retried by the platform with backoff, so failures just propagate. */
122
145
  alarm() {
123
146
  return this.getCell()
@@ -1,4 +1,5 @@
1
1
  export { durableObjectAlarms, type AlarmStorage, type DurableObjectAlarms } from './alarm-scheduler';
2
+ export { deleteTerminalRunStorage, ProjectorCoverageError, RunNotTerminalError, type DeleteTerminalRunStorageOptions, type TerminalRunStorageHost, } from './delete-terminal-run-storage';
2
3
  export { durableObjectEventStore, type DurableObjectEventStore, type DurableObjectStoreOptions, } from './event-store';
3
4
  export { durableObjectLauncher, durableObjectScheduleHost, LoomsDurableObject, type DurableObjectRunStub, type LoomsDurableObjectConfig, } from './durable-object';
4
5
  export { r2BlobStore, type R2BucketLike, type R2ListResult, type R2ObjectBodyLike, type R2StoredObject, } from './r2-blob-store';
@@ -1,4 +1,5 @@
1
1
  export { durableObjectAlarms } from './alarm-scheduler.js';
2
+ export { deleteTerminalRunStorage, ProjectorCoverageError, RunNotTerminalError, } from './delete-terminal-run-storage.js';
2
3
  export { durableObjectEventStore, } from './event-store.js';
3
4
  export { durableObjectLauncher, durableObjectScheduleHost, LoomsDurableObject, } from './durable-object.js';
4
5
  export { r2BlobStore, } from './r2-blob-store.js';
@@ -7,6 +7,7 @@ export * from './validate-event';
7
7
  export * from './envelope';
8
8
  export * from './catalog';
9
9
  export * from './effects';
10
+ export * from './signals';
10
11
  export * from './protocol';
11
12
  export * from './subscription';
12
13
  export * from './thread';
@@ -6,6 +6,7 @@ export * from './validate-event.js';
6
6
  export * from './envelope.js';
7
7
  export * from './catalog.js';
8
8
  export * from './effects.js';
9
+ export * from './signals.js';
9
10
  export * from './protocol.js';
10
11
  export * from './subscription.js';
11
12
  export * from './thread.js';