@swirls/looms 0.23.0 → 0.25.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 (53) hide show
  1. package/CHANGELOG.md +22 -0
  2. package/dist/agent/threads.js +4 -1
  3. package/dist/approval/effects.d.ts +26 -26
  4. package/dist/approval/module.d.ts +52 -52
  5. package/dist/debugger/app/assets/index-GLtrulmj.js +23 -0
  6. package/dist/debugger/app/assets/{routes-Ch30UGik.js → routes-CECZJJob.js} +1 -1
  7. package/dist/debugger/app/index.html +1 -1
  8. package/dist/evaluator/effects.d.ts +33 -33
  9. package/dist/evaluator/module.d.ts +66 -66
  10. package/dist/nats/index.d.ts +1 -1
  11. package/dist/nats/index.js +1 -1
  12. package/dist/nats/projector.d.ts +17 -0
  13. package/dist/nats/projector.js +29 -8
  14. package/dist/nats/subjects.d.ts +8 -0
  15. package/dist/nats/subjects.js +10 -0
  16. package/dist/nats/transport.d.ts +10 -0
  17. package/dist/nats/transport.js +13 -4
  18. package/dist/swarm/board.d.ts +292 -0
  19. package/dist/swarm/board.js +123 -0
  20. package/dist/swarm/conformance.d.ts +15 -0
  21. package/dist/swarm/conformance.js +225 -0
  22. package/dist/swarm/definitions.d.ts +94 -0
  23. package/dist/swarm/definitions.js +51 -0
  24. package/dist/swarm/effects.d.ts +4720 -0
  25. package/dist/swarm/effects.js +296 -0
  26. package/dist/swarm/ensure.d.ts +16 -0
  27. package/dist/swarm/ensure.js +24 -0
  28. package/dist/swarm/events.d.ts +240 -0
  29. package/dist/swarm/events.js +49 -0
  30. package/dist/swarm/index.d.ts +15 -0
  31. package/dist/swarm/index.js +15 -0
  32. package/dist/swarm/memory-board.d.ts +10 -0
  33. package/dist/swarm/memory-board.js +344 -0
  34. package/dist/swarm/module.d.ts +9593 -0
  35. package/dist/swarm/module.js +94 -0
  36. package/dist/swarm/projections.d.ts +60 -0
  37. package/dist/swarm/projections.js +102 -0
  38. package/dist/swarm/prompt.d.ts +4 -0
  39. package/dist/swarm/prompt.js +35 -0
  40. package/dist/swarm/scope.d.ts +357 -0
  41. package/dist/swarm/scope.js +8 -0
  42. package/dist/swarm/services.d.ts +29 -0
  43. package/dist/swarm/services.js +40 -0
  44. package/dist/swarm/signals.d.ts +14 -0
  45. package/dist/swarm/signals.js +15 -0
  46. package/dist/swarm/steps.d.ts +15 -0
  47. package/dist/swarm/steps.js +27 -0
  48. package/dist/swarm/threads.d.ts +41 -0
  49. package/dist/swarm/threads.js +244 -0
  50. package/dist/swarm/tools.d.ts +19 -0
  51. package/dist/swarm/tools.js +100 -0
  52. package/package.json +7 -2
  53. package/dist/debugger/app/assets/index-CxbIGkpY.js +0 -22
@@ -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: {
@@ -1,3 +1,3 @@
1
1
  export { LoomsHeaders, natsProjector, type NatsProjectorOptions, type NatsProjectorSettings, } from './projector';
2
- export { anyAttributeTokens, attributeTokens, attributeTokensOf, encodeEventType, encodeSubjectToken, eventSubject, runSubjectFilter, streamSubject, } from './subjects';
2
+ export { anyAttributeTokens, attributeTokens, attributeTokensOf, CURSOR_TYPE, cursorSubject, encodeEventType, encodeSubjectToken, eventSubject, runSubjectFilter, streamSubject, } from './subjects';
3
3
  export { NatsProjectorError, SERVER_BATCH_LIMIT, WRONG_LAST_SEQUENCE, natsConnectionTransport, type NatsCommit, type NatsConnectionSource, type NatsConnectionTransportOptions, type NatsOutgoingMessage, type NatsProjectorTransport, type NatsStoredMessage, type NatsStreamSettings, } from './transport';
@@ -1,3 +1,3 @@
1
1
  export { LoomsHeaders, natsProjector, } from './projector.js';
2
- export { anyAttributeTokens, attributeTokens, attributeTokensOf, encodeEventType, encodeSubjectToken, eventSubject, runSubjectFilter, streamSubject, } from './subjects.js';
2
+ export { anyAttributeTokens, attributeTokens, attributeTokensOf, CURSOR_TYPE, cursorSubject, encodeEventType, encodeSubjectToken, eventSubject, runSubjectFilter, streamSubject, } from './subjects.js';
3
3
  export { NatsProjectorError, SERVER_BATCH_LIMIT, WRONG_LAST_SEQUENCE, natsConnectionTransport, } from './transport.js';
@@ -8,6 +8,8 @@ export declare const LoomsHeaders: {
8
8
  readonly type: 'Looms-Type';
9
9
  readonly threadId: 'Looms-Thread-Id';
10
10
  readonly ephemeral: 'Looms-Ephemeral';
11
+ /** Set to `true` on a run's cursor message, which is not an event. */
12
+ readonly cursor: 'Looms-Cursor';
11
13
  };
12
14
  export interface NatsProjectorSettings {
13
15
  /**
@@ -24,6 +26,21 @@ export interface NatsProjectorSettings {
24
26
  * already in the stream under the old subjects.
25
27
  */
26
28
  readonly subjectAttributes?: readonly string[];
29
+ /**
30
+ * What happens to ephemeral events, such as the tokens of a model's answer. `publish`, the
31
+ * default, stores them like any other, marked by the `Looms-Ephemeral` header. `skip` leaves
32
+ * them out of the stream.
33
+ *
34
+ * Ephemeral events take sequence numbers in a run's log, and the projector finds its place
35
+ * from the run's last message. So with `skip`, a batch whose newest event is ephemeral ends
36
+ * with one small cursor message on `<run's subjects>.looms.cursor`, carrying that event's
37
+ * sequence in `Looms-Seq` and `Looms-Cursor: true`. It replaces the run's earlier cursor, so
38
+ * a run never holds more than one. A reader of the stream skips it: it is not an event.
39
+ *
40
+ * The stream has to allow a message to replace the earlier ones on its subject
41
+ * (`allow_rollup_hdrs` on NATS).
42
+ */
43
+ readonly ephemeral?: 'publish' | 'skip';
27
44
  /** Events per atomic batch. At most what the transport takes, which is also the default. */
28
45
  readonly maxBatch?: number;
29
46
  /** Projector name for delivery cursors and diagnostics. Defaults to `nats`. */
@@ -1,7 +1,7 @@
1
1
  import { Effect } from 'effect';
2
2
  import { encodeLoomsEvent, isJsonObject, readAttributes } from '@swirls/looms/core';
3
3
  import { ReplicaGapError } from '@swirls/looms/projectors';
4
- import { anyAttributeTokens, attributeTokens, attributeTokensOf, eventSubject, isValidSubjectPrefix, runSubjectFilter, streamSubject, } from './subjects.js';
4
+ import { anyAttributeTokens, attributeTokens, attributeTokensOf, CURSOR_TYPE, cursorSubject, eventSubject, isValidSubjectPrefix, runSubjectFilter, streamSubject, } from './subjects.js';
5
5
  import { NatsProjectorError, SERVER_BATCH_LIMIT, natsConnectionTransport, } from './transport.js';
6
6
  /** Headers on every message, so consumers can route without decoding the body. */
7
7
  export const LoomsHeaders = {
@@ -11,6 +11,8 @@ export const LoomsHeaders = {
11
11
  type: 'Looms-Type',
12
12
  threadId: 'Looms-Thread-Id',
13
13
  ephemeral: 'Looms-Ephemeral',
14
+ /** Set to `true` on a run's cursor message, which is not an event. */
15
+ cursor: 'Looms-Cursor',
14
16
  };
15
17
  function groupByRun(events) {
16
18
  const groups = new Map();
@@ -72,6 +74,20 @@ function outgoing(prefix, runId, scope, event) {
72
74
  headers: Object.fromEntries(headers),
73
75
  };
74
76
  }
77
+ /** The message that records how far a run has been read when its newest events were left out. */
78
+ function cursorMessage(prefix, runId, scope, seq) {
79
+ return {
80
+ subject: cursorSubject(prefix, runId, scope),
81
+ payload: JSON.stringify({ runId, seq }),
82
+ headers: {
83
+ [LoomsHeaders.runId]: runId,
84
+ [LoomsHeaders.seq]: String(seq),
85
+ [LoomsHeaders.type]: CURSOR_TYPE,
86
+ [LoomsHeaders.cursor]: 'true',
87
+ },
88
+ replaces: true,
89
+ };
90
+ }
75
91
  /**
76
92
  * Replicates committed events to a NATS JetStream stream, one subject per event:
77
93
  * `<prefix>.run.<runId>.<type tokens>`, with the run's `subjectAttributes` before the run id
@@ -94,7 +110,9 @@ export function natsProjector(options) {
94
110
  message: `Subject prefix "${prefix}" must be dot-separated [A-Za-z0-9_-] tokens`,
95
111
  });
96
112
  }
97
- const transport = options.transport ?? natsConnectionTransport({ ...options, subjects: [streamSubject(prefix)] });
113
+ const skips = options.ephemeral === 'skip';
114
+ const transport = options.transport ??
115
+ natsConnectionTransport({ ...options, subjects: [streamSubject(prefix)], replaces: skips });
98
116
  const limit = Math.min(transport.maxBatch ?? SERVER_BATCH_LIMIT, SERVER_BATCH_LIMIT);
99
117
  const maxBatch = Math.min(options.maxBatch ?? limit, limit);
100
118
  if (!Number.isInteger(maxBatch) || maxBatch < 1) {
@@ -137,12 +155,15 @@ export function natsProjector(options) {
137
155
  const scope = tail.scope ?? startedScope(names, events) ?? attributeTokens(names, undefined);
138
156
  const filter = runSubjectFilter(prefix, runId, scope);
139
157
  let expected = tail.streamSeq;
140
- for (const batch of chunk(pending, maxBatch)) {
141
- expected = yield* transport.commit({
142
- filter,
143
- expected,
144
- messages: batch.map((event) => outgoing(prefix, runId, scope, event)),
145
- });
158
+ const kept = skips ? pending.filter((event) => !event.ephemeral) : pending;
159
+ const messages = kept.map((event) => outgoing(prefix, runId, scope, event));
160
+ const newest = pending.at(-1);
161
+ // Nothing stored says the run got this far, so a cursor does.
162
+ if (skips && newest?.ephemeral) {
163
+ messages.push(cursorMessage(prefix, runId, scope, newest.seq));
164
+ }
165
+ for (const batch of chunk(messages, maxBatch)) {
166
+ expected = yield* transport.commit({ filter, expected, messages: batch });
146
167
  }
147
168
  });
148
169
  return {
@@ -33,3 +33,11 @@ export declare function anyAttributeTokens(count: number): readonly string[];
33
33
  export declare function runSubjectFilter(prefix: string, runId: string, scope?: readonly string[]): string;
34
34
  /** `<prefix>.run.<attribute tokens>.<runId>.<type tokens>`. */
35
35
  export declare function eventSubject(prefix: string, runId: string, type: string, scope?: readonly string[]): string;
36
+ /** The event type the cursor message is filed under. No event of a run has it. */
37
+ export declare const CURSOR_TYPE = "looms.cursor";
38
+ /**
39
+ * `<prefix>.run.<attribute tokens>.<runId>.looms.cursor`: where a run's cursor is kept when
40
+ * ephemeral events are left out of the stream. It is on the run's subjects, so it is the
41
+ * run's last message whenever the run's newest events were ephemeral.
42
+ */
43
+ export declare function cursorSubject(prefix: string, runId: string, scope?: readonly string[]): string;
@@ -73,3 +73,13 @@ export function runSubjectFilter(prefix, runId, scope = []) {
73
73
  export function eventSubject(prefix, runId, type, scope = []) {
74
74
  return [prefix, 'run', ...scope, encodeSubjectToken(runId), encodeEventType(type)].join('.');
75
75
  }
76
+ /** The event type the cursor message is filed under. No event of a run has it. */
77
+ export const CURSOR_TYPE = 'looms.cursor';
78
+ /**
79
+ * `<prefix>.run.<attribute tokens>.<runId>.looms.cursor`: where a run's cursor is kept when
80
+ * ephemeral events are left out of the stream. It is on the run's subjects, so it is the
81
+ * run's last message whenever the run's newest events were ephemeral.
82
+ */
83
+ export function cursorSubject(prefix, runId, scope = []) {
84
+ return eventSubject(prefix, runId, CURSOR_TYPE, scope);
85
+ }
@@ -22,6 +22,11 @@ export interface NatsOutgoingMessage {
22
22
  readonly headers: {
23
23
  readonly [name: string]: string;
24
24
  };
25
+ /**
26
+ * True when storing this message drops every earlier message on its subject, so the subject
27
+ * only ever holds the newest. The stream has to allow it (`allow_rollup_hdrs` on NATS).
28
+ */
29
+ readonly replaces?: boolean;
25
30
  }
26
31
  /** A message the stream holds. */
27
32
  export interface NatsStoredMessage {
@@ -90,6 +95,11 @@ export interface NatsStreamSettings {
90
95
  export type NatsConnectionTransportOptions = NatsConnectionSource & NatsStreamSettings & {
91
96
  /** The subjects a stream made by `init` takes. */
92
97
  readonly subjects: readonly string[];
98
+ /**
99
+ * True when messages will be sent that replace the earlier ones on their subject. `init`
100
+ * then makes the stream with `allow_rollup_hdrs`, and refuses an existing one without it.
101
+ */
102
+ readonly replaces?: boolean;
93
103
  };
94
104
  /**
95
105
  * The transport over a NATS connection. A commit is a JetStream atomic batch whose first
@@ -45,6 +45,9 @@ function wireMessage(message, batch) {
45
45
  header.set('Nats-Expected-Last-Subject-Sequence', String(batch.expected.sequence));
46
46
  header.set('Nats-Expected-Last-Subject-Sequence-Subject', batch.expected.filter);
47
47
  }
48
+ if (message.replaces) {
49
+ header.set('Nats-Rollup', 'sub');
50
+ }
48
51
  if (batch.commit) {
49
52
  header.set('Nats-Batch-Commit', '1');
50
53
  }
@@ -96,14 +99,19 @@ export function natsConnectionTransport(options) {
96
99
  const init = Effect.gen(function* () {
97
100
  const streams = (yield* jsm).streams;
98
101
  const info = yield* attempt(`Reading stream ${stream} failed`, () => streams.info(stream)).pipe(Effect.catchIf((error) => error.errCode === JetStreamApiCodes.StreamNotFound, () => Effect.succeed(null)));
99
- if (info?.config.allow_atomic === true) {
100
- return info;
101
- }
102
- if (info) {
102
+ if (info && info.config.allow_atomic !== true) {
103
103
  return yield* new NatsProjectorError({
104
104
  message: `Stream ${stream} must set allow_atomic: true for the Looms NATS projector`,
105
105
  });
106
106
  }
107
+ if (info && options.replaces === true && !info.config.allow_rollup_hdrs) {
108
+ return yield* new NatsProjectorError({
109
+ message: `Stream ${stream} must set allow_rollup_hdrs: true to leave ephemeral events out`,
110
+ });
111
+ }
112
+ if (info) {
113
+ return info;
114
+ }
107
115
  if (options.createStream === false) {
108
116
  return yield* new NatsProjectorError({ message: `Stream ${stream} does not exist` });
109
117
  }
@@ -112,6 +120,7 @@ export function natsConnectionTransport(options) {
112
120
  name: stream,
113
121
  subjects: [...options.subjects],
114
122
  allow_atomic: true,
123
+ ...(options.replaces === true ? { allow_rollup_hdrs: true } : undefined),
115
124
  }));
116
125
  });
117
126
  const last = (filter) => Effect.gen(function* () {
@@ -0,0 +1,292 @@
1
+ import { Schema } from 'effect';
2
+ /**
3
+ * A message board is the only thing swarm members share. It holds channels of threaded messages,
4
+ * tasks that members claim under a lease, and one ordered event log that a swarm follows.
5
+ *
6
+ * Implement {@link MessageBoard} over any store and check it with `boardConformance`.
7
+ */
8
+ export declare const BoardLabelsSchema: Schema.$Record<Schema.String, Schema.String>;
9
+ export type BoardLabels = Schema.Schema.Type<typeof BoardLabelsSchema>;
10
+ export declare const BoardMessageSchema: Schema.Struct<{
11
+ readonly id: Schema.String;
12
+ /** A path such as `support` or `support/billing`. The first post creates it. */
13
+ readonly channel: Schema.String;
14
+ readonly text: Schema.String;
15
+ /** The member or person who wrote it. */
16
+ readonly by: Schema.String;
17
+ /** The root message of the thread, or null when this message is a root. */
18
+ readonly re: Schema.NullOr<Schema.String>;
19
+ /** Names written as `@name` in `text`. */
20
+ readonly mentions: Schema.$Array<Schema.String>;
21
+ /** `key=value` state. Keys under `board.` belong to the board. */
22
+ readonly labels: Schema.$Record<Schema.String, Schema.String>;
23
+ readonly createdAt: Schema.Finite;
24
+ }>;
25
+ export type BoardMessage = Schema.Schema.Type<typeof BoardMessageSchema>;
26
+ export declare const TaskStateSchema: Schema.Union<readonly [Schema.Literal<"waiting">, Schema.Literal<"ready">, Schema.Literal<"claimed">, Schema.Literal<"blocked">, Schema.Literal<"completed">, Schema.Literal<"failed">, Schema.Literal<"canceled">]>;
27
+ export type TaskState = Schema.Schema.Type<typeof TaskStateSchema>;
28
+ /** A task is a thread with state the board keeps. Its id is the id of its root message. */
29
+ export declare const BoardTaskSchema: Schema.Struct<{
30
+ readonly id: Schema.String;
31
+ readonly channel: Schema.String;
32
+ readonly text: Schema.String;
33
+ readonly by: Schema.String;
34
+ /** The only member who may claim it, or null when anyone may. */
35
+ readonly for: Schema.NullOr<Schema.String>;
36
+ /** Tasks that must complete before this one is ready. */
37
+ readonly needs: Schema.$Array<Schema.String>;
38
+ readonly state: Schema.Union<readonly [Schema.Literal<"waiting">, Schema.Literal<"ready">, Schema.Literal<"claimed">, Schema.Literal<"blocked">, Schema.Literal<"completed">, Schema.Literal<"failed">, Schema.Literal<"canceled">]>;
39
+ /** Who holds the current claim. */
40
+ readonly holder: Schema.NullOr<Schema.String>;
41
+ /** Counts claims. A claim from an earlier epoch can no longer change the task. */
42
+ readonly epoch: Schema.Finite;
43
+ readonly leaseUntil: Schema.NullOr<Schema.Finite>;
44
+ /** The result, failure reason, or blocker written when the task last changed state. */
45
+ readonly note: Schema.NullOr<Schema.String>;
46
+ readonly createdAt: Schema.Finite;
47
+ readonly updatedAt: Schema.Finite;
48
+ }>;
49
+ export type BoardTask = Schema.Schema.Type<typeof BoardTaskSchema>;
50
+ export declare const TaskClaimSchema: Schema.Struct<{
51
+ readonly task: Schema.Struct<{
52
+ readonly id: Schema.String;
53
+ readonly channel: Schema.String;
54
+ readonly text: Schema.String;
55
+ readonly by: Schema.String;
56
+ /** The only member who may claim it, or null when anyone may. */
57
+ readonly for: Schema.NullOr<Schema.String>;
58
+ /** Tasks that must complete before this one is ready. */
59
+ readonly needs: Schema.$Array<Schema.String>;
60
+ readonly state: Schema.Union<readonly [Schema.Literal<"waiting">, Schema.Literal<"ready">, Schema.Literal<"claimed">, Schema.Literal<"blocked">, Schema.Literal<"completed">, Schema.Literal<"failed">, Schema.Literal<"canceled">]>;
61
+ /** Who holds the current claim. */
62
+ readonly holder: Schema.NullOr<Schema.String>;
63
+ /** Counts claims. A claim from an earlier epoch can no longer change the task. */
64
+ readonly epoch: Schema.Finite;
65
+ readonly leaseUntil: Schema.NullOr<Schema.Finite>;
66
+ /** The result, failure reason, or blocker written when the task last changed state. */
67
+ readonly note: Schema.NullOr<Schema.String>;
68
+ readonly createdAt: Schema.Finite;
69
+ readonly updatedAt: Schema.Finite;
70
+ }>;
71
+ /** Proves the holder to `renew` and `settle`. It stops working when the claim is lost. */
72
+ readonly token: Schema.String;
73
+ readonly until: Schema.Finite;
74
+ }>;
75
+ export type TaskClaim = Schema.Schema.Type<typeof TaskClaimSchema>;
76
+ export declare const BoardEventTypeSchema: Schema.Union<readonly [Schema.Literal<"message.posted">, Schema.Literal<"message.labeled">, Schema.Literal<"task.created">, Schema.Literal<"task.ready">, Schema.Literal<"task.claimed">, Schema.Literal<"task.blocked">, Schema.Literal<"task.completed">, Schema.Literal<"task.failed">, Schema.Literal<"task.canceled">, Schema.Literal<"task.reopened">]>;
77
+ export type BoardEventType = Schema.Schema.Type<typeof BoardEventTypeSchema>;
78
+ export declare const BoardEventSchema: Schema.Struct<{
79
+ /** Opaque position in the board's log. Pass it back unchanged; do not compare or parse it. */
80
+ readonly cursor: Schema.String;
81
+ readonly type: Schema.Union<readonly [Schema.Literal<"message.posted">, Schema.Literal<"message.labeled">, Schema.Literal<"task.created">, Schema.Literal<"task.ready">, Schema.Literal<"task.claimed">, Schema.Literal<"task.blocked">, Schema.Literal<"task.completed">, Schema.Literal<"task.failed">, Schema.Literal<"task.canceled">, Schema.Literal<"task.reopened">]>;
82
+ readonly at: Schema.Finite;
83
+ /** Who caused the event. `BOARD_ACTOR` when the board did, such as an expired lease. */
84
+ readonly by: Schema.String;
85
+ /** The message as it was after the event. Present on message events and on `task.created`. */
86
+ readonly message: Schema.optional<Schema.Struct<{
87
+ readonly id: Schema.String;
88
+ /** A path such as `support` or `support/billing`. The first post creates it. */
89
+ readonly channel: Schema.String;
90
+ readonly text: Schema.String;
91
+ /** The member or person who wrote it. */
92
+ readonly by: Schema.String;
93
+ /** The root message of the thread, or null when this message is a root. */
94
+ readonly re: Schema.NullOr<Schema.String>;
95
+ /** Names written as `@name` in `text`. */
96
+ readonly mentions: Schema.$Array<Schema.String>;
97
+ /** `key=value` state. Keys under `board.` belong to the board. */
98
+ readonly labels: Schema.$Record<Schema.String, Schema.String>;
99
+ readonly createdAt: Schema.Finite;
100
+ }>>;
101
+ /** The task as it was after the event. Present on every task event. */
102
+ readonly task: Schema.optional<Schema.Struct<{
103
+ readonly id: Schema.String;
104
+ readonly channel: Schema.String;
105
+ readonly text: Schema.String;
106
+ readonly by: Schema.String;
107
+ /** The only member who may claim it, or null when anyone may. */
108
+ readonly for: Schema.NullOr<Schema.String>;
109
+ /** Tasks that must complete before this one is ready. */
110
+ readonly needs: Schema.$Array<Schema.String>;
111
+ readonly state: Schema.Union<readonly [Schema.Literal<"waiting">, Schema.Literal<"ready">, Schema.Literal<"claimed">, Schema.Literal<"blocked">, Schema.Literal<"completed">, Schema.Literal<"failed">, Schema.Literal<"canceled">]>;
112
+ /** Who holds the current claim. */
113
+ readonly holder: Schema.NullOr<Schema.String>;
114
+ /** Counts claims. A claim from an earlier epoch can no longer change the task. */
115
+ readonly epoch: Schema.Finite;
116
+ readonly leaseUntil: Schema.NullOr<Schema.Finite>;
117
+ /** The result, failure reason, or blocker written when the task last changed state. */
118
+ readonly note: Schema.NullOr<Schema.String>;
119
+ readonly createdAt: Schema.Finite;
120
+ readonly updatedAt: Schema.Finite;
121
+ }>>;
122
+ }>;
123
+ export type BoardEvent = Schema.Schema.Type<typeof BoardEventSchema>;
124
+ /** The `by` of events the board causes itself. */
125
+ export declare const BOARD_ACTOR = "board";
126
+ /** The label a task's root message carries. Its value is the task state. */
127
+ export declare const TASK_LABEL = "board.task";
128
+ /** Label keys with this prefix are written only by the board. */
129
+ export declare const RESERVED_LABEL_PREFIX = "board.";
130
+ export declare const DEFAULT_LEASE_MS: number;
131
+ 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';
133
+ 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
+ readonly _tag: "BoardError";
135
+ } & Readonly<A>;
136
+ /**
137
+ * A request the board refused. Retrying the same request fails the same way, so the swarm module
138
+ * reports it to the calling agent and does not retry. Throw any other error for a fault that a
139
+ * retry might clear.
140
+ */
141
+ export declare class BoardError extends BoardError_base<{
142
+ readonly code: BoardErrorCode;
143
+ readonly message: string;
144
+ }> {
145
+ }
146
+ export interface PostInput {
147
+ readonly by: string;
148
+ readonly channel: string;
149
+ readonly text: string;
150
+ readonly labels?: BoardLabels;
151
+ /**
152
+ * Idempotency key. Posting the same key again returns the first message and writes nothing.
153
+ * The same key in a different channel or thread fails with `duplicate_key`.
154
+ */
155
+ readonly key?: string;
156
+ }
157
+ export interface ReplyInput {
158
+ readonly by: string;
159
+ /** Any message of the thread. The reply attaches to that thread's root. */
160
+ readonly to: string;
161
+ readonly text: string;
162
+ readonly labels?: BoardLabels;
163
+ readonly key?: string;
164
+ }
165
+ export interface LabelInput {
166
+ readonly by: string;
167
+ readonly message: string;
168
+ readonly set?: BoardLabels;
169
+ readonly unset?: readonly string[];
170
+ /**
171
+ * Compare-and-set. Each key must hold the given value, or be absent for `null`, or the call
172
+ * fails with `label_conflict` and changes nothing.
173
+ */
174
+ readonly if?: {
175
+ readonly [key: string]: string | null;
176
+ };
177
+ }
178
+ export interface MessageQuery {
179
+ /** `support` matches that channel. `support/` matches it and every channel below it. */
180
+ readonly channel?: string;
181
+ /** Only the thread with this root: the root itself and its replies. */
182
+ readonly thread?: string;
183
+ readonly by?: string;
184
+ readonly mentions?: string;
185
+ /** Every pair must be on the message. */
186
+ readonly labels?: BoardLabels;
187
+ /** Only messages after the one with this id. */
188
+ readonly after?: string;
189
+ /** At most this many. Without `after` these are the latest matches. Default 50. */
190
+ readonly limit?: number;
191
+ }
192
+ export interface CreateTaskInput {
193
+ readonly by: string;
194
+ readonly channel: string;
195
+ readonly text: string;
196
+ readonly for?: string;
197
+ readonly needs?: readonly string[];
198
+ readonly labels?: BoardLabels;
199
+ readonly key?: string;
200
+ }
201
+ export interface TaskQuery {
202
+ readonly channel?: string;
203
+ readonly state?: TaskState;
204
+ readonly for?: string;
205
+ readonly holder?: string;
206
+ readonly limit?: number;
207
+ }
208
+ export interface ClaimInput {
209
+ readonly by: string;
210
+ /** Claim this task. Fails when it is held, assigned to someone else, or not ready. */
211
+ readonly task?: string;
212
+ /**
213
+ * Without `task`: claim the oldest ready task in this channel filter that is assigned to the
214
+ * caller, then the oldest unassigned one. Resolves to null when there is none.
215
+ */
216
+ readonly channel?: string;
217
+ /** Default {@link DEFAULT_LEASE_MS}, at most {@link MAX_LEASE_MS}. */
218
+ readonly leaseMs?: number;
219
+ }
220
+ export interface RenewInput {
221
+ readonly task: string;
222
+ readonly token: string;
223
+ readonly leaseMs?: number;
224
+ }
225
+ /** `released` returns the task to ready without finishing it. */
226
+ export type SettleOutcome = 'completed' | 'failed' | 'blocked' | 'released';
227
+ export interface SettleInput {
228
+ readonly task: string;
229
+ readonly token: string;
230
+ readonly outcome: SettleOutcome;
231
+ readonly note?: string;
232
+ }
233
+ export interface TaskChangeInput {
234
+ readonly by: string;
235
+ readonly task: string;
236
+ readonly note?: string;
237
+ }
238
+ export interface EventQuery {
239
+ /** Only events after this cursor. Omit to read from the start of the log. */
240
+ readonly after?: string;
241
+ /** Default 100. */
242
+ readonly limit?: number;
243
+ }
244
+ export interface EventPage {
245
+ readonly events: readonly BoardEvent[];
246
+ /** The cursor of the last event returned, or the `after` that was passed when there were none. */
247
+ readonly cursor: string | null;
248
+ /** Whether more events were already in the log past this page. */
249
+ readonly more: boolean;
250
+ }
251
+ /**
252
+ * The storage contract behind a swarm. One instance is one board.
253
+ *
254
+ * Rules every implementation keeps:
255
+ *
256
+ * - Every write appends to one totally ordered event log, in the order the writes took effect.
257
+ * - `post`, `reply` and `createTask` are idempotent on `key`.
258
+ * - At most one claim holds a task. `claim` on a held task fails with `task_claimed`.
259
+ * - A claim ends when it is settled, when its lease passes, or when the task is canceled. After
260
+ * that its token fails with `claim_lost` and changes nothing, so a member that stalled cannot
261
+ * settle a task another member has since claimed.
262
+ * - A task whose lease has passed is ready again, and the log gains a `task.ready` event no later
263
+ * than the next call that reads tasks or events.
264
+ * - Completing a task makes ready every waiting task whose `needs` are now all completed.
265
+ * - Refusals reject with {@link BoardError}. Any other rejection is treated as a fault and retried.
266
+ */
267
+ export interface MessageBoard {
268
+ post(input: PostInput): Promise<BoardMessage>;
269
+ reply(input: ReplyInput): Promise<BoardMessage>;
270
+ label(input: LabelInput): Promise<BoardMessage>;
271
+ /** Oldest first. */
272
+ messages(query?: MessageQuery): Promise<readonly BoardMessage[]>;
273
+ createTask(input: CreateTaskInput): Promise<BoardTask>;
274
+ /** Oldest first. */
275
+ tasks(query?: TaskQuery): Promise<readonly BoardTask[]>;
276
+ claim(input: ClaimInput): Promise<TaskClaim | null>;
277
+ renew(input: RenewInput): Promise<TaskClaim>;
278
+ settle(input: SettleInput): Promise<BoardTask>;
279
+ /** Return a blocked, failed or canceled task to ready, or to waiting if it has unmet needs. */
280
+ reopen(input: TaskChangeInput): Promise<BoardTask>;
281
+ cancel(input: TaskChangeInput): Promise<BoardTask>;
282
+ events(query?: EventQuery): Promise<EventPage>;
283
+ }
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>;
286
+ /** The distinct `@name` handles in `text`, lowercased, in the order they first appear. */
287
+ export declare function parseMentions(text: string): string[];
288
+ /** Whether `channel` is selected by `filter`. A filter ending in `/` selects a whole subtree. */
289
+ export declare function channelMatches(filter: string, channel: string): boolean;
290
+ /** Whether a task is finished and will not change state again without `reopen`. */
291
+ export declare function isFinishedTask(state: TaskState): boolean;
292
+ export {};