@swirls/looms 0.10.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 (45) hide show
  1. package/CHANGELOG.md +26 -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/agent/module.d.ts +512 -512
  7. package/dist/cli/commands.d.ts +1 -1
  8. package/dist/cli/commands.js +47 -12
  9. package/dist/client/client.d.ts +20 -21
  10. package/dist/client/client.js +2 -1
  11. package/dist/cloudflare/delete-terminal-run-storage.d.ts +39 -0
  12. package/dist/cloudflare/delete-terminal-run-storage.js +98 -0
  13. package/dist/cloudflare/durable-object.d.ts +11 -1
  14. package/dist/cloudflare/durable-object.js +23 -0
  15. package/dist/cloudflare/index.d.ts +1 -0
  16. package/dist/cloudflare/index.js +1 -0
  17. package/dist/core/run-context.d.ts +50 -0
  18. package/dist/core/run-context.js +21 -1
  19. package/dist/debugger/app/assets/{index-D-2Q7ecG.js → index-VTotlHcm.js} +2 -2
  20. package/dist/debugger/app/assets/{routes-lvmllT60.js → routes-CEdsN9DO.js} +2 -2
  21. package/dist/debugger/app/index.html +1 -1
  22. package/dist/projectors/event-log-ops.d.ts +0 -6
  23. package/dist/projectors/event-log-ops.js +2 -12
  24. package/dist/projectors/event-log.d.ts +10 -5
  25. package/dist/projectors/event-log.js +26 -22
  26. package/dist/projectors/replica/columns.d.ts +41 -0
  27. package/dist/projectors/replica/columns.js +77 -0
  28. package/dist/projectors/replica/drizzle.d.ts +328 -57
  29. package/dist/projectors/replica/drizzle.js +18 -14
  30. package/dist/projectors/replica/migrations.d.ts +25 -5
  31. package/dist/projectors/replica/migrations.js +62 -14
  32. package/dist/projectors/replica/postgres.d.ts +12 -11
  33. package/dist/projectors/replica/postgres.js +12 -26
  34. package/dist/projectors/replica/sqlite-bun.d.ts +3 -1
  35. package/dist/projectors/replica/sqlite-bun.js +6 -2
  36. package/dist/projectors/replica/sqlite-migrations.d.ts +5 -5
  37. package/dist/projectors/replica/sqlite-migrations.js +22 -9
  38. package/dist/projectors/replica/sqlite.d.ts +12 -11
  39. package/dist/projectors/replica/sqlite.js +23 -16
  40. package/dist/runtime/looms.d.ts +27 -36
  41. package/dist/runtime/looms.js +1 -0
  42. package/dist/runtime/runtime.js +7 -1
  43. package/dist/runtime/server/http.js +4 -2
  44. package/dist/runtime/types.d.ts +6 -1
  45. package/package.json +1 -1
@@ -6,7 +6,7 @@ export declare const looms: Command.Command<"looms", {
6
6
  readonly url: string;
7
7
  }, {
8
8
  readonly url: string;
9
- }, CliError.UserError, never>;
9
+ }, CliError.UserError, Path.Path>;
10
10
  export declare const cliTestLayer: Layer.Layer<ChildProcessSpawner.ChildProcessSpawner | FileSystem.FileSystem | Path.Path | Stdio.Stdio | Terminal.Terminal, never, never>;
11
11
  /** Run the CLI with an explicit argv (for tests and programmatic use). */
12
12
  export declare const runCli: (argv: ReadonlyArray<string>) => Effect.Effect<void, CliError.CliError, Command.Environment>;
@@ -4,9 +4,9 @@ import { ChildProcessSpawner } from 'effect/unstable/process';
4
4
  import { steer as steerEvent } from '@swirls/looms/agent';
5
5
  import { decision } from '@swirls/looms/approval';
6
6
  import { createLoomsClient } from '@swirls/looms/client';
7
- import { stringifyJson, stringifyJsonPretty } from '@swirls/looms/core';
7
+ import { stringifyJson, stringifyJsonPretty, } from '@swirls/looms/core';
8
8
  import { postgresReplica } from '@swirls/looms/projectors/replica';
9
- import { generateReplicaMigrations, } from '@swirls/looms/projectors/replica/migrations';
9
+ import { generateReplicaMigrations, postgresReplicaMigrations, } from '@swirls/looms/projectors/replica/migrations';
10
10
  import {} from '@swirls/looms/projectors/replica/sqlite';
11
11
  import { openSqliteReplicaFile } from '@swirls/looms/projectors/replica/sqlite-bun';
12
12
  import { createLooms } from '@swirls/looms/runtime';
@@ -122,6 +122,36 @@ const tail = Command.make('tail', {
122
122
  })).pipe(Command.withDescription('Stream events for a run'), Command.withShortDescription('Tail run events'));
123
123
  const databaseFlag = Flag.string('database').pipe(Flag.withDescription('Postgres connection string, or a SQLite file path with --dialect sqlite (env DATABASE_URL)'), Flag.withFallbackConfig(Config.string('DATABASE_URL')));
124
124
  const dialectFlag = Flag.string('dialect').pipe(Flag.withDescription('Replica dialect: postgres (default) or sqlite'), Flag.withDefault('postgres'));
125
+ const configFlag = Flag.optional(Flag.string('config').pipe(Flag.withDescription('Module that exports the run attributes from defineRunAttributes, as `attributes` or default')));
126
+ const RunAttributeFieldsSchema = Schema.Record(Schema.String, Schema.Struct({
127
+ required: Schema.optional(Schema.Boolean),
128
+ index: Schema.optional(Schema.Boolean),
129
+ fieldName: Schema.optional(Schema.String),
130
+ }));
131
+ function configError(cause, userMessage) {
132
+ return new CliError.UserError({ cause, userMessage });
133
+ }
134
+ function loadAttributes(config) {
135
+ if (Option.isNone(config)) {
136
+ return Effect.succeed({});
137
+ }
138
+ return Effect.gen(function* () {
139
+ const path = yield* Path.Path;
140
+ const url = yield* path
141
+ .toFileUrl(path.resolve(config.value))
142
+ .pipe(Effect.mapError((cause) => configError(cause, `Invalid --config ${config.value}`)));
143
+ const exported = yield* Effect.tryPromise({
144
+ try: () => import(url.href).then((module) => module),
145
+ catch: (cause) => configError(cause, `Could not load --config ${config.value}: ${String(cause)}`),
146
+ });
147
+ const attributes = yield* Schema.decodeUnknownEffect(RunAttributeFieldsSchema)(exported.attributes ?? exported.default).pipe(Effect.mapError((cause) => configError(cause, `--config ${config.value} must export defineRunAttributes(...) as \`attributes\` or default`)));
148
+ yield* Effect.try({
149
+ try: () => postgresReplicaMigrations(attributes),
150
+ catch: (cause) => configError(cause, cause instanceof Error ? cause.message : String(cause)),
151
+ });
152
+ return attributes;
153
+ });
154
+ }
125
155
  function asDialect(value) {
126
156
  switch (value) {
127
157
  case 'postgres':
@@ -131,9 +161,9 @@ function asDialect(value) {
131
161
  return undefined;
132
162
  }
133
163
  }
134
- function openReplica(dialect, database, migrate) {
164
+ function openReplica(dialect, database, migrate, additionalFields) {
135
165
  if (dialect === 'sqlite') {
136
- const replica = openSqliteReplicaFile(database, migrate);
166
+ const replica = openSqliteReplicaFile(database, migrate, additionalFields);
137
167
  return {
138
168
  pendingMigrations: () => replica.pendingMigrations(),
139
169
  migrate: () => replica.migrate(),
@@ -141,7 +171,7 @@ function openReplica(dialect, database, migrate) {
141
171
  dispose: () => replica.dispose?.() ?? Promise.resolve(),
142
172
  };
143
173
  }
144
- const replica = postgresReplica({ url: database, migrate });
174
+ const replica = postgresReplica({ url: database, migrate, additionalFields });
145
175
  return {
146
176
  pendingMigrations: () => replica.pendingMigrations(),
147
177
  migrate: () => replica.migrate(),
@@ -154,8 +184,10 @@ const generate = Command.make('generate', {
154
184
  dialect: dialectFlag,
155
185
  journal: Flag.optional(Flag.string('journal').pipe(Flag.withDescription('Also update a migration journal. Only `drizzle` is supported, and only for Postgres'))),
156
186
  check: Flag.boolean('check').pipe(Flag.withDescription('Exit non-zero when a migration is pending, and write nothing'), Flag.withDefault(false)),
157
- }, Effect.fn('replica.generate')(function* ({ out, dialect, journal, check }) {
187
+ config: configFlag,
188
+ }, Effect.fn('replica.generate')(function* ({ out, dialect, journal, check, config }) {
158
189
  const parsed = asDialect(dialect);
190
+ const additionalFields = yield* loadAttributes(config);
159
191
  if (!parsed) {
160
192
  return yield* new CliError.UserError({
161
193
  cause: dialect,
@@ -175,8 +207,8 @@ const generate = Command.make('generate', {
175
207
  });
176
208
  }
177
209
  const generateOptions = Option.isSome(journal)
178
- ? { out, check, dialect: parsed, journal: 'drizzle' }
179
- : { out, check, dialect: parsed };
210
+ ? { out, check, dialect: parsed, additionalFields, journal: 'drizzle' }
211
+ : { out, check, dialect: parsed, additionalFields };
180
212
  const result = yield* tryClient(() => generateReplicaMigrations(generateOptions));
181
213
  if (check && result.pending.length > 0) {
182
214
  return yield* new CliError.UserError({
@@ -192,8 +224,9 @@ const generate = Command.make('generate', {
192
224
  }
193
225
  return yield* Effect.void;
194
226
  })).pipe(Command.withDescription('Write replica migrations the host does not already have'), Command.withShortDescription('Write replica SQL'));
195
- const migrate = Command.make('migrate', { database: databaseFlag, dialect: dialectFlag }, Effect.fn('replica.migrate')(function* ({ database, dialect }) {
227
+ const migrate = Command.make('migrate', { database: databaseFlag, dialect: dialectFlag, config: configFlag }, Effect.fn('replica.migrate')(function* ({ database, dialect, config }) {
196
228
  const parsed = asDialect(dialect);
229
+ const additionalFields = yield* loadAttributes(config);
197
230
  if (!parsed) {
198
231
  return yield* new CliError.UserError({
199
232
  cause: dialect,
@@ -206,7 +239,7 @@ const migrate = Command.make('migrate', { database: databaseFlag, dialect: diale
206
239
  userMessage: 'SQLite replica --database is a file path, not a Postgres URL.',
207
240
  });
208
241
  }
209
- const replica = openReplica(parsed, database, 'auto');
242
+ const replica = openReplica(parsed, database, 'auto', additionalFields);
210
243
  yield* tryClient(() => replica.migrate().then(() => replica.dispose()));
211
244
  return yield* Console.log('Looms replica migrations applied');
212
245
  })).pipe(Command.withDescription('Apply pending replica migrations'), Command.withShortDescription('Apply replica SQL'));
@@ -214,8 +247,10 @@ const status = Command.make('status', {
214
247
  database: databaseFlag,
215
248
  dialect: dialectFlag,
216
249
  run: Flag.optional(Flag.string('run').pipe(Flag.withDescription('Also print freshness for this run id'))),
217
- }, Effect.fn('replica.status')(function* ({ database, dialect, run }) {
250
+ config: configFlag,
251
+ }, Effect.fn('replica.status')(function* ({ database, dialect, run, config }) {
218
252
  const parsed = asDialect(dialect);
253
+ const additionalFields = yield* loadAttributes(config);
219
254
  if (!parsed) {
220
255
  return yield* new CliError.UserError({
221
256
  cause: dialect,
@@ -228,7 +263,7 @@ const status = Command.make('status', {
228
263
  userMessage: 'SQLite replica --database is a file path, not a Postgres URL.',
229
264
  });
230
265
  }
231
- const replica = openReplica(parsed, database, 'verify');
266
+ const replica = openReplica(parsed, database, 'verify', additionalFields);
232
267
  const pending = yield* tryClient(() => replica.pendingMigrations());
233
268
  yield* Console.log(pending.length === 0
234
269
  ? 'Looms replica schema is up to date'
@@ -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;
@@ -2115,15 +2120,8 @@ export declare function createLoomsClient(options?: LoomsClientOptions): {
2115
2120
  * Subscribe to the run log, then start execution so deltas arrive live.
2116
2121
  * Yields events in store order, including live module events such as `agent.turn.text_delta`.
2117
2122
  */
2118
- streamRun: (args: {
2119
- kind: string;
2120
- definitionName: string;
2121
- definitionVersion?: string;
2122
- input?: JsonValue;
2123
- runId?: string;
2124
- trace?: TraceContext;
2125
- }) => StreamHandle;
2126
- 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;
2127
2125
  };
2128
2126
  export type LoomsClient = ReturnType<typeof createLoomsClient>;
2129
2127
  export interface SubscribeEventsOptions {
@@ -2144,3 +2142,4 @@ export interface SubscriptionSocketConstructor {
2144
2142
  }
2145
2143
  /** Resolve a possibly-relative HTTP base so `new URL(path, base)` never throws on `''` or `/app`. */
2146
2144
  export declare function absoluteHttpBase(baseUrl: string): string;
2145
+ export {};
@@ -280,7 +280,8 @@ export function createLoomsClient(options = {}) {
280
280
  * Yields events in store order, including live module events such as `agent.turn.text_delta`.
281
281
  */
282
282
  streamRun,
283
- stream: (definition, input) => streamRun({
283
+ stream: (definition, ...[input, streamOptions]) => streamRun({
284
+ ...streamOptions,
284
285
  kind: definition.kind,
285
286
  definitionName: definition.name,
286
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';
@@ -14,6 +14,55 @@ export type RunAttributes = {
14
14
  export type SecretContext = {
15
15
  readonly [key: string]: string;
16
16
  };
17
+ /** One declared run attribute. A replica stores each declared attribute in its own column. */
18
+ export interface RunAttributeField {
19
+ /** A start without this attribute is rejected. */
20
+ readonly required?: boolean;
21
+ /** Index the replica column. */
22
+ readonly index?: boolean;
23
+ /** Replica column name. Defaults to the key in snake_case. */
24
+ readonly fieldName?: string;
25
+ }
26
+ /** Declared run attributes, keyed by attribute name. */
27
+ export type RunAttributeFields = {
28
+ readonly [name: string]: RunAttributeField;
29
+ };
30
+ type RequiredAttributeKeys<Fields extends RunAttributeFields> = {
31
+ [Key in keyof Fields & string]: Fields[Key] extends {
32
+ readonly required: true;
33
+ } ? Key : never;
34
+ }[keyof Fields & string];
35
+ /**
36
+ * The `attributes` a start accepts. Without a declaration this is any string map.
37
+ * With one, only declared keys are allowed and `required` keys must be present.
38
+ */
39
+ export type RunAttributesInput<Fields extends RunAttributeFields = RunAttributeFields> = string extends keyof Fields ? RunAttributes : {
40
+ readonly [Key in RequiredAttributeKeys<Fields>]: string;
41
+ } & {
42
+ readonly [Key in Exclude<keyof Fields & string, RequiredAttributeKeys<Fields>>]?: string;
43
+ };
44
+ export type HasRequiredAttributes<Fields extends RunAttributeFields> = [
45
+ RequiredAttributeKeys<Fields>
46
+ ] extends [never] ? false : true;
47
+ /** `{ attributes }` for a start: required when a declared attribute is. */
48
+ export type RunAttributesOption<Fields extends RunAttributeFields = RunAttributeFields> = HasRequiredAttributes<Fields> extends true ? {
49
+ readonly attributes: RunAttributesInput<Fields>;
50
+ } : {
51
+ readonly attributes?: RunAttributesInput<Fields>;
52
+ };
53
+ /** Declare run attributes once and pass the result to the runtime, the replica, and the client. */
54
+ export declare function defineRunAttributes<const Fields extends RunAttributeFields>(fields: Fields): Fields;
55
+ declare const InvalidRunAttributesError_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 & {
56
+ readonly _tag: "InvalidRunAttributesError";
57
+ } & Readonly<A>;
58
+ export declare class InvalidRunAttributesError extends InvalidRunAttributesError_base<{
59
+ readonly message: string;
60
+ readonly issues: readonly string[];
61
+ }> {
62
+ constructor(issues: readonly string[]);
63
+ }
64
+ /** Missing required and undeclared attributes, in declaration order then input order. */
65
+ export declare function runAttributeIssues(fields: RunAttributeFields, attributes: RunAttributes): readonly string[];
17
66
  export declare const RunAttributesSchema: Schema.$Record<Schema.String, Schema.String>;
18
67
  export declare const SecretContextSchema: Schema.$Record<Schema.String, Schema.String>;
19
68
  export interface RunSecretStore {
@@ -31,3 +80,4 @@ export declare function sameStringRecord(left: {
31
80
  /** Reads a string map from an event payload. Anything else becomes an empty map. */
32
81
  export declare function readAttributes(value: JsonValue | undefined): RunAttributes;
33
82
  export declare function readSecretContext(value: JsonValue): SecretContext;
83
+ export {};
@@ -1,4 +1,24 @@
1
- import { Option, Schema } from 'effect';
1
+ import { Data, Option, Schema } from 'effect';
2
+ /** Declare run attributes once and pass the result to the runtime, the replica, and the client. */
3
+ export function defineRunAttributes(fields) {
4
+ return fields;
5
+ }
6
+ export class InvalidRunAttributesError extends Data.TaggedError('InvalidRunAttributesError') {
7
+ constructor(issues) {
8
+ super({ message: `Invalid run attributes: ${issues.join('; ')}`, issues });
9
+ this.name = 'InvalidRunAttributesError';
10
+ }
11
+ }
12
+ /** Missing required and undeclared attributes, in declaration order then input order. */
13
+ export function runAttributeIssues(fields, attributes) {
14
+ const missing = Object.entries(fields)
15
+ .filter(([name, field]) => field.required === true && attributes[name] === undefined)
16
+ .map(([name]) => `"${name}" is required`);
17
+ const undeclared = Object.keys(attributes)
18
+ .filter((name) => !Object.hasOwn(fields, name))
19
+ .map((name) => `"${name}" is not a declared attribute`);
20
+ return [...missing, ...undeclared];
21
+ }
2
22
  export const RunAttributesSchema = Schema.Record(Schema.String, Schema.String);
3
23
  export const SecretContextSchema = Schema.Record(Schema.String, Schema.String);
4
24
  const decodeAttributes = Schema.decodeUnknownOption(RunAttributesSchema);