@swirls/looms 0.25.0 → 0.27.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 (109) hide show
  1. package/CHANGELOG.md +42 -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 +2 -1
  6. package/dist/actor/routing.d.ts +6 -3
  7. package/dist/actor/routing.js +6 -4
  8. package/dist/agent/agent-session.js +2 -2
  9. package/dist/agent/debugger/agent-chat.js +4 -3
  10. package/dist/agent/definitions.d.ts +16 -4
  11. package/dist/agent/effects.js +20 -9
  12. package/dist/agent/llm.d.ts +3 -1
  13. package/dist/agent/threads.js +4 -1
  14. package/dist/ai-vercel/messages.d.ts +3 -3
  15. package/dist/ai-vercel/messages.js +23 -6
  16. package/dist/ai-vercel/vercel-llm.js +1 -1
  17. package/dist/approval/steps.d.ts +3 -1
  18. package/dist/approval/steps.js +2 -2
  19. package/dist/client/client.d.ts +7 -1
  20. package/dist/client/client.js +5 -2
  21. package/dist/cloudflare/durable-object.d.ts +3 -1
  22. package/dist/cloudflare/durable-object.js +1 -0
  23. package/dist/cloudflare/queue-consumer.d.ts +3 -1
  24. package/dist/cloudflare/queue-consumer.js +2 -1
  25. package/dist/cloudflare/router.d.ts +3 -1
  26. package/dist/cloudflare/router.js +1 -1
  27. package/dist/core/compose.d.ts +8 -2
  28. package/dist/core/compose.js +6 -3
  29. package/dist/core/effects.d.ts +3 -0
  30. package/dist/core/envelope.d.ts +2 -0
  31. package/dist/core/envelope.js +2 -2
  32. package/dist/core/event-codec.d.ts +4 -3
  33. package/dist/core/event-codec.js +7 -7
  34. package/dist/core/fold.d.ts +3 -0
  35. package/dist/core/fold.js +3 -1
  36. package/dist/core/fork.js +1 -1
  37. package/dist/core/ids.d.ts +70 -5
  38. package/dist/core/ids.js +164 -41
  39. package/dist/core/snapshots.d.ts +2 -0
  40. package/dist/core/snapshots.js +2 -1
  41. package/dist/core/thread.d.ts +8 -0
  42. package/dist/debugger/app/assets/{index-GLtrulmj.js → index-D_FKxPrN.js} +2 -2
  43. package/dist/debugger/app/assets/routes-CkwzFejg.js +47 -0
  44. package/dist/debugger/app/index.html +1 -1
  45. package/dist/debugger/context.d.ts +4 -1
  46. package/dist/debugger/context.js +4 -4
  47. package/dist/debugger/shell/debugger-shell.d.ts +4 -1
  48. package/dist/debugger/shell/debugger-shell.js +2 -2
  49. package/dist/debugger/shell/use-start-run.d.ts +1 -1
  50. package/dist/debugger/shell/use-start-run.js +1 -2
  51. package/dist/evaluator/steps.d.ts +2 -2
  52. package/dist/evaluator/steps.js +3 -3
  53. package/dist/react/react.d.ts +8 -3
  54. package/dist/react/react.js +15 -2
  55. package/dist/react/store.d.ts +5 -1
  56. package/dist/react/store.js +5 -4
  57. package/dist/runtime/cancellation.js +5 -5
  58. package/dist/runtime/deadline-transition-planner.d.ts +1 -0
  59. package/dist/runtime/deadline-transition-planner.js +8 -7
  60. package/dist/runtime/effect-admission.js +1 -0
  61. package/dist/runtime/helpers.d.ts +6 -5
  62. package/dist/runtime/helpers.js +8 -8
  63. package/dist/runtime/local-effect-executor.js +15 -10
  64. package/dist/runtime/looms.d.ts +6 -1
  65. package/dist/runtime/looms.js +4 -1
  66. package/dist/runtime/retry-policy.d.ts +2 -1
  67. package/dist/runtime/retry-policy.js +2 -1
  68. package/dist/runtime/runtime.js +10 -10
  69. package/dist/runtime/server/routes/runs.js +5 -5
  70. package/dist/runtime/types.d.ts +7 -1
  71. package/dist/runtime/wake-engine.js +10 -9
  72. package/dist/runtime/worker-callbacks.js +9 -8
  73. package/dist/runtime/worker-effect-dispatch.d.ts +3 -2
  74. package/dist/runtime/worker-effect-dispatch.js +7 -5
  75. package/dist/swarm/board.d.ts +51 -3
  76. package/dist/swarm/board.js +8 -0
  77. package/dist/swarm/conformance.js +54 -1
  78. package/dist/swarm/definitions.d.ts +15 -0
  79. package/dist/swarm/definitions.js +3 -0
  80. package/dist/swarm/effects.d.ts +1009 -31
  81. package/dist/swarm/effects.js +73 -18
  82. package/dist/swarm/ensure.d.ts +9 -2
  83. package/dist/swarm/ensure.js +2 -1
  84. package/dist/swarm/events.d.ts +51 -0
  85. package/dist/swarm/events.js +10 -0
  86. package/dist/swarm/index.d.ts +1 -0
  87. package/dist/swarm/index.js +1 -0
  88. package/dist/swarm/memory-board.js +18 -2
  89. package/dist/swarm/module.d.ts +2055 -115
  90. package/dist/swarm/module.js +3 -1
  91. package/dist/swarm/prompt.d.ts +5 -0
  92. package/dist/swarm/prompt.js +27 -2
  93. package/dist/swarm/scope.d.ts +80 -0
  94. package/dist/swarm/services.d.ts +2 -2
  95. package/dist/swarm/services.js +5 -2
  96. package/dist/swarm/steps.d.ts +3 -3
  97. package/dist/swarm/steps.js +5 -5
  98. package/dist/swarm/threads.d.ts +4 -0
  99. package/dist/swarm/threads.js +24 -2
  100. package/dist/swarm/tools.d.ts +3 -2
  101. package/dist/swarm/tools.js +25 -18
  102. package/dist/workflow/effects.js +6 -5
  103. package/dist/workflow/graph.d.ts +3 -3
  104. package/dist/workflow/graph.js +5 -5
  105. package/dist/workflow/module.d.ts +8 -2
  106. package/dist/workflow/threads.d.ts +14 -2
  107. package/dist/workflow/threads.js +54 -44
  108. package/package.json +1 -1
  109. package/dist/debugger/app/assets/routes-CECZJJob.js +0 -47
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Predicate } from 'effect';
2
- import { EventStoreTag, makeMemoryEventStore, makeMemorySnapshotStore, snapshotStoreOf, withBlobOffload, SnapshotStoreTag, } from '@swirls/looms/core';
2
+ import { EventStoreTag, makeMemoryEventStore, makeMemorySnapshotStore, snapshotStoreOf, withBlobOffload, SnapshotStoreTag, resolveIds, } from '@swirls/looms/core';
3
3
  import { createRuntime, } from './runtime.js';
4
4
  import { createFetchHandler, handlesPath, mountDebugger, serveHttp, } from './server.js';
5
5
  class LoomsInitializationError extends Data.TaggedError('LoomsInitializationError') {
@@ -13,6 +13,8 @@ class LoomsInitializationError extends Data.TaggedError('LoomsInitializationErro
13
13
  }
14
14
  export function createLooms(options = {}) {
15
15
  const modules = options.modules ?? [];
16
+ // Checked here so a format that breaks a rule fails where it is configured.
17
+ const ids = resolveIds(options.ids);
16
18
  const debuggerMount = options.debugger ? mountDebugger(options.debugger) : undefined;
17
19
  let initPromise;
18
20
  let runningServer;
@@ -39,6 +41,7 @@ export function createLooms(options = {}) {
39
41
  }
40
42
  const runtime = createRuntime({
41
43
  modules,
44
+ ids,
42
45
  store,
43
46
  maxWakeIterations: options.maxWakeIterations,
44
47
  livenessLeaseMs: options.livenessLeaseMs,
@@ -1,4 +1,4 @@
1
- import { type EventEnvelope, type EventOrigin, type OutstandingEffect, type RetryPolicy } from '@swirls/looms/core';
1
+ import { type EventEnvelope, type EventOrigin, type OutstandingEffect, type RetryPolicy, type LoomsIds } from '@swirls/looms/core';
2
2
  export declare function retryBackoff(retry: RetryPolicy, attempt: number): number;
3
3
  /** Policy backoff, extended when the failed attempt asked to wait longer. */
4
4
  export declare function retryDelay(retry: RetryPolicy, attempt: number, retryAfterMs?: number): number;
@@ -15,6 +15,7 @@ export declare function planAttemptFailure(input: {
15
15
  readonly now: number;
16
16
  readonly retry: RetryPolicy | undefined;
17
17
  readonly origin: EventOrigin;
18
+ readonly ids: LoomsIds;
18
19
  /** Customer/domain failures must not be retried even when attempts remain. */
19
20
  readonly nonRetryable?: boolean;
20
21
  readonly retryAfterMs?: number;
@@ -20,6 +20,7 @@ export function planAttemptFailure(input) {
20
20
  return {
21
21
  event: createEffectFailedEvent(runId, item, error, {
22
22
  nonRetryable: input.nonRetryable === true,
23
+ ids: input.ids,
23
24
  }),
24
25
  retrying: false,
25
26
  };
@@ -37,6 +38,6 @@ export function planAttemptFailure(input) {
37
38
  threadId: item.threadId,
38
39
  causationId: item.causingEventId,
39
40
  origin: input.origin,
40
- }),
41
+ }, { ids: input.ids }),
41
42
  };
42
43
  }
@@ -1,5 +1,5 @@
1
1
  import { Clock, Effect, ManagedRuntime, Predicate } from 'effect';
2
- import { cachedDefinitionResolver, chainDefinitionResolvers, composeModules, createEvent, createThreadId, createRunId, DEFAULT_DEFINITION_VERSION, DEFAULT_SNAPSHOT_EVERY, staticDefinitionResolver, descendantThreadIds, EventStoreTag, foldRun, hasEntries, InvalidRunAttributesError, isRunTerminal, runAttributeIssues, unavailableRunLauncher, planFork, project, readTraceContext, replayTo, summarizeRun, } from '@swirls/looms/core';
2
+ import { cachedDefinitionResolver, chainDefinitionResolvers, composeModules, createEvent, DEFAULT_DEFINITION_VERSION, DEFAULT_SNAPSHOT_EVERY, staticDefinitionResolver, descendantThreadIds, EventStoreTag, foldRun, hasEntries, InvalidRunAttributesError, isRunTerminal, runAttributeIssues, unavailableRunLauncher, planFork, project, readTraceContext, replayTo, summarizeRun, } from '@swirls/looms/core';
3
3
  import { createCancellation } from './cancellation.js';
4
4
  import { nextRuntimeDeadline } from './deadline-transition-planner.js';
5
5
  import { ForkConflictError, RunNotFinishedError, RunNotFoundError, RunTerminalError, RuntimeExecutionError, StartRunConflictError, } from './errors.js';
@@ -61,7 +61,7 @@ export function createRuntime(options) {
61
61
  if (options.localLauncher && !options.store && !options.launcher) {
62
62
  throw new Error('localLauncher requires options.store');
63
63
  }
64
- const registry = composeModules(options.modules);
64
+ const registry = composeModules(options.modules, { ids: options.ids });
65
65
  const runSecrets = createRunSecrets({
66
66
  provider: options.secretProvider,
67
67
  sealer: options.secretSealer,
@@ -120,7 +120,7 @@ export function createRuntime(options) {
120
120
  if (filteredEvents.length === 0) {
121
121
  return { events: [], value: current.state };
122
122
  }
123
- const batch = yield* validateAndCreateEvents(registry.catalogs, runId, filteredEvents.map((input) => ({
123
+ const batch = yield* validateAndCreateEvents(registry, runId, filteredEvents.map((input) => ({
124
124
  ...input,
125
125
  idempotencyKey: input.idempotencyKey ?? signalKey,
126
126
  })), { origin: { type: 'external' }, threadId: current.state.rootThreadId });
@@ -133,7 +133,7 @@ export function createRuntime(options) {
133
133
  const forWaits = terminal || current.state.closeWaiting
134
134
  ? batch.filter((event) => event.type !== 'runtime.child.settled')
135
135
  : batch;
136
- const satisfiedEvents = waitSatisfiedEvents(folded, forWaits).map((input) => createEvent(runId, input));
136
+ const satisfiedEvents = waitSatisfiedEvents(folded, forWaits).map((input) => createEvent(runId, input, { ids: registry.ids }));
137
137
  return {
138
138
  events: [...batch, ...satisfiedEvents],
139
139
  value: current.state,
@@ -159,7 +159,7 @@ export function createRuntime(options) {
159
159
  }
160
160
  const store = yield* EventStoreTag;
161
161
  observe({ type: 'run.start', runId, at: currentTimeMillis() });
162
- const threadId = args.threadId ?? createThreadId();
162
+ const threadId = args.threadId ?? registry.ids.create('thread');
163
163
  const startedEvents = yield* threadStartedEvents(definitionResolver, {
164
164
  kind: args.kind,
165
165
  definitionName: args.definitionName,
@@ -208,7 +208,7 @@ export function createRuntime(options) {
208
208
  events: [],
209
209
  value: { threadId: rootThreadId, state: existing.state },
210
210
  })))
211
- : validateAndCreateEvents(registry.catalogs, runId, [
211
+ : validateAndCreateEvents(registry, runId, [
212
212
  {
213
213
  type: 'runtime.run.started',
214
214
  payload: startPayload,
@@ -370,7 +370,7 @@ export function createRuntime(options) {
370
370
  threadId: item.threadId,
371
371
  causationId: item.causingEventId,
372
372
  origin: { type: 'external', actorId: 'operator' },
373
- });
373
+ }, { ids: registry.ids });
374
374
  return { events: [retryEvent], value: undefined };
375
375
  }));
376
376
  })).pipe(Effect.andThen(runtime.wake(runId))),
@@ -389,7 +389,7 @@ export function createRuntime(options) {
389
389
  }),
390
390
  recoverDeadlines: Effect.suspend(() => runtime.rescanTimers),
391
391
  startRun: (args) => {
392
- const runId = args.runId ?? createRunId();
392
+ const runId = args.runId ?? registry.ids.create('run');
393
393
  return withRunIngress(runId, commitStart(args, runId)).pipe(Effect.flatMap((started) => runtime.wake(runId).pipe(Effect.map((state) => ({
394
394
  runId,
395
395
  threadId: state.rootThreadId ?? started.threadId,
@@ -397,7 +397,7 @@ export function createRuntime(options) {
397
397
  })))));
398
398
  },
399
399
  launchRun: (args) => {
400
- const runId = args.runId ?? createRunId();
400
+ const runId = args.runId ?? registry.ids.create('run');
401
401
  return withRunIngress(runId, commitStart(args, runId)).pipe(Effect.flatMap((started) => Effect.gen(function* () {
402
402
  if (!isRunTerminal(started.state)) {
403
403
  const now = yield* Clock.currentTimeMillis;
@@ -414,7 +414,7 @@ export function createRuntime(options) {
414
414
  accept: (runId, events, signalOpts) => appendAndWake(runId, events, signalOpts),
415
415
  cancel: cancellation,
416
416
  fork: (sourceRunId, forkOptions) => {
417
- const runId = forkOptions?.runId ?? createRunId();
417
+ const runId = forkOptions?.runId ?? registry.ids.create('run');
418
418
  return withRunIngress(runId, Effect.gen(function* () {
419
419
  const store = yield* EventStoreTag;
420
420
  const source = yield* loadCursor(store, sourceRunId);
@@ -1,5 +1,5 @@
1
1
  import { Effect, Schema } from 'effect';
2
- import { createRunId, EventStoreTag, findSignal, JsonValueSchema, RunAttributesSchema, readTraceHeaders, runSignal, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
2
+ import { EventStoreTag, findSignal, JsonValueSchema, RunAttributesSchema, readTraceHeaders, runSignal, SecretContextSchema, stringifyJson, subscriptionFilter, subscriptionFromSeq, } from '@swirls/looms/core';
3
3
  import { createEventStreamResponse } from '../../sse.js';
4
4
  import { acceptsEventStream, EventInputBodySchema, extractIdempotencyKey, prefersAsyncResponse, provideStore, readIntegerQuery, readJson, readOptionalJson, RequestQueryError, } from '../http.js';
5
5
  import { route } from '../route-table.js';
@@ -42,7 +42,7 @@ const ForkBodySchema = Schema.Struct({
42
42
  runId: Schema.optional(Schema.String),
43
43
  secrets: Schema.optional(SecretContextSchema),
44
44
  });
45
- function readStartRunArgs(req) {
45
+ function readStartRunArgs(req, ids) {
46
46
  return Effect.gen(function* () {
47
47
  const body = yield* readJson(req).pipe(Effect.flatMap(Schema.decodeUnknownEffect(StartRunBodySchema)));
48
48
  const definitionName = body.definitionName ?? body.name;
@@ -55,7 +55,7 @@ function readStartRunArgs(req) {
55
55
  definitionName,
56
56
  definitionVersion: body.definitionVersion,
57
57
  input: body.input ?? null,
58
- runId: body.runId ?? createRunId(),
58
+ runId: body.runId ?? ids.create('run'),
59
59
  idempotencyKey: extractIdempotencyKey(req, body.idempotencyKey),
60
60
  attributes: body.attributes,
61
61
  secrets: body.secrets,
@@ -134,7 +134,7 @@ export function runRoutes({ runtime, store }) {
134
134
  name: 'runs.start',
135
135
  access: 'write',
136
136
  handle: ({ req, url }) => Effect.gen(function* () {
137
- const args = yield* readStartRunArgs(req);
137
+ const args = yield* readStartRunArgs(req, runtime.registry.ids);
138
138
  if (args instanceof Response) {
139
139
  return args;
140
140
  }
@@ -151,7 +151,7 @@ export function runRoutes({ runtime, store }) {
151
151
  name: 'runs.launch',
152
152
  access: 'write',
153
153
  handle: ({ req }) => Effect.gen(function* () {
154
- const args = yield* readStartRunArgs(req);
154
+ const args = yield* readStartRunArgs(req, runtime.registry.ids);
155
155
  if (args instanceof Response) {
156
156
  return args;
157
157
  }
@@ -1,5 +1,5 @@
1
1
  import type { Effect } from 'effect';
2
- import type { AnyRuntimeModule, ComposedRegistry, DefinitionResolver, EventEnvelope, EventInput, WorkerCallback, WorkerCallbackInput, DefinitionResolveError, WorkerCallbackResult, WorkerSecretsResult, EventStore, EventStoreAppendError, EventStoreError, EventStoreFencedError, EventStoreTag, EventStoreTrimCoverage, RunLauncher, RunLaunchSource, RunAttributeFields, RunAttributes, SecretContext, TraceContext, EventStoreTruncationError, JsonValue, ProjectionDefinition, ReplayStep, RunState, RunSummary, SnapshotStore, SnapshotStoreError } from '@swirls/looms/core';
2
+ import type { AnyRuntimeModule, LoomsIds, ComposedRegistry, DefinitionResolver, EventEnvelope, EventInput, WorkerCallback, WorkerCallbackInput, DefinitionResolveError, WorkerCallbackResult, WorkerSecretsResult, EventStore, EventStoreAppendError, EventStoreError, EventStoreFencedError, EventStoreTag, EventStoreTrimCoverage, RunLauncher, RunLaunchSource, RunAttributeFields, RunAttributes, SecretContext, TraceContext, EventStoreTruncationError, JsonValue, ProjectionDefinition, ReplayStep, RunState, RunSummary, SnapshotStore, SnapshotStoreError } from '@swirls/looms/core';
3
3
  import type { EventStoreTrimmedError } from '@swirls/looms/core';
4
4
  import type { DuplicateEffectDispatchError, MaxWakeIterationsError } from './errors';
5
5
  import type { RuntimeObserver } from './observer';
@@ -8,6 +8,12 @@ import type { WakeScheduler } from './wake-scheduler';
8
8
  export type WakeError = DuplicateEffectDispatchError | MaxWakeIterationsError | EventStoreTruncationError | EventStoreTrimmedError | EventStoreFencedError | EventStoreError | Error;
9
9
  export interface CreateRuntimeOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
10
10
  readonly modules: TModules;
11
+ /**
12
+ * The id format for every event, run, thread, and wait this runtime names, and what reducers
13
+ * and effect handlers see as `ctx.ids`. Defaults to `typeIds` (TypeID). A custom format must
14
+ * return non-empty ids with no `:`, and its `derive` must be a pure function of its arguments.
15
+ */
16
+ readonly ids?: LoomsIds;
11
17
  /**
12
18
  * Loads a definition that was not registered on a module. Registered definitions are checked
13
19
  * first. Lookups are cached, including misses. Start fails with `UnknownDefinitionError`
@@ -39,7 +39,7 @@ export function createWakeEngine(options) {
39
39
  threadId: state.rootThreadId,
40
40
  origin: { type: 'system' },
41
41
  idempotencyKey: `child-close:${runId}`,
42
- });
42
+ }, { ids: registry.ids });
43
43
  const appended = yield* appendObserved(store, runId, stripSeq([requested]));
44
44
  next = yield* applyAppend(store, runId, next, stripSeq([requested]), appended);
45
45
  }
@@ -141,7 +141,7 @@ export function createWakeEngine(options) {
141
141
  let cursor = yield* loadCursor(store, runId);
142
142
  const closeEvents = childCloseCancellations(cursor.state);
143
143
  if (closeEvents.length > 0) {
144
- const created = closeEvents.map((input) => createEvent(runId, input));
144
+ const created = closeEvents.map((input) => createEvent(runId, input, { ids: registry.ids }));
145
145
  const appended = yield* appendObserved(store, runId, stripSeq(created));
146
146
  cursor = yield* applyAppend(store, runId, cursor, stripSeq(created), appended);
147
147
  }
@@ -150,6 +150,7 @@ export function createWakeEngine(options) {
150
150
  const events = planTerminalCancellationTransitions({
151
151
  runId,
152
152
  state: cursor.state,
153
+ registry,
153
154
  now,
154
155
  });
155
156
  if (events.length > 0) {
@@ -190,13 +191,13 @@ export function createWakeEngine(options) {
190
191
  ...synthesizedThreadFailed(beforeFold, intermediateState, produced),
191
192
  ...cascadedCancellations(intermediateState, produced),
192
193
  ];
193
- const synthesizedEvents = synthesized.map((input) => createEvent(runId, input));
194
+ const synthesizedEvents = synthesized.map((input) => createEvent(runId, input, { ids: registry.ids }));
194
195
  const stateAfterSynth = synthesizedEvents.length > 0
195
196
  ? foldRun(synthesizedEvents, registry, { runId, initial: intermediateState })
196
197
  : intermediateState;
197
198
  const allNewEvents = [...produced, ...synthesizedEvents];
198
199
  const satisfied = waitSatisfiedEvents(stateAfterSynth, allNewEvents);
199
- const satisfiedEvents = satisfied.map((input) => createEvent(runId, input));
200
+ const satisfiedEvents = satisfied.map((input) => createEvent(runId, input, { ids: registry.ids }));
200
201
  const fullBatch = [...allNewEvents, ...satisfiedEvents];
201
202
  const appendResult = yield* appendObserved(store, runId, stripSeq(fullBatch));
202
203
  cursor = yield* applyAppend(store, runId, cursor, stripSeq(fullBatch), appendResult);
@@ -310,7 +311,7 @@ export function createWakeEngine(options) {
310
311
  // them, and its worker asks for the attempt's secrets once it has started.
311
312
  const dispatchEvent = yield* dispatchWorkerEffect(runId, hasEntries(admission.secrets)
312
313
  ? { ...workerPlan, task: { ...workerPlan.task, secrets: admission.secrets } }
313
- : workerPlan, options.worker, now);
314
+ : workerPlan, options.worker, now, { ids: registry.ids });
314
315
  const dispatchAppend = yield* appendObserved(store, runId, stripSeq([dispatchEvent]));
315
316
  cursor = yield* applyAppend(store, runId, cursor, stripSeq([dispatchEvent]), dispatchAppend);
316
317
  }
@@ -358,7 +359,7 @@ export function createWakeEngine(options) {
358
359
  DEFAULT_LOST_ATTEMPT_LIMIT;
359
360
  return execution.attempt >= limit
360
361
  ? [
361
- createEffectFailedEvent(runId, item, `attempt ${execution.attempt} was lost before it finished, and no attempts remain`),
362
+ createEffectFailedEvent(runId, item, `attempt ${execution.attempt} was lost before it finished, and no attempts remain`, { ids: registry.ids }),
362
363
  ]
363
364
  : [];
364
365
  });
@@ -382,7 +383,7 @@ export function createWakeEngine(options) {
382
383
  },
383
384
  threadId: item.threadId,
384
385
  origin: { type: 'system' },
385
- }));
386
+ }, { ids: registry.ids }));
386
387
  for (const item of due) {
387
388
  observe({
388
389
  type: 'effect.attempt',
@@ -491,7 +492,7 @@ export function createWakeEngine(options) {
491
492
  payload: { reason: root.error ?? 'cancelled' },
492
493
  threadId: null,
493
494
  origin: { type: 'system' },
494
- })
495
+ }, { ids: registry.ids })
495
496
  : createEvent(runId, {
496
497
  type: 'runtime.run.completed',
497
498
  payload: {
@@ -500,7 +501,7 @@ export function createWakeEngine(options) {
500
501
  },
501
502
  threadId: null,
502
503
  origin: { type: 'system' },
503
- });
504
+ }, { ids: registry.ids });
504
505
  const appendResult = yield* appendObserved(store, runId, stripSeq([completed]));
505
506
  cursor = yield* applyAppend(store, runId, cursor, stripSeq([completed]), appendResult);
506
507
  }
@@ -13,13 +13,13 @@ function workerDeadline(retry, startedAt, now) {
13
13
  ].filter(Predicate.isNotNull);
14
14
  return deadlines.length > 0 ? Math.min(...deadlines) : null;
15
15
  }
16
- function workerStartedEvent(runId, item, attempt, retry, now) {
16
+ function workerStartedEvent(runId, item, attempt, retry, now, ids) {
17
17
  return createEvent(runId, {
18
18
  type: 'runtime.effect.worker.started',
19
19
  payload: { effectId: item.effectId, attempt, deadlineAt: workerDeadline(retry, now, now) },
20
20
  threadId: item.threadId,
21
21
  origin: WORKER_ORIGIN,
22
- });
22
+ }, { ids });
23
23
  }
24
24
  const STALE = {
25
25
  events: [],
@@ -73,7 +73,7 @@ function planWorkerCallback(input) {
73
73
  switch (callback.kind) {
74
74
  case 'started': {
75
75
  return Effect.succeed(item && (execution.status === 'dispatched' || execution.status === 'dispatch_wait')
76
- ? accepted([workerStartedEvent(runId, item, callback.attempt, retry, now)])
76
+ ? accepted([workerStartedEvent(runId, item, callback.attempt, retry, now, registry.ids)])
77
77
  : STALE);
78
78
  }
79
79
  case 'heartbeat': {
@@ -91,21 +91,21 @@ function planWorkerCallback(input) {
91
91
  const payload = callback.details === undefined ? recorded : { ...recorded, details: callback.details };
92
92
  return Effect.succeed(accepted([
93
93
  ...(implicitStart
94
- ? [workerStartedEvent(runId, item, callback.attempt, retry, now)]
94
+ ? [workerStartedEvent(runId, item, callback.attempt, retry, now, registry.ids)]
95
95
  : []),
96
96
  createEvent(runId, {
97
97
  type: 'runtime.effect.heartbeat',
98
98
  payload,
99
99
  threadId: item.threadId,
100
100
  origin: WORKER_ORIGIN,
101
- }),
101
+ }, { ids: registry.ids }),
102
102
  ], [notice('effect.heartbeat')]));
103
103
  }
104
104
  case 'complete': {
105
105
  if (!item) {
106
106
  return Effect.succeed(STALE);
107
107
  }
108
- return Effect.forEach(callback.events, (event) => materializeEffectOutcome(registry.catalogs, runId, item, event)).pipe(Effect.map((outcomes) => accepted([
108
+ return Effect.forEach(callback.events, (event) => materializeEffectOutcome(registry, runId, item, event)).pipe(Effect.map((outcomes) => accepted([
109
109
  ...outcomes,
110
110
  createEvent(runId, {
111
111
  type: 'runtime.effect.completed',
@@ -114,7 +114,7 @@ function planWorkerCallback(input) {
114
114
  effectId: item.effectId,
115
115
  causationId: item.causingEventId,
116
116
  origin: WORKER_ORIGIN,
117
- }),
117
+ }, { ids: registry.ids }),
118
118
  ])));
119
119
  }
120
120
  case 'fail': {
@@ -122,6 +122,7 @@ function planWorkerCallback(input) {
122
122
  return Effect.succeed(STALE);
123
123
  }
124
124
  const failure = planAttemptFailure({
125
+ ids: registry.ids,
125
126
  runId,
126
127
  item,
127
128
  attempt: callback.attempt,
@@ -153,7 +154,7 @@ function planWorkerCallback(input) {
153
154
  threadId: item?.threadId ?? null,
154
155
  effectId: callback.effectId,
155
156
  origin: WORKER_ORIGIN,
156
- }),
157
+ }, { ids: registry.ids }),
157
158
  ], [notice('effect.cancellation')], true));
158
159
  }
159
160
  default: {
@@ -1,5 +1,5 @@
1
1
  import { Effect } from 'effect';
2
- import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState } from '@swirls/looms/core';
2
+ import { type ComposedRegistry, type EffectDefinition, type EffectExecutionRecord, type EffectPlacement, type EventEnvelope, type OutstandingEffect, type RetryPolicy, type RunState, type LoomsIds } from '@swirls/looms/core';
3
3
  import type { EffectWorker, EffectWorkerTask } from './types';
4
4
  /** Caps how many times one attempt's unacknowledged dispatch can be deferred before parking as ambiguous. */
5
5
  export declare const DEFAULT_MAX_WORKER_DISPATCH_DEFERRALS = 32;
@@ -44,7 +44,8 @@ export declare function planWorkerEffects(input: {
44
44
  * arrived, so a later `started` from `dispatch_wait` is accepted.
45
45
  * - Missing worker: ambiguous (misconfiguration).
46
46
  */
47
- export declare function dispatchWorkerEffect(runId: string, plan: WorkerEffectDispatchPlan, worker: EffectWorker | undefined, now: number, options?: {
47
+ export declare function dispatchWorkerEffect(runId: string, plan: WorkerEffectDispatchPlan, worker: EffectWorker | undefined, now: number, options: {
48
+ readonly ids: LoomsIds;
48
49
  readonly maxDispatchDeferrals?: number;
49
50
  }): Effect.Effect<EventEnvelope>;
50
51
  /**
@@ -99,7 +99,7 @@ export function planWorkerEffects(input) {
99
99
  threadId: item.threadId,
100
100
  causationId: item.causingEventId,
101
101
  origin: { type: 'system' },
102
- }),
102
+ }, { ids: input.registry.ids }),
103
103
  task: workerTask(input.runId, item, attempt, {
104
104
  details: existing?.heartbeatDetails,
105
105
  attributes: input.state.attributes,
@@ -139,7 +139,8 @@ function withinInFlightLimit(input, workerItems, due) {
139
139
  * arrived, so a later `started` from `dispatch_wait` is accepted.
140
140
  * - Missing worker: ambiguous (misconfiguration).
141
141
  */
142
- export function dispatchWorkerEffect(runId, plan, worker, now, options = {}) {
142
+ export function dispatchWorkerEffect(runId, plan, worker, now, options) {
143
+ const { ids } = options;
143
144
  const dispatched = createEvent(runId, {
144
145
  type: 'runtime.effect.dispatched',
145
146
  payload: {
@@ -150,14 +151,14 @@ export function dispatchWorkerEffect(runId, plan, worker, now, options = {}) {
150
151
  threadId: plan.item.threadId,
151
152
  causationId: plan.item.causingEventId,
152
153
  origin: { type: 'system' },
153
- });
154
+ }, { ids });
154
155
  const ambiguous = (error) => createEvent(runId, {
155
156
  type: 'runtime.effect.ambiguous',
156
157
  payload: { effectId: plan.item.effectId, attempt: plan.attempt, error },
157
158
  threadId: plan.item.threadId,
158
159
  causationId: plan.item.causingEventId,
159
160
  origin: { type: 'system' },
160
- });
161
+ }, { ids });
161
162
  if (!worker) {
162
163
  return Effect.succeed(ambiguous(`no effect worker is configured for "${plan.item.effect.type}"`));
163
164
  }
@@ -168,6 +169,7 @@ export function dispatchWorkerEffect(runId, plan, worker, now, options = {}) {
168
169
  onFailure: (error) => {
169
170
  if (worker.dispatchSemantics === 'acknowledged') {
170
171
  return planAttemptFailure({
172
+ ids: ids,
171
173
  runId,
172
174
  item: plan.item,
173
175
  attempt: plan.attempt,
@@ -193,7 +195,7 @@ export function dispatchWorkerEffect(runId, plan, worker, now, options = {}) {
193
195
  threadId: plan.item.threadId,
194
196
  causationId: plan.item.causingEventId,
195
197
  origin: { type: 'system' },
196
- });
198
+ }, { ids });
197
199
  },
198
200
  onSuccess: () => dispatched,
199
201
  }));
@@ -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
  /**