@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
package/CHANGELOG.md CHANGED
@@ -1,5 +1,47 @@
1
1
  # @swirls/looms
2
2
 
3
+ ## 0.27.0
4
+
5
+ ### Minor Changes
6
+
7
+ - a72ee36: Board messages and tasks can carry files, so swarm members can send each other screenshots, recordings, and documents.
8
+
9
+ `post`, `reply`, and `createTask` on `MessageBoard` take `attachments`, a list of the agent module's `Attachment` references, and every `BoardMessage` now has an `attachments` list. The board keeps the references and never the bytes. A member that is woken by a message with files gets them on its first message, the new `board_view` tool shows it the files on any other message, and `board_post`, `board_reply`, and `board_create_task` accept `attachments`.
10
+
11
+ A tool result with an `attachments` list at its top level now shows those files to the model: the agent keeps them on the tool message, and the Vercel AI adapter sends them beside the result.
12
+
13
+ Breaking for board implementations: `BoardMessage.attachments` is required, `MessageQuery` gains `id`, and `boardConformance` checks both.
14
+
15
+ - a72ee36: Swarms, agent tools, and the model adapter now know which run they work for, so a host with many tenants can keep each tenant's boards and files apart.
16
+
17
+ - `resolveAttachment(attachment, run)` receives the run the model call is made for: `runId`, `threadId`, `attributes`, and `secrets`. `LlmCompleteArgs` carries it as `run`.
18
+ - A tool's `handler(input, ctx)` and an agent's `resolveTools(ctx)` receive the same values.
19
+ - The swarm `boards` resolver is called as `boards(boardId, caller)`. Throw `BoardError` with the new code `board_denied` for a board the caller's tenant does not own. A swarm whose own board is refused fails.
20
+ - `ensureSwarm` takes `{ attributes }` as a fifth argument. Member runs inherit them.
21
+ - A member's run id is now derived in the host's id format, so it is a valid id under a custom format. It was `<swarm run id>:<member>:<n>`. `activationRunId` returns it.
22
+ - A board write's idempotency key now names the run as well as the effect, so two runs that share a board cannot collide.
23
+ - A swarm that cannot read its board tries again with a growing delay, up to 15 minutes. It used to stop reading after five attempts.
24
+
25
+ Breaking: `LlmCompleteArgs.run` is required, and `resolveAttachments` takes the run as a third argument.
26
+
27
+ ## 0.26.0
28
+
29
+ ### Minor Changes
30
+
31
+ - 8795ca9: Ids are TypeIDs by default, and a host can supply its own id format.
32
+
33
+ Every run, thread, event, and wait id is now a [TypeID](https://github.com/jetify-com/typeid): `run_`, `thr_`, `evt_`, or `wait_` followed by 26 characters. Ids Looms draws carry a UUIDv7 and sort by creation time within a process. Ids a reducer derives for a child carry a UUIDv8 whose bits are SHA-256 over the parts.
34
+
35
+ Pass `ids` to use another format, for example UUIDs that match the tables run data is replicated into. A format is a `LoomsIds` object: `create(kind)` draws an id and `derive(kind, parts)` names a child. The option is accepted by `createLooms`, `createRuntime`, `createActorCell`, `createLocalActorHost`, the Durable Object config, `routeToDurableObject`, the queue consumer, `createLoomsClient`, `LoomsProvider`, `createLoomsStore`, `preloadRunStore`, and `DebuggerShell`. Reducers and effect handlers read the configured format as `ctx.ids`. An id must be a non-empty string with no `:`; a format that breaks either rule throws `InvalidIdFormatError`. `derive` must be a pure function of its arguments.
36
+
37
+ Breaking changes:
38
+
39
+ - Every id Looms draws or derives has a new shape. Derived thread ids were bare UUID-shaped strings and now start with `thr_`. Derived ids come from SHA-256 instead of FNV-1a, so every derived child has a new name: a run in flight across the upgrade will not replay. Let in-flight runs finish, or cancel them, before upgrading.
40
+ - `ThreadContext`, `StartContext`, `LocalEffectContext`, `WorkerEffectContext`, and `AgentToolResolutionContext` have a required `ids` field. Code that builds one by hand must add it.
41
+ - A workflow's `pendingCancels` state holds `{ target, execution }` records instead of id strings. The workflow no longer reads a child's kind from a `run_` prefix.
42
+ - `deterministicThreadId` and `deterministicRunId` hash their parts as JSON, so `('a:b', 'c')` and `('a', 'b:c')` no longer collide, and `1` and `'1'` differ.
43
+ - `gate`, `evaluate`, `post`, `createTask`, and `boardTools` draw their call ids as `wait_<26 characters>` without the `approval`, `evaluator`, or `swarm` label.
44
+
3
45
  ## 0.25.0
4
46
 
5
47
  ### Minor Changes
@@ -1,4 +1,4 @@
1
- import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type EventStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot, type SnapshotStore } from '@swirls/looms/core';
1
+ import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type EventStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot, type SnapshotStore, type LoomsIds } from '@swirls/looms/core';
2
2
  import { type Authorize, type EffectWorker, type LoomsRuntime, type RunSignalOptions, type StartResult, type StartRunArgs, type WakeScheduler, type RuntimeObserver, type SecretProvider, type SecretSealer } from '@swirls/looms/runtime';
3
3
  export interface ActorCellOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
4
4
  readonly runId: string;
@@ -7,6 +7,8 @@ export interface ActorCellOptions<TModules extends readonly AnyRuntimeModule[] =
7
7
  readonly modules: TModules;
8
8
  /** Loads definitions that were not registered on a module. See `CreateRuntimeOptions`. */
9
9
  readonly definitionResolver?: DefinitionResolver;
10
+ /** The id format. See `CreateRuntimeOptions.ids`. */
11
+ readonly ids?: LoomsIds;
10
12
  readonly snapshotEvery?: number;
11
13
  readonly maxWakeIterations?: number;
12
14
  /** See `CreateRuntimeOptions.livenessLeaseMs`. */
@@ -11,6 +11,7 @@ export function createActorCell(options) {
11
11
  const runtime = createRuntime({
12
12
  modules: options.modules,
13
13
  definitionResolver: options.definitionResolver,
14
+ ids: options.ids,
14
15
  store,
15
16
  scheduler,
16
17
  launcher: options.launcher,
@@ -1,4 +1,4 @@
1
- import type { AnyRuntimeModule, DefinitionResolver, EventInput, EventStore, EventStoreTrimCoverage, RunAttributeFields, RunLauncher, RunState, SnapshotStore } from '@swirls/looms/core';
1
+ import type { AnyRuntimeModule, DefinitionResolver, EventInput, EventStore, EventStoreTrimCoverage, RunAttributeFields, RunLauncher, RunState, SnapshotStore, LoomsIds } from '@swirls/looms/core';
2
2
  import { type Authorize, type RunSignalOptions, type StartResult, type StartRunArgs, type RuntimeObserver, type SecretProvider, type SecretSealer } from '@swirls/looms/runtime';
3
3
  import { type ActorCell } from './cell';
4
4
  export interface LocalActorHostOptions<TModules extends readonly AnyRuntimeModule[] = readonly AnyRuntimeModule[]> {
@@ -6,6 +6,8 @@ export interface LocalActorHostOptions<TModules extends readonly AnyRuntimeModul
6
6
  readonly modules: TModules;
7
7
  /** Loads definitions that were not registered on a module. See `CreateRuntimeOptions`. */
8
8
  readonly definitionResolver?: DefinitionResolver;
9
+ /** The id format. See `CreateRuntimeOptions.ids`. */
10
+ readonly ids?: LoomsIds;
9
11
  /** Declared run attributes. See `CreateRuntimeOptions`. */
10
12
  readonly attributes?: RunAttributeFields;
11
13
  /** Told about wakes, appends, snapshots and effect attempts. See `CreateRuntimeOptions`. */
@@ -59,6 +59,7 @@ export function createLocalActorHost(options) {
59
59
  scheduler,
60
60
  modules: options.modules,
61
61
  definitionResolver: options.definitionResolver,
62
+ ids: options.ids,
62
63
  attributes: options.attributes,
63
64
  observer: options.observer,
64
65
  secretProvider: options.secretProvider,
@@ -109,7 +110,7 @@ export function createLocalActorHost(options) {
109
110
  }
110
111
  return Effect.runPromise(Effect.gen(function* () {
111
112
  const { runId, request } = yield* Effect.tryPromise({
112
- try: () => resolveRunTarget(req),
113
+ try: () => resolveRunTarget(req, { ids: options.ids }),
113
114
  catch: (cause) => new ActorHostError(cause),
114
115
  });
115
116
  const cell = yield* Effect.tryPromise({
@@ -1,4 +1,4 @@
1
- import { type AnyRuntimeModule } from '@swirls/looms/core';
1
+ import { type LoomsIds, type AnyRuntimeModule } from '@swirls/looms/core';
2
2
  /**
3
3
  * Extracts the target `runId` from a Looms HTTP request.
4
4
  * Inspects `x-looms-run-id` and `/runs/:runId/*`.
@@ -32,7 +32,10 @@ export declare class RunTargetError extends RunTargetError_base<{
32
32
  /**
33
33
  * Resolves the destination `runId` for routing to an actor cell.
34
34
  * For `POST /runs` and `POST /runs/launch` without a `runId`, creates a fresh
35
- * `runId`, injects it into the body, and sets `x-looms-run-id`.
35
+ * `runId` in the `ids` format (default `typeIds`), injects it into the body, and sets
36
+ * `x-looms-run-id`.
36
37
  */
37
- export declare function resolveRunTarget(req: Request): Promise<ResolvedRunTarget>;
38
+ export declare function resolveRunTarget(req: Request, options?: {
39
+ readonly ids?: LoomsIds;
40
+ }): Promise<ResolvedRunTarget>;
38
41
  export {};
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Option, Predicate, Schema } from 'effect';
2
- import { composeModules, createRunId, isJsonObject, publishDefinition, publishEffects, publishModules, stringifyJson, } from '@swirls/looms/core';
2
+ import { composeModules, resolveIds, isJsonObject, publishDefinition, publishEffects, publishModules, stringifyJson, } from '@swirls/looms/core';
3
3
  const RunTargetBodySchema = Schema.Struct({
4
4
  runId: Schema.optional(Schema.NonEmptyString),
5
5
  });
@@ -78,9 +78,11 @@ export class RunTargetError extends Data.TaggedError('RunTargetError') {
78
78
  /**
79
79
  * Resolves the destination `runId` for routing to an actor cell.
80
80
  * For `POST /runs` and `POST /runs/launch` without a `runId`, creates a fresh
81
- * `runId`, injects it into the body, and sets `x-looms-run-id`.
81
+ * `runId` in the `ids` format (default `typeIds`), injects it into the body, and sets
82
+ * `x-looms-run-id`.
82
83
  */
83
- export function resolveRunTarget(req) {
84
+ export function resolveRunTarget(req, options) {
85
+ const ids = resolveIds(options?.ids);
84
86
  return Effect.runPromise(Effect.gen(function* () {
85
87
  const existing = runIdFromRequest(req);
86
88
  if (existing) {
@@ -108,7 +110,7 @@ export function resolveRunTarget(req) {
108
110
  runId = decoded.value.runId;
109
111
  }
110
112
  else {
111
- runId = createRunId();
113
+ runId = ids.create('run');
112
114
  }
113
115
  const decodedRecord = decodePayloadRecord(text);
114
116
  const payloadObj = Option.isSome(decodedRecord) && isJsonObject(decodedRecord.value)
@@ -1,5 +1,5 @@
1
1
  import { Predicate } from 'effect';
2
- import { cancel, createWaitId, deterministicThreadId, emit, spawn, wait, } from '@swirls/looms/core';
2
+ import { cancel, createWaitId, emit, spawn, wait, } from '@swirls/looms/core';
3
3
  import { agentModule } from './scope.js';
4
4
  import { attachmentsField, userLine } from './types.js';
5
5
  function objectPayload(event) {
@@ -237,7 +237,7 @@ export function createAgentSessionThread(definitions) {
237
237
  if (next) {
238
238
  effects.push(emit(agentModule.input('session.turn.started', {
239
239
  messageId: next.messageId,
240
- childThreadId: deterministicThreadId(ctx.threadId, 'turn', next.messageId),
240
+ childThreadId: ctx.ids.derive('thread', [ctx.threadId, 'turn', next.messageId]),
241
241
  }, { threadId: ctx.threadId }), `session_admit_${next.messageId}`));
242
242
  return effects;
243
243
  }
@@ -1,7 +1,7 @@
1
1
  import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  import { Bot, CornerDownRight, GitFork, MessageSquare, Settings2, User, Wrench } from 'lucide-react';
3
3
  import { useMemo, useState } from 'react';
4
- import { createEventId, isJsonObject, isJsonString, } from '@swirls/looms/core';
4
+ import { isJsonObject, isJsonString } from '@swirls/looms/core';
5
5
  import { Button, cn, Composer, EmptyState, errorMessage, FollowList, inputForm, JsonTree, messageInput, parseStructuredJson, Select, SelectContent, SelectItem, SelectTrigger, SelectValue, shortId, useDebugger, useStartRun, } from '@swirls/looms/debugger';
6
6
  import { useLiveFold, useProjection, useRunStore, useRunSummary } from '@swirls/looms/react';
7
7
  import { conversation, turnActivity } from '../projections.js';
@@ -115,7 +115,7 @@ export function AgentChat(context) {
115
115
  }
116
116
  setDraft('');
117
117
  start(input, session
118
- ? (started) => client.signal(started.runId, agentSessionMessageEvents({ messageId: createEventId(), text: content }, { threadId: started.threadId }))
118
+ ? (started) => client.signal(started.runId, agentSessionMessageEvents({ messageId: client.ids.create('event'), text: content }, { threadId: started.threadId }))
119
119
  : undefined);
120
120
  }
121
121
  return (_jsxs("div", { className: "flex h-full min-h-0 flex-col", children: [runId ? (_jsx(Transcript, { runId: runId })) : (_jsx("div", { className: "min-h-0 flex-1", children: _jsx(EmptyState, { icon: _jsx(MessageSquare, {}), title: `Talk to ${definition.name}`, children: "Your first message starts a new run." }) })), runId ? (_jsx(FollowUp, { runId: runId, session: session, delivery: delivery, setDelivery: setDelivery, startError: error, onForked: context.onStarted })) : (_jsx(Composer, { value: draft, onChange: setDraft, onSubmit: send, pending: pending, placeholder: `Message ${definition.name}…`, submitLabel: "Start", error: error }))] }));
@@ -140,6 +140,7 @@ function ContinueRun({ runId, status, onForked, }) {
140
140
  return (_jsxs("div", { className: "border-border shrink-0 border-t p-3", children: [_jsxs("div", { className: "flex items-center gap-2", children: [_jsxs("p", { className: "text-muted-foreground min-w-0 flex-1 text-xs", children: ["Run ", status, ". Continue from where it stopped in a new run."] }), _jsxs(Button, { size: "sm", variant: "outline", disabled: pending, onClick: continueInNewRun, children: [_jsx(GitFork, {}), "Continue in new run"] })] }), error ? _jsx("p", { className: "text-status-failed mt-2 text-[11px]", children: error }) : null] }));
141
141
  }
142
142
  function Reply({ runId, session, delivery, setDelivery, startError }) {
143
+ const { client } = useDebugger();
143
144
  const store = useRunStore(runId);
144
145
  const { rootThreadId, status, finished } = useRunSummary(store);
145
146
  const turn = useProjection(store, turnActivity);
@@ -167,7 +168,7 @@ function Reply({ runId, session, delivery, setDelivery, startError }) {
167
168
  setError(null);
168
169
  const events = session
169
170
  ? agentSessionMessageEvents({
170
- messageId: createEventId(),
171
+ messageId: client.ids.create('event'),
171
172
  text: content,
172
173
  delivery,
173
174
  activeChildThreadId: delivery === 'steer' ? activeSessionChild(store.events()) : undefined,
@@ -1,6 +1,6 @@
1
1
  import type { StandardSchemaV1 } from '@standard-schema/spec';
2
2
  import type { Schema } from 'effect';
3
- import { type JsonValue, type RuntimeEffect, type SchemaInput } from '@swirls/looms/core';
3
+ import { type JsonValue, type RuntimeEffect, type SchemaInput, type LoomsIds, type RunAttributes, type SecretContext } from '@swirls/looms/core';
4
4
  import type { StopWhen } from './stop-when';
5
5
  import type { Message, ToolCall } from './types';
6
6
  export declare const TEAM_MEMBER_MAX_DEPTH: 3;
@@ -25,8 +25,19 @@ export declare function defaultAgentCompactor(ctx: AgentCompactionContext): Agen
25
25
  /** Whether a model error reports that the prompt exceeded the model's context window. */
26
26
  export declare function isContextOverflowError(error: Error): boolean;
27
27
  export declare function buildStructuredOutputInstructions(toolName?: "submit_output"): string;
28
- export interface ToolContext {
28
+ /**
29
+ * The run an agent is working in. A host that serves many tenants reads the tenant from
30
+ * `attributes`, which a run is started with and which the runs it launches inherit.
31
+ */
32
+ export interface AgentRunContext {
33
+ readonly runId: string;
29
34
  readonly threadId: string;
35
+ /** Labels safe for every reader of the run. */
36
+ readonly attributes: RunAttributes;
37
+ /** Bearer material for this attempt. Never copy it into a tool result or an event. */
38
+ readonly secrets: SecretContext;
39
+ }
40
+ export interface ToolContext extends AgentRunContext {
30
41
  readonly turn: number;
31
42
  readonly signal?: AbortSignal;
32
43
  }
@@ -82,10 +93,11 @@ export interface AgentTurnContext<TInput = JsonValue> {
82
93
  readonly signal?: AbortSignal;
83
94
  }
84
95
  /** What `resolveTools` sees. It runs before each model turn and again when a tool executes. */
85
- export interface AgentToolResolutionContext<TInput = JsonValue> {
86
- readonly threadId: string;
96
+ export interface AgentToolResolutionContext<TInput = JsonValue> extends AgentRunContext {
87
97
  readonly turn: number;
88
98
  readonly input: TInput;
99
+ /** The id format the host was configured with. */
100
+ readonly ids: LoomsIds;
89
101
  }
90
102
  export interface AgentTurnResult<TOutput extends JsonValue = JsonValue> {
91
103
  message: Message;
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Predicate, Schema } from 'effect';
2
- import { createThreadId, DEFAULT_DEFINITION_VERSION, validateInputEffect, } from '@swirls/looms/core';
2
+ import { DEFAULT_DEFINITION_VERSION, validateInputEffect, } from '@swirls/looms/core';
3
3
  import { buildStructuredOutputInstructions, defaultAgentCompactor, defineTool, isContextOverflowError, normalizeTools, STRUCTURED_OUTPUT_TOOL_NAME, TEAM_MEMBER_MAX_DEPTH, } from './definitions.js';
4
4
  import { AgentDefinitionsTag } from './definitions-store.js';
5
5
  import { LlmTag } from './llm.js';
@@ -88,8 +88,14 @@ export const callLlmEffect = agentModule.effect({
88
88
  structuredOutput: input.structuredOutput ?? null,
89
89
  alreadyCompacted: input.alreadyCompacted ?? false,
90
90
  consumedSteerMessageIds: [...(input.consumedSteerMessageIds ?? [])],
91
- runId: ctx.runId,
91
+ run: {
92
+ runId: ctx.runId,
93
+ threadId: ctx.threadId,
94
+ attributes: ctx.attributes,
95
+ secrets: ctx.secrets,
96
+ },
92
97
  threadId: ctx.threadId,
98
+ ids: ctx.ids,
93
99
  signal: ctx.signal,
94
100
  emit: (event) => ctx.emit(event),
95
101
  }),
@@ -124,7 +130,7 @@ function runCallLlm(args) {
124
130
  },
125
131
  ];
126
132
  }
127
- const tools = yield* agentTools(definition, { threadId, turn, input });
133
+ const tools = yield* agentTools(definition, { ...args.run, turn, input, ids: args.ids });
128
134
  const instructions = definition.output
129
135
  ? `${definition.instructions}\n\n${buildStructuredOutputInstructions(STRUCTURED_OUTPUT_TOOL_NAME)}`
130
136
  : definition.instructions;
@@ -161,6 +167,7 @@ function runCallLlm(args) {
161
167
  messages: [{ role: 'system', content: instructions }, ...turnMessages],
162
168
  tools,
163
169
  toolSpecs: toolSpecs(tools),
170
+ run: args.run,
164
171
  signal,
165
172
  onTextDelta: (delta) => emit({
166
173
  type: 'agent.turn.text_delta',
@@ -270,6 +277,12 @@ export const executeToolEffect = agentModule.effect({
270
277
  execute: (input, ctx) => Effect.gen(function* () {
271
278
  const threadId = ctx.threadId;
272
279
  const agents = yield* AgentDefinitionsTag;
280
+ const run = {
281
+ runId: ctx.runId,
282
+ threadId,
283
+ attributes: ctx.attributes,
284
+ secrets: ctx.secrets,
285
+ };
273
286
  const definition = input.definitionName
274
287
  ? yield* agents.resolve(input.definitionName, input.definitionVersion)
275
288
  : undefined;
@@ -289,9 +302,10 @@ export const executeToolEffect = agentModule.effect({
289
302
  ];
290
303
  }
291
304
  const resolved = yield* agentTools(definition, {
292
- threadId,
305
+ ...run,
293
306
  turn: input.turn,
294
307
  input: input.input ?? null,
308
+ ids: ctx.ids,
295
309
  }).pipe(Effect.match({
296
310
  onFailure: (error) => ({ ok: false, error: error.message }),
297
311
  onSuccess: (tools) => ({ ok: true, tools }),
@@ -328,10 +342,7 @@ export const executeToolEffect = agentModule.effect({
328
342
  ];
329
343
  }
330
344
  const result = yield* Effect.tryPromise({
331
- try: () => Promise.resolve(tool.handler(validated.value, {
332
- threadId,
333
- turn: input.turn,
334
- })),
345
+ try: () => Promise.resolve(tool.handler(validated.value, { ...run, turn: input.turn, signal: ctx.signal })),
335
346
  catch: (cause) => new AgentExecutionError(`run tool ${tool.name}`, cause),
336
347
  }).pipe(Effect.match({
337
348
  onFailure: (error) => ({ ok: false, error: error.message }),
@@ -380,7 +391,7 @@ export const executeToolEffect = agentModule.effect({
380
391
  ];
381
392
  }
382
393
  const childInput = tool.mapInput ? tool.mapInput(validated.value) : validated.value;
383
- const childThreadId = createThreadId();
394
+ const childThreadId = ctx.ids.create('thread');
384
395
  return [
385
396
  {
386
397
  type: 'agent.spawn.requested',
@@ -1,6 +1,6 @@
1
1
  import { Context, Effect, Layer } from 'effect';
2
2
  import { type JsonValue } from '@swirls/looms/core';
3
- import type { AgentTurnContext, AgentTurnResult, ToolLike } from './definitions';
3
+ import type { AgentRunContext, AgentTurnContext, AgentTurnResult, ToolLike } from './definitions';
4
4
  import type { Message, ToolCall } from './types';
5
5
  export interface LlmToolSpec {
6
6
  readonly name: string;
@@ -13,6 +13,8 @@ export interface LlmCompleteArgs {
13
13
  messages: Message[];
14
14
  tools: ToolLike[];
15
15
  toolSpecs?: LlmToolSpec[];
16
+ /** The run this call is made for, so an adapter can scope what it reads to the run's tenant. */
17
+ run: AgentRunContext;
16
18
  onTextDelta?: (delta: string) => void | Promise<void>;
17
19
  signal?: AbortSignal;
18
20
  }
@@ -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;
@@ -1,4 +1,4 @@
1
- import { type JsonValue, type RuntimeEffect } from '@swirls/looms/core';
1
+ import { type JsonValue, type LoomsIds, type RuntimeEffect } from '@swirls/looms/core';
2
2
  import type { ApprovalAction } from './events';
3
3
  export declare function gate(args: {
4
4
  title: string;
@@ -8,4 +8,6 @@ export declare function gate(args: {
8
8
  schema?: JsonValue;
9
9
  /** Absolute epoch milliseconds. Decision and timer waits race; the first wins. */
10
10
  timeoutAt?: number;
11
+ /** The id format to draw `approvalId` from. Pass `ctx.ids`. Defaults to `typeIds`. */
12
+ ids?: LoomsIds;
11
13
  }): RuntimeEffect[];
@@ -1,7 +1,7 @@
1
- import { createWaitId, invoke, wait } from '@swirls/looms/core';
1
+ import { createWaitId, invoke, typeIds, wait, } from '@swirls/looms/core';
2
2
  import { requestApprovalEffect } from './effects.js';
3
3
  export function gate(args) {
4
- const approvalId = args.approvalId ?? createWaitId('approval');
4
+ const approvalId = args.approvalId ?? (args.ids ?? typeIds).create('wait');
5
5
  const actions = args.actions ?? [
6
6
  { id: 'approve', label: 'Approve', outcome: 'approve' },
7
7
  { id: 'reject', label: 'Reject', outcome: 'reject' },
@@ -1,5 +1,5 @@
1
1
  import { Schema } from 'effect';
2
- import { type DefinitionInput, type DefinitionRef, type EventEnvelope, type EventInput, type HasRequiredAttributes, type JsonValue, type RunAttributeFields, type RunAttributesOption, type RunState, type SecretContext, type SubscriptionTransport, type TraceContext, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerSecretsResult } from '@swirls/looms/core';
2
+ import { type LoomsIds, type DefinitionInput, type DefinitionRef, type EventEnvelope, type EventInput, type HasRequiredAttributes, type JsonValue, type RunAttributeFields, type RunAttributesOption, type RunState, type SecretContext, type SubscriptionTransport, type TraceContext, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerSecretsResult } from '@swirls/looms/core';
3
3
  export interface LoomsClientOptions<Fields extends RunAttributeFields = RunAttributeFields> {
4
4
  baseUrl?: string;
5
5
  fetch?: typeof fetch;
@@ -11,6 +11,10 @@ export interface LoomsClientOptions<Fields extends RunAttributeFields = RunAttri
11
11
  grant?: string;
12
12
  /** Declared run attributes, from `defineRunAttributes`. Types `attributes` on starts. */
13
13
  attributes?: Fields;
14
+ /**
15
+ * The id format for the run id of a `stream` started without one. Match the host's `ids`. Defaults to `typeIds` (TypeID).
16
+ */
17
+ ids?: LoomsIds;
14
18
  }
15
19
  type ClientStartArgs<Fields extends RunAttributeFields> = {
16
20
  kind: string;
@@ -32,6 +36,8 @@ export interface StreamHandle extends AsyncIterable<EventEnvelope> {
32
36
  readonly runId: string;
33
37
  }
34
38
  export declare function createLoomsClient<const Fields extends RunAttributeFields = RunAttributeFields>(options?: LoomsClientOptions<Fields>): {
39
+ /** The id format this client draws from. */
40
+ ids: LoomsIds;
35
41
  /**
36
42
  * Start a run by `{ kind, definitionName }` when you only have names. Answers after the first
37
43
  * wake, so a short run can come back finished.
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect, Option, Predicate, Schema, Stream } from 'effect';
2
- import { createRunId, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, cleanUndefined, EventTypeCatalogSchema, JsonValueSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, SignalCatalogSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
2
+ import { resolveIds, DefinitionCatalogSchema, EffectCatalogSchema, EventEnvelopeSchema, cleanUndefined, EventTypeCatalogSchema, JsonValueSchema, readSubscriptionData, ReplayStepSchema, RunStateSchema, RunSummariesSchema, SecretContextSchema, SignalCatalogSchema, stringifyJson, traceHeaders, } from '@swirls/looms/core';
3
3
  import { consumeSseStreamEffect, eventsFromSseData, sseFrames } from './sse.js';
4
4
  class LoomsClientError extends Data.TaggedError('LoomsClientError') {
5
5
  constructor(message, cause) {
@@ -91,6 +91,7 @@ const PreviewEventsResultSchema = Schema.Struct({
91
91
  export function createLoomsClient(options = {}) {
92
92
  const baseUrl = (options.baseUrl ?? '').replace(/\/$/, '');
93
93
  const fetchImpl = options.fetch ?? fetch;
94
+ const ids = resolveIds(options.ids);
94
95
  function request(path, schema, init) {
95
96
  const headers = new Headers(init?.headers);
96
97
  if (!headers.has('content-type')) {
@@ -211,7 +212,7 @@ export function createLoomsClient(options = {}) {
211
212
  });
212
213
  const streamRun = (args) => {
213
214
  const { trace, ...body } = args;
214
- const runId = body.runId ?? createRunId();
215
+ const runId = body.runId ?? ids.create('run');
215
216
  const stream = Stream.unwrap(Effect.tryPromise({
216
217
  try: (signal) => fetchImpl(`${baseUrl}/runs`, {
217
218
  method: 'POST',
@@ -236,6 +237,8 @@ export function createLoomsClient(options = {}) {
236
237
  return Object.assign(Stream.toAsyncIterable(stream), { runId });
237
238
  };
238
239
  return {
240
+ /** The id format this client draws from. */
241
+ ids,
239
242
  /**
240
243
  * Start a run by `{ kind, definitionName }` when you only have names. Answers after the first
241
244
  * wake, so a short run can come back finished.
@@ -1,5 +1,5 @@
1
1
  import { DurableObject } from 'cloudflare:workers';
2
- import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type BlobStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot } from '@swirls/looms/core';
2
+ import { type AnyRuntimeModule, type DefinitionResolver, type EventInput, type BlobStore, type EventStoreTrimCoverage, type LaunchRunArgs, type RunAttributeFields, type RunLauncher, type RunState, type RunStatusSnapshot, type LoomsIds } from '@swirls/looms/core';
3
3
  import type { Projector } from '@swirls/looms/projectors';
4
4
  import { type Authorize, type EffectWorker, type RunSignalOptions, type StartResult, type StartRunArgs, type RuntimeObserver, type SecretProvider, type SecretSealer } from '@swirls/looms/runtime';
5
5
  import { type DeleteTerminalRunStorageOptions } from './delete-terminal-run-storage';
@@ -7,6 +7,8 @@ export interface LoomsDurableObjectConfig {
7
7
  readonly modules: readonly AnyRuntimeModule[];
8
8
  /** Loads definitions that were not registered on a module. See `CreateRuntimeOptions`. */
9
9
  readonly definitionResolver?: DefinitionResolver;
10
+ /** The id format. See `CreateRuntimeOptions.ids`. */
11
+ readonly ids?: LoomsIds;
10
12
  /** Declared run attributes. Pass the same declaration to the replica. */
11
13
  readonly attributes?: RunAttributeFields;
12
14
  /** Told about wakes, appends, snapshots and effect attempts. See `CreateRuntimeOptions`. */
@@ -53,6 +53,7 @@ export class LoomsDurableObject extends DurableObject {
53
53
  scheduler: alarms.scheduler,
54
54
  modules: config.modules,
55
55
  definitionResolver: config.definitionResolver,
56
+ ids: config.ids,
56
57
  attributes: config.attributes,
57
58
  observer: config.observer,
58
59
  secretProvider: config.secretProvider,
@@ -1,5 +1,5 @@
1
1
  import { Effect } from 'effect';
2
- import { type BlobStore, type EventInput, type JsonValue, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerEffectContext, type WorkerEffectDefinition, type WorkerSecretsResult } from '@swirls/looms/core';
2
+ import { type BlobStore, type EventInput, type JsonValue, type WorkerCallback, type WorkerCallbackInput, type WorkerCallbackResult, type WorkerEffectContext, type WorkerEffectDefinition, type WorkerSecretsResult, type LoomsIds } from '@swirls/looms/core';
3
3
  import { type QueueEffectMessage, type QueueMessageLike } from './queue-message';
4
4
  /** The worker half of the Looms HTTP API. `createLoomsClient({ baseUrl, workerCallbackToken })` is one. */
5
5
  export interface WorkerCallbackClient {
@@ -43,6 +43,8 @@ export interface QueueConsumerOptions {
43
43
  readonly callbacks: WorkerCallbackClient;
44
44
  /** Reads inputs the producer offloaded. Use the store the producer writes to. */
45
45
  readonly blobs?: BlobStore;
46
+ /** The id format handlers see as `ctx.ids`. Match the host's `ids`. Defaults to `typeIds`. */
47
+ readonly ids?: LoomsIds;
46
48
  }
47
49
  export interface QueueBatchLike {
48
50
  readonly messages: ReadonlyArray<QueueMessageLike>;
@@ -1,5 +1,5 @@
1
1
  import { Data, Effect } from 'effect';
2
- import { resolveJson, validateInput, } from '@swirls/looms/core';
2
+ import { resolveJson, validateInput, resolveIds, } from '@swirls/looms/core';
3
3
  import { readQueueEffectMessage, } from './queue-message.js';
4
4
  /**
5
5
  * Build a `handlers` map from **worker-placed** effect definitions. Input is validated with each
@@ -93,6 +93,7 @@ function runAttempt(task, attempt, handler, cancelRequested, options) {
93
93
  attributes: task.attributes ?? {},
94
94
  secrets,
95
95
  trace: task.trace ?? null,
96
+ ids: resolveIds(options.ids),
96
97
  heartbeat: (details) => Effect.runPromise(callback(() => options.callbacks.workerCallback(task.runId, details === undefined
97
98
  ? { ...attempt, kind: 'heartbeat' }
98
99
  : { ...attempt, kind: 'heartbeat', details })).pipe(Effect.map((result) => {
@@ -1,4 +1,4 @@
1
- import type { AnyRuntimeModule } from '@swirls/looms/core';
1
+ import type { AnyRuntimeModule, LoomsIds } from '@swirls/looms/core';
2
2
  import { type AuthDecision, type RouteInfo } from '@swirls/looms/runtime';
3
3
  export interface DurableObjectStubLike {
4
4
  fetch(request: Request): Promise<Response>;
@@ -26,4 +26,6 @@ export type RouteAuthorize = (request: Request, route: RouteInfo) => AuthDecisio
26
26
  export declare function routeToDurableObject(namespace: DurableObjectNamespaceLike, req: Request, options?: {
27
27
  readonly modules?: readonly AnyRuntimeModule[] | (() => readonly AnyRuntimeModule[]);
28
28
  readonly authorize?: RouteAuthorize;
29
+ /** The id format for a run started without a `runId`. Match the Durable Object's `ids`. */
30
+ readonly ids?: LoomsIds;
29
31
  }): Promise<Response | null>;