@swirls/looms 0.26.0 → 0.27.1

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 (42) hide show
  1. package/CHANGELOG.md +30 -0
  2. package/dist/agent/definitions.d.ts +14 -4
  3. package/dist/agent/effects.d.ts +266 -266
  4. package/dist/agent/effects.js +16 -7
  5. package/dist/agent/llm.d.ts +3 -1
  6. package/dist/agent/module.d.ts +727 -727
  7. package/dist/agent/threads.js +4 -1
  8. package/dist/ai-vercel/messages.d.ts +3 -3
  9. package/dist/ai-vercel/messages.js +23 -6
  10. package/dist/ai-vercel/vercel-llm.js +1 -1
  11. package/dist/cloudflare/durable-object.js +6 -6
  12. package/dist/cloudflare/event-store.d.ts +4 -3
  13. package/dist/cloudflare/event-store.js +10 -3
  14. package/dist/evaluator/effects.d.ts +33 -33
  15. package/dist/evaluator/module.d.ts +66 -66
  16. package/dist/projectors/delivery.d.ts +6 -0
  17. package/dist/projectors/delivery.js +14 -0
  18. package/dist/swarm/board.d.ts +51 -3
  19. package/dist/swarm/board.js +8 -0
  20. package/dist/swarm/conformance.js +54 -1
  21. package/dist/swarm/definitions.d.ts +15 -0
  22. package/dist/swarm/definitions.js +3 -0
  23. package/dist/swarm/effects.d.ts +1009 -31
  24. package/dist/swarm/effects.js +73 -18
  25. package/dist/swarm/ensure.d.ts +9 -2
  26. package/dist/swarm/ensure.js +2 -1
  27. package/dist/swarm/events.d.ts +51 -0
  28. package/dist/swarm/events.js +10 -0
  29. package/dist/swarm/index.d.ts +1 -0
  30. package/dist/swarm/index.js +1 -0
  31. package/dist/swarm/memory-board.js +18 -2
  32. package/dist/swarm/module.d.ts +2055 -115
  33. package/dist/swarm/module.js +3 -1
  34. package/dist/swarm/prompt.d.ts +5 -0
  35. package/dist/swarm/prompt.js +27 -2
  36. package/dist/swarm/scope.d.ts +80 -0
  37. package/dist/swarm/services.d.ts +2 -2
  38. package/dist/swarm/services.js +5 -2
  39. package/dist/swarm/threads.d.ts +4 -0
  40. package/dist/swarm/threads.js +24 -2
  41. package/dist/swarm/tools.js +12 -5
  42. package/package.json +1 -1
@@ -4,7 +4,7 @@ import { STRUCTURED_OUTPUT_TOOL_NAME } from './definitions.js';
4
4
  import { callLlmEffect, executeToolEffect } from './effects.js';
5
5
  import { agentModule } from './scope.js';
6
6
  import { closeOpenToolCalls, insertToolResult } from './transcript.js';
7
- import { attachmentsFrom, userLine } from './types.js';
7
+ import { attachmentsField, attachmentsFrom, userLine } from './types.js';
8
8
  function inputToLine(input) {
9
9
  if (input === null) {
10
10
  return null;
@@ -170,11 +170,14 @@ export const agentThread = agentModule.thread({
170
170
  structuredOutput =
171
171
  isJsonObject(result) && 'output' in result ? (result.output ?? null) : result;
172
172
  }
173
+ // A result shaped `{ attachments }` shows those files to the model with the result.
174
+ const files = !error && isJsonObject(result) ? result.attachments : undefined;
173
175
  const lines = insertToolResult(state.lines, {
174
176
  role: 'tool',
175
177
  content,
176
178
  toolCallId,
177
179
  name: name ?? undefined,
180
+ ...attachmentsField(files),
178
181
  });
179
182
  return {
180
183
  ...state,
@@ -1,5 +1,5 @@
1
1
  import { type ModelMessage } from 'ai';
2
- import type { Attachment, Message, ToolCall } from '@swirls/looms/agent';
2
+ import type { AgentRunContext, Attachment, Message, ToolCall } from '@swirls/looms/agent';
3
3
  import type { JsonValue } from '@swirls/looms/core';
4
4
  /** An attachment's bytes (or base64 text), or a URL the model provider can fetch. */
5
5
  export type AttachmentData = Uint8Array | ArrayBuffer | string | URL;
@@ -8,7 +8,7 @@ export type AttachmentData = Uint8Array | ArrayBuffer | string | URL;
8
8
  * one that is gone, too large, or of a type the model cannot read. The message then names the
9
9
  * file in its text so the model knows it exists.
10
10
  */
11
- export type AttachmentResolver = (attachment: Attachment) => AttachmentData | null | Promise<AttachmentData | null>;
11
+ export type AttachmentResolver = (attachment: Attachment, run: AgentRunContext) => AttachmentData | null | Promise<AttachmentData | null>;
12
12
  export interface ToModelMessagesOptions {
13
13
  /**
14
14
  * Attachment contents by attachment id, from `resolveAttachments`. An attachment missing here
@@ -17,7 +17,7 @@ export interface ToModelMessagesOptions {
17
17
  readonly attachments?: ReadonlyMap<string, AttachmentData>;
18
18
  }
19
19
  /** Resolves every attachment in `messages` once, for `toModelMessages`. */
20
- export declare function resolveAttachments(messages: readonly Message[], resolve: AttachmentResolver): Promise<Map<string, AttachmentData>>;
20
+ export declare function resolveAttachments(messages: readonly Message[], resolve: AttachmentResolver, run: AgentRunContext): Promise<Map<string, AttachmentData>>;
21
21
  export declare function toModelMessages(messages: readonly Message[], options?: ToModelMessagesOptions): ModelMessage[];
22
22
  export declare function toLoomsToolCalls(calls: ReadonlyArray<{
23
23
  toolCallId: string;
@@ -18,13 +18,13 @@ function toAiJson(value) {
18
18
  return converted;
19
19
  }
20
20
  /** Resolves every attachment in `messages` once, for `toModelMessages`. */
21
- export function resolveAttachments(messages, resolve) {
21
+ export function resolveAttachments(messages, resolve, run) {
22
22
  const pending = new Map();
23
23
  for (const message of messages) {
24
24
  for (const attachment of message.attachments ?? []) {
25
25
  if (!pending.has(attachment.id)) {
26
26
  // Called inside a promise so a resolver that throws rejects instead of throwing here.
27
- pending.set(attachment.id, Promise.resolve().then(() => resolve(attachment)));
27
+ pending.set(attachment.id, Promise.resolve().then(() => resolve(attachment, run)));
28
28
  }
29
29
  }
30
30
  }
@@ -113,7 +113,7 @@ export function toModelMessages(messages, options = {}) {
113
113
  type: 'tool-result',
114
114
  toolCallId: message.toolCallId ?? message.name ?? 'unknown',
115
115
  toolName: message.name ?? 'unknown',
116
- output: parseToolOutput(message.content),
116
+ output: toolOutput(message, options.attachments),
117
117
  },
118
118
  ],
119
119
  });
@@ -126,9 +126,26 @@ export function toModelMessages(messages, options = {}) {
126
126
  }
127
127
  return converted;
128
128
  }
129
- function parseToolOutput(content) {
130
- return Option.match(decodeJson(content), {
131
- onNone: () => ({ type: 'text', value: content }),
129
+ /**
130
+ * A tool result as the model reads it. Files on the result are sent beside its text. A file
131
+ * that cannot be read is left out: the result's own text already names it.
132
+ */
133
+ function toolOutput(message, attachments) {
134
+ const files = [];
135
+ for (const attachment of message.attachments ?? []) {
136
+ const found = attachments?.get(attachment.id) ?? (attachment.url ? new URL(attachment.url) : null);
137
+ if (found !== null) {
138
+ const data = found instanceof URL ? { type: 'url', url: found } : { type: 'data', data: found };
139
+ files.push(attachment.name
140
+ ? { type: 'file', data, mediaType: attachment.mediaType, filename: attachment.name }
141
+ : { type: 'file', data, mediaType: attachment.mediaType });
142
+ }
143
+ }
144
+ if (files.length > 0) {
145
+ return { type: 'content', value: [{ type: 'text', text: message.content }, ...files] };
146
+ }
147
+ return Option.match(decodeJson(message.content), {
148
+ onNone: () => ({ type: 'text', value: message.content }),
132
149
  onSome: (value) => ({ type: 'json', value: toAiJson(value) }),
133
150
  });
134
151
  }
@@ -39,7 +39,7 @@ export function vercelLlm(options) {
39
39
  const { resolveAttachment } = options;
40
40
  const attachments = resolveAttachment
41
41
  ? yield* Effect.tryPromise({
42
- try: () => resolveAttachments(args.messages, resolveAttachment),
42
+ try: () => resolveAttachments(args.messages, resolveAttachment, args.run),
43
43
  catch: (cause) => new VercelLlmError(cause),
44
44
  })
45
45
  : undefined;
@@ -37,7 +37,7 @@ export class LoomsDurableObject extends DurableObject {
37
37
  if (!runId) {
38
38
  throw new Error('LoomsDurableObject requires a named Durable Object id (use idFromName / getByName)');
39
39
  }
40
- const alarms = durableObjectAlarms(this.ctx.storage, () => this.store?.projectorDelivery?.nextRetryAt(runId).pipe(Effect.orDie) ??
40
+ const alarms = durableObjectAlarms(this.ctx.storage, () => this.store?.projectorDelivery?.nextDueAt(runId).pipe(Effect.orDie) ??
41
41
  Effect.succeed(null));
42
42
  const store = durableObjectEventStore(this.ctx, {
43
43
  projectors: config.projectors,
@@ -68,12 +68,12 @@ export class LoomsDurableObject extends DurableObject {
68
68
  worker: config.worker,
69
69
  });
70
70
  const delivery = store.projectorDelivery;
71
- // Projector recover/deliver opens Hyperdrive/Postgres and runs projector.init.
72
- // That must not block the first request on a cold (or empty) cell. Schedule it
73
- // the same way post-append delivery uses waitUntil; deliverExclusive still
74
- // serializes per run and projector, and alarms retry from durable cursors.
71
+ // Projector delivery can open Hyperdrive/Postgres. Started from this request, even under
72
+ // waitUntil, that I/O kept the caller's stub.fetch open for seconds after the handler
73
+ // returned. Leave it to the alarm instead: the alarm deadline already includes when
74
+ // delivery is next due, so arming it once here covers work left by an earlier instance.
75
75
  if (delivery) {
76
- this.ctx.waitUntil(Effect.runPromise(delivery.recover(runId).pipe(Effect.andThen(delivery.deliver(runId)))));
76
+ void Effect.runPromise(delivery.nextDueAt(runId).pipe(Effect.orDie, Effect.flatMap((at) => (at === null ? Effect.void : alarms.scheduleAtEarliest(at)))));
77
77
  }
78
78
  return cell.recoverWake().then(() => cell);
79
79
  });
@@ -12,8 +12,9 @@ export interface DurableObjectEventStore extends EventStore {
12
12
  }
13
13
  /**
14
14
  * Creates an EventStore backed by a Durable Object's embedded SQLite database (`ctx.storage.sql`).
15
- * Optionally attaches projectors. Their delivery is scheduled with `waitUntil`, so an append
16
- * returns when the log commits. A crashed delivery is retried from the durable cursor on the next
17
- * alarm or request.
15
+ * Optionally attaches projectors. With `scheduleProjectorRetry`, an append arms the alarm to
16
+ * deliver at once rather than delivering under the request's `waitUntil`, which kept the
17
+ * Durable Object's `fetch` response open for seconds of Hyperdrive/Postgres I/O after the handler
18
+ * returned. Delivery runs from durable cursors, so a crashed one is retried on the next alarm.
18
19
  */
19
20
  export declare function durableObjectEventStore(ctx: DurableObjectState, options?: DurableObjectStoreOptions): DurableObjectEventStore;
@@ -4,9 +4,10 @@ import { sqliteEventStore, sqlStorageExec } from '@swirls/looms/core/sqlite-stor
4
4
  import { createProjectorDelivery, sqliteProjectorCursorStore, withProjectors, } from '@swirls/looms/projectors';
5
5
  /**
6
6
  * Creates an EventStore backed by a Durable Object's embedded SQLite database (`ctx.storage.sql`).
7
- * Optionally attaches projectors. Their delivery is scheduled with `waitUntil`, so an append
8
- * returns when the log commits. A crashed delivery is retried from the durable cursor on the next
9
- * alarm or request.
7
+ * Optionally attaches projectors. With `scheduleProjectorRetry`, an append arms the alarm to
8
+ * deliver at once rather than delivering under the request's `waitUntil`, which kept the
9
+ * Durable Object's `fetch` response open for seconds of Hyperdrive/Postgres I/O after the handler
10
+ * returned. Delivery runs from durable cursors, so a crashed one is retried on the next alarm.
10
11
  */
11
12
  export function durableObjectEventStore(ctx, options = {}) {
12
13
  const exec = sqlStorageExec(ctx.storage.sql, {
@@ -23,6 +24,12 @@ export function durableObjectEventStore(ctx, options = {}) {
23
24
  const wrapped = withProjectors(store, options.projectors, {
24
25
  delivery,
25
26
  scheduleDelivery: (_runId, work) => {
27
+ // The alarm delivers instead of this request, so the append's response is not held
28
+ // open by projector I/O. Without an alarm to arm, fall back to waitUntil.
29
+ if (options.scheduleProjectorRetry) {
30
+ void Effect.runPromise(options.scheduleProjectorRetry(Date.now()));
31
+ return;
32
+ }
26
33
  ctx.waitUntil(Effect.runPromise(work));
27
34
  },
28
35
  });
@@ -7,6 +7,39 @@ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").LocalE
7
7
  readonly definitionVersion?: string | undefined;
8
8
  readonly input?: Schema.Json | undefined;
9
9
  }, EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
10
+ readonly type: "evaluator.evaluated";
11
+ readonly payload: {
12
+ readonly evaluationId: string;
13
+ readonly definitionName?: string | undefined;
14
+ readonly answers: {
15
+ readonly [x: string]: {
16
+ readonly type: "boolean";
17
+ readonly value: boolean;
18
+ readonly probability: number;
19
+ } | {
20
+ readonly type: "choice";
21
+ readonly value: string;
22
+ } | {
23
+ readonly type: "score";
24
+ readonly value: number;
25
+ };
26
+ };
27
+ readonly route: string;
28
+ readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
29
+ readonly usage?: {
30
+ readonly input: number;
31
+ readonly output: number;
32
+ } | undefined;
33
+ };
34
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
35
+ readonly type: "evaluator.requested";
36
+ readonly payload: {
37
+ readonly evaluationId: string;
38
+ readonly definitionName?: string | undefined;
39
+ readonly state: string;
40
+ readonly model?: string | undefined;
41
+ };
42
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
10
43
  readonly type: "runtime.child.close.requested";
11
44
  readonly payload: {
12
45
  readonly policy: "terminate" | "wait";
@@ -252,37 +285,4 @@ export declare const evaluateEffect: NoInfer<import("@swirls/looms/core").LocalE
252
285
  readonly payload: Schema.Json;
253
286
  };
254
287
  };
255
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
256
- readonly type: "evaluator.evaluated";
257
- readonly payload: {
258
- readonly evaluationId: string;
259
- readonly definitionName?: string | undefined;
260
- readonly answers: {
261
- readonly [x: string]: {
262
- readonly type: "boolean";
263
- readonly value: boolean;
264
- readonly probability: number;
265
- } | {
266
- readonly type: "choice";
267
- readonly value: string;
268
- } | {
269
- readonly type: "score";
270
- readonly value: number;
271
- };
272
- };
273
- readonly route: string;
274
- readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
275
- readonly usage?: {
276
- readonly input: number;
277
- readonly output: number;
278
- } | undefined;
279
- };
280
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
281
- readonly type: "evaluator.requested";
282
- readonly payload: {
283
- readonly evaluationId: string;
284
- readonly definitionName?: string | undefined;
285
- readonly state: string;
286
- readonly model?: string | undefined;
287
- };
288
288
  })>>;
@@ -43,6 +43,39 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
43
43
  readonly definitionVersion?: string | undefined;
44
44
  readonly input?: import("effect/Schema").Json | undefined;
45
45
  }, import("./definitions-store").EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
46
+ readonly type: "evaluator.evaluated";
47
+ readonly payload: {
48
+ readonly evaluationId: string;
49
+ readonly definitionName?: string | undefined;
50
+ readonly answers: {
51
+ readonly [x: string]: {
52
+ readonly type: "boolean";
53
+ readonly value: boolean;
54
+ readonly probability: number;
55
+ } | {
56
+ readonly type: "choice";
57
+ readonly value: string;
58
+ } | {
59
+ readonly type: "score";
60
+ readonly value: number;
61
+ };
62
+ };
63
+ readonly route: string;
64
+ readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
65
+ readonly usage?: {
66
+ readonly input: number;
67
+ readonly output: number;
68
+ } | undefined;
69
+ };
70
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
71
+ readonly type: "evaluator.requested";
72
+ readonly payload: {
73
+ readonly evaluationId: string;
74
+ readonly definitionName?: string | undefined;
75
+ readonly state: string;
76
+ readonly model?: string | undefined;
77
+ };
78
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
46
79
  readonly type: "runtime.child.close.requested";
47
80
  readonly payload: {
48
81
  readonly policy: "terminate" | "wait";
@@ -288,39 +321,6 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
288
321
  readonly payload: import("effect/Schema").Json;
289
322
  };
290
323
  };
291
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
292
- readonly type: "evaluator.evaluated";
293
- readonly payload: {
294
- readonly evaluationId: string;
295
- readonly definitionName?: string | undefined;
296
- readonly answers: {
297
- readonly [x: string]: {
298
- readonly type: "boolean";
299
- readonly value: boolean;
300
- readonly probability: number;
301
- } | {
302
- readonly type: "choice";
303
- readonly value: string;
304
- } | {
305
- readonly type: "score";
306
- readonly value: number;
307
- };
308
- };
309
- readonly route: string;
310
- readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
311
- readonly usage?: {
312
- readonly input: number;
313
- readonly output: number;
314
- } | undefined;
315
- };
316
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
317
- readonly type: "evaluator.requested";
318
- readonly payload: {
319
- readonly evaluationId: string;
320
- readonly definitionName?: string | undefined;
321
- readonly state: string;
322
- readonly model?: string | undefined;
323
- };
324
324
  })>;
325
325
  }, {
326
326
  evaluator: import("@swirls/looms/core").ThreadDefinition<{
@@ -391,6 +391,39 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
391
391
  readonly definitionVersion?: string | undefined;
392
392
  readonly input?: import("effect/Schema").Json | undefined;
393
393
  }, import("./definitions-store").EvaluatorDefinitionsTag | EvaluatorTag, (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
394
+ readonly type: "evaluator.evaluated";
395
+ readonly payload: {
396
+ readonly evaluationId: string;
397
+ readonly definitionName?: string | undefined;
398
+ readonly answers: {
399
+ readonly [x: string]: {
400
+ readonly type: "boolean";
401
+ readonly value: boolean;
402
+ readonly probability: number;
403
+ } | {
404
+ readonly type: "choice";
405
+ readonly value: string;
406
+ } | {
407
+ readonly type: "score";
408
+ readonly value: number;
409
+ };
410
+ };
411
+ readonly route: string;
412
+ readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
413
+ readonly usage?: {
414
+ readonly input: number;
415
+ readonly output: number;
416
+ } | undefined;
417
+ };
418
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
419
+ readonly type: "evaluator.requested";
420
+ readonly payload: {
421
+ readonly evaluationId: string;
422
+ readonly definitionName?: string | undefined;
423
+ readonly state: string;
424
+ readonly model?: string | undefined;
425
+ };
426
+ }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
394
427
  readonly type: "runtime.child.close.requested";
395
428
  readonly payload: {
396
429
  readonly policy: "terminate" | "wait";
@@ -636,39 +669,6 @@ export declare function evaluator(options?: EvaluatorModuleOptions): import("@sw
636
669
  readonly payload: import("effect/Schema").Json;
637
670
  };
638
671
  };
639
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
640
- readonly type: "evaluator.evaluated";
641
- readonly payload: {
642
- readonly evaluationId: string;
643
- readonly definitionName?: string | undefined;
644
- readonly answers: {
645
- readonly [x: string]: {
646
- readonly type: "boolean";
647
- readonly value: boolean;
648
- readonly probability: number;
649
- } | {
650
- readonly type: "choice";
651
- readonly value: string;
652
- } | {
653
- readonly type: "score";
654
- readonly value: number;
655
- };
656
- };
657
- readonly route: string;
658
- readonly reason: "model" | "skipped" | "unavailable" | "uncertain";
659
- readonly usage?: {
660
- readonly input: number;
661
- readonly output: number;
662
- } | undefined;
663
- };
664
- }) | (Omit<import("@swirls/looms/core").EventInput, "payload" | "type"> & {
665
- readonly type: "evaluator.requested";
666
- readonly payload: {
667
- readonly evaluationId: string;
668
- readonly definitionName?: string | undefined;
669
- readonly state: string;
670
- readonly model?: string | undefined;
671
- };
672
672
  })>;
673
673
  };
674
674
  readonly threads: {
@@ -80,6 +80,12 @@ export interface ProjectorDelivery {
80
80
  status(runId?: string): Effect.Effect<readonly ProjectorDeliveryStatus[], ProjectorCursorError>;
81
81
  requeue(runId: string, projectorName: string, version?: string): Effect.Effect<void, ProjectorDeliveryFailure | UnknownProjectorError>;
82
82
  nextRetryAt(runId?: string): Effect.Effect<number | null, ProjectorCursorError>;
83
+ /**
84
+ * When delivery for a run is next due: now if a projector is behind the log and not backing
85
+ * off, its retry deadline if it is, or null when every projector is caught up or dead-lettered.
86
+ * Reads only the cursors and the log tail, so it never runs `projector.init`.
87
+ */
88
+ nextDueAt(runId: string): Effect.Effect<number | null, ProjectorDeliveryFailure>;
83
89
  inspect(runId?: string): Effect.Effect<readonly ProjectorOperationalStatus[], ProjectorDeliveryFailure>;
84
90
  /** Re-register retry deadlines and resume due retryable projector work. */
85
91
  recover(runId?: string): Effect.Effect<number, ProjectorDeliveryFailure>;
@@ -192,6 +192,20 @@ export function createProjectorDelivery(source, projectors, cursors, options = {
192
192
  .filter((deadline) => deadline !== null);
193
193
  return deadlines.length === 0 ? null : Math.min(...deadlines);
194
194
  })),
195
+ nextDueAt: (runId) => Effect.gen(function* () {
196
+ const sourceTail = yield* source.tail(runId);
197
+ const deadlines = yield* Effect.forEach(projectors, (projector) => cursors.get(runId, projector).pipe(Effect.map((status) => {
198
+ if (status.state === 'dead-letter') {
199
+ return null;
200
+ }
201
+ if (status.nextRetryAt !== null) {
202
+ return status.nextRetryAt;
203
+ }
204
+ return sourceTail > status.cursor ? now() : null;
205
+ })));
206
+ const due = deadlines.filter((deadline) => deadline !== null);
207
+ return due.length === 0 ? null : Math.min(...due);
208
+ }),
195
209
  inspect: (runId) => cursors.list(runId).pipe(Effect.flatMap((statuses) => Effect.forEach(statuses, (status) => source.tail(status.runId).pipe(Effect.map((sourceTail) => ({
196
210
  ...status,
197
211
  sourceTail,
@@ -1,4 +1,6 @@
1
1
  import { Schema } from 'effect';
2
+ import { type Attachment } from '@swirls/looms/agent';
3
+ import type { RunAttributes, SecretContext } from '@swirls/looms/core';
2
4
  /**
3
5
  * A message board is the only thing swarm members share. It holds channels of threaded messages,
4
6
  * tasks that members claim under a lease, and one ordered event log that a swarm follows.
@@ -20,6 +22,17 @@ export declare const BoardMessageSchema: Schema.Struct<{
20
22
  readonly mentions: Schema.$Array<Schema.String>;
21
23
  /** `key=value` state. Keys under `board.` belong to the board. */
22
24
  readonly labels: Schema.$Record<Schema.String, Schema.String>;
25
+ /**
26
+ * Files that travel with the message: screenshots, recordings, documents. The board holds
27
+ * these references and never the bytes, which stay wherever the application stored them.
28
+ */
29
+ readonly attachments: Schema.$Array<Schema.Struct<{
30
+ readonly id: Schema.String;
31
+ readonly mediaType: Schema.String;
32
+ readonly name: Schema.optional<Schema.String>;
33
+ readonly size: Schema.optional<Schema.Finite>;
34
+ readonly url: Schema.optional<Schema.String>;
35
+ }>>;
23
36
  readonly createdAt: Schema.Finite;
24
37
  }>;
25
38
  export type BoardMessage = Schema.Schema.Type<typeof BoardMessageSchema>;
@@ -96,6 +109,17 @@ export declare const BoardEventSchema: Schema.Struct<{
96
109
  readonly mentions: Schema.$Array<Schema.String>;
97
110
  /** `key=value` state. Keys under `board.` belong to the board. */
98
111
  readonly labels: Schema.$Record<Schema.String, Schema.String>;
112
+ /**
113
+ * Files that travel with the message: screenshots, recordings, documents. The board holds
114
+ * these references and never the bytes, which stay wherever the application stored them.
115
+ */
116
+ readonly attachments: Schema.$Array<Schema.Struct<{
117
+ readonly id: Schema.String;
118
+ readonly mediaType: Schema.String;
119
+ readonly name: Schema.optional<Schema.String>;
120
+ readonly size: Schema.optional<Schema.Finite>;
121
+ readonly url: Schema.optional<Schema.String>;
122
+ }>>;
99
123
  readonly createdAt: Schema.Finite;
100
124
  }>>;
101
125
  /** The task as it was after the event. Present on every task event. */
@@ -127,9 +151,11 @@ export declare const BOARD_ACTOR = "board";
127
151
  export declare const TASK_LABEL = "board.task";
128
152
  /** Label keys with this prefix are written only by the board. */
129
153
  export declare const RESERVED_LABEL_PREFIX = "board.";
154
+ /** The most files one message can carry. */
155
+ export declare const MAX_ATTACHMENTS = 10;
130
156
  export declare const DEFAULT_LEASE_MS: number;
131
157
  export declare const MAX_LEASE_MS: number;
132
- export type BoardErrorCode = 'invalid_input' | 'message_not_found' | 'task_not_found' | 'duplicate_key' | 'reserved_label' | 'label_conflict' | 'invalid_needs' | 'task_claimed' | 'task_assigned' | 'task_not_ready' | 'task_finished' | 'claim_lost';
158
+ export type BoardErrorCode = 'invalid_input' | 'board_denied' | 'message_not_found' | 'task_not_found' | 'duplicate_key' | 'reserved_label' | 'label_conflict' | 'invalid_needs' | 'task_claimed' | 'task_assigned' | 'task_not_ready' | 'task_finished' | 'claim_lost';
133
159
  declare const BoardError_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 & {
134
160
  readonly _tag: "BoardError";
135
161
  } & Readonly<A>;
@@ -148,6 +174,8 @@ export interface PostInput {
148
174
  readonly channel: string;
149
175
  readonly text: string;
150
176
  readonly labels?: BoardLabels;
177
+ /** At most {@link MAX_ATTACHMENTS}. Stored and returned as given. */
178
+ readonly attachments?: readonly Attachment[];
151
179
  /**
152
180
  * Idempotency key. Posting the same key again returns the first message and writes nothing.
153
181
  * The same key in a different channel or thread fails with `duplicate_key`.
@@ -160,6 +188,7 @@ export interface ReplyInput {
160
188
  readonly to: string;
161
189
  readonly text: string;
162
190
  readonly labels?: BoardLabels;
191
+ readonly attachments?: readonly Attachment[];
163
192
  readonly key?: string;
164
193
  }
165
194
  export interface LabelInput {
@@ -176,6 +205,8 @@ export interface LabelInput {
176
205
  };
177
206
  }
178
207
  export interface MessageQuery {
208
+ /** Only the message with this id. */
209
+ readonly id?: string;
179
210
  /** `support` matches that channel. `support/` matches it and every channel below it. */
180
211
  readonly channel?: string;
181
212
  /** Only the thread with this root: the root itself and its replies. */
@@ -196,6 +227,8 @@ export interface CreateTaskInput {
196
227
  readonly for?: string;
197
228
  readonly needs?: readonly string[];
198
229
  readonly labels?: BoardLabels;
230
+ /** Kept on the task's root message. */
231
+ readonly attachments?: readonly Attachment[];
199
232
  readonly key?: string;
200
233
  }
201
234
  export interface TaskQuery {
@@ -255,6 +288,8 @@ export interface EventPage {
255
288
  *
256
289
  * - Every write appends to one totally ordered event log, in the order the writes took effect.
257
290
  * - `post`, `reply` and `createTask` are idempotent on `key`.
291
+ * - A message returns the attachments it was written with, in order, and an empty list when it
292
+ * had none. More than {@link MAX_ATTACHMENTS} is refused with `invalid_input`.
258
293
  * - At most one claim holds a task. `claim` on a held task fails with `task_claimed`.
259
294
  * - A claim ends when it is settled, when its lease passes, or when the task is canceled. After
260
295
  * that its token fails with `claim_lost` and changes nothing, so a member that stalled cannot
@@ -281,8 +316,21 @@ export interface MessageBoard {
281
316
  cancel(input: TaskChangeInput): Promise<BoardTask>;
282
317
  events(query?: EventQuery): Promise<EventPage>;
283
318
  }
284
- /** Looks a board up by id, so one host can serve a board per tenant. */
285
- export type BoardResolver = (boardId: string) => MessageBoard | Promise<MessageBoard>;
319
+ /** The run a board call is made from: the swarm's run, a member's run, or a run that used a step. */
320
+ export interface BoardCaller {
321
+ readonly runId: string;
322
+ readonly threadId: string;
323
+ /** The labels the run was started with, such as its tenant. A swarm's members inherit them. */
324
+ readonly attributes: RunAttributes;
325
+ /** Bearer material for this attempt. */
326
+ readonly secrets: SecretContext;
327
+ }
328
+ /**
329
+ * Looks a board up by id, so one host can serve a board per tenant. A board id reaches the
330
+ * resolver from a run's input, so a host with tenants checks it against `caller.attributes` and
331
+ * throws {@link BoardError} with `board_denied` for a board the caller's tenant does not own.
332
+ */
333
+ export type BoardResolver = (boardId: string, caller: BoardCaller) => MessageBoard | Promise<MessageBoard>;
286
334
  /** The distinct `@name` handles in `text`, lowercased, in the order they first appear. */
287
335
  export declare function parseMentions(text: string): string[];
288
336
  /** Whether `channel` is selected by `filter`. A filter ending in `/` selects a whole subtree. */
@@ -1,4 +1,5 @@
1
1
  import { Data, Schema } from 'effect';
2
+ import { AttachmentSchema } from '@swirls/looms/agent';
2
3
  /**
3
4
  * A message board is the only thing swarm members share. It holds channels of threaded messages,
4
5
  * tasks that members claim under a lease, and one ordered event log that a swarm follows.
@@ -19,6 +20,11 @@ export const BoardMessageSchema = Schema.Struct({
19
20
  mentions: Schema.Array(Schema.String),
20
21
  /** `key=value` state. Keys under `board.` belong to the board. */
21
22
  labels: BoardLabelsSchema,
23
+ /**
24
+ * Files that travel with the message: screenshots, recordings, documents. The board holds
25
+ * these references and never the bytes, which stay wherever the application stored them.
26
+ */
27
+ attachments: Schema.Array(AttachmentSchema),
22
28
  createdAt: Schema.Finite,
23
29
  });
24
30
  export const TaskStateSchema = Schema.Union([
@@ -89,6 +95,8 @@ export const BOARD_ACTOR = 'board';
89
95
  export const TASK_LABEL = 'board.task';
90
96
  /** Label keys with this prefix are written only by the board. */
91
97
  export const RESERVED_LABEL_PREFIX = 'board.';
98
+ /** The most files one message can carry. */
99
+ export const MAX_ATTACHMENTS = 10;
92
100
  export const DEFAULT_LEASE_MS = 15 * 60_000;
93
101
  export const MAX_LEASE_MS = 60 * 60_000;
94
102
  /**