@swirls/looms 0.5.2 → 0.6.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 (39) hide show
  1. package/CHANGELOG.md +10 -0
  2. package/dist/agent/definitions.d.ts +0 -12
  3. package/dist/agent/effects.js +0 -24
  4. package/dist/agent/module.d.ts +507 -507
  5. package/dist/agent/projections.d.ts +5 -0
  6. package/dist/agent/projections.js +5 -0
  7. package/dist/approval/effects.d.ts +26 -26
  8. package/dist/client/client.d.ts +2 -0
  9. package/dist/client/client.js +13 -1
  10. package/dist/client/index.d.ts +1 -1
  11. package/dist/client/index.js +1 -1
  12. package/dist/cloudflare/queue-consumer.js +6 -1
  13. package/dist/core/blob-store.js +5 -1
  14. package/dist/core/definition-resolver.d.ts +16 -0
  15. package/dist/core/definition-resolver.js +23 -0
  16. package/dist/core/definition-version.d.ts +3 -0
  17. package/dist/core/definition-version.js +5 -0
  18. package/dist/core/effects.js +1 -1
  19. package/dist/core/module.d.ts +12 -3
  20. package/dist/core/module.js +18 -3
  21. package/dist/debugger/app/assets/{index-C31SnCuN.js → index-CUO1xyYW.js} +2 -2
  22. package/dist/debugger/app/assets/{routes-DPA3O5AF.js → routes-lt_6J025.js} +12 -12
  23. package/dist/debugger/app/index.html +1 -1
  24. package/dist/react/store.d.ts +1 -1
  25. package/dist/react/store.js +2 -1
  26. package/dist/runtime/cancellation.js +21 -0
  27. package/dist/runtime/dispatch-effect.js +4 -1
  28. package/dist/runtime/filesystem-blob-store.js +17 -8
  29. package/dist/runtime/repository.js +2 -1
  30. package/dist/runtime/server/routes/runs.js +6 -11
  31. package/dist/runtime/sse.d.ts +3 -1
  32. package/dist/runtime/sse.js +5 -2
  33. package/dist/runtime/types.d.ts +2 -1
  34. package/dist/runtime/wake-engine.js +16 -11
  35. package/dist/runtime/worker-effect-dispatch.d.ts +3 -1
  36. package/dist/runtime/worker-effect-dispatch.js +14 -5
  37. package/dist/testing/corpus-module.js +11 -2
  38. package/dist/workflow/threads.js +5 -8
  39. package/package.json +1 -1
@@ -16,6 +16,11 @@ export declare const turnActivity: import("@swirls/looms/core").ProjectionDefini
16
16
  readonly rootThreadId: string | null;
17
17
  readonly active: boolean;
18
18
  }>;
19
+ /**
20
+ * Cumulative token totals for a run. Folds usage attached to `agent.message`.
21
+ * Modern turns also emit `agent.turn.usage` with the same numbers — fold that event in a
22
+ * custom projector when you need turn-level rows; do not add both or totals double.
23
+ */
19
24
  export declare const tokenUsage: import("@swirls/looms/core").ProjectionDefinition<{
20
25
  readonly input: number;
21
26
  readonly output: number;
@@ -102,6 +102,11 @@ export const turnActivity = agentModule.projection({
102
102
  }
103
103
  },
104
104
  });
105
+ /**
106
+ * Cumulative token totals for a run. Folds usage attached to `agent.message`.
107
+ * Modern turns also emit `agent.turn.usage` with the same numbers — fold that event in a
108
+ * custom projector when you need turn-level rows; do not add both or totals double.
109
+ */
105
110
  export const tokenUsage = agentModule.projection({
106
111
  name: 'tokenUsage',
107
112
  shape: TokenUsageSchema,
@@ -9,32 +9,6 @@ export declare const requestApprovalEffect: NoInfer<import("@swirls/looms/core")
9
9
  }[];
10
10
  readonly schema?: import("effect/Schema").Json | undefined;
11
11
  }, never, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
12
- readonly type: "approval.decided";
13
- readonly payload: {
14
- readonly approvalId: string;
15
- readonly actionId: string;
16
- readonly outcome: "approve" | "reject";
17
- readonly payload?: import("effect/Schema").Json | undefined;
18
- };
19
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
20
- readonly type: "approval.requested";
21
- readonly payload: {
22
- readonly approvalId: string;
23
- readonly title: string;
24
- readonly description?: string | undefined;
25
- readonly actions: readonly {
26
- readonly id: string;
27
- readonly label: string;
28
- readonly outcome: "approve" | "reject";
29
- }[];
30
- readonly schema?: import("effect/Schema").Json | undefined;
31
- };
32
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
33
- readonly type: "approval.timed_out";
34
- readonly payload: {
35
- readonly approvalId: string;
36
- };
37
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
38
12
  readonly type: "runtime.child.close.requested";
39
13
  readonly payload: {
40
14
  readonly policy: "terminate" | "wait";
@@ -271,4 +245,30 @@ export declare const requestApprovalEffect: NoInfer<import("@swirls/looms/core")
271
245
  readonly payload: import("effect/Schema").Json;
272
246
  };
273
247
  };
248
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
249
+ readonly type: "approval.decided";
250
+ readonly payload: {
251
+ readonly approvalId: string;
252
+ readonly actionId: string;
253
+ readonly outcome: "approve" | "reject";
254
+ readonly payload?: import("effect/Schema").Json | undefined;
255
+ };
256
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
257
+ readonly type: "approval.requested";
258
+ readonly payload: {
259
+ readonly approvalId: string;
260
+ readonly title: string;
261
+ readonly description?: string | undefined;
262
+ readonly actions: readonly {
263
+ readonly id: string;
264
+ readonly label: string;
265
+ readonly outcome: "approve" | "reject";
266
+ }[];
267
+ readonly schema?: import("effect/Schema").Json | undefined;
268
+ };
269
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
270
+ readonly type: "approval.timed_out";
271
+ readonly payload: {
272
+ readonly approvalId: string;
273
+ };
274
274
  })>>;
@@ -1903,3 +1903,5 @@ export interface SubscriptionSocket {
1903
1903
  export interface SubscriptionSocketConstructor {
1904
1904
  new (url: string): SubscriptionSocket;
1905
1905
  }
1906
+ /** Resolve a possibly-relative HTTP base so `new URL(path, base)` never throws on `''` or `/app`. */
1907
+ export declare function absoluteHttpBase(baseUrl: string): string;
@@ -302,8 +302,20 @@ function eventsQuery(runId, fromSeq, settings) {
302
302
  }
303
303
  return `/runs/${encodeURIComponent(runId)}/events?${params.toString()}`;
304
304
  }
305
+ /** Resolve a possibly-relative HTTP base so `new URL(path, base)` never throws on `''` or `/app`. */
306
+ export function absoluteHttpBase(baseUrl) {
307
+ try {
308
+ return new URL(baseUrl).toString();
309
+ }
310
+ catch {
311
+ const page = typeof globalThis.location !== 'undefined' && Predicate.isString(globalThis.location.href)
312
+ ? globalThis.location.href
313
+ : 'http://localhost/';
314
+ return new URL(baseUrl === '' ? '.' : baseUrl, page).toString();
315
+ }
316
+ }
305
317
  function webSocketUrl(baseUrl, path) {
306
- const url = new URL(path, baseUrl);
318
+ const url = new URL(path, absoluteHttpBase(baseUrl));
307
319
  url.protocol = url.protocol === 'https:' ? 'wss:' : 'ws:';
308
320
  return url.toString();
309
321
  }
@@ -1,2 +1,2 @@
1
- export { createLoomsClient, type LoomsClient, type LoomsClientOptions, type StartResult, type StreamHandle, type SubscribeEventsOptions, type SubscriptionSocket, type SubscriptionSocketConstructor, } from './client';
1
+ export { absoluteHttpBase, createLoomsClient, type LoomsClient, type LoomsClientOptions, type StartResult, type StreamHandle, type SubscribeEventsOptions, type SubscriptionSocket, type SubscriptionSocketConstructor, } from './client';
2
2
  export { consumeSseStream, consumeSseStreamEffect, delay, eventsFromSseData, parseSseFrame, type SseFrame, } from './sse';
@@ -1,2 +1,2 @@
1
- export { createLoomsClient, } from './client.js';
1
+ export { absoluteHttpBase, createLoomsClient, } from './client.js';
2
2
  export { consumeSseStream, consumeSseStreamEffect, delay, eventsFromSseData, parseSseFrame, } from './sse.js';
@@ -39,7 +39,12 @@ function runAttempt(task, attempt, handler, cancelRequested, options) {
39
39
  if (cancelRequested) {
40
40
  controller.abort();
41
41
  }
42
- const report = (input) => callback(() => options.callbacks.workerCallback(task.runId, input)).pipe(Effect.ignore);
42
+ const report = (input) => {
43
+ const send = (remaining) => callback(() => options.callbacks.workerCallback(task.runId, input)).pipe(Effect.asVoid, Effect.catch(() => remaining <= 0
44
+ ? Effect.logWarning(`[@swirls/looms/cloudflare] lost terminal worker callback for ${task.runId} ${attempt.effectId} attempt ${attempt.attempt}`).pipe(Effect.asVoid)
45
+ : Effect.sleep(50 * (5 - remaining)).pipe(Effect.andThen(send(remaining - 1)))));
46
+ return send(4);
47
+ };
43
48
  const ctx = {
44
49
  signal: controller.signal,
45
50
  heartbeat: (details) => Effect.runPromise(callback(() => options.callbacks.workerCallback(task.runId, details === undefined
@@ -32,7 +32,11 @@ export function blobStoreFromBytes(bytes) {
32
32
  }
33
33
  const existing = yield* bytes.read(objectKey(digest));
34
34
  if (existing) {
35
- return yield* Effect.void;
35
+ const existingDigest = yield* sha256Hex(existing);
36
+ // A truncated or corrupted object must be overwritten; skipping leaves get() broken forever.
37
+ if (existingDigest === digest) {
38
+ return yield* Effect.void;
39
+ }
36
40
  }
37
41
  return yield* bytes.write(objectKey(digest), body);
38
42
  }),
@@ -37,4 +37,20 @@ export declare function cachedDefinitionResolver(inner: DefinitionResolver, opti
37
37
  export declare function pinnedDefinitionRefs(events: readonly EventEnvelope[]): readonly VersionedDefinition[];
38
38
  /** Resolves every pinned identity so a later synchronous lookup can see it. */
39
39
  export declare function primePinnedDefinitions(resolver: DefinitionResolver, events: readonly EventEnvelope[]): Effect.Effect<void, DefinitionResolveError>;
40
+ /**
41
+ * Resolves definitions pinned on a materialized run state (snapshot). Needed because delta-only
42
+ * priming misses identities whose start events sit behind the snapshot cursor.
43
+ */
44
+ export declare function primePinnedDefinitionsFromState(resolver: DefinitionResolver, state: {
45
+ readonly startIdentity: {
46
+ readonly kind: string;
47
+ readonly definitionName: string;
48
+ readonly definitionVersion: string;
49
+ } | null;
50
+ readonly threads: Readonly<Record<string, {
51
+ readonly kind: string;
52
+ readonly definitionName: string;
53
+ readonly definitionVersion: string;
54
+ }>>;
55
+ }): Effect.Effect<void, DefinitionResolveError>;
40
56
  export {};
@@ -111,6 +111,29 @@ export function primePinnedDefinitions(resolver, events) {
111
111
  }
112
112
  });
113
113
  }
114
+ /**
115
+ * Resolves definitions pinned on a materialized run state (snapshot). Needed because delta-only
116
+ * priming misses identities whose start events sit behind the snapshot cursor.
117
+ */
118
+ export function primePinnedDefinitionsFromState(resolver, state) {
119
+ return Effect.gen(function* () {
120
+ const seen = new Set();
121
+ const resolve = (kind, name, version) => {
122
+ const key = definitionKey(kind, name, version);
123
+ if (seen.has(key)) {
124
+ return Effect.void;
125
+ }
126
+ seen.add(key);
127
+ return resolver.resolve(kind, name, version).pipe(Effect.asVoid);
128
+ };
129
+ if (state.startIdentity) {
130
+ yield* resolve(state.startIdentity.kind, state.startIdentity.definitionName, state.startIdentity.definitionVersion);
131
+ }
132
+ for (const thread of Object.values(state.threads)) {
133
+ yield* resolve(thread.kind, thread.definitionName, thread.definitionVersion);
134
+ }
135
+ });
136
+ }
114
137
  function readPinned(payload) {
115
138
  if (!Predicate.isObject(payload) || !('kind' in payload) || !('definitionName' in payload)) {
116
139
  return undefined;
@@ -0,0 +1,3 @@
1
+ /** Default pinned definition version when a start event omits one. */
2
+ export declare const DEFAULT_DEFINITION_VERSION = "v1";
3
+ export declare function definitionKey(kind: string, name: string, version: string): string;
@@ -0,0 +1,5 @@
1
+ /** Default pinned definition version when a start event omits one. */
2
+ export const DEFAULT_DEFINITION_VERSION = 'v1';
3
+ export function definitionKey(kind, name, version) {
4
+ return `${kind}:${name}@${version}`;
5
+ }
@@ -1,6 +1,6 @@
1
1
  import { Data, Effect, Predicate, Schema } from 'effect';
2
+ import { DEFAULT_DEFINITION_VERSION } from './definition-version.js';
2
3
  import { EventInputSchema } from './envelope.js';
3
- import { DEFAULT_DEFINITION_VERSION } from './module.js';
4
4
  import { validateInputEffect, } from './schema.js';
5
5
  import { asJson } from './types.js';
6
6
  export const WaitConditionSchema = Schema.Union([
@@ -1,14 +1,25 @@
1
1
  import type { Context, Effect, Layer } from 'effect';
2
2
  import type { EventCatalog } from './catalog';
3
3
  import type { DefinitionResolver } from './definition-resolver';
4
- import type { EffectContext, EffectDefinition, RuntimeEffect } from './effects';
4
+ import { type EffectContext, type EffectDefinition, type RuntimeEffect } from './effects';
5
5
  import type { EventInput } from './envelope';
6
6
  import type { ProjectionDefinition } from './projection';
7
7
  import type { InferDefinedSchema, SchemaInput } from './schema';
8
8
  import type { ThreadDefinition } from './thread';
9
9
  import type { JsonValue } from './types';
10
+ export { DEFAULT_DEFINITION_VERSION, definitionKey } from './definition-version';
10
11
  export type NextEffectHandler = (effect: RuntimeEffect, ctx: EffectContext) => Effect.Effect<ReadonlyArray<EventInput>, Error>;
11
12
  export type EffectMiddleware = (effect: RuntimeEffect, ctx: EffectContext, next: NextEffectHandler) => Effect.Effect<ReadonlyArray<EventInput>, Error>;
13
+ /** Continues the middleware chain for the effect `onEffect` already matched. */
14
+ export type OnEffectNext = () => Effect.Effect<ReadonlyArray<EventInput>, Error>;
15
+ /**
16
+ * Middleware that runs only for one effect definition. The handler receives the effect's
17
+ * decoded input type and must call `next()` to continue (or `failEffect` to reject the attempt).
18
+ *
19
+ * Middleware wraps local (in-process) effect dispatch only. Effects routed to an `EffectWorker`
20
+ * never see it.
21
+ */
22
+ export declare function onEffect<TInput>(definition: EffectDefinition<TInput>, handler: (input: TInput, ctx: EffectContext, next: OnEffectNext) => Effect.Effect<ReadonlyArray<EventInput>, Error>): EffectMiddleware;
12
23
  /**
13
24
  * Names the threads whose in-process effects an admitted signal event interrupts, so a running
14
25
  * effect (such as a model call) can stop early. The runtime also interrupts each named thread's
@@ -31,8 +42,6 @@ export interface DefinitionRef {
31
42
  readonly input?: SchemaInput | undefined;
32
43
  readonly description?: string | undefined;
33
44
  }
34
- export declare const DEFAULT_DEFINITION_VERSION = "v1";
35
- export declare function definitionKey(kind: string, name: string, version: string): string;
36
45
  /** A definition registered on a host, keyed by `${kind}:${name}@${version}`. */
37
46
  export interface RegisteredDefinition {
38
47
  readonly kind: string;
@@ -1,6 +1,21 @@
1
- export const DEFAULT_DEFINITION_VERSION = 'v1';
2
- export function definitionKey(kind, name, version) {
3
- return `${kind}:${name}@${version}`;
1
+ import { isPrimitiveEffect, } from './effects.js';
2
+ export { DEFAULT_DEFINITION_VERSION, definitionKey } from './definition-version.js';
3
+ /**
4
+ * Middleware that runs only for one effect definition. The handler receives the effect's
5
+ * decoded input type and must call `next()` to continue (or `failEffect` to reject the attempt).
6
+ *
7
+ * Middleware wraps local (in-process) effect dispatch only. Effects routed to an `EffectWorker`
8
+ * never see it.
9
+ */
10
+ export function onEffect(definition, handler) {
11
+ return (effect, ctx, next) => {
12
+ if (isPrimitiveEffect(effect) || effect.type !== definition.type) {
13
+ return next(effect, ctx);
14
+ }
15
+ // SAFETY: matched definition's phantom TInput is the schema type handlers receive after validation.
16
+ // oxlint-disable-next-line typescript/no-unsafe-type-assertion
17
+ return handler(effect.input, ctx, () => next(effect, ctx));
18
+ };
4
19
  }
5
20
  export function defineRuntimeModule(module) {
6
21
  return module;