effect-assistant 0.13.1 → 0.14.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.
- package/dist/Assistant.d.ts +3 -3
- package/dist/Assistant.d.ts.map +1 -1
- package/dist/Assistant.js +1 -1
- package/dist/Assistant.js.map +1 -1
- package/dist/AssistantEngine.d.ts +2 -2
- package/dist/AssistantEngine.d.ts.map +1 -1
- package/dist/AssistantEngine.js +8 -8
- package/dist/AssistantEngine.js.map +1 -1
- package/dist/ChatSignal.js +1 -1
- package/dist/ChatSignal.js.map +1 -1
- package/dist/Timeline.d.ts +5 -1
- package/dist/Timeline.d.ts.map +1 -1
- package/dist/Timeline.js +12 -2
- package/dist/Timeline.js.map +1 -1
- package/package.json +1 -1
- package/src/Assistant.ts +10 -7
- package/src/AssistantEngine.ts +10 -10
- package/src/ChatSignal.ts +1 -1
- package/src/Timeline.ts +14 -2
package/dist/Assistant.d.ts
CHANGED
|
@@ -305,15 +305,15 @@ export interface Service<Events = never> {
|
|
|
305
305
|
*/
|
|
306
306
|
readonly subscribe: {
|
|
307
307
|
(chatId: ChatId, options?: SubscribeOptions & {
|
|
308
|
-
readonly
|
|
308
|
+
readonly signals?: false | undefined;
|
|
309
309
|
}): Stream.Stream<Entry<Events>>;
|
|
310
310
|
/**
|
|
311
|
-
* With `
|
|
311
|
+
* With `signals: true`, the stream also has the chat's signals (see `ChatSignal`): the status of
|
|
312
312
|
* what a turn is doing, and whether a message to the user is on its way. They come in order
|
|
313
313
|
* with the entries, only while the stream runs, and are never stored.
|
|
314
314
|
*/
|
|
315
315
|
(chatId: ChatId, options: SubscribeOptions & {
|
|
316
|
-
readonly
|
|
316
|
+
readonly signals: true;
|
|
317
317
|
}): Stream.Stream<Entry<Events> | ChatSignal>;
|
|
318
318
|
};
|
|
319
319
|
/**
|
package/dist/Assistant.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Assistant.d.ts","names":[],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AAO,MAAM,MAAM,SAAS,OAAO;;;;;;;;YASzC,MAAM;;;;;;;qBAQL,cAAW,eAAiB,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAqDjC,aACL,2BACA,cAAc,cAAc,4BAC5B,eAAe,cAAc,+BAA4C,MAEzE,MAAI;;WAGC,SAAS;;;;;WAKT,cAAc;;;;;;;WAOd,SAAS;MAEnB,UAAU,MAAM,eAAe"}
|
package/dist/Assistant.js
CHANGED
|
@@ -115,7 +115,7 @@ const make = (name, options) => {
|
|
|
115
115
|
const chats = yield* Chats;
|
|
116
116
|
const decode = (item) => isChatSignal(item) ? Option.some(item) : decodeEntry(definition.app, item);
|
|
117
117
|
function subscribe(chatId, options) {
|
|
118
|
-
return engine.subscribe(name, chatId, options?.after ?? 0, options?.
|
|
118
|
+
return engine.subscribe(name, chatId, options?.after ?? 0, options?.signals === true).pipe(Stream.filterMap(Filter.fromPredicateOption(decode)));
|
|
119
119
|
}
|
|
120
120
|
return Key.of({
|
|
121
121
|
submit: Effect.fn("Assistant.submit")(function* (chatId, input) {
|
package/dist/Assistant.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Assistant.js","names":["Telemetry.TurnTracer","AssistantEvent.AssistantEvent","AppEvents.make","AssistantEvent.isInput","AppEvents.encode","Chats.Chats","ChatSignal.isChatSignal","AppEvents.decodeEntry","Telemetry.withoutTracing","Turns.register"],"sources":["../src/Assistant.ts"],"sourcesContent":["/**\n * This module provides `Assistant.make`, which defines an assistant that works in a chat the way a\n * colleague does: the user messages it, it works in the background with the app's tools, and it\n * messages the user back.\n *\n * A definition is what the rest of an app imports. Yielding it (`yield* MyAssistant`) returns the\n * assistant's {@link Service}, which submits inputs to chats and streams them back. Its `toLayer`\n * registers the handler that runs each {@link Turn} with the `AssistantEngine`, and its\n * `layerClient` provides the service without a handler. Code that runs inside a chat reads and\n * extends that chat through the definition's {@link Chat} key.\n *\n * @since 0.1.0\n */\nimport type * as AiError from \"effect/ai/AiError\"\nimport type * as LanguageModel from \"effect/ai/LanguageModel\"\nimport type * as Prompt from \"effect/ai/Prompt\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Filter from \"effect/Filter\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Tracer from \"effect/Tracer\"\nimport { AssistantEngine } from \"./AssistantEngine.ts\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport type * as AssistantLoop from \"./AssistantLoop.ts\"\nimport type * as BlockKit from \"./BlockKit.ts\"\nimport { ChatId } from \"./ChatId.ts\"\nimport * as ChatSignal from \"./ChatSignal.ts\"\nimport * as Chats from \"./Chats.ts\"\nimport type { CurrentChat } from \"./CurrentChat.ts\"\nimport type * as Instructions from \"./Instructions.ts\"\nimport * as AppEvents from \"./internal/events.ts\"\nimport * as Telemetry from \"./internal/telemetry.ts\"\nimport * as Turns from \"./internal/turns.ts\"\nimport type * as Specialist from \"./Specialist.ts\"\n\nconst TypeId = \"~effect-assistant/Assistant\" as const\n\n/**\n * Represents the services that a turn provides to its tools, its loop, and its specialists. These\n * are the turn's chat (`CurrentChat`) and the chat's specialist runner (`Specialist.Runner`).\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type TurnServices = CurrentChat | Specialist.Runner\n\n/**\n * Represents the options accepted by `turn.run`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface RunOptions<T extends Record<string, Tool.Any> = Record<never, never>, Events = never> {\n /** The assistant's role and rules. The loop places `Instructions.protocol` before them. */\n readonly instructions: string | Instructions.Resolved\n /**\n * Tools the model can use in addition to the assistant's own. This is an `effect/ai` toolkit,\n * and its handlers come from the layer. Combine several toolkits with `Toolkit.merge`, for\n * example `Memory.Tools`, a `Skill.toolkit(...)`, or a `ToolDiscovery.make(...)` toolkit together\n * with your own.\n */\n readonly toolkit?: Toolkit.Toolkit<T> | undefined\n /** The maximum number of model calls per turn. Defaults to 16. */\n readonly maxSteps?: number | undefined\n /** The message the reply pass gives the model when the turn would end without a reply. */\n readonly replyNudge?: string | undefined\n /**\n * Selects which of the chat's entries the model reads, for example only those since the last\n * summary, and maps the app's own events it should read into prompt messages. Defaults to all\n * entries, without the app's events.\n */\n readonly history?: HistoryView<Events> | undefined\n}\n\n/**\n * Represents a function that selects which of a chat's entries the model reads, and what else it\n * reads with them.\n *\n * **Details**\n *\n * The function receives the chat's entries, the app's own events among them, and returns, in\n * order, a mix of entries and `Prompt.Message`s. The model reads the returned entries the same way\n * it reads the full history, and reads each prompt message unchanged, where the view put it. The\n * model reads none of the app's events by itself: map those it should read to a message, and an\n * app event's entry left in the result is dropped.\n *\n * A message stands right after the entry before it: one that came after the model's last read, or\n * between a tool call and its result, moves after them, as an input does.\n *\n * **Example** (Telling the model about an order the user placed)\n *\n * ```ts\n * import { Assistant, InputId } from \"effect-assistant\"\n * import * as Prompt from \"effect/ai/Prompt\"\n * import * as Schema from \"effect/Schema\"\n *\n * class OrderPlaced extends Schema.TaggedClass<OrderPlaced>()(\"OrderPlaced\", {\n * id: InputId.InputId,\n * reference: Schema.String\n * }) {}\n *\n * const MyAssistant = Assistant.make(\"my-assistant\", { events: [OrderPlaced] })\n *\n * const withOrders: Assistant.HistoryView<OrderPlaced> = (entries) =>\n * entries.map((entry) =>\n * entry.event instanceof OrderPlaced\n * ? Prompt.userMessage({\n * content: [Prompt.textPart({ text: `The user placed order ${entry.event.reference}.` })]\n * })\n * : entry\n * )\n *\n * // An `OrderPlaced` that the API submits wakes a turn, which reads it as this note.\n * const MyAssistantLive = MyAssistant.toLayer((turn) =>\n * turn.run({ instructions: \"Be brief.\", history: withOrders })\n * )\n * ```\n *\n * @category models\n * @since 0.1.0\n */\nexport type HistoryView<Events = never> = (\n entries: ReadonlyArray<Entry<Events>>\n) => ReadonlyArray<Entry<Events> | Prompt.Message>\n\n/**\n * Represents an entry in a chat's log, with the assistant's own events decoded to their types.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Entry<Events = never> {\n readonly chatId: ChatId\n readonly sequence: number\n readonly at: number\n readonly event: AssistantEvent.AssistantEvent | Events\n}\n\n/**\n * Represents the options accepted by `turn.replyIfOwed`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ReplyOptions {\n /** The assistant's instructions, as passed to `turn.run`. `Instructions.protocol` is added. */\n readonly instructions: string | Instructions.Resolved\n /**\n * The message given to the model after the history. Defaults to a message saying that it\n * hasn't replied yet and should reply now.\n */\n readonly nudge?: string | undefined\n}\n\n/**\n * Represents one turn, as the assistant's handler receives it.\n *\n * `Events` is the type of the app's own events that the assistant registered with its `events`\n * option.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Turn<Events = never> {\n readonly chatId: ChatId\n /**\n * Returns the model's history, built from the chat's entries (all of them, or those a view\n * keeps), together with how far into the chat it reaches.\n *\n * Read it before every model call, as the loop does. Each step records how far its model call\n * read, and the turn ends once it has handled what the model saw. An input that arrived after\n * that is handled by the next turn.\n */\n readonly history: (view?: HistoryView<Events>) => Effect.Effect<AssistantLoop.ChatHistory>\n /**\n * Returns the full system prompt for the given instructions. It contains\n * `Instructions.protocol`, the instructions, and the specialist runs that are working now.\n */\n readonly instructions: (instructions: string | Instructions.Resolved) => Instructions.Resolved\n /**\n * Runs the agent loop over the chat. The loop uses `Instructions.protocol`, the assistant's own\n * tools, and the instructions and tools in `options`. Every step is a tool call, and\n * the loop ends with `replyIfOwed`.\n */\n readonly run: <T extends Record<string, Tool.Any> = Record<never, never>>(\n options: RunOptions<T, Events>\n ) => Stream.Stream<\n AssistantLoop.Event,\n AiError.AiError,\n LanguageModel.LanguageModel | TurnServices | AssistantLoop.ToolkitServices<T>\n >\n /**\n * Runs one more pass when the turn would otherwise end without a reply to the user's latest\n * message. In this pass the model can only reply.\n *\n * The stream is empty when no reply is owed, or when an input arrived that the next turn will\n * read. `run` runs this pass with its own prompt and tools, so the pass reuses the cached\n * prompt.\n */\n readonly replyIfOwed: (\n options: ReplyOptions\n ) => Stream.Stream<AssistantLoop.Event, AiError.AiError, LanguageModel.LanguageModel | TurnServices>\n}\n\n/**\n * Represents an assistant's handler, which runs a turn and returns it as a stream of the loop's\n * events.\n *\n * The handler may return the stream directly or from an Effect. `R` is the services the stream\n * requires, and `RE` is the services the Effect requires.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Handler<R = never, RE = R, Events = never> = (\n turn: Turn<Events>\n) =>\n | Stream.Stream<AssistantLoop.Event, unknown, R>\n | Effect.Effect<Stream.Stream<AssistantLoop.Event, unknown, R>, unknown, RE>\n\n/**\n * Computes the services an assistant's handler needs beyond those its turns provide (the turn\n * services and `LanguageModel`) and its tools' handlers (which its layer requires). These are the\n * services that its build Effect must require.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type HandlerServices<R> = Exclude<R, TurnServices | LanguageModel.LanguageModel | Tool.Handler<string>>\n\nconst toStream = <R, RE>(\n result:\n | Stream.Stream<AssistantLoop.Event, unknown, R>\n | Effect.Effect<Stream.Stream<AssistantLoop.Event, unknown, R>, unknown, RE>\n): Stream.Stream<AssistantLoop.Event, unknown, R | RE> => (Effect.isEffect(result) ? Stream.unwrap(result) : result)\n\n/**\n * Sets the tracer that an assistant's turns and specialist runs record their spans with. Each\n * turn's `invoke_agent` span is then the root of a trace on that tracer, with the turn's model\n * calls and tool calls below it. By default they use the tracer of the fiber that runs them.\n *\n * Provide it to the assistant's layer to send the agent's work to its own backend, such as an LLM\n * observability tool, while the rest of the app traces elsewhere.\n *\n * @example\n * ```ts\n * const AgentTracer = Layer.effect(\n * Assistant.TurnTracer,\n * OtlpTracer.make({ url: \"https://llm-observability.example.com/v1/traces\" }).pipe(Effect.map(Option.some))\n * )\n *\n * const MyAssistantLive = MyAssistant.toLayer(handler).pipe(Layer.provide(AgentTracer))\n * ```\n *\n * @category references\n * @since 0.12.0\n */\nexport const TurnTracer: Context.Reference<Option.Option<Tracer.Tracer>> = Telemetry.TurnTracer\n\n/**\n * Identifies an assistant's service in a context. Each assistant has its own identifier, keyed by\n * its name.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Identifier<Name extends string> {\n readonly \"~effect-assistant/Assistant\": Name\n}\n\n/**\n * Identifies, in a context, the chat that an assistant's turns run in.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ChatIdentifier<Name extends string> {\n readonly \"~effect-assistant/Assistant/Chat\": Name\n}\n\n/**\n * Represents the chat that a turn of this assistant runs in, typed with the assistant's events.\n *\n * Use `yield* MyAssistant.Chat` in the handler, in the handler's build, or in a tool that its\n * turns run. Code that doesn't know the assistant uses `CurrentChat` instead.\n *\n * @see {@link CurrentChat} for the same chat without the assistant's event types\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Chat<Events = never> {\n readonly chatId: ChatId\n /**\n * The chat's entries so far, in order. They include the library's events and the assistant's\n * own events, typed.\n */\n readonly entries: Effect.Effect<ReadonlyArray<Entry<Events>>>\n /**\n * Appends events after the chat's last entry and sends them to the chat's subscribers. The\n * events can be the library's or the assistant's own, such as a summary. None of them wakes a\n * turn: only what comes in through the assistant's `submit` does.\n */\n append(...events: ReadonlyArray<AssistantEvent.AssistantEvent | Events>): Effect.Effect<void>\n}\n\n/**\n * Represents the options accepted by an assistant's `subscribe`.\n *\n * @category models\n * @since 0.13.0\n */\nexport interface SubscribeOptions {\n /** The `sequence` after which the stream starts. Defaults to `0`, the whole log. */\n readonly after?: number | undefined\n}\n\n/**\n * Represents the service that `yield* MyAssistant` returns. It gives code outside a chat, such as\n * a server or a workflow, access to the assistant's chats. Code that runs inside a chat uses\n * `CurrentChat` instead.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Service<Events = never> {\n /**\n * Stores an input or one of the assistant's own events, then returns. Examples are a user's\n * message or block answer, a workflow's progress, or the order the user placed. Each one is an\n * input: storing it wakes a turn, which the assistant runs in the background. The handler decides\n * what the turn does with it, and an app event the model should read needs a history view that\n * maps it (see {@link HistoryView}). To store an app event without waking a turn, append it from\n * within the chat instead (`yield* MyAssistant.Chat`).\n *\n * Fails with `GetChatError` when the app's `Chats` service reports that the chat can't be used,\n * because the app doesn't know the chat or has deleted it.\n */\n // Method syntax: a service for these events is one for any (`Service<any>`), for helpers over assistants.\n submit(chatId: ChatId, input: AssistantEvent.Input | Events): Effect.Effect<void, Chats.GetChatError>\n /**\n * Streams the chat's stored entries, then live ones, with the assistant's own events decoded.\n * A reader that already has the earlier entries passes `after` and receives only the entries\n * after that `sequence`.\n *\n * For a chat client, pipe the whole log into `Timeline.changes(MyAssistant, { after })`, which\n * streams the chat's timeline, as its user sees it. Its `after` goes there, not here: a message\n * on the timeline depends on earlier entries. The timeline shows only the app events named in its\n * `show`, none by default (see `Timeline.changes`).\n */\n readonly subscribe: {\n (chatId: ChatId, options?: SubscribeOptions & { readonly live?: false | undefined }): Stream.Stream<Entry<Events>>\n /**\n * With `live: true`, the stream also has the chat's signals (see `ChatSignal`): the status of\n * what a turn is doing, and whether a message to the user is on its way. They come in order\n * with the entries, only while the stream runs, and are never stored.\n */\n (\n chatId: ChatId,\n options: SubscribeOptions & { readonly live: true }\n ): Stream.Stream<Entry<Events> | ChatSignal.ChatSignal>\n }\n /**\n * Deletes a chat by storing a `ChatDeleted` event and stopping everything that works in it.\n *\n * **Details**\n *\n * A turn or specialist run working in the chat stops, and subscribers' streams end with the\n * `ChatDeleted` event. After that the chat stores nothing more: a later input, a run's report,\n * or a workflow's event for it is dropped without an error. The log is kept, and removing it is\n * up to the app. Deleting a chat a second time does nothing.\n *\n * When the app's `Chats` service reports a chat as deleted, the assistant deletes it in the same\n * way the next time it checks. It checks before an input is stored and before each model call.\n */\n readonly delete: (chatId: ChatId) => Effect.Effect<void>\n}\n\n/**\n * Represents an assistant's definition.\n *\n * The definition holds what callers and the UI need to know about the assistant, builds its\n * handler's layer, and is the key of its service (`yield* MyAssistant`). `Events` is the type of\n * the app's own events that the assistant registered.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Assistant<\n Name extends string = string,\n Specs extends Specialist.Any = never,\n Events = never\n> extends Context.Service<Identifier<Name>, Service<Events>> {\n readonly [TypeId]: typeof TypeId\n readonly name: Name\n readonly blocks: BlockKit.BlockKit | undefined\n /** The specialists the assistant can hand work to. */\n readonly specialists: ReadonlyArray<Specs>\n /** The schemas of the app's own events the assistant stores. */\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n /**\n * Creates a layer that registers the assistant's handler with the engine and provides the\n * assistant's service.\n *\n * **Details**\n *\n * `build` is the handler, or an Effect that returns it. The handler may use the turn services,\n * `LanguageModel`, its tools' handlers (which the layer then requires), and services that its\n * build Effect required (see `Specialist.CheckServices`). The layer requires the\n * `AssistantEngine`, the `LanguageModel`, and each specialist's handler\n * (`Research.toLayer(...)`).\n *\n * **Example** (Providing an assistant's handler)\n *\n * ```ts\n * import { Assistant, AssistantEngine, ChatLog } from \"effect-assistant\"\n * import type * as LanguageModel from \"effect/ai/LanguageModel\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const MyAssistantLive = MyAssistant.toLayer((turn) =>\n * turn.run({ instructions: \"You help a small team. Be brief.\" })\n * )\n *\n * const AppLive = MyAssistantLive.pipe(\n * Layer.provide(ModelLive),\n * Layer.provideMerge(AssistantEngine.layerMemory),\n * Layer.provideMerge(ChatLog.layerMemory)\n * )\n * ```\n */\n readonly toLayer: <R = never, RE = never, E = never, RX = never>(\n build: (Handler<R, RE, Events> | Effect.Effect<Handler<R, RE, Events>, E, RX>) &\n Specialist.CheckServices<Exclude<HandlerServices<R | RE>, RX | ChatIdentifier<Name>>>\n ) => Layer.Layer<\n Identifier<Name>,\n never,\n | AssistantEngine\n | LanguageModel.LanguageModel\n | Specialist.HandlerOf<Specs>\n | Exclude<RX, Scope.Scope | CurrentChat | ChatIdentifier<Name>>\n | Specialist.ToolHandlers<R | RE>\n >\n /**\n * A layer that provides the assistant's service without its handler.\n *\n * **When to use**\n *\n * Use it in a process that submits to chats that another process runs, such as a web server in\n * front of a cluster.\n *\n * **Example** (Serving clients in front of a cluster)\n *\n * ```ts\n * import { Assistant, AssistantEngine } from \"effect-assistant\"\n * import * as Layer from \"effect/Layer\"\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * // Requires `Sharding`. The cluster's runners run the chats, with `AssistantEngine.layerCluster`.\n * const MyAssistantClient = MyAssistant.layerClient.pipe(\n * Layer.provide(AssistantEngine.layerClusterClient)\n * )\n * ```\n */\n readonly layerClient: Layer.Layer<Identifier<Name>, never, AssistantEngine>\n /**\n * The key of the chat that the assistant's turns run in, typed with its events. See\n * {@link Chat}.\n */\n readonly Chat: Context.Service<ChatIdentifier<Name>, Chat<Events>>\n /** A schema that encodes the chat's entries to JSON, including the assistant's own events. */\n readonly Entry: Schema.Codec<Entry<Events>, Schema.Json>\n}\n\n/**\n * Represents any assistant, for use in generic constraints.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type Any = Assistant<any, any, any>\n\n/**\n * Returns `true` when the value is an assistant's definition, created with {@link make}.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isAssistant = (u: unknown): u is Any => Predicate.hasProperty(u, TypeId)\n\nfunction entrySchema<E>(events: ReadonlyArray<AssistantEvent.AppEventSchema>): Schema.Codec<Entry<E>, Schema.Json>\n// The overload states the decoded type: the library's events, or one of these schemas' types.\nfunction entrySchema(events: ReadonlyArray<AssistantEvent.AppEventSchema>): Schema.Top {\n return Schema.toCodecJson(\n Schema.Struct({\n chatId: ChatId,\n sequence: Schema.Int,\n at: Schema.Finite,\n event: Schema.Union([AssistantEvent.AssistantEvent, ...events])\n })\n )\n}\n\n/**\n * Creates an assistant definition from its name, its UI blocks, its specialists, and the schemas of\n * the app's own events it stores.\n *\n * **Details**\n *\n * The definition holds no code that runs turns. Provide a handler with its `toLayer`, then yield\n * the definition to get the assistant's {@link Service}.\n *\n * The definition only says which of the app's events a chat stores. What happens with one is up\n * to the places that use it. One that comes in through the service's `submit`, from outside a\n * turn, is an input and wakes a turn, like a user's message; one a turn appends to its chat never\n * does. The handler decides what a turn does, a history view says how the model reads an event\n * ({@link HistoryView}), and the chat's timeline says which its user sees\n * (`Timeline.changes`).\n *\n * **Example** (Defining an assistant and submitting a message)\n *\n * ```ts\n * import { Assistant, AssistantEvent, ChatId } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const program = Effect.gen(function* () {\n * const assistant = yield* MyAssistant\n * const chatId = yield* ChatId.make()\n *\n * yield* assistant.submit(chatId, AssistantEvent.UserMessage.make({ text: \"Weather in Oslo?\" }))\n * })\n * ```\n *\n * @see {@link Assistant} for the definition's members\n * @see {@link Service} for what `yield* MyAssistant` returns\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <\n const Name extends string,\n const Specs extends ReadonlyArray<Specialist.Any> = readonly [],\n const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []\n>(\n name: Name,\n options?: {\n /** UI blocks the assistant can add to its messages. */\n readonly blocks?: BlockKit.BlockKit | undefined\n /**\n * The specialists the assistant can hand work to. Each specialist's `toLayer` must be\n * provided to the assistant's layer.\n */\n readonly specialists?: Specs | undefined\n /**\n * The schemas of the app's own events, each a tagged struct or class. `submit` and the chat's\n * `append` store them, in their JSON form, and the chat's `entries` and `subscribe` read them\n * back, decoded. Each needs a tag of its own that isn't one of the library's: `make` throws\n * otherwise.\n */\n readonly events?: Events | undefined\n }\n): Assistant<Name, Specs[number], Events[number][\"Type\"]> => {\n const events = options?.events ?? []\n\n const definition: Turns.Definition = {\n name,\n blocks: options?.blocks,\n specialists: options?.specialists ?? [],\n app: AppEvents.make(events)\n }\n\n type OwnEvents = Events[number][\"Type\"]\n\n const Key = Context.Service<Identifier<Name>, Service<OwnEvents>>(`effect-assistant/Assistant/${name}`)\n\n // The app's own events go to the engine encoded, as they're stored; the library's go unchanged.\n const stored = (\n input: AssistantEvent.Input | OwnEvents\n ): Effect.Effect<AssistantEvent.Input | AssistantEvent.StoredAppEvent> =>\n AssistantEvent.isInput(input) ? Effect.succeed(input) : AppEvents.encode(definition.app, input)\n\n const ChatKey = Context.Service<ChatIdentifier<Name>, Chat<OwnEvents>>(`effect-assistant/Assistant/${name}/Chat`)\n\n // On the engine and the app's `Chats` the layer was given, so every caller sees the same ones.\n const makeService = Effect.gen(function* () {\n const engine = yield* AssistantEngine\n const chats = yield* Chats.Chats\n\n const decode = (\n item: AssistantEvent.Entry | ChatSignal.ChatSignal\n ): Option.Option<Entry<OwnEvents> | ChatSignal.ChatSignal> =>\n ChatSignal.isChatSignal(item) ? Option.some(item) : AppEvents.decodeEntry(definition.app, item)\n\n function subscribe(\n chatId: ChatId,\n options?: SubscribeOptions & { readonly live?: false | undefined }\n ): Stream.Stream<Entry<OwnEvents>>\n function subscribe(\n chatId: ChatId,\n options: SubscribeOptions & { readonly live: true }\n ): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal>\n function subscribe(\n chatId: ChatId,\n options?: SubscribeOptions & { readonly live?: boolean | undefined }\n ): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal> {\n return engine\n .subscribe(name, chatId, options?.after ?? 0, options?.live === true)\n .pipe(Stream.filterMap(Filter.fromPredicateOption(decode)))\n }\n\n return Key.of({\n submit: Effect.fn(\"Assistant.submit\")(function* (chatId: ChatId, input: AssistantEvent.Input | OwnEvents) {\n // Checked here, where the caller can handle it: the chat checks again when it stores the input.\n yield* chats.get(chatId)\n yield* engine.submit(name, chatId, yield* stored(input))\n }),\n subscribe,\n delete: (chatId) => engine.delete(name, chatId)\n })\n })\n\n // The signature checks what the handler uses (`CheckServices`); the layer's services, which the build\n // required, are provided to it and to every turn's stream, so what's left is the turn services.\n function toLayer<R = never, RE = never, E = never, RX = never>(\n build: (Handler<R, RE, OwnEvents> | Effect.Effect<Handler<R, RE, OwnEvents>, E, RX>) &\n Specialist.CheckServices<Exclude<HandlerServices<R | RE>, RX | ChatIdentifier<Name>>>\n ): Layer.Layer<\n Identifier<Name>,\n never,\n | AssistantEngine\n | LanguageModel.LanguageModel\n | Specialist.HandlerOf<Specs[number]>\n | Exclude<RX, Scope.Scope | CurrentChat | ChatIdentifier<Name>>\n | Specialist.ToolHandlers<R | RE>\n >\n function toLayer(\n build: Handler<any, any, any> | Effect.Effect<Handler<any, any, any>, unknown, any>\n ): Layer.Layer<Identifier<Name>, never, any> {\n return Layer.effect(\n Key,\n Effect.gen(function* () {\n // Without the layer's scope: what a build or a turn sets up lives as long as the chat or the turn.\n const context = yield* Effect.context().pipe(\n Effect.map(Context.omit(Scope.Scope)),\n Effect.map(Telemetry.withoutTracing)\n )\n\n const registration = yield* Turns.register(definition, {\n // The build runs per chat activation, in the chat; here it only keeps the layer's services for it.\n open: (typed) =>\n Effect.gen(function* () {\n // The chat's entries are already decoded with this assistant's events.\n const chat = ChatKey.of({ chatId: typed.chatId, entries: typed.entries, append: typed.append })\n const handler = Effect.isEffect(build) ? yield* Effect.provideService(build, ChatKey, chat) : build\n\n return (turn: Turn<any>) =>\n Stream.provide(toStream(handler(turn)), context).pipe(Stream.provideService(ChatKey, chat))\n }).pipe(Effect.provide(context), Effect.orDie)\n })\n\n yield* (yield* AssistantEngine).register(registration)\n\n return yield* makeService\n })\n )\n }\n\n // The key is a function, whose own `name` is read-only: the assistant's name replaces it.\n const named = Object.defineProperty(Key, \"name\", { value: name, writable: true })\n\n return Object.assign(named, {\n [TypeId]: TypeId,\n name,\n blocks: options?.blocks,\n specialists: options?.specialists ?? [],\n events,\n toLayer,\n layerClient: Layer.effect(Key, makeService),\n Chat: ChatKey,\n Entry: entrySchema<OwnEvents>(events)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;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|
|
1
|
+
{"version":3,"file":"Assistant.js","names":["Telemetry.TurnTracer","AssistantEvent.AssistantEvent","AppEvents.make","AssistantEvent.isInput","AppEvents.encode","Chats.Chats","ChatSignal.isChatSignal","AppEvents.decodeEntry","Telemetry.withoutTracing","Turns.register"],"sources":["../src/Assistant.ts"],"sourcesContent":["/**\n * This module provides `Assistant.make`, which defines an assistant that works in a chat the way a\n * colleague does: the user messages it, it works in the background with the app's tools, and it\n * messages the user back.\n *\n * A definition is what the rest of an app imports. Yielding it (`yield* MyAssistant`) returns the\n * assistant's {@link Service}, which submits inputs to chats and streams them back. Its `toLayer`\n * registers the handler that runs each {@link Turn} with the `AssistantEngine`, and its\n * `layerClient` provides the service without a handler. Code that runs inside a chat reads and\n * extends that chat through the definition's {@link Chat} key.\n *\n * @since 0.1.0\n */\nimport type * as AiError from \"effect/ai/AiError\"\nimport type * as LanguageModel from \"effect/ai/LanguageModel\"\nimport type * as Prompt from \"effect/ai/Prompt\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Filter from \"effect/Filter\"\nimport * as Layer from \"effect/Layer\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Tracer from \"effect/Tracer\"\nimport { AssistantEngine } from \"./AssistantEngine.ts\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport type * as AssistantLoop from \"./AssistantLoop.ts\"\nimport type * as BlockKit from \"./BlockKit.ts\"\nimport { ChatId } from \"./ChatId.ts\"\nimport * as ChatSignal from \"./ChatSignal.ts\"\nimport * as Chats from \"./Chats.ts\"\nimport type { CurrentChat } from \"./CurrentChat.ts\"\nimport type * as Instructions from \"./Instructions.ts\"\nimport * as AppEvents from \"./internal/events.ts\"\nimport * as Telemetry from \"./internal/telemetry.ts\"\nimport * as Turns from \"./internal/turns.ts\"\nimport type * as Specialist from \"./Specialist.ts\"\n\nconst TypeId = \"~effect-assistant/Assistant\" as const\n\n/**\n * Represents the services that a turn provides to its tools, its loop, and its specialists. These\n * are the turn's chat (`CurrentChat`) and the chat's specialist runner (`Specialist.Runner`).\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type TurnServices = CurrentChat | Specialist.Runner\n\n/**\n * Represents the options accepted by `turn.run`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface RunOptions<T extends Record<string, Tool.Any> = Record<never, never>, Events = never> {\n /** The assistant's role and rules. The loop places `Instructions.protocol` before them. */\n readonly instructions: string | Instructions.Resolved\n /**\n * Tools the model can use in addition to the assistant's own. This is an `effect/ai` toolkit,\n * and its handlers come from the layer. Combine several toolkits with `Toolkit.merge`, for\n * example `Memory.Tools`, a `Skill.toolkit(...)`, or a `ToolDiscovery.make(...)` toolkit together\n * with your own.\n */\n readonly toolkit?: Toolkit.Toolkit<T> | undefined\n /** The maximum number of model calls per turn. Defaults to 16. */\n readonly maxSteps?: number | undefined\n /** The message the reply pass gives the model when the turn would end without a reply. */\n readonly replyNudge?: string | undefined\n /**\n * Selects which of the chat's entries the model reads, for example only those since the last\n * summary, and maps the app's own events it should read into prompt messages. Defaults to all\n * entries, without the app's events.\n */\n readonly history?: HistoryView<Events> | undefined\n}\n\n/**\n * Represents a function that selects which of a chat's entries the model reads, and what else it\n * reads with them.\n *\n * **Details**\n *\n * The function receives the chat's entries, the app's own events among them, and returns, in\n * order, a mix of entries and `Prompt.Message`s. The model reads the returned entries the same way\n * it reads the full history, and reads each prompt message unchanged, where the view put it. The\n * model reads none of the app's events by itself: map those it should read to a message, and an\n * app event's entry left in the result is dropped.\n *\n * A message stands right after the entry before it: one that came after the model's last read, or\n * between a tool call and its result, moves after them, as an input does.\n *\n * **Example** (Telling the model about an order the user placed)\n *\n * ```ts\n * import { Assistant, InputId } from \"effect-assistant\"\n * import * as Prompt from \"effect/ai/Prompt\"\n * import * as Schema from \"effect/Schema\"\n *\n * class OrderPlaced extends Schema.TaggedClass<OrderPlaced>()(\"OrderPlaced\", {\n * id: InputId.InputId,\n * reference: Schema.String\n * }) {}\n *\n * const MyAssistant = Assistant.make(\"my-assistant\", { events: [OrderPlaced] })\n *\n * const withOrders: Assistant.HistoryView<OrderPlaced> = (entries) =>\n * entries.map((entry) =>\n * entry.event instanceof OrderPlaced\n * ? Prompt.userMessage({\n * content: [Prompt.textPart({ text: `The user placed order ${entry.event.reference}.` })]\n * })\n * : entry\n * )\n *\n * // An `OrderPlaced` that the API submits wakes a turn, which reads it as this note.\n * const MyAssistantLive = MyAssistant.toLayer((turn) =>\n * turn.run({ instructions: \"Be brief.\", history: withOrders })\n * )\n * ```\n *\n * @category models\n * @since 0.1.0\n */\nexport type HistoryView<Events = never> = (\n entries: ReadonlyArray<Entry<Events>>\n) => ReadonlyArray<Entry<Events> | Prompt.Message>\n\n/**\n * Represents an entry in a chat's log, with the assistant's own events decoded to their types.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Entry<Events = never> {\n readonly chatId: ChatId\n readonly sequence: number\n readonly at: number\n readonly event: AssistantEvent.AssistantEvent | Events\n}\n\n/**\n * Represents the options accepted by `turn.replyIfOwed`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ReplyOptions {\n /** The assistant's instructions, as passed to `turn.run`. `Instructions.protocol` is added. */\n readonly instructions: string | Instructions.Resolved\n /**\n * The message given to the model after the history. Defaults to a message saying that it\n * hasn't replied yet and should reply now.\n */\n readonly nudge?: string | undefined\n}\n\n/**\n * Represents one turn, as the assistant's handler receives it.\n *\n * `Events` is the type of the app's own events that the assistant registered with its `events`\n * option.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Turn<Events = never> {\n readonly chatId: ChatId\n /**\n * Returns the model's history, built from the chat's entries (all of them, or those a view\n * keeps), together with how far into the chat it reaches.\n *\n * Read it before every model call, as the loop does. Each step records how far its model call\n * read, and the turn ends once it has handled what the model saw. An input that arrived after\n * that is handled by the next turn.\n */\n readonly history: (view?: HistoryView<Events>) => Effect.Effect<AssistantLoop.ChatHistory>\n /**\n * Returns the full system prompt for the given instructions. It contains\n * `Instructions.protocol`, the instructions, and the specialist runs that are working now.\n */\n readonly instructions: (instructions: string | Instructions.Resolved) => Instructions.Resolved\n /**\n * Runs the agent loop over the chat. The loop uses `Instructions.protocol`, the assistant's own\n * tools, and the instructions and tools in `options`. Every step is a tool call, and\n * the loop ends with `replyIfOwed`.\n */\n readonly run: <T extends Record<string, Tool.Any> = Record<never, never>>(\n options: RunOptions<T, Events>\n ) => Stream.Stream<\n AssistantLoop.Event,\n AiError.AiError,\n LanguageModel.LanguageModel | TurnServices | AssistantLoop.ToolkitServices<T>\n >\n /**\n * Runs one more pass when the turn would otherwise end without a reply to the user's latest\n * message. In this pass the model can only reply.\n *\n * The stream is empty when no reply is owed, or when an input arrived that the next turn will\n * read. `run` runs this pass with its own prompt and tools, so the pass reuses the cached\n * prompt.\n */\n readonly replyIfOwed: (\n options: ReplyOptions\n ) => Stream.Stream<AssistantLoop.Event, AiError.AiError, LanguageModel.LanguageModel | TurnServices>\n}\n\n/**\n * Represents an assistant's handler, which runs a turn and returns it as a stream of the loop's\n * events.\n *\n * The handler may return the stream directly or from an Effect. `R` is the services the stream\n * requires, and `RE` is the services the Effect requires.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Handler<R = never, RE = R, Events = never> = (\n turn: Turn<Events>\n) =>\n | Stream.Stream<AssistantLoop.Event, unknown, R>\n | Effect.Effect<Stream.Stream<AssistantLoop.Event, unknown, R>, unknown, RE>\n\n/**\n * Computes the services an assistant's handler needs beyond those its turns provide (the turn\n * services and `LanguageModel`) and its tools' handlers (which its layer requires). These are the\n * services that its build Effect must require.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type HandlerServices<R> = Exclude<R, TurnServices | LanguageModel.LanguageModel | Tool.Handler<string>>\n\nconst toStream = <R, RE>(\n result:\n | Stream.Stream<AssistantLoop.Event, unknown, R>\n | Effect.Effect<Stream.Stream<AssistantLoop.Event, unknown, R>, unknown, RE>\n): Stream.Stream<AssistantLoop.Event, unknown, R | RE> => (Effect.isEffect(result) ? Stream.unwrap(result) : result)\n\n/**\n * Sets the tracer that an assistant's turns and specialist runs record their spans with. Each\n * turn's `invoke_agent` span is then the root of a trace on that tracer, with the turn's model\n * calls and tool calls below it. By default they use the tracer of the fiber that runs them.\n *\n * Provide it to the assistant's layer to send the agent's work to its own backend, such as an LLM\n * observability tool, while the rest of the app traces elsewhere.\n *\n * @example\n * ```ts\n * const AgentTracer = Layer.effect(\n * Assistant.TurnTracer,\n * OtlpTracer.make({ url: \"https://llm-observability.example.com/v1/traces\" }).pipe(Effect.map(Option.some))\n * )\n *\n * const MyAssistantLive = MyAssistant.toLayer(handler).pipe(Layer.provide(AgentTracer))\n * ```\n *\n * @category references\n * @since 0.12.0\n */\nexport const TurnTracer: Context.Reference<Option.Option<Tracer.Tracer>> = Telemetry.TurnTracer\n\n/**\n * Identifies an assistant's service in a context. Each assistant has its own identifier, keyed by\n * its name.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Identifier<Name extends string> {\n readonly \"~effect-assistant/Assistant\": Name\n}\n\n/**\n * Identifies, in a context, the chat that an assistant's turns run in.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ChatIdentifier<Name extends string> {\n readonly \"~effect-assistant/Assistant/Chat\": Name\n}\n\n/**\n * Represents the chat that a turn of this assistant runs in, typed with the assistant's events.\n *\n * Use `yield* MyAssistant.Chat` in the handler, in the handler's build, or in a tool that its\n * turns run. Code that doesn't know the assistant uses `CurrentChat` instead.\n *\n * @see {@link CurrentChat} for the same chat without the assistant's event types\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Chat<Events = never> {\n readonly chatId: ChatId\n /**\n * The chat's entries so far, in order. They include the library's events and the assistant's\n * own events, typed.\n */\n readonly entries: Effect.Effect<ReadonlyArray<Entry<Events>>>\n /**\n * Appends events after the chat's last entry and sends them to the chat's subscribers. The\n * events can be the library's or the assistant's own, such as a summary. None of them wakes a\n * turn: only what comes in through the assistant's `submit` does.\n */\n append(...events: ReadonlyArray<AssistantEvent.AssistantEvent | Events>): Effect.Effect<void>\n}\n\n/**\n * Represents the options accepted by an assistant's `subscribe`.\n *\n * @category models\n * @since 0.13.0\n */\nexport interface SubscribeOptions {\n /** The `sequence` after which the stream starts. Defaults to `0`, the whole log. */\n readonly after?: number | undefined\n}\n\n/**\n * Represents the service that `yield* MyAssistant` returns. It gives code outside a chat, such as\n * a server or a workflow, access to the assistant's chats. Code that runs inside a chat uses\n * `CurrentChat` instead.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Service<Events = never> {\n /**\n * Stores an input or one of the assistant's own events, then returns. Examples are a user's\n * message or block answer, a workflow's progress, or the order the user placed. Each one is an\n * input: storing it wakes a turn, which the assistant runs in the background. The handler decides\n * what the turn does with it, and an app event the model should read needs a history view that\n * maps it (see {@link HistoryView}). To store an app event without waking a turn, append it from\n * within the chat instead (`yield* MyAssistant.Chat`).\n *\n * Fails with `GetChatError` when the app's `Chats` service reports that the chat can't be used,\n * because the app doesn't know the chat or has deleted it.\n */\n // Method syntax: a service for these events is one for any (`Service<any>`), for helpers over assistants.\n submit(chatId: ChatId, input: AssistantEvent.Input | Events): Effect.Effect<void, Chats.GetChatError>\n /**\n * Streams the chat's stored entries, then live ones, with the assistant's own events decoded.\n * A reader that already has the earlier entries passes `after` and receives only the entries\n * after that `sequence`.\n *\n * For a chat client, pipe the whole log into `Timeline.changes(MyAssistant, { after })`, which\n * streams the chat's timeline, as its user sees it. Its `after` goes there, not here: a message\n * on the timeline depends on earlier entries. The timeline shows only the app events named in its\n * `show`, none by default (see `Timeline.changes`).\n */\n readonly subscribe: {\n (\n chatId: ChatId,\n options?: SubscribeOptions & { readonly signals?: false | undefined }\n ): Stream.Stream<Entry<Events>>\n /**\n * With `signals: true`, the stream also has the chat's signals (see `ChatSignal`): the status of\n * what a turn is doing, and whether a message to the user is on its way. They come in order\n * with the entries, only while the stream runs, and are never stored.\n */\n (\n chatId: ChatId,\n options: SubscribeOptions & { readonly signals: true }\n ): Stream.Stream<Entry<Events> | ChatSignal.ChatSignal>\n }\n /**\n * Deletes a chat by storing a `ChatDeleted` event and stopping everything that works in it.\n *\n * **Details**\n *\n * A turn or specialist run working in the chat stops, and subscribers' streams end with the\n * `ChatDeleted` event. After that the chat stores nothing more: a later input, a run's report,\n * or a workflow's event for it is dropped without an error. The log is kept, and removing it is\n * up to the app. Deleting a chat a second time does nothing.\n *\n * When the app's `Chats` service reports a chat as deleted, the assistant deletes it in the same\n * way the next time it checks. It checks before an input is stored and before each model call.\n */\n readonly delete: (chatId: ChatId) => Effect.Effect<void>\n}\n\n/**\n * Represents an assistant's definition.\n *\n * The definition holds what callers and the UI need to know about the assistant, builds its\n * handler's layer, and is the key of its service (`yield* MyAssistant`). `Events` is the type of\n * the app's own events that the assistant registered.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Assistant<\n Name extends string = string,\n Specs extends Specialist.Any = never,\n Events = never\n> extends Context.Service<Identifier<Name>, Service<Events>> {\n readonly [TypeId]: typeof TypeId\n readonly name: Name\n readonly blocks: BlockKit.BlockKit | undefined\n /** The specialists the assistant can hand work to. */\n readonly specialists: ReadonlyArray<Specs>\n /** The schemas of the app's own events the assistant stores. */\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n /**\n * Creates a layer that registers the assistant's handler with the engine and provides the\n * assistant's service.\n *\n * **Details**\n *\n * `build` is the handler, or an Effect that returns it. The handler may use the turn services,\n * `LanguageModel`, its tools' handlers (which the layer then requires), and services that its\n * build Effect required (see `Specialist.CheckServices`). The layer requires the\n * `AssistantEngine`, the `LanguageModel`, and each specialist's handler\n * (`Research.toLayer(...)`).\n *\n * **Example** (Providing an assistant's handler)\n *\n * ```ts\n * import { Assistant, AssistantEngine, ChatLog } from \"effect-assistant\"\n * import type * as LanguageModel from \"effect/ai/LanguageModel\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const MyAssistantLive = MyAssistant.toLayer((turn) =>\n * turn.run({ instructions: \"You help a small team. Be brief.\" })\n * )\n *\n * const AppLive = MyAssistantLive.pipe(\n * Layer.provide(ModelLive),\n * Layer.provideMerge(AssistantEngine.layerMemory),\n * Layer.provideMerge(ChatLog.layerMemory)\n * )\n * ```\n */\n readonly toLayer: <R = never, RE = never, E = never, RX = never>(\n build: (Handler<R, RE, Events> | Effect.Effect<Handler<R, RE, Events>, E, RX>) &\n Specialist.CheckServices<Exclude<HandlerServices<R | RE>, RX | ChatIdentifier<Name>>>\n ) => Layer.Layer<\n Identifier<Name>,\n never,\n | AssistantEngine\n | LanguageModel.LanguageModel\n | Specialist.HandlerOf<Specs>\n | Exclude<RX, Scope.Scope | CurrentChat | ChatIdentifier<Name>>\n | Specialist.ToolHandlers<R | RE>\n >\n /**\n * A layer that provides the assistant's service without its handler.\n *\n * **When to use**\n *\n * Use it in a process that submits to chats that another process runs, such as a web server in\n * front of a cluster.\n *\n * **Example** (Serving clients in front of a cluster)\n *\n * ```ts\n * import { Assistant, AssistantEngine } from \"effect-assistant\"\n * import * as Layer from \"effect/Layer\"\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * // Requires `Sharding`. The cluster's runners run the chats, with `AssistantEngine.layerCluster`.\n * const MyAssistantClient = MyAssistant.layerClient.pipe(\n * Layer.provide(AssistantEngine.layerClusterClient)\n * )\n * ```\n */\n readonly layerClient: Layer.Layer<Identifier<Name>, never, AssistantEngine>\n /**\n * The key of the chat that the assistant's turns run in, typed with its events. See\n * {@link Chat}.\n */\n readonly Chat: Context.Service<ChatIdentifier<Name>, Chat<Events>>\n /** A schema that encodes the chat's entries to JSON, including the assistant's own events. */\n readonly Entry: Schema.Codec<Entry<Events>, Schema.Json>\n}\n\n/**\n * Represents any assistant, for use in generic constraints.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type Any = Assistant<any, any, any>\n\n/**\n * Returns `true` when the value is an assistant's definition, created with {@link make}.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isAssistant = (u: unknown): u is Any => Predicate.hasProperty(u, TypeId)\n\nfunction entrySchema<E>(events: ReadonlyArray<AssistantEvent.AppEventSchema>): Schema.Codec<Entry<E>, Schema.Json>\n// The overload states the decoded type: the library's events, or one of these schemas' types.\nfunction entrySchema(events: ReadonlyArray<AssistantEvent.AppEventSchema>): Schema.Top {\n return Schema.toCodecJson(\n Schema.Struct({\n chatId: ChatId,\n sequence: Schema.Int,\n at: Schema.Finite,\n event: Schema.Union([AssistantEvent.AssistantEvent, ...events])\n })\n )\n}\n\n/**\n * Creates an assistant definition from its name, its UI blocks, its specialists, and the schemas of\n * the app's own events it stores.\n *\n * **Details**\n *\n * The definition holds no code that runs turns. Provide a handler with its `toLayer`, then yield\n * the definition to get the assistant's {@link Service}.\n *\n * The definition only says which of the app's events a chat stores. What happens with one is up\n * to the places that use it. One that comes in through the service's `submit`, from outside a\n * turn, is an input and wakes a turn, like a user's message; one a turn appends to its chat never\n * does. The handler decides what a turn does, a history view says how the model reads an event\n * ({@link HistoryView}), and the chat's timeline says which its user sees\n * (`Timeline.changes`).\n *\n * **Example** (Defining an assistant and submitting a message)\n *\n * ```ts\n * import { Assistant, AssistantEvent, ChatId } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const program = Effect.gen(function* () {\n * const assistant = yield* MyAssistant\n * const chatId = yield* ChatId.make()\n *\n * yield* assistant.submit(chatId, AssistantEvent.UserMessage.make({ text: \"Weather in Oslo?\" }))\n * })\n * ```\n *\n * @see {@link Assistant} for the definition's members\n * @see {@link Service} for what `yield* MyAssistant` returns\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <\n const Name extends string,\n const Specs extends ReadonlyArray<Specialist.Any> = readonly [],\n const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []\n>(\n name: Name,\n options?: {\n /** UI blocks the assistant can add to its messages. */\n readonly blocks?: BlockKit.BlockKit | undefined\n /**\n * The specialists the assistant can hand work to. Each specialist's `toLayer` must be\n * provided to the assistant's layer.\n */\n readonly specialists?: Specs | undefined\n /**\n * The schemas of the app's own events, each a tagged struct or class. `submit` and the chat's\n * `append` store them, in their JSON form, and the chat's `entries` and `subscribe` read them\n * back, decoded. Each needs a tag of its own that isn't one of the library's: `make` throws\n * otherwise.\n */\n readonly events?: Events | undefined\n }\n): Assistant<Name, Specs[number], Events[number][\"Type\"]> => {\n const events = options?.events ?? []\n\n const definition: Turns.Definition = {\n name,\n blocks: options?.blocks,\n specialists: options?.specialists ?? [],\n app: AppEvents.make(events)\n }\n\n type OwnEvents = Events[number][\"Type\"]\n\n const Key = Context.Service<Identifier<Name>, Service<OwnEvents>>(`effect-assistant/Assistant/${name}`)\n\n // The app's own events go to the engine encoded, as they're stored; the library's go unchanged.\n const stored = (\n input: AssistantEvent.Input | OwnEvents\n ): Effect.Effect<AssistantEvent.Input | AssistantEvent.StoredAppEvent> =>\n AssistantEvent.isInput(input) ? Effect.succeed(input) : AppEvents.encode(definition.app, input)\n\n const ChatKey = Context.Service<ChatIdentifier<Name>, Chat<OwnEvents>>(`effect-assistant/Assistant/${name}/Chat`)\n\n // On the engine and the app's `Chats` the layer was given, so every caller sees the same ones.\n const makeService = Effect.gen(function* () {\n const engine = yield* AssistantEngine\n const chats = yield* Chats.Chats\n\n const decode = (\n item: AssistantEvent.Entry | ChatSignal.ChatSignal\n ): Option.Option<Entry<OwnEvents> | ChatSignal.ChatSignal> =>\n ChatSignal.isChatSignal(item) ? Option.some(item) : AppEvents.decodeEntry(definition.app, item)\n\n function subscribe(\n chatId: ChatId,\n options?: SubscribeOptions & { readonly signals?: false | undefined }\n ): Stream.Stream<Entry<OwnEvents>>\n function subscribe(\n chatId: ChatId,\n options: SubscribeOptions & { readonly signals: true }\n ): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal>\n function subscribe(\n chatId: ChatId,\n options?: SubscribeOptions & { readonly signals?: boolean | undefined }\n ): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal> {\n return engine\n .subscribe(name, chatId, options?.after ?? 0, options?.signals === true)\n .pipe(Stream.filterMap(Filter.fromPredicateOption(decode)))\n }\n\n return Key.of({\n submit: Effect.fn(\"Assistant.submit\")(function* (chatId: ChatId, input: AssistantEvent.Input | OwnEvents) {\n // Checked here, where the caller can handle it: the chat checks again when it stores the input.\n yield* chats.get(chatId)\n yield* engine.submit(name, chatId, yield* stored(input))\n }),\n subscribe,\n delete: (chatId) => engine.delete(name, chatId)\n })\n })\n\n // The signature checks what the handler uses (`CheckServices`); the layer's services, which the build\n // required, are provided to it and to every turn's stream, so what's left is the turn services.\n function toLayer<R = never, RE = never, E = never, RX = never>(\n build: (Handler<R, RE, OwnEvents> | Effect.Effect<Handler<R, RE, OwnEvents>, E, RX>) &\n Specialist.CheckServices<Exclude<HandlerServices<R | RE>, RX | ChatIdentifier<Name>>>\n ): Layer.Layer<\n Identifier<Name>,\n never,\n | AssistantEngine\n | LanguageModel.LanguageModel\n | Specialist.HandlerOf<Specs[number]>\n | Exclude<RX, Scope.Scope | CurrentChat | ChatIdentifier<Name>>\n | Specialist.ToolHandlers<R | RE>\n >\n function toLayer(\n build: Handler<any, any, any> | Effect.Effect<Handler<any, any, any>, unknown, any>\n ): Layer.Layer<Identifier<Name>, never, any> {\n return Layer.effect(\n Key,\n Effect.gen(function* () {\n // Without the layer's scope: what a build or a turn sets up lives as long as the chat or the turn.\n const context = yield* Effect.context().pipe(\n Effect.map(Context.omit(Scope.Scope)),\n Effect.map(Telemetry.withoutTracing)\n )\n\n const registration = yield* Turns.register(definition, {\n // The build runs per chat activation, in the chat; here it only keeps the layer's services for it.\n open: (typed) =>\n Effect.gen(function* () {\n // The chat's entries are already decoded with this assistant's events.\n const chat = ChatKey.of({ chatId: typed.chatId, entries: typed.entries, append: typed.append })\n const handler = Effect.isEffect(build) ? yield* Effect.provideService(build, ChatKey, chat) : build\n\n return (turn: Turn<any>) =>\n Stream.provide(toStream(handler(turn)), context).pipe(Stream.provideService(ChatKey, chat))\n }).pipe(Effect.provide(context), Effect.orDie)\n })\n\n yield* (yield* AssistantEngine).register(registration)\n\n return yield* makeService\n })\n )\n }\n\n // The key is a function, whose own `name` is read-only: the assistant's name replaces it.\n const named = Object.defineProperty(Key, \"name\", { value: name, writable: true })\n\n return Object.assign(named, {\n [TypeId]: TypeId,\n name,\n blocks: options?.blocks,\n specialists: options?.specialists ?? [],\n events,\n toLayer,\n layerClient: Layer.effect(Key, makeService),\n Chat: ChatKey,\n Entry: entrySchema<OwnEvents>(events)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0CA,MAAM,SAAS;AAmMf,MAAM,YACJ,WAGyD,OAAO,SAAS,MAAM,IAAI,OAAO,OAAO,MAAM,IAAI;;;;;;;;;;;;;;;;;;;;;;AAuB7G,MAAa,aAA8DA;;;;;;;AA6O3E,MAAa,eAAe,MAAyB,UAAU,YAAY,GAAG,MAAM;AAIpF,SAAS,YAAY,QAAkE;CACrF,OAAO,OAAO,YACZ,OAAO,OAAO;EACZ,QAAQ;EACR,UAAU,OAAO;EACjB,IAAI,OAAO;EACX,OAAO,OAAO,MAAM,CAACC,gBAA+B,GAAG,MAAM,CAAC;CAChE,CAAC,CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,MAAa,QAKX,MACA,YAgB2D;CAC3D,MAAM,SAAS,SAAS,UAAU,CAAC;CAEnC,MAAM,aAA+B;EACnC;EACA,QAAQ,SAAS;EACjB,aAAa,SAAS,eAAe,CAAC;EACtC,KAAKC,OAAe,MAAM;CAC5B;CAIA,MAAM,MAAM,QAAQ,QAA8C,8BAA8B,MAAM;CAGtG,MAAM,UACJ,UAEAC,QAAuB,KAAK,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,QAAQ,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK,OAAO,eAAe,SAAS,IAAI,CAAC;GAC9F,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,GAAG,OAAO,KAAK,EACjD,CAAC;GAED,QAAQ,OAAO,gBAAA,CAAiB,SAAS,YAAY;GAErD,OAAO,OAAO;EAChB,CAAC,CACH;CACF;CAGA,MAAM,QAAQ,OAAO,eAAe,KAAK,QAAQ;EAAE,OAAO;EAAM,UAAU;CAAK,CAAC;CAEhF,OAAO,OAAO,OAAO,OAAO;GACzB,SAAS;EACV;EACA,QAAQ,SAAS;EACjB,aAAa,SAAS,eAAe,CAAC;EACtC;EACA;EACA,aAAa,MAAM,OAAO,KAAK,WAAW;EAC1C,MAAM;EACN,OAAO,YAAuB,MAAM;CACtC,CAAC;AACH"}
|
|
@@ -21,10 +21,10 @@ declare const AssistantEngine_base: Context.ServiceClass<AssistantEngine, "effec
|
|
|
21
21
|
*/
|
|
22
22
|
readonly submit: (assistant: string, chatId: ChatId, input: Input | StoredAppEvent) => Effect.Effect<void>;
|
|
23
23
|
/**
|
|
24
|
-
* Streams the chat's stored entries after the `after` sequence, then live ones. With `
|
|
24
|
+
* Streams the chat's stored entries after the `after` sequence, then live ones. With `signals`,
|
|
25
25
|
* the chat's signals too, in order with the entries.
|
|
26
26
|
*/
|
|
27
|
-
readonly subscribe: (assistant: string, chatId: ChatId, after: number,
|
|
27
|
+
readonly subscribe: (assistant: string, chatId: ChatId, after: number, signals: boolean) => Stream.Stream<Entry | ChatSignal>;
|
|
28
28
|
/**
|
|
29
29
|
* Deletes one of the assistant's chats. The chat's log records the deletion, and everything
|
|
30
30
|
* that works in the chat stops.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantEngine.d.ts","names":[],"sources":["../src/AssistantEngine.ts"],"mappings":";;;;;;;;;;;;;;;;WA+CuB,WAAC,cAAc,iBAAuB,OAAO,oBAAoB,MAAM;;;;;WAKzE,SACf,mBACA,QAAQ,QACR,OAAO,QAAuB,mBAC3B,OAAO;;;;;WAKQ,YAClB,mBACA,QAAQ,QACR,eACA,
|
|
1
|
+
{"version":3,"file":"AssistantEngine.d.ts","names":[],"sources":["../src/AssistantEngine.ts"],"mappings":";;;;;;;;;;;;;;;;WA+CuB,WAAC,cAAc,iBAAuB,OAAO,oBAAoB,MAAM;;;;;WAKzE,SACf,mBACA,QAAQ,QACR,OAAO,QAAuB,mBAC3B,OAAO;;;;;WAKQ,YAClB,mBACA,QAAQ,QACR,eACA,qBACG,OAAO,OAAO,QAAuB;;;;;WAKzB,SAAC,mBAAmB,QAAQ,WAAW,OAAO;;;;;;;;;qBA5BtD,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAsExB,aAAa,MAAM,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmNjD,cAAc,MAAM,MAAM,wBAAwB,UAAU,SAAS;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwFrE,oBAAoB,MAAM,MAAM,wBAAwB,SAAS"}
|
package/dist/AssistantEngine.js
CHANGED
|
@@ -137,12 +137,12 @@ const layerMemory = Layer.effect(AssistantEngine, Effect.gen(function* () {
|
|
|
137
137
|
chatId
|
|
138
138
|
}));
|
|
139
139
|
}),
|
|
140
|
-
subscribe: (assistant, chatId, after,
|
|
140
|
+
subscribe: (assistant, chatId, after, signals) => Stream.unwrap(Effect.gen(function* () {
|
|
141
141
|
const chat = yield* RcMap.get(chats, new ChatKey({
|
|
142
142
|
assistant,
|
|
143
143
|
chatId
|
|
144
144
|
}));
|
|
145
|
-
return
|
|
145
|
+
return signals ? chat.live(after) : chat.stream(after);
|
|
146
146
|
}))
|
|
147
147
|
});
|
|
148
148
|
}));
|
|
@@ -150,7 +150,7 @@ const Submit = Rpc.make("Submit", { payload: { input: Schema.Union([Input, Store
|
|
|
150
150
|
const Subscribe = Rpc.make("Subscribe", {
|
|
151
151
|
payload: {
|
|
152
152
|
after: Schema.Int,
|
|
153
|
-
|
|
153
|
+
signals: Schema.optionalKey(Schema.Boolean)
|
|
154
154
|
},
|
|
155
155
|
success: Schema.Union([Entry, ChatSignal]),
|
|
156
156
|
stream: true
|
|
@@ -170,9 +170,9 @@ const makeClusterClient = Effect.gen(function* () {
|
|
|
170
170
|
const makeClient = yield* chatEntity(assistant).client.pipe(Effect.provide(context));
|
|
171
171
|
const client = {
|
|
172
172
|
submit: (chatId, input) => makeClient(chatId).Submit({ input }, { discard: true }).pipe(Effect.orDie),
|
|
173
|
-
subscribe: (chatId, after,
|
|
173
|
+
subscribe: (chatId, after, signals) => makeClient(chatId).Subscribe({
|
|
174
174
|
after,
|
|
175
|
-
|
|
175
|
+
signals
|
|
176
176
|
}).pipe(Stream.orDie),
|
|
177
177
|
delete: (chatId) => makeClient(chatId).Delete().pipe(Effect.orDie)
|
|
178
178
|
};
|
|
@@ -183,8 +183,8 @@ const makeClusterClient = Effect.gen(function* () {
|
|
|
183
183
|
submit: Effect.fn("AssistantEngine.submit")(function* (assistant, chatId, input) {
|
|
184
184
|
yield* (yield* clientOf(assistant)).submit(chatId, input);
|
|
185
185
|
}),
|
|
186
|
-
subscribe: (assistant, chatId, after,
|
|
187
|
-
return (yield* clientOf(assistant)).subscribe(chatId, after,
|
|
186
|
+
subscribe: (assistant, chatId, after, signals) => Stream.unwrap(Effect.gen(function* () {
|
|
187
|
+
return (yield* clientOf(assistant)).subscribe(chatId, after, signals);
|
|
188
188
|
})),
|
|
189
189
|
delete: Effect.fn("AssistantEngine.delete")(function* (assistant, chatId) {
|
|
190
190
|
yield* (yield* clientOf(assistant)).delete(chatId);
|
|
@@ -252,7 +252,7 @@ const layerCluster = Layer.effect(AssistantEngine, Effect.gen(function* () {
|
|
|
252
252
|
yield* chat.resume;
|
|
253
253
|
return ChatEntity.of({
|
|
254
254
|
Submit: (request) => chat.submit(request.payload.input),
|
|
255
|
-
Subscribe: (request) => request.payload.
|
|
255
|
+
Subscribe: (request) => request.payload.signals === true ? chat.live(request.payload.after) : chat.stream(request.payload.after),
|
|
256
256
|
Delete: () => chat.delete
|
|
257
257
|
});
|
|
258
258
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantEngine.js","names":["Chat.make","History.needsTurn","AssistantEvent.Input","AssistantEvent.StoredAppEvent","AssistantEvent.Entry","ChatSignal.ChatSignal"],"sources":["../src/AssistantEngine.ts"],"sourcesContent":["/**\n * This module provides the `AssistantEngine` service, which runs assistants' chats, and its\n * implementations.\n *\n * An assistant's `toLayer` registers the assistant with the engine, and the assistant's `submit`\n * and `subscribe` go through it. Pick one engine for the app, as with a workflow engine.\n * {@link layerMemory} runs chats in the process, for tests and single-process apps.\n * {@link layerCluster} runs each chat as a cluster entity, so a turn cut off by a crash resumes, and\n * {@link layerClusterClient} reaches those chats from a process that runs none.\n *\n * @since 0.1.0\n */\nimport * as ClusterSchema from \"effect/cluster/ClusterSchema\"\nimport * as Entity from \"effect/cluster/Entity\"\nimport * as Sharding from \"effect/cluster/Sharding\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Layer from \"effect/Layer\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as RcMap from \"effect/RcMap\"\nimport * as Rpc from \"effect/rpc/Rpc\"\nimport * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport { ChatId } from \"./ChatId.ts\"\nimport { ChatLog } from \"./ChatLog.ts\"\nimport * as ChatSignal from \"./ChatSignal.ts\"\nimport * as Chat from \"./internal/chat.ts\"\nimport * as History from \"./internal/history.ts\"\nimport type * as Turns from \"./internal/turns.ts\"\n\n/**\n * Service that runs assistants' chats. An assistant's `toLayer` registers the assistant with it,\n * and the assistant's `submit` and `subscribe` use it.\n *\n * @category services\n * @since 0.1.0\n */\nexport class AssistantEngine extends Context.Service<\n AssistantEngine,\n {\n /** Registers an assistant for as long as the scope is open. */\n readonly register: (registration: Turns.Registration) => Effect.Effect<void, never, Scope.Scope>\n /**\n * Stores an input in one of the assistant's chats. The assistant works on it in the\n * background.\n */\n readonly submit: (\n assistant: string,\n chatId: ChatId,\n input: AssistantEvent.Input | AssistantEvent.StoredAppEvent\n ) => Effect.Effect<void>\n /**\n * Streams the chat's stored entries after the `after` sequence, then live ones. With `live`,\n * the chat's signals too, in order with the entries.\n */\n readonly subscribe: (\n assistant: string,\n chatId: ChatId,\n after: number,\n live: boolean\n ) => Stream.Stream<AssistantEvent.Entry | ChatSignal.ChatSignal>\n /**\n * Deletes one of the assistant's chats. The chat's log records the deletion, and everything\n * that works in the chat stops.\n */\n readonly delete: (assistant: string, chatId: ChatId) => Effect.Effect<void>\n }\n>()(\"effect-assistant/AssistantEngine\") {}\n\nclass ChatKey extends Data.Class<{ readonly assistant: string; readonly chatId: ChatId }> {}\n\nconst notRegistered = (assistant: string) =>\n Effect.die(`The ${assistant} assistant isn't registered: provide its toLayer.`)\n\n/**\n * Layer that runs chats in the current process. Each chat's turns run as fibers, one at a time.\n *\n * **Details**\n *\n * With `ChatLog.layerSql()`, the engine resumes chats at startup. When an assistant registers, the\n * engine finds the chats that assistant was working on when the process stopped (a turn cut off\n * partway, or an input that no turn read) and runs a turn for each. Run this engine in one process\n * only, because two processes would run the same chat and write its log at the same time.\n *\n * **Example** (Running chats in memory)\n *\n * ```ts\n * import { Assistant, AssistantEngine, ChatLog } from \"effect-assistant\"\n * import type * as LanguageModel from \"effect/ai/LanguageModel\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const AppLive = MyAssistant.toLayer((turn) => turn.run({ instructions: \"Be brief.\" })).pipe(\n * Layer.provide(ModelLive),\n * Layer.provideMerge(AssistantEngine.layerMemory),\n * Layer.provideMerge(ChatLog.layerMemory)\n * )\n * ```\n *\n * @see {@link layerCluster} for running each chat as a cluster entity\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerMemory: Layer.Layer<AssistantEngine, never, ChatLog> = Layer.effect(\n AssistantEngine,\n Effect.gen(function* () {\n // Without the layer's scope, so a chat's resources close with its entry.\n const context = yield* Effect.context<ChatLog>().pipe(Effect.map(Context.omit(Scope.Scope)))\n const log = yield* ChatLog\n const registered = new Map<string, Turns.Registration>()\n // A chat's keep-alive: a hold on its entry, so it stays open while runs or turns work in the background.\n const held = MutableHashMap.empty<ChatKey, Scope.Closeable>()\n\n // One entry per open chat, like a cluster entity: opened when used, closed five minutes after the last use.\n const chats: RcMap.RcMap<ChatKey, Chat.Chat> = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: ChatKey) {\n const registration = registered.get(key.assistant)\n\n if (registration === undefined) return yield* notRegistered(key.assistant)\n\n return yield* Chat.make({\n registration,\n chatId: key.chatId,\n keepAlive: (enabled) => keepAlive(key, enabled)\n }).pipe(Effect.provide(context))\n }),\n idleTimeToLive: \"5 minutes\"\n })\n\n // On: a hold on the chat's entry, in a scope of its own. Off: closing that scope lets the entry go idle.\n const keepAlive = Effect.fnUntraced(function* (key: ChatKey, enabled: boolean) {\n if (enabled) {\n const scope = yield* Scope.make()\n\n yield* Effect.provideService(RcMap.get(chats, key), Scope.Scope, scope)\n\n return MutableHashMap.set(held, key, scope)\n }\n\n const scope = MutableHashMap.get(held, key)\n\n MutableHashMap.remove(held, key)\n\n if (Option.isSome(scope)) yield* Scope.close(scope.value, Exit.void)\n })\n\n const withChat = Effect.fnUntraced(function* <A>(\n assistant: string,\n chatId: ChatId,\n f: (chat: Chat.Chat) => Effect.Effect<A>\n ) {\n const chat = yield* RcMap.get(chats, new ChatKey({ assistant, chatId }))\n\n return yield* f(chat)\n }, Effect.scoped)\n\n // A chat owes a turn when its last turn was cut off, or an input came after.\n const resumeAll = Effect.fnUntraced(function* (registration: Turns.Registration) {\n const { name } = registration.definition\n\n for (const chatId of yield* log.unfinished) {\n const entries = yield* log.read(chatId)\n\n const lastTurn = entries.findLast(({ event }) => Predicate.isTagged(event, \"TurnStarted\"))?.event\n const ours = Predicate.isTagged(lastTurn, \"TurnStarted\") && lastTurn.assistant === name\n\n if (ours && History.needsTurn(entries)) yield* withChat(name, chatId, (chat) => chat.resume)\n }\n })\n\n return AssistantEngine.of({\n register: Effect.fn(\"AssistantEngine.register\")(function* (registration: Turns.Registration) {\n registered.set(registration.definition.name, registration)\n // Chats this assistant was working on when the process stopped: pick them up again.\n yield* Effect.forkScoped(resumeAll(registration))\n }),\n submit: (assistant, chatId, input) => withChat(assistant, chatId, (chat) => chat.submitInBackground(input)),\n // The chat deletes itself, so a chat that's open stops; the entry goes, and the next open finds it deleted.\n delete: Effect.fn(\"AssistantEngine.delete\")(function* (assistant: string, chatId: ChatId) {\n yield* withChat(assistant, chatId, (chat) => chat.delete)\n yield* RcMap.invalidate(chats, new ChatKey({ assistant, chatId }))\n }),\n // The subscriber holds the chat open while it streams.\n subscribe: (assistant, chatId, after, live) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const chat = yield* RcMap.get(chats, new ChatKey({ assistant, chatId }))\n\n return live ? chat.live(after) : chat.stream(after)\n })\n )\n })\n })\n)\n\ninterface EntityClient {\n readonly submit: (chatId: ChatId, input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) => Effect.Effect<void>\n readonly subscribe: (\n chatId: ChatId,\n after: number,\n live: boolean\n ) => Stream.Stream<AssistantEvent.Entry | ChatSignal.ChatSignal>\n readonly delete: (chatId: ChatId) => Effect.Effect<void>\n}\n\nconst Submit = Rpc.make(\"Submit\", {\n payload: { input: Schema.Union([AssistantEvent.Input, AssistantEvent.StoredAppEvent]) }\n}).annotate(ClusterSchema.Persisted, true)\n\nconst Subscribe = Rpc.make(\"Subscribe\", {\n payload: { after: Schema.Int, live: Schema.optionalKey(Schema.Boolean) },\n success: Schema.Union([AssistantEvent.Entry, ChatSignal.ChatSignal]),\n stream: true\n})\n\nconst Delete = Rpc.make(\"Delete\")\n\nconst chatEntity = (assistant: string) => Entity.make(`Assistant/${assistant}`, [Submit, Subscribe, Delete])\n\ntype EngineClient = Omit<AssistantEngine[\"Service\"], \"register\">\n\n// Entity clients are made on first use, so a process that registers no assistant can still reach its chats.\nconst makeClusterClient = Effect.gen(function* () {\n const context = yield* Effect.context<Sharding.Sharding>()\n const clients = new Map<string, EntityClient>()\n\n const clientOf = Effect.fnUntraced(function* (assistant: string) {\n const known = clients.get(assistant)\n\n if (known !== undefined) return known\n\n const makeClient = yield* chatEntity(assistant).client.pipe(Effect.provide(context))\n\n const client: EntityClient = {\n submit: (chatId, input) => makeClient(chatId).Submit({ input }, { discard: true }).pipe(Effect.orDie),\n subscribe: (chatId, after, live) => makeClient(chatId).Subscribe({ after, live }).pipe(Stream.orDie),\n delete: (chatId) => makeClient(chatId).Delete().pipe(Effect.orDie)\n }\n\n clients.set(assistant, client)\n\n return client\n })\n\n const engine: EngineClient = {\n submit: Effect.fn(\"AssistantEngine.submit\")(function* (\n assistant: string,\n chatId: ChatId,\n input: AssistantEvent.Input | AssistantEvent.StoredAppEvent\n ) {\n const client = yield* clientOf(assistant)\n\n yield* client.submit(chatId, input)\n }),\n subscribe: (assistant, chatId, after, live) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* clientOf(assistant)\n\n return client.subscribe(chatId, after, live)\n })\n ),\n delete: Effect.fn(\"AssistantEngine.delete\")(function* (assistant: string, chatId: ChatId) {\n const client = yield* clientOf(assistant)\n\n yield* client.delete(chatId)\n })\n }\n\n return engine\n})\n\n/**\n * Layer that runs chats as cluster entities, one entity per chat, keyed by chat id.\n *\n * **Details**\n *\n * The layer requires `Sharding`. Use a `SingleRunner` for one process with SQL storage, a runner\n * of the app's cluster, or `TestRunner` in tests.\n *\n * **Example** (Running chats on a single runner with Postgres)\n *\n * ```ts\n * import * as NodeCrypto from \"@effect/platform-node/NodeCrypto\"\n * import * as PgClient from \"@effect/sql-pg/PgClient\"\n * import { Assistant, AssistantEngine, ChatLog } from \"effect-assistant\"\n * import type * as LanguageModel from \"effect/ai/LanguageModel\"\n * import * as SingleRunner from \"effect/cluster/SingleRunner\"\n * import * as Config from \"effect/Config\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const AppLive = MyAssistant.toLayer((turn) => turn.run({ instructions: \"Be brief.\" })).pipe(\n * Layer.provide(ModelLive),\n * Layer.provideMerge(AssistantEngine.layerCluster),\n * Layer.provideMerge(\n * Layer.merge(\n * ChatLog.layerSql(),\n * SingleRunner.layer({ runnerStorage: \"sql\" }).pipe(Layer.provide(NodeCrypto.layer))\n * )\n * ),\n * Layer.provide(PgClient.layerConfig({ url: Config.Redacted(\"DATABASE_URL\") }))\n * )\n * ```\n *\n * @see {@link layerMemory} for running chats in one process\n * @see {@link layerClusterClient} for a process that only reaches chats the cluster runs\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerCluster: Layer.Layer<AssistantEngine, never, ChatLog | Sharding.Sharding> = Layer.effect(\n AssistantEngine,\n Effect.gen(function* () {\n // Without the layer's scope, so a chat's resources close with its entity.\n const context = yield* Effect.context<ChatLog | Sharding.Sharding>().pipe(Effect.map(Context.omit(Scope.Scope)))\n const sharding = yield* Sharding.Sharding\n\n const register = Effect.fnUntraced(function* (registration: Turns.Registration) {\n const ChatEntity = chatEntity(registration.definition.name)\n\n const handlers = Effect.gen(function* () {\n const address = yield* Entity.CurrentAddress\n const chatId = yield* Schema.decodeUnknownEffect(ChatId)(address.entityId).pipe(Effect.orDie)\n // The entity's own: `Entity.keepAlive` needs its address and keep-alive latch, which is in there too.\n const entityContext = yield* Effect.context<Entity.CurrentAddress | Sharding.Sharding>()\n\n const keepAlive = (enabled: boolean) =>\n Entity.keepAlive(enabled).pipe(\n Effect.provide(entityContext),\n Effect.catchCause((cause) => Effect.logWarning(\"assistant chat keep-alive failed\", cause))\n )\n\n // A keep-alive left on from before a restart (by a run cut off) has done its job: it started the entity.\n yield* keepAlive(false)\n\n const chat = yield* Chat.make({ registration, chatId, keepAlive })\n yield* chat.resume\n\n return ChatEntity.of({\n // The turns run inside the request, so a crash leaves it unprocessed and the cluster redelivers it.\n Submit: (request) => chat.submit(request.payload.input),\n Subscribe: (request) =>\n request.payload.live === true ? chat.live(request.payload.after) : chat.stream(request.payload.after),\n Delete: () => chat.delete\n })\n })\n\n yield* sharding.registerEntity(ChatEntity, handlers.pipe(Effect.provide(context)), {\n maxIdleTime: \"5 minutes\",\n concurrency: \"unbounded\"\n })\n })\n\n const client = yield* makeClusterClient\n\n return AssistantEngine.of({\n register: (registration) => register(registration).pipe(Effect.provide(context)),\n ...client\n })\n })\n)\n\n/**\n * Layer that reaches chats running as cluster entities elsewhere, and runs none itself.\n *\n * **When to use**\n *\n * Use it in a process that only submits to, subscribes to, and deletes chats that the cluster's\n * runners run with {@link layerCluster}, such as a web server that provides an assistant's\n * `layerClient`. It needs no `ChatLog`, since the runners store the chats.\n *\n * **Details**\n *\n * The layer requires `Sharding`. An assistant's `toLayer` can't register with it: it dies, since\n * no chats run in this process.\n *\n * **Example** (A web server in front of the cluster)\n *\n * ```ts\n * import { Assistant, AssistantEngine } from \"effect-assistant\"\n * import type * as Sharding from \"effect/cluster/Sharding\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ShardingLive: Layer.Layer<Sharding.Sharding>\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const MyAssistantClient = MyAssistant.layerClient.pipe(\n * Layer.provide(AssistantEngine.layerClusterClient),\n * Layer.provide(ShardingLive)\n * )\n * ```\n *\n * @see {@link layerCluster} for the runners that run the chats\n *\n * @category layers\n * @since 0.3.0\n */\nexport const layerClusterClient: Layer.Layer<AssistantEngine, never, Sharding.Sharding> = Layer.effect(\n AssistantEngine,\n Effect.gen(function* () {\n const client = yield* makeClusterClient\n\n return AssistantEngine.of({\n register: (registration) =>\n Effect.die(\n `The ${registration.definition.name} assistant can't register with AssistantEngine.layerClusterClient, which runs no chats: provide AssistantEngine.layerCluster where its toLayer runs.`\n ),\n ...client\n })\n })\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2CA,IAAa,kBAAb,cAAqC,QAAQ,QA8B3C,CAAC,CAAC,kCAAkC,CAAC,CAAC,CAAC;AAEzC,IAAM,UAAN,cAAsB,KAAK,MAA+D,CAAC;AAE3F,MAAM,iBAAiB,cACrB,OAAO,IAAI,OAAO,UAAU,kDAAkD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmChF,MAAa,cAA4D,MAAM,OAC7E,iBACA,OAAO,IAAI,aAAa;CAEtB,MAAM,UAAU,OAAO,OAAO,QAAiB,CAAC,CAAC,KAAK,OAAO,IAAI,QAAQ,KAAK,MAAM,KAAK,CAAC,CAAC;CAC3F,MAAM,MAAM,OAAO;CACnB,MAAM,6BAAa,IAAI,IAAgC;CAEvD,MAAM,OAAO,eAAe,MAAgC;CAG5D,MAAM,QAAyC,OAAO,MAAM,KAAK;EAC/D,QAAQ,OAAO,WAAW,WAAW,KAAc;GACjD,MAAM,eAAe,WAAW,IAAI,IAAI,SAAS;GAEjD,IAAI,iBAAiB,KAAA,GAAW,OAAO,OAAO,cAAc,IAAI,SAAS;GAEzE,OAAO,OAAOA,KAAU;IACtB;IACA,QAAQ,IAAI;IACZ,YAAY,YAAY,UAAU,KAAK,OAAO;GAChD,CAAC,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,CAAC;EACjC,CAAC;EACD,gBAAgB;CAClB,CAAC;CAGD,MAAM,YAAY,OAAO,WAAW,WAAW,KAAc,SAAkB;EAC7E,IAAI,SAAS;GACX,MAAM,QA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AQ,QAAQ,CAAC,CAAC,KAAK,OAAO,KAAK;GAE5F,MAAM,gBAAgB,OAAO,OAAO,QAAmD;GAEvF,MAAM,aAAa,YACjB,OAAO,UAAU,OAAO,CAAC,CAAC,KACxB,OAAO,QAAQ,aAAa,GAC5B,OAAO,YAAY,UAAU,OAAO,WAAW,oCAAoC,KAAK,CAAC,CAC3F;GAGF,OAAO,UAAU,KAAK;GAEtB,MAAM,OAAO,OAAOL,KAAU;IAAE;IAAc;IAAQ;GAAU,CAAC;GACjE,OAAO,KAAK;GAEZ,OAAO,WAAW,GAAG;IAEnB,SAAS,YAAY,KAAK,OAAO,QAAQ,QAAQ,KAAK;IACtD,YAAY,YACV,QAAQ,QAAQ,SAAS,OAAO,KAAK,KAAK,QAAQ,QAAQ,KAAK,IAAI,KAAK,OAAO,QAAQ,QAAQ,KAAK;IACtG,cAAc,KAAK;GACrB,CAAC;EACH,CAAC;EAED,OAAO,SAAS,eAAe,YAAY,SAAS,KAAK,OAAO,QAAQ,OAAO,CAAC,GAAG;GACjF,aAAa;GACb,aAAa;EACf,CAAC;CACH,CAAC;CAED,MAAM,SAAS,OAAO;CAEtB,OAAO,gBAAgB,GAAG;EACxB,WAAW,iBAAiB,SAAS,YAAY,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,CAAC;EAC/E,GAAG;CACL,CAAC;AACH,CAAC,CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,qBAA6E,MAAM,OAC9F,iBACA,OAAO,IAAI,aAAa;CACtB,MAAM,SAAS,OAAO;CAEtB,OAAO,gBAAgB,GAAG;EACxB,WAAW,iBACT,OAAO,IACL,OAAO,aAAa,WAAW,KAAK,qJACtC;EACF,GAAG;CACL,CAAC;AACH,CAAC,CACH"}
|
|
1
|
+
{"version":3,"file":"AssistantEngine.js","names":["Chat.make","History.needsTurn","AssistantEvent.Input","AssistantEvent.StoredAppEvent","AssistantEvent.Entry","ChatSignal.ChatSignal"],"sources":["../src/AssistantEngine.ts"],"sourcesContent":["/**\n * This module provides the `AssistantEngine` service, which runs assistants' chats, and its\n * implementations.\n *\n * An assistant's `toLayer` registers the assistant with the engine, and the assistant's `submit`\n * and `subscribe` go through it. Pick one engine for the app, as with a workflow engine.\n * {@link layerMemory} runs chats in the process, for tests and single-process apps.\n * {@link layerCluster} runs each chat as a cluster entity, so a turn cut off by a crash resumes, and\n * {@link layerClusterClient} reaches those chats from a process that runs none.\n *\n * @since 0.1.0\n */\nimport * as ClusterSchema from \"effect/cluster/ClusterSchema\"\nimport * as Entity from \"effect/cluster/Entity\"\nimport * as Sharding from \"effect/cluster/Sharding\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Layer from \"effect/Layer\"\nimport * as MutableHashMap from \"effect/MutableHashMap\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as RcMap from \"effect/RcMap\"\nimport * as Rpc from \"effect/rpc/Rpc\"\nimport * as Schema from \"effect/Schema\"\nimport * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport { ChatId } from \"./ChatId.ts\"\nimport { ChatLog } from \"./ChatLog.ts\"\nimport * as ChatSignal from \"./ChatSignal.ts\"\nimport * as Chat from \"./internal/chat.ts\"\nimport * as History from \"./internal/history.ts\"\nimport type * as Turns from \"./internal/turns.ts\"\n\n/**\n * Service that runs assistants' chats. An assistant's `toLayer` registers the assistant with it,\n * and the assistant's `submit` and `subscribe` use it.\n *\n * @category services\n * @since 0.1.0\n */\nexport class AssistantEngine extends Context.Service<\n AssistantEngine,\n {\n /** Registers an assistant for as long as the scope is open. */\n readonly register: (registration: Turns.Registration) => Effect.Effect<void, never, Scope.Scope>\n /**\n * Stores an input in one of the assistant's chats. The assistant works on it in the\n * background.\n */\n readonly submit: (\n assistant: string,\n chatId: ChatId,\n input: AssistantEvent.Input | AssistantEvent.StoredAppEvent\n ) => Effect.Effect<void>\n /**\n * Streams the chat's stored entries after the `after` sequence, then live ones. With `signals`,\n * the chat's signals too, in order with the entries.\n */\n readonly subscribe: (\n assistant: string,\n chatId: ChatId,\n after: number,\n signals: boolean\n ) => Stream.Stream<AssistantEvent.Entry | ChatSignal.ChatSignal>\n /**\n * Deletes one of the assistant's chats. The chat's log records the deletion, and everything\n * that works in the chat stops.\n */\n readonly delete: (assistant: string, chatId: ChatId) => Effect.Effect<void>\n }\n>()(\"effect-assistant/AssistantEngine\") {}\n\nclass ChatKey extends Data.Class<{ readonly assistant: string; readonly chatId: ChatId }> {}\n\nconst notRegistered = (assistant: string) =>\n Effect.die(`The ${assistant} assistant isn't registered: provide its toLayer.`)\n\n/**\n * Layer that runs chats in the current process. Each chat's turns run as fibers, one at a time.\n *\n * **Details**\n *\n * With `ChatLog.layerSql()`, the engine resumes chats at startup. When an assistant registers, the\n * engine finds the chats that assistant was working on when the process stopped (a turn cut off\n * partway, or an input that no turn read) and runs a turn for each. Run this engine in one process\n * only, because two processes would run the same chat and write its log at the same time.\n *\n * **Example** (Running chats in memory)\n *\n * ```ts\n * import { Assistant, AssistantEngine, ChatLog } from \"effect-assistant\"\n * import type * as LanguageModel from \"effect/ai/LanguageModel\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const AppLive = MyAssistant.toLayer((turn) => turn.run({ instructions: \"Be brief.\" })).pipe(\n * Layer.provide(ModelLive),\n * Layer.provideMerge(AssistantEngine.layerMemory),\n * Layer.provideMerge(ChatLog.layerMemory)\n * )\n * ```\n *\n * @see {@link layerCluster} for running each chat as a cluster entity\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerMemory: Layer.Layer<AssistantEngine, never, ChatLog> = Layer.effect(\n AssistantEngine,\n Effect.gen(function* () {\n // Without the layer's scope, so a chat's resources close with its entry.\n const context = yield* Effect.context<ChatLog>().pipe(Effect.map(Context.omit(Scope.Scope)))\n const log = yield* ChatLog\n const registered = new Map<string, Turns.Registration>()\n // A chat's keep-alive: a hold on its entry, so it stays open while runs or turns work in the background.\n const held = MutableHashMap.empty<ChatKey, Scope.Closeable>()\n\n // One entry per open chat, like a cluster entity: opened when used, closed five minutes after the last use.\n const chats: RcMap.RcMap<ChatKey, Chat.Chat> = yield* RcMap.make({\n lookup: Effect.fnUntraced(function* (key: ChatKey) {\n const registration = registered.get(key.assistant)\n\n if (registration === undefined) return yield* notRegistered(key.assistant)\n\n return yield* Chat.make({\n registration,\n chatId: key.chatId,\n keepAlive: (enabled) => keepAlive(key, enabled)\n }).pipe(Effect.provide(context))\n }),\n idleTimeToLive: \"5 minutes\"\n })\n\n // On: a hold on the chat's entry, in a scope of its own. Off: closing that scope lets the entry go idle.\n const keepAlive = Effect.fnUntraced(function* (key: ChatKey, enabled: boolean) {\n if (enabled) {\n const scope = yield* Scope.make()\n\n yield* Effect.provideService(RcMap.get(chats, key), Scope.Scope, scope)\n\n return MutableHashMap.set(held, key, scope)\n }\n\n const scope = MutableHashMap.get(held, key)\n\n MutableHashMap.remove(held, key)\n\n if (Option.isSome(scope)) yield* Scope.close(scope.value, Exit.void)\n })\n\n const withChat = Effect.fnUntraced(function* <A>(\n assistant: string,\n chatId: ChatId,\n f: (chat: Chat.Chat) => Effect.Effect<A>\n ) {\n const chat = yield* RcMap.get(chats, new ChatKey({ assistant, chatId }))\n\n return yield* f(chat)\n }, Effect.scoped)\n\n // A chat owes a turn when its last turn was cut off, or an input came after.\n const resumeAll = Effect.fnUntraced(function* (registration: Turns.Registration) {\n const { name } = registration.definition\n\n for (const chatId of yield* log.unfinished) {\n const entries = yield* log.read(chatId)\n\n const lastTurn = entries.findLast(({ event }) => Predicate.isTagged(event, \"TurnStarted\"))?.event\n const ours = Predicate.isTagged(lastTurn, \"TurnStarted\") && lastTurn.assistant === name\n\n if (ours && History.needsTurn(entries)) yield* withChat(name, chatId, (chat) => chat.resume)\n }\n })\n\n return AssistantEngine.of({\n register: Effect.fn(\"AssistantEngine.register\")(function* (registration: Turns.Registration) {\n registered.set(registration.definition.name, registration)\n // Chats this assistant was working on when the process stopped: pick them up again.\n yield* Effect.forkScoped(resumeAll(registration))\n }),\n submit: (assistant, chatId, input) => withChat(assistant, chatId, (chat) => chat.submitInBackground(input)),\n // The chat deletes itself, so a chat that's open stops; the entry goes, and the next open finds it deleted.\n delete: Effect.fn(\"AssistantEngine.delete\")(function* (assistant: string, chatId: ChatId) {\n yield* withChat(assistant, chatId, (chat) => chat.delete)\n yield* RcMap.invalidate(chats, new ChatKey({ assistant, chatId }))\n }),\n // The subscriber holds the chat open while it streams.\n subscribe: (assistant, chatId, after, signals) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const chat = yield* RcMap.get(chats, new ChatKey({ assistant, chatId }))\n\n return signals ? chat.live(after) : chat.stream(after)\n })\n )\n })\n })\n)\n\ninterface EntityClient {\n readonly submit: (chatId: ChatId, input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) => Effect.Effect<void>\n readonly subscribe: (\n chatId: ChatId,\n after: number,\n signals: boolean\n ) => Stream.Stream<AssistantEvent.Entry | ChatSignal.ChatSignal>\n readonly delete: (chatId: ChatId) => Effect.Effect<void>\n}\n\nconst Submit = Rpc.make(\"Submit\", {\n payload: { input: Schema.Union([AssistantEvent.Input, AssistantEvent.StoredAppEvent]) }\n}).annotate(ClusterSchema.Persisted, true)\n\nconst Subscribe = Rpc.make(\"Subscribe\", {\n payload: { after: Schema.Int, signals: Schema.optionalKey(Schema.Boolean) },\n success: Schema.Union([AssistantEvent.Entry, ChatSignal.ChatSignal]),\n stream: true\n})\n\nconst Delete = Rpc.make(\"Delete\")\n\nconst chatEntity = (assistant: string) => Entity.make(`Assistant/${assistant}`, [Submit, Subscribe, Delete])\n\ntype EngineClient = Omit<AssistantEngine[\"Service\"], \"register\">\n\n// Entity clients are made on first use, so a process that registers no assistant can still reach its chats.\nconst makeClusterClient = Effect.gen(function* () {\n const context = yield* Effect.context<Sharding.Sharding>()\n const clients = new Map<string, EntityClient>()\n\n const clientOf = Effect.fnUntraced(function* (assistant: string) {\n const known = clients.get(assistant)\n\n if (known !== undefined) return known\n\n const makeClient = yield* chatEntity(assistant).client.pipe(Effect.provide(context))\n\n const client: EntityClient = {\n submit: (chatId, input) => makeClient(chatId).Submit({ input }, { discard: true }).pipe(Effect.orDie),\n subscribe: (chatId, after, signals) => makeClient(chatId).Subscribe({ after, signals }).pipe(Stream.orDie),\n delete: (chatId) => makeClient(chatId).Delete().pipe(Effect.orDie)\n }\n\n clients.set(assistant, client)\n\n return client\n })\n\n const engine: EngineClient = {\n submit: Effect.fn(\"AssistantEngine.submit\")(function* (\n assistant: string,\n chatId: ChatId,\n input: AssistantEvent.Input | AssistantEvent.StoredAppEvent\n ) {\n const client = yield* clientOf(assistant)\n\n yield* client.submit(chatId, input)\n }),\n subscribe: (assistant, chatId, after, signals) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const client = yield* clientOf(assistant)\n\n return client.subscribe(chatId, after, signals)\n })\n ),\n delete: Effect.fn(\"AssistantEngine.delete\")(function* (assistant: string, chatId: ChatId) {\n const client = yield* clientOf(assistant)\n\n yield* client.delete(chatId)\n })\n }\n\n return engine\n})\n\n/**\n * Layer that runs chats as cluster entities, one entity per chat, keyed by chat id.\n *\n * **Details**\n *\n * The layer requires `Sharding`. Use a `SingleRunner` for one process with SQL storage, a runner\n * of the app's cluster, or `TestRunner` in tests.\n *\n * **Example** (Running chats on a single runner with Postgres)\n *\n * ```ts\n * import * as NodeCrypto from \"@effect/platform-node/NodeCrypto\"\n * import * as PgClient from \"@effect/sql-pg/PgClient\"\n * import { Assistant, AssistantEngine, ChatLog } from \"effect-assistant\"\n * import type * as LanguageModel from \"effect/ai/LanguageModel\"\n * import * as SingleRunner from \"effect/cluster/SingleRunner\"\n * import * as Config from \"effect/Config\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>\n *\n * const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const AppLive = MyAssistant.toLayer((turn) => turn.run({ instructions: \"Be brief.\" })).pipe(\n * Layer.provide(ModelLive),\n * Layer.provideMerge(AssistantEngine.layerCluster),\n * Layer.provideMerge(\n * Layer.merge(\n * ChatLog.layerSql(),\n * SingleRunner.layer({ runnerStorage: \"sql\" }).pipe(Layer.provide(NodeCrypto.layer))\n * )\n * ),\n * Layer.provide(PgClient.layerConfig({ url: Config.Redacted(\"DATABASE_URL\") }))\n * )\n * ```\n *\n * @see {@link layerMemory} for running chats in one process\n * @see {@link layerClusterClient} for a process that only reaches chats the cluster runs\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layerCluster: Layer.Layer<AssistantEngine, never, ChatLog | Sharding.Sharding> = Layer.effect(\n AssistantEngine,\n Effect.gen(function* () {\n // Without the layer's scope, so a chat's resources close with its entity.\n const context = yield* Effect.context<ChatLog | Sharding.Sharding>().pipe(Effect.map(Context.omit(Scope.Scope)))\n const sharding = yield* Sharding.Sharding\n\n const register = Effect.fnUntraced(function* (registration: Turns.Registration) {\n const ChatEntity = chatEntity(registration.definition.name)\n\n const handlers = Effect.gen(function* () {\n const address = yield* Entity.CurrentAddress\n const chatId = yield* Schema.decodeUnknownEffect(ChatId)(address.entityId).pipe(Effect.orDie)\n // The entity's own: `Entity.keepAlive` needs its address and keep-alive latch, which is in there too.\n const entityContext = yield* Effect.context<Entity.CurrentAddress | Sharding.Sharding>()\n\n const keepAlive = (enabled: boolean) =>\n Entity.keepAlive(enabled).pipe(\n Effect.provide(entityContext),\n Effect.catchCause((cause) => Effect.logWarning(\"assistant chat keep-alive failed\", cause))\n )\n\n // A keep-alive left on from before a restart (by a run cut off) has done its job: it started the entity.\n yield* keepAlive(false)\n\n const chat = yield* Chat.make({ registration, chatId, keepAlive })\n yield* chat.resume\n\n return ChatEntity.of({\n // The turns run inside the request, so a crash leaves it unprocessed and the cluster redelivers it.\n Submit: (request) => chat.submit(request.payload.input),\n Subscribe: (request) =>\n request.payload.signals === true ? chat.live(request.payload.after) : chat.stream(request.payload.after),\n Delete: () => chat.delete\n })\n })\n\n yield* sharding.registerEntity(ChatEntity, handlers.pipe(Effect.provide(context)), {\n maxIdleTime: \"5 minutes\",\n concurrency: \"unbounded\"\n })\n })\n\n const client = yield* makeClusterClient\n\n return AssistantEngine.of({\n register: (registration) => register(registration).pipe(Effect.provide(context)),\n ...client\n })\n })\n)\n\n/**\n * Layer that reaches chats running as cluster entities elsewhere, and runs none itself.\n *\n * **When to use**\n *\n * Use it in a process that only submits to, subscribes to, and deletes chats that the cluster's\n * runners run with {@link layerCluster}, such as a web server that provides an assistant's\n * `layerClient`. It needs no `ChatLog`, since the runners store the chats.\n *\n * **Details**\n *\n * The layer requires `Sharding`. An assistant's `toLayer` can't register with it: it dies, since\n * no chats run in this process.\n *\n * **Example** (A web server in front of the cluster)\n *\n * ```ts\n * import { Assistant, AssistantEngine } from \"effect-assistant\"\n * import type * as Sharding from \"effect/cluster/Sharding\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ShardingLive: Layer.Layer<Sharding.Sharding>\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const MyAssistantClient = MyAssistant.layerClient.pipe(\n * Layer.provide(AssistantEngine.layerClusterClient),\n * Layer.provide(ShardingLive)\n * )\n * ```\n *\n * @see {@link layerCluster} for the runners that run the chats\n *\n * @category layers\n * @since 0.3.0\n */\nexport const layerClusterClient: Layer.Layer<AssistantEngine, never, Sharding.Sharding> = Layer.effect(\n AssistantEngine,\n Effect.gen(function* () {\n const client = yield* makeClusterClient\n\n return AssistantEngine.of({\n register: (registration) =>\n Effect.die(\n `The ${registration.definition.name} assistant can't register with AssistantEngine.layerClusterClient, which runs no chats: provide AssistantEngine.layerCluster where its toLayer runs.`\n ),\n ...client\n })\n })\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;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AO,OAAOL,KAAU;IAAE;IAAc;IAAQ;GAAU,CAAC;GACjE,OAAO,KAAK;GAEZ,OAAO,WAAW,GAAG;IAEnB,SAAS,YAAY,KAAK,OAAO,QAAQ,QAAQ,KAAK;IACtD,YAAY,YACV,QAAQ,QAAQ,YAAY,OAAO,KAAK,KAAK,QAAQ,QAAQ,KAAK,IAAI,KAAK,OAAO,QAAQ,QAAQ,KAAK;IACzG,cAAc,KAAK;GACrB,CAAC;EACH,CAAC;EAED,OAAO,SAAS,eAAe,YAAY,SAAS,KAAK,OAAO,QAAQ,OAAO,CAAC,GAAG;GACjF,aAAa;GACb,aAAa;EACf,CAAC;CACH,CAAC;CAED,MAAM,SAAS,OAAO;CAEtB,OAAO,gBAAgB,GAAG;EACxB,WAAW,iBAAiB,SAAS,YAAY,CAAC,CAAC,KAAK,OAAO,QAAQ,OAAO,CAAC;EAC/E,GAAG;CACL,CAAC;AACH,CAAC,CACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAsCA,MAAa,qBAA6E,MAAM,OAC9F,iBACA,OAAO,IAAI,aAAa;CACtB,MAAM,SAAS,OAAO;CAEtB,OAAO,gBAAgB,GAAG;EACxB,WAAW,iBACT,OAAO,IACL,OAAO,aAAa,WAAW,KAAK,qJACtC;EACF,GAAG;CACL,CAAC;AACH,CAAC,CACH"}
|
package/dist/ChatSignal.js
CHANGED
|
@@ -6,7 +6,7 @@ import * as Schema from "effect/Schema";
|
|
|
6
6
|
* status of what the assistant is doing, and whether it is writing a message to the user.
|
|
7
7
|
*
|
|
8
8
|
* Signals are never stored. They reach only the subscribers that are listening when they are sent
|
|
9
|
-
* (`assistant.subscribe(chatId, {
|
|
9
|
+
* (`assistant.subscribe(chatId, { signals: true })`), between the chat's entries and in order with
|
|
10
10
|
* them. A turn's model never reads them, compaction never sees them, and a client that loads the
|
|
11
11
|
* chat again starts without them. The turn itself shows in the log, from its `TurnStarted` to its
|
|
12
12
|
* `TurnCompleted` or `TurnFailed`.
|
package/dist/ChatSignal.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ChatSignal.js","names":[],"sources":["../src/ChatSignal.ts"],"sourcesContent":["/**\n * This module provides the signals a chat sends its live subscribers while a turn works: a short\n * status of what the assistant is doing, and whether it is writing a message to the user.\n *\n * Signals are never stored. They reach only the subscribers that are listening when they are sent\n * (`assistant.subscribe(chatId, {
|
|
1
|
+
{"version":3,"file":"ChatSignal.js","names":[],"sources":["../src/ChatSignal.ts"],"sourcesContent":["/**\n * This module provides the signals a chat sends its live subscribers while a turn works: a short\n * status of what the assistant is doing, and whether it is writing a message to the user.\n *\n * Signals are never stored. They reach only the subscribers that are listening when they are sent\n * (`assistant.subscribe(chatId, { signals: true })`), between the chat's entries and in order with\n * them. A turn's model never reads them, compaction never sees them, and a client that loads the\n * chat again starts without them. The turn itself shows in the log, from its `TurnStarted` to its\n * `TurnCompleted` or `TurnFailed`.\n *\n * There is no signal that clears a status: the next one replaces it, typing hides it, and the\n * turn's end clears it. Typing stops before the turn ends, also when it fails, so neither\n * outlives its turn.\n *\n * @since 0.13.0\n */\nimport * as Schema from \"effect/Schema\"\n\n/**\n * Represents the line the chat shows next to the assistant while a turn works, like \"Checking\n * last summer's campaign budget\". The latest one shows until the next, until the model starts\n * writing to the user, or until the turn ends.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class Status extends Schema.TaggedClass<Status>()(\"Status\", {\n text: Schema.String\n}) {}\n\n/**\n * Represents the model starting to write a message to the user. The status line goes: the user\n * sees the message coming instead.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class TypingStarted extends Schema.TaggedClass<TypingStarted>()(\"TypingStarted\", {}) {}\n\n/**\n * Represents the end of the typing: the message is in the chat's log, or the model wrote none.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport class TypingStopped extends Schema.TaggedClass<TypingStopped>()(\"TypingStopped\", {}) {}\n\n/**\n * Schema for any of a chat's signals.\n *\n * @category schemas\n * @since 0.13.0\n */\nexport const ChatSignal = Schema.Union([Status, TypingStarted, TypingStopped])\n\n/**\n * Represents any of a chat's signals.\n *\n * @category models\n * @since 0.13.0\n */\nexport type ChatSignal = typeof ChatSignal.Type\n\n/**\n * Returns whether a value is one of a chat's signals, such as an item of a live subscription that\n * isn't an entry.\n *\n * @category guards\n * @since 0.13.0\n */\nexport const isChatSignal: (u: unknown) => u is ChatSignal = Schema.is(ChatSignal)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,IAAa,SAAb,cAA4B,OAAO,YAAoB,CAAC,CAAC,UAAU,EACjE,MAAM,OAAO,OACf,CAAC,CAAC,CAAC,CAAC;;;;;;;;AASJ,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQ7F,IAAa,gBAAb,cAAmC,OAAO,YAA2B,CAAC,CAAC,iBAAiB,CAAC,CAAC,CAAC,CAAC,CAAC;;;;;;;AAQ7F,MAAa,aAAa,OAAO,MAAM;CAAC;CAAQ;CAAe;AAAa,CAAC;;;;;;;;AAiB7E,MAAa,eAAgD,OAAO,GAAG,UAAU"}
|
package/dist/Timeline.d.ts
CHANGED
|
@@ -35,6 +35,8 @@ export declare const Block: Schema.Struct<{
|
|
|
35
35
|
readonly props: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
36
36
|
readonly status: Schema.Literals<readonly ["open", "answered", "closed"]>;
|
|
37
37
|
readonly answer: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
38
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
39
|
+
readonly answeredAt: Schema.optional<Schema.Finite>;
|
|
38
40
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
39
41
|
readonly result: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
40
42
|
}>;
|
|
@@ -85,6 +87,8 @@ export declare const AssistantMessage: Schema.TaggedStruct<"AssistantMessage", {
|
|
|
85
87
|
readonly props: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
86
88
|
readonly status: Schema.Literals<readonly ["open", "answered", "closed"]>;
|
|
87
89
|
readonly answer: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
90
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
91
|
+
readonly answeredAt: Schema.optional<Schema.Finite>;
|
|
88
92
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
89
93
|
readonly result: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
90
94
|
}>>;
|
|
@@ -202,7 +206,7 @@ export type SpecialistWorking = typeof SpecialistWorking.Type;
|
|
|
202
206
|
* something that arrived. `specialists` lists the specialists that are working. When the chat is
|
|
203
207
|
* idle, nothing is working, even if a workflow is waiting on a timer or on the user.
|
|
204
208
|
*
|
|
205
|
-
* On a live subscription (`subscribe(chatId, {
|
|
209
|
+
* On a live subscription (`subscribe(chatId, { signals: true })`), `status` is a short line about what
|
|
206
210
|
* the running turn is doing, and `typing` is true while the model writes a message to the user. Both
|
|
207
211
|
* come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline
|
|
208
212
|
* folded from the log alone has neither.
|
package/dist/Timeline.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Timeline.d.ts","names":[],"sources":["../src/Timeline.ts"],"mappings":";;;;;;;;;;;;;;;;qBA6Ca,aAAW,OAAA;;;;;;;YAQZ,qBAAqB,YAAY;;;;;;;;;qBAUhC,OAAK,OAAA
|
|
1
|
+
{"version":3,"file":"Timeline.d.ts","names":[],"sources":["../src/Timeline.ts"],"mappings":";;;;;;;;;;;;;;;;qBA6Ca,aAAW,OAAA;;;;;;;YAQZ,qBAAqB,YAAY;;;;;;;;;qBAUhC,OAAK,OAAA;;;;;;;;;;;;;;;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C,MAAM;;;;;;;;;;;;;;;;;qBAmC9E;GACV,SAAS,cAAc,YAA2B;GAClD,cAAc,aAAa,MAAM,uBAChC,SAAS,cAAc,WACvB,YAAY,WAAW,SACvB,UAAU,YAAY,QACrB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAmDC;GACV,SAAS,cAAc,YAA2B;GAClD,cAAc,aAAa,MAAM,uBAChC,SAAS,cAAc,WACvB,YAAY,WAAW,SACvB,UAAU,YAAY,QACrB,SAAS;;;;;;;;;iBA6TG,WAAW;;WAEjB,QAAQ,cAAc;;WAEtB,OAAO,OAAO,MAAM,MAAgB,SAAS,OAAO;;;;;;;;iBAS9C,eACf,aAAa,cAAc,uCACnB,YAAY;;;;;WAKX;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAkFE;GACV,cAAc,aAAa,MAAM,uBAChC,YAAY,WAAW,SACvB,UAAU,eAAe,SACvB,GAAG,GACL,SAAS,OAAO,OAAO,WAA0B,YAAuB,GAAG,OACxE,OAAO,OAAO,OAAO,uBAAuB,GAAG;GACnD,GAAG,GAAG,cAAc,aAAa,MAAM,uBACtC,SAAS,OAAO,OAAO,WAA0B,YAAuB,GAAG,IAC3E,YAAY,WAAW,SACvB,UAAU,eAAe,QACxB,OAAO,OAAO,OAAO,uBAAuB,GAAG"}
|
package/dist/Timeline.js
CHANGED
|
@@ -78,6 +78,8 @@ const Block = Schema.Struct({
|
|
|
78
78
|
props: Schema.Json,
|
|
79
79
|
status: BlockStatus,
|
|
80
80
|
answer: Schema.optional(Schema.Json),
|
|
81
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
82
|
+
answeredAt: Schema.optional(Schema.Finite),
|
|
81
83
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
82
84
|
result: Schema.optional(Schema.Json)
|
|
83
85
|
});
|
|
@@ -153,7 +155,7 @@ const SpecialistWorking = Schema.Struct({
|
|
|
153
155
|
* something that arrived. `specialists` lists the specialists that are working. When the chat is
|
|
154
156
|
* idle, nothing is working, even if a workflow is waiting on a timer or on the user.
|
|
155
157
|
*
|
|
156
|
-
* On a live subscription (`subscribe(chatId, {
|
|
158
|
+
* On a live subscription (`subscribe(chatId, { signals: true })`), `status` is a short line about what
|
|
157
159
|
* the running turn is doing, and `typing` is true while the model writes a message to the user. Both
|
|
158
160
|
* come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline
|
|
159
161
|
* folded from the log alone has neither.
|
|
@@ -424,6 +426,7 @@ const folding = (show) => {
|
|
|
424
426
|
let activity = empty$1;
|
|
425
427
|
let live = noLive;
|
|
426
428
|
let blocks = /* @__PURE__ */ new Map();
|
|
429
|
+
const answeredAt = /* @__PURE__ */ new Map();
|
|
427
430
|
const items = /* @__PURE__ */ new Map();
|
|
428
431
|
const sent = /* @__PURE__ */ new Map();
|
|
429
432
|
const results = /* @__PURE__ */ new Map();
|
|
@@ -442,10 +445,16 @@ const folding = (show) => {
|
|
|
442
445
|
...block,
|
|
443
446
|
result
|
|
444
447
|
};
|
|
445
|
-
|
|
448
|
+
if (state?.answer === void 0) return shown;
|
|
449
|
+
const answered = {
|
|
446
450
|
...shown,
|
|
447
451
|
answer: toJson(state.answer.value)
|
|
448
452
|
};
|
|
453
|
+
const at = answeredAt.get(message.id);
|
|
454
|
+
return at === void 0 ? answered : {
|
|
455
|
+
...answered,
|
|
456
|
+
answeredAt: at
|
|
457
|
+
};
|
|
449
458
|
};
|
|
450
459
|
const itemOf = (message, at) => {
|
|
451
460
|
const block = blockOf(message);
|
|
@@ -585,6 +594,7 @@ const folding = (show) => {
|
|
|
585
594
|
});
|
|
586
595
|
}
|
|
587
596
|
blocks = apply$2(blocks, event);
|
|
597
|
+
if (Predicate.isTagged(event, "BlockAnswer") && blocks.get(event.messageId)?.answer === event) answeredAt.set(event.messageId, entry.at);
|
|
588
598
|
const decidedBefore = approvals;
|
|
589
599
|
approvals = apply$1(approvals, entry);
|
|
590
600
|
const all = [...[...new Set(touched(event, entry.at))].flatMap((id) => {
|
package/dist/Timeline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Timeline.js","names":["AssistantEvent.Attachment","AssistantEvent.ToolOutcome","AppEvents.tagOf","AssistantActivity.empty","AppEvents.decodeWith","AssistantActivity.apply","AssistantEvent.isLibraryEvent","BlockKit.apply","ToolApproval.apply","ChatSignal.isChatSignal"],"sources":["../src/Timeline.ts"],"sourcesContent":["/**\n * This module provides a chat's timeline: the chat as its user sees it. A chat client receives the\n * timeline and nothing else.\n *\n * A {@link Timeline} holds the chat's items: the messages with their blocks, the app's own events\n * it shows (each typed with its event, see {@link EventItem}), and the tool calls waiting for the\n * user's approval ({@link ApprovalItem}). It also holds the chat's\n * {@link Activity}, and whether the last turn failed or the chat was deleted. It never contains the\n * model's output, tool calls or results, what the model read, or why a turn failed. The server\n * streams {@link Change}s by piping the assistant's `subscribe` through {@link changes}, and the\n * client folds them with {@link fold} (or {@link apply}, from {@link empty}). On the server,\n * {@link fromEntries} builds a whole timeline from a chat's log, and {@link snapshot} the whole\n * timeline as one change.\n *\n * **Only the app events in `show` reach the timeline**, and none by default: an event that is only\n * for the assistant, like a summary of the chat, stays out. The RPC's schema, `Change([...])`,\n * names the same events and types the client's timeline with them.\n *\n * @since 0.3.0\n */\nimport { dual } from \"effect/Function\"\nimport * as Match from \"effect/Match\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaTransformation from \"effect/SchemaTransformation\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Assistant from \"./Assistant.ts\"\nimport * as AssistantActivity from \"./AssistantActivity.ts\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport * as BlockKit from \"./BlockKit.ts\"\nimport * as ChatSignal from \"./ChatSignal.ts\"\nimport { InputId } from \"./InputId.ts\"\nimport * as AppEvents from \"./internal/events.ts\"\nimport * as ToolApproval from \"./ToolApproval.ts\"\nimport { toJson } from \"./internal/schema.ts\"\n\n/**\n * Schema for the status of a block. A block is `\"open\"` while it accepts an answer, `\"answered\"`\n * once the user has used it, and `\"closed\"` when it closed without an answer because the user\n * answered in words or moved on.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const BlockStatus = Schema.Literals([\"open\", \"answered\", \"closed\"])\n\n/**\n * The status of a block.\n *\n * @category models\n * @since 0.1.0\n */\nexport type BlockStatus = typeof BlockStatus.Type\n\n/**\n * Schema for a block on an assistant's message. It holds the block's kind, its props (JSON, as\n * the block's props schema encodes them), its status, and the user's answer (JSON, as the block's\n * answer schema encodes it).\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Block = Schema.Struct({\n kind: Schema.String,\n props: Schema.Json,\n status: BlockStatus,\n answer: Schema.optional(Schema.Json),\n /** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */\n result: Schema.optional(Schema.Json)\n})\n\n/**\n * Represents a block on an assistant's message.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Block = typeof Block.Type\n\n/**\n * Schema for a message the user sent. `at` is when it was stored, in epoch\n * milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const UserMessage = Schema.TaggedStruct(\"UserMessage\", {\n id: InputId,\n text: Schema.String,\n attachments: Schema.optional(Schema.Array(AssistantEvent.Attachment)),\n at: Schema.Finite\n})\n\n/**\n * Represents a message the user sent.\n *\n * @category models\n * @since 0.1.0\n */\nexport type UserMessage = typeof UserMessage.Type\n\n/**\n * Schema for a message the assistant sent the user, including its block if it has one.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AssistantMessage = Schema.TaggedStruct(\"AssistantMessage\", {\n id: Schema.String,\n text: Schema.String,\n at: Schema.Finite,\n block: Schema.optional(Block)\n})\n\n/**\n * Represents a message the assistant sent the user.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AssistantMessage = typeof AssistantMessage.Type\n\n/**\n * Represents one of the app's own events in the timeline: an item between the messages, in the\n * order the chat stored it.\n *\n * **Details**\n *\n * The item's `_tag` is the event's, so a match over a timeline's items takes a handler per event\n * beside `UserMessage` and `AssistantMessage`. The event, decoded with its schema, is in `event`,\n * and the item's own fields sit beside it rather than spread into it: an event may have an `id` or\n * an `at` of its own, and a class instance keeps its prototype. `id` is fixed per entry of the\n * chat's log, and `at` is when the event was stored, in epoch milliseconds.\n *\n * @category models\n * @since 0.3.0\n */\nexport type EventItem<E> = E extends { readonly _tag: infer Tag extends string }\n ? { readonly _tag: Tag; readonly id: string; readonly at: number; readonly event: E }\n : never\n\n/**\n * Schema for a tool call that waits, or waited, for the user's approval, as an item on the\n * timeline.\n *\n * **Details**\n *\n * It is only the yes or no: the assistant's own message tells the user what it asks them to\n * approve, so the item carries no params. `id` is the call's id, which the decision is for (see\n * `ToolApproval.approve`), and `tool` the tool's name, for a label. `status` is where the call stands\n * (`ToolApproval.Status`); `reason` is the user's, when they rejected it with one; `outcome` is how\n * the approved call went, once it ran. `at` is when the call started waiting, in epoch\n * milliseconds. A change updates the item in place as the call is decided and run.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport const ApprovalItem = Schema.TaggedStruct(\"ToolApproval\", {\n id: Schema.String,\n tool: Schema.String,\n status: Schema.Literals([\"pending\", \"approved\", \"rejected\", \"expired\"]),\n reason: Schema.optional(Schema.String),\n outcome: Schema.optional(AssistantEvent.ToolOutcome),\n at: Schema.Finite\n})\n\n/**\n * Represents a tool call that waits, or waited, for the user's approval, as an item on the\n * timeline.\n *\n * @category models\n * @since 0.4.0\n */\nexport type ApprovalItem = typeof ApprovalItem.Type\n\n/**\n * Represents an item in the chat's timeline: a message the user or the assistant sent, one of the\n * app's own events it shows (see {@link EventItem}), or a tool call waiting for the user's approval\n * (see {@link ApprovalItem}).\n *\n * **Example** (Showing each item of a chat)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n * import * as Match from \"effect/Match\"\n * import * as Schema from \"effect/Schema\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const line = (item: Timeline.Item<DailyBudgetReached>) =>\n * Match.valueTags(item, {\n * UserMessage: (sent) => `You: ${sent.text}`,\n * AssistantMessage: (sent) => `Assistant: ${sent.text}`,\n * DailyBudgetReached: () => \"You've reached today's budget.\"\n * })\n * ```\n *\n * @category models\n * @since 0.3.0\n */\nexport type Item<Events = never> = UserMessage | AssistantMessage | EventItem<Events> | ApprovalItem\n\n/**\n * Schema for a specialist that is working for the assistant. It holds the specialist's name and\n * when it started, in epoch milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const SpecialistWorking = Schema.Struct({\n specialist: Schema.String,\n since: Schema.Finite\n})\n\n/**\n * Represents a specialist that is working for the assistant.\n *\n * @category models\n * @since 0.1.0\n */\nexport type SpecialistWorking = typeof SpecialistWorking.Type\n\n/**\n * Schema for what is working in the chat.\n *\n * `working` is true while the assistant runs a turn, or when a turn is about to start for\n * something that arrived. `specialists` lists the specialists that are working. When the chat is\n * idle, nothing is working, even if a workflow is waiting on a timer or on the user.\n *\n * On a live subscription (`subscribe(chatId, { live: true })`), `status` is a short line about what\n * the running turn is doing, and `typing` is true while the model writes a message to the user. Both\n * come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline\n * folded from the log alone has neither.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Activity = Schema.Struct({\n working: Schema.Boolean,\n specialists: Schema.Array(SpecialistWorking),\n status: Schema.optional(Schema.String),\n typing: Schema.Boolean\n})\n\n/**\n * Represents what is working in the chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Activity = typeof Activity.Type\n\n/**\n * Represents a chat's timeline: the chat as its user sees it, typed with the app's events it shows.\n * It holds the chat's items in order, what is working in it, whether the last turn failed, and\n * whether the chat was deleted. `sequence` is the position in the chat's log that the timeline is up to.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface Timeline<Events = never> {\n readonly sequence: number\n readonly items: ReadonlyArray<Item<Events>>\n readonly activity: Activity\n /** Whether the last turn failed with no message after it. */\n readonly failed: boolean\n /** Whether the chat was deleted. A deleted chat accepts nothing more, and its stream ends. */\n readonly deleted: boolean\n}\n\n/**\n * Represents a change to a chat's timeline, typed with the app's events it shows.\n *\n * **Details**\n *\n * A change holds each item that is new or changed (for example, a message whose block was\n * answered or closed, or a call the user approved), in full. It also holds the current activity, whether the last turn failed,\n * and whether the chat was deleted. `sequence` is the position in the chat's log that the change is up\n * to.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface Change<Events = never> {\n readonly sequence: number\n readonly items: ReadonlyArray<Item<Events>>\n readonly activity: Activity\n readonly failed: boolean\n readonly deleted: boolean\n}\n\nconst eventItem = (schema: AssistantEvent.AppEventSchema) =>\n Schema.Struct({ _tag: Schema.Literal(AppEvents.tagOf(schema)), id: Schema.String, at: Schema.Finite, event: schema })\n\nfunction makeChange<const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(\n events?: Events\n): Schema.Codec<Change<Events[number][\"Type\"]>, Schema.Json>\n// The overload states the decoded type: an item per given schema, each typed with its own event.\nfunction makeChange(events: ReadonlyArray<AssistantEvent.AppEventSchema> = []): Schema.Top {\n const AnyItem = Schema.toCodecJson(\n Schema.Union([UserMessage, AssistantMessage, ApprovalItem, ...events.map(eventItem)])\n )\n\n const decodeItem = Schema.decodeUnknownOption(AnyItem)\n const encodeItem = Schema.encodeUnknownSync(AnyItem)\n\n return Schema.Struct({\n sequence: Schema.Int,\n // An item for an event this schema doesn't name, or that doesn't decode (from a newer server, say), is left out\n // rather than failing the whole change.\n items: Schema.Array(Schema.Json).pipe(\n Schema.decodeTo(\n Schema.Array(Schema.toType(AnyItem)),\n SchemaTransformation.transform<ReadonlyArray<typeof AnyItem.Type>, ReadonlyArray<Schema.Json>>({\n decode: (json) => json.flatMap((item) => Option.toArray(decodeItem(item))),\n encode: (items) => items.map((item) => encodeItem(item))\n })\n )\n ),\n activity: Activity,\n failed: Schema.Boolean,\n deleted: Schema.Boolean\n })\n}\n\n/**\n * Creates the schema for the changes to a chat's timeline, with items for the given app events,\n * in JSON.\n *\n * **Details**\n *\n * It is the success schema of the RPC that streams a chat's timeline: name the events the chat's\n * users see, the same ones the handler passes to {@link changes} as `show`. Tool calls waiting for\n * approval are always in it, as {@link ApprovalItem}s. Each item decodes its\n * event with that event's schema, so the client gets `Change<Events>` typed with them and folds it\n * with {@link fold}, no definition needed. `Change()` carries no app events.\n *\n * A handler whose changes show an event the schema doesn't name doesn't compile.\n *\n * **Example** (An RPC that streams a chat's timeline, with the budget notice)\n *\n * ```ts\n * import { ChatId, Timeline } from \"effect-assistant\"\n * import * as Rpc from \"effect/rpc/Rpc\"\n * import * as Schema from \"effect/Schema\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const Subscribe = Rpc.make(\"Subscribe\", {\n * payload: { chatId: ChatId.ChatId },\n * success: Timeline.Change([DailyBudgetReached]),\n * stream: true\n * })\n * ```\n *\n * @category schemas\n * @since 0.3.0\n */\nexport const Change: <const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(\n events?: Events\n) => Schema.Codec<Change<Events[number][\"Type\"]>, Schema.Json> = makeChange\n\n/**\n * The timeline of a chat before anything has happened in it, with no items and nothing working.\n * Use it as the starting point when folding changes with {@link apply}.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const empty: Timeline = {\n sequence: 0,\n items: [],\n activity: { working: false, specialists: [], typing: false },\n failed: false,\n deleted: false\n}\n\n/**\n * Returns the timeline after a change.\n *\n * **Details**\n *\n * Each item in the change replaces the item with the same id, in place, and new items are added\n * after the rest. The change's activity, `failed`, and `deleted` replace the timeline's. Applying a\n * change twice changes nothing, so a client that resubscribes from the start can fold again and get\n * the same timeline.\n *\n * The timeline is typed with the change's events, as its RPC's schema decoded them (see\n * {@link Change}). To fold a stream of changes, use {@link fold}: in\n * `Stream.scan(() => Timeline.empty, Timeline.apply)`, TypeScript fixes the state's type from\n * `empty` before it sees the changes' events, so that form needs the timeline's type written out.\n *\n * **Example** (Folding changes into your own state)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n *\n * interface State<Events> {\n * readonly timeline: Timeline.Timeline<Events>\n * readonly unread: number\n * }\n *\n * const next = <Events>(state: State<Events>, change: Timeline.Change<Events>): State<Events> => ({\n * timeline: Timeline.apply(state.timeline, change),\n * unread: state.unread + change.items.length\n * })\n * ```\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const apply = <Events>(timeline: Timeline<Events>, change: Change<Events>): Timeline<Events> => {\n const changed = new Map(change.items.map((item) => [item.id, item]))\n const known = new Set(timeline.items.map((item) => item.id))\n\n return {\n sequence: Math.max(timeline.sequence, change.sequence),\n items: [\n ...timeline.items.map((item) => changed.get(item.id) ?? item),\n ...change.items.filter((item) => !known.has(item.id))\n ],\n activity: change.activity,\n failed: change.failed,\n deleted: change.deleted\n }\n}\n\n/**\n * Returns the timelines a stream of changes folds to, from {@link empty}, typed with the changes'\n * events.\n *\n * **Example** (A chat's timeline on the client)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n * import * as Schema from \"effect/Schema\"\n * import * as Stream from \"effect/Stream\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * // The stream of an RPC whose success schema is `Timeline.Change([DailyBudgetReached])`.\n * declare const changes: Stream.Stream<Timeline.Change<DailyBudgetReached>>\n *\n * const timelines = changes.pipe(Timeline.fold) // Stream<Timeline.Timeline<DailyBudgetReached>>\n * ```\n *\n * @category combinators\n * @since 0.3.0\n */\nexport const fold = <Events, E, R>(\n changes: Stream.Stream<Change<Events>, E, R>\n): Stream.Stream<Timeline<Events>, E, R> => changes.pipe(Stream.scan((): Timeline<Events> => empty, apply))\n\n/**\n * Returns whether nothing is working in the chat: no turn is running or about to start, and no\n * specialist is working.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isIdle = <Events>(timeline: Timeline<Events>): boolean =>\n !timeline.activity.working && timeline.activity.specialists.length === 0\n\ninterface AnyEventItem {\n readonly _tag: string\n readonly id: string\n readonly at: number\n readonly event: { readonly _tag: string }\n}\n\ntype AnyItem = UserMessage | AssistantMessage | AnyEventItem | ApprovalItem\n\n// What the fold below builds: the overloads that use it type its items with the events shown.\ninterface AnyChange {\n readonly sequence: number\n readonly items: ReadonlyArray<AnyItem>\n readonly activity: Activity\n readonly failed: boolean\n readonly deleted: boolean\n}\n\n/**\n * Represents the options for building a chat's timeline from its log.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface ShowOptions<Show extends ReadonlyArray<AssistantEvent.AppEventSchema>> {\n /**\n * The schemas of the app's events the chat's users see. Each becomes an item in the timeline;\n * the app's other events are left out. Defaults to none.\n */\n readonly show?: Show | undefined\n}\n\n/**\n * Represents the schemas an assistant's timeline may show: some of its own events.\n *\n * @category utility types\n * @since 0.3.0\n */\nexport type Shown<Events> = ReadonlyArray<AssistantEvent.AppEventSchema & { readonly Type: Events }>\n\nfunction snapshotWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change\nfunction snapshotWith<Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n): Change<Show[number][\"Type\"]>\nfunction snapshotWith(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n _definition?: Schemas,\n options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): AnyChange {\n const timeline = folding(options?.show ?? [])\n\n for (const entry of entries) timeline.step(entry)\n\n return timeline.snapshot\n}\n\n/**\n * Returns a chat's whole timeline as one change, built from the entries of its log.\n *\n * **When to use**\n *\n * Use it on the server for an RPC that returns a whole chat at once: its success schema is\n * {@link Change} with the same events as `show`, and the client applies it to {@link empty}.\n *\n * **Details**\n *\n * Only the app's events in `show` become items; without it, the timeline has none.\n *\n * @category constructors\n * @since 0.3.0\n */\nexport const snapshot: {\n (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change\n <Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n ): Change<Show[number][\"Type\"]>\n} = snapshotWith\n\nfunction fromEntriesWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline\nfunction fromEntriesWith<Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n): Timeline<Show[number][\"Type\"]>\nfunction fromEntriesWith(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n _definition?: Schemas,\n options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): AnyChange {\n const timeline = folding(options?.show ?? [])\n\n for (const entry of entries) timeline.step(entry)\n\n return timeline.snapshot\n}\n\n/**\n * Returns a chat's timeline, built from the entries of its log.\n *\n * **When to use**\n *\n * Use it in server-side code that reads a whole chat. A client gets the timeline as a stream from\n * {@link changes} instead, and an RPC that returns a whole chat sends a {@link snapshot}.\n *\n * **Details**\n *\n * Only the app's events in `show` become items, typed with their schemas; without it, the timeline\n * has none.\n *\n * **Example** (Building a chat's timeline from its log)\n *\n * ```ts\n * import { type ChatId, ChatLog, Timeline } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * const timelineOf = (chatId: ChatId.ChatId) =>\n * ChatLog.ChatLog.use((log) => log.read(chatId)).pipe(\n * Effect.map((entries) => Timeline.fromEntries(entries))\n * )\n * ```\n *\n * @see {@link changes} for a stream of changes instead of a whole timeline\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const fromEntries: {\n (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline\n <Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n ): Timeline<Show[number][\"Type\"]>\n} = fromEntriesWith\n\ninterface Schemas {\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n}\n\ninterface Folding {\n readonly step: (entry: AssistantEvent.AnyEntry) => AnyChange | undefined\n readonly signal: (signal: ChatSignal.ChatSignal) => AnyChange | undefined\n readonly snapshot: AnyChange\n}\n\ninterface LiveState {\n readonly status: string | undefined\n readonly typing: boolean\n}\n\nconst noLive: LiveState = { status: undefined, typing: false }\n\nconst applySignal = (live: LiveState, signal: ChatSignal.ChatSignal): LiveState =>\n Match.value(signal).pipe(\n Match.tagsExhaustive({\n Status: ({ text }): LiveState => ({ ...live, status: text }),\n TypingStarted: (): LiveState => ({ status: undefined, typing: true }),\n TypingStopped: (): LiveState => ({ ...live, typing: false })\n })\n )\n\nconst activityOf = (activity: AssistantActivity.State, live: LiveState): Activity => {\n const { status } = live\n\n const shown: Activity = {\n working: activity.turnSince !== undefined || activity.queued,\n specialists: [...activity.specialists.values()].map((run) => ({\n specialist: run.specialist,\n since: run.since\n })),\n typing: live.typing\n }\n\n return status === undefined ? shown : { ...shown, status }\n}\n\nconst sameActivity = (a: Activity, b: Activity) =>\n a.working === b.working &&\n a.status === b.status &&\n a.typing === b.typing &&\n a.specialists.length === b.specialists.length &&\n a.specialists.every((run, i) => {\n const other = b.specialists[i]\n\n return other !== undefined && run.specialist === other.specialist && run.since === other.since\n })\n\nconst folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding => {\n const shown = new Map(show.map((schema) => [AppEvents.tagOf(schema), schema]))\n let approvals: ReadonlyMap<string, ToolApproval.State> = new Map()\n let sequence = 0\n let failed = false\n let deleted = false\n let activity = AssistantActivity.empty\n let live = noLive\n let blocks: ReadonlyMap<string, BlockKit.State> = new Map()\n // The items in order, and the assistant's messages as stored: their blocks change as the chat goes on.\n const items = new Map<string, AnyItem>()\n const sent = new Map<string, AssistantEvent.AssistantMessage>()\n // The results a block can show, by id: a message shows one stored before it.\n const results = new Map<string, Schema.Json>()\n\n const blockOf = (message: AssistantEvent.AssistantMessage): Block | undefined => {\n if (message.block === undefined) return undefined\n\n const state = blocks.get(message.id)\n const status = state === undefined || state.open ? \"open\" : state.answer === undefined ? \"closed\" : \"answered\"\n const block: Block = { kind: message.block.kind, props: toJson(message.block.props), status }\n const { resultId } = message.block\n const result = resultId === undefined ? undefined : results.get(resultId)\n const shown = result === undefined ? block : { ...block, result }\n\n return state?.answer === undefined ? shown : { ...shown, answer: toJson(state.answer.value) }\n }\n\n const itemOf = (message: AssistantEvent.AssistantMessage, at: number): AssistantMessage => {\n const block = blockOf(message)\n\n return block === undefined\n ? AssistantMessage.make({ id: message.id, text: message.text, at })\n : AssistantMessage.make({ id: message.id, text: message.text, at, block })\n }\n\n const touched = (event: AssistantEvent.AssistantEvent, at: number): ReadonlyArray<string> =>\n Match.value(event).pipe(\n Match.tagsExhaustive({\n UserMessage: (message) => {\n items.set(\n message.id,\n message.attachments === undefined\n ? UserMessage.make({ id: message.id, text: message.text, at })\n : UserMessage.make({\n id: message.id,\n text: message.text,\n attachments: message.attachments,\n at\n })\n )\n failed = false\n\n return [message.id]\n },\n AssistantMessage: (message) => {\n sent.set(message.id, message)\n items.set(message.id, itemOf(message, at))\n failed = false\n\n return [message.id, ...(message.closes ?? [])]\n },\n BlockAnswer: (answer) => {\n failed = false\n\n return [answer.messageId]\n },\n BlocksClosed: (closed) => closed.messageIds,\n ApprovalRequested: () => [],\n ApprovalDecision: () => {\n failed = false\n\n return []\n },\n ApprovalsExpired: () => [],\n TurnFailed: () => {\n failed = true\n\n return []\n },\n ModelOutput: () => [],\n ToolStarted: () => [],\n ToolResult: (result) => {\n if (result.resultId !== undefined && result.outcome === \"success\") {\n results.set(result.resultId, result.full ?? result.result)\n }\n\n return []\n },\n TurnStarted: () => [],\n TurnCompleted: () => [],\n SpecialistStarted: () => [],\n SpecialistFinished: () => [],\n ChatDeleted: () => {\n deleted = true\n\n return []\n }\n })\n )\n\n // Decoded as `subscribe` streams it, or as the log stores it; one that doesn't decode is left out.\n const eventItemOf = (entry: AssistantEvent.AnyEntry): Option.Option<AnyEventItem> => {\n const schema = shown.get(entry.event._tag)\n\n if (schema === undefined) return Option.none()\n\n const event = Schema.is(schema)(entry.event) ? Option.some(entry.event) : AppEvents.decodeWith(schema, entry.event)\n\n return Option.map(event, (decoded) => ({\n _tag: decoded._tag,\n id: `app-event:${entry.sequence}`,\n at: entry.at,\n event: decoded\n }))\n }\n\n const callsOf = (event: AssistantEvent.AssistantEvent): ReadonlyArray<string> =>\n Predicate.isTagged(event, \"ApprovalsExpired\")\n ? event.callIds\n : Predicate.isTagged(event, \"ApprovalRequested\") ||\n Predicate.isTagged(event, \"ApprovalDecision\") ||\n Predicate.isTagged(event, \"ToolResult\")\n ? [event.callId]\n : []\n\n // The items of the calls this entry changed.\n const approvalItems = (event: AssistantEvent.AssistantEvent, before: ReadonlyMap<string, ToolApproval.State>) =>\n callsOf(event).flatMap((callId) => {\n const state = approvals.get(callId)\n\n if (state === undefined || state === before.get(callId)) return []\n\n const item = ApprovalItem.make({\n id: callId,\n tool: state.request.tool,\n status: state.status,\n reason: state.reason,\n outcome: state.outcome,\n at: state.at\n })\n\n items.set(callId, item)\n\n return [item]\n })\n\n // A turn's end clears what it showed, also when a signal didn't arrive.\n const settle = (event: { readonly _tag: string }) => {\n if (\n Predicate.isTagged(event, \"TurnCompleted\") ||\n Predicate.isTagged(event, \"TurnFailed\") ||\n Predicate.isTagged(event, \"ChatDeleted\")\n ) {\n live = noLive\n }\n }\n\n const signal = (received: ChatSignal.ChatSignal): AnyChange | undefined => {\n const previous = activityOf(activity, live)\n\n live = applySignal(live, received)\n\n const now = activityOf(activity, live)\n\n return sameActivity(previous, now) ? undefined : { sequence, items: [], activity: now, failed, deleted }\n }\n\n const step = (entry: AssistantEvent.AnyEntry): AnyChange | undefined => {\n const previous = { activity: activityOf(activity, live), failed, deleted }\n const { event } = entry\n\n sequence = entry.sequence\n activity = AssistantActivity.apply(activity, entry)\n settle(event)\n\n if (!AssistantEvent.isLibraryEvent(event)) {\n const now = activityOf(activity, live)\n\n return Option.match(eventItemOf(entry), {\n onNone: () =>\n sameActivity(previous.activity, now) ? undefined : { sequence, items: [], activity: now, failed, deleted },\n onSome: (item) => {\n items.set(item.id, item)\n\n return { sequence, items: [item], activity: now, failed, deleted }\n }\n })\n }\n\n blocks = BlockKit.apply(blocks, event)\n\n const decidedBefore = approvals\n approvals = ToolApproval.apply(approvals, entry)\n\n const changed = [...new Set(touched(event, entry.at))].flatMap((id) => {\n const message = sent.get(id)\n const current = items.get(id)\n\n if (message === undefined || current === undefined) return current === undefined ? [] : [current]\n\n const next = itemOf(message, current.at)\n items.set(id, next)\n\n return [next]\n })\n\n const all = [...changed, ...approvalItems(event, decidedBefore)]\n const now = activityOf(activity, live)\n\n return all.length === 0 &&\n failed === previous.failed &&\n deleted === previous.deleted &&\n sameActivity(previous.activity, now)\n ? undefined\n : { sequence, items: all, activity: now, failed, deleted }\n }\n\n return {\n step,\n signal,\n get snapshot() {\n return { sequence, items: [...items.values()], activity: activityOf(activity, live), failed, deleted }\n }\n }\n}\n\nconst merge = (changes: ReadonlyArray<AnyChange>): AnyChange | undefined => {\n const last = changes.at(-1)\n\n if (last === undefined) return undefined\n\n const items = new Map<string, AnyItem>()\n\n for (const change of changes) for (const item of change.items) items.set(item.id, item)\n\n return {\n sequence: last.sequence,\n items: [...items.values()],\n activity: last.activity,\n failed: last.failed,\n deleted: last.deleted\n }\n}\n\n/**\n * Represents an assistant's definition as the timeline reads it. An assistant made with\n * `Assistant.make` fits it.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Definition<Events = never> {\n /** The schemas of the assistant's events. */\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n /** The schema of the chat's entries, typed with the assistant's events: it types `show`. */\n readonly Entry: Schema.Codec<Assistant.Entry<Events>, Schema.Json>\n}\n\n/**\n * Represents the options accepted by {@link changes}.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface ChangesOptions<\n Show extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []\n> extends ShowOptions<Show> {\n /**\n * The `sequence` up to which the client already has the timeline. The result contains only the\n * changes after it. Defaults to `0`, every change.\n */\n readonly after?: number | undefined\n}\n\nfunction changesWith<E, R, Events, const Show extends Shown<Events> = readonly []>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n): Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\nfunction changesWith<E, R>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n _definition: Schemas,\n options?: ChangesOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): Stream.Stream<AnyChange, E, R> {\n const after = options?.after ?? 0\n\n return entries.pipe(\n Stream.mapAccumArray(\n () => folding(options?.show ?? []),\n (timeline, chunk) => {\n const changed = chunk.flatMap((item) => {\n if (ChatSignal.isChatSignal(item)) return Option.toArray(Option.fromUndefinedOr(timeline.signal(item)))\n\n const change = timeline.step(item)\n\n return change === undefined || item.sequence <= after ? [] : [change]\n })\n\n const merged = merge(changed)\n\n return [timeline, merged === undefined ? [] : [merged]]\n }\n )\n )\n}\n\n/**\n * Returns the stream of changes to a chat's timeline that its entries produce, for a chat client.\n *\n * **Details**\n *\n * The entries must stream from the start of the chat's log, as `assistant.subscribe(chatId)` does\n * without `after`. The fold reads every entry, because a message depends on earlier entries: its\n * block is answered or closed later. `after` only skips emitting the changes up to that `sequence`, so a\n * client that has the timeline up to a `sequence` receives only what changed since. Pass `after` here,\n * not to `subscribe`: a subscription that starts after a `sequence` gives the fold an incomplete log,\n * and the changes it produces are wrong.\n *\n * Each chunk of entries becomes one change; the stored entries, for example, arrive as one chunk.\n *\n * **Only the app's events in `show` reach the client.** Each one becomes an item between the\n * messages (see {@link EventItem}); the app's other events, like a summary of the chat for the\n * model, are left out. Without `show`, none are shown. The changes are typed with the events shown,\n * so the RPC's success schema names the same ones (`Timeline.Change([...])`), and a handler that\n * shows one the schema doesn't name doesn't compile. A timeline shows a turn as working once it\n * starts, or from the user's input.\n *\n * **Example** (Streaming a chat's timeline to a client, with the one app event its user sees)\n *\n * ```ts\n * import { Assistant, type ChatId, Timeline } from \"effect-assistant\"\n * import * as Schema from \"effect/Schema\"\n * import * as Stream from \"effect/Stream\"\n *\n * class Summary extends Schema.TaggedClass<Summary>()(\"Summary\", { text: Schema.String, throughSequence: Schema.Int }) {}\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const MyAssistant = Assistant.make(\"my-assistant\", { events: [Summary, DailyBudgetReached] })\n *\n * // The summary is for the model: only the budget notice reaches the user.\n * const watch = (chatId: ChatId.ChatId, after: number) =>\n * Stream.unwrap(\n * MyAssistant.useSync((assistant) =>\n * assistant.subscribe(chatId).pipe(Timeline.changes(MyAssistant, { show: [DailyBudgetReached], after }))\n * )\n * )\n * ```\n *\n * @see {@link fold} for folding the changes into a timeline on the client\n *\n * @category utils\n * @since 0.3.0\n */\nexport const changes: {\n <Events, const Show extends Shown<Events> = readonly []>(\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n ): <E, R>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>\n ) => Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\n <E, R, Events, const Show extends Shown<Events> = readonly []>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n ): Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\n} = dual((args) => Stream.isStream(args[0]), changesWith)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAa,cAAc,OAAO,SAAS;CAAC;CAAQ;CAAY;AAAQ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KAAK,YAAY,QAAQ,CAAC,IAAI,CAAC,MAAM;EACtE,CAAC;EAED,MAAM,SAAS,MAAM,OAAO;EAE5B,OAAO,CAAC,UAAU,WAAW,KAAA,IAAY,CAAC,IAAI,CAAC,MAAM,CAAC;CACxD,CACF,CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAa,UAYT,MAAM,SAAS,OAAO,SAAS,KAAK,EAAE,GAAG,WAAW"}
|
|
1
|
+
{"version":3,"file":"Timeline.js","names":["AssistantEvent.Attachment","AssistantEvent.ToolOutcome","AppEvents.tagOf","AssistantActivity.empty","AppEvents.decodeWith","AssistantActivity.apply","AssistantEvent.isLibraryEvent","BlockKit.apply","ToolApproval.apply","ChatSignal.isChatSignal"],"sources":["../src/Timeline.ts"],"sourcesContent":["/**\n * This module provides a chat's timeline: the chat as its user sees it. A chat client receives the\n * timeline and nothing else.\n *\n * A {@link Timeline} holds the chat's items: the messages with their blocks, the app's own events\n * it shows (each typed with its event, see {@link EventItem}), and the tool calls waiting for the\n * user's approval ({@link ApprovalItem}). It also holds the chat's\n * {@link Activity}, and whether the last turn failed or the chat was deleted. It never contains the\n * model's output, tool calls or results, what the model read, or why a turn failed. The server\n * streams {@link Change}s by piping the assistant's `subscribe` through {@link changes}, and the\n * client folds them with {@link fold} (or {@link apply}, from {@link empty}). On the server,\n * {@link fromEntries} builds a whole timeline from a chat's log, and {@link snapshot} the whole\n * timeline as one change.\n *\n * **Only the app events in `show` reach the timeline**, and none by default: an event that is only\n * for the assistant, like a summary of the chat, stays out. The RPC's schema, `Change([...])`,\n * names the same events and types the client's timeline with them.\n *\n * @since 0.3.0\n */\nimport { dual } from \"effect/Function\"\nimport * as Match from \"effect/Match\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaTransformation from \"effect/SchemaTransformation\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Assistant from \"./Assistant.ts\"\nimport * as AssistantActivity from \"./AssistantActivity.ts\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport * as BlockKit from \"./BlockKit.ts\"\nimport * as ChatSignal from \"./ChatSignal.ts\"\nimport { InputId } from \"./InputId.ts\"\nimport * as AppEvents from \"./internal/events.ts\"\nimport * as ToolApproval from \"./ToolApproval.ts\"\nimport { toJson } from \"./internal/schema.ts\"\n\n/**\n * Schema for the status of a block. A block is `\"open\"` while it accepts an answer, `\"answered\"`\n * once the user has used it, and `\"closed\"` when it closed without an answer because the user\n * answered in words or moved on.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const BlockStatus = Schema.Literals([\"open\", \"answered\", \"closed\"])\n\n/**\n * The status of a block.\n *\n * @category models\n * @since 0.1.0\n */\nexport type BlockStatus = typeof BlockStatus.Type\n\n/**\n * Schema for a block on an assistant's message. It holds the block's kind, its props (JSON, as\n * the block's props schema encodes them), its status, and the user's answer (JSON, as the block's\n * answer schema encodes it).\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Block = Schema.Struct({\n kind: Schema.String,\n props: Schema.Json,\n status: BlockStatus,\n answer: Schema.optional(Schema.Json),\n /** When the user answered, in epoch milliseconds, once the block is answered. */\n answeredAt: Schema.optional(Schema.Finite),\n /** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */\n result: Schema.optional(Schema.Json)\n})\n\n/**\n * Represents a block on an assistant's message.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Block = typeof Block.Type\n\n/**\n * Schema for a message the user sent. `at` is when it was stored, in epoch\n * milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const UserMessage = Schema.TaggedStruct(\"UserMessage\", {\n id: InputId,\n text: Schema.String,\n attachments: Schema.optional(Schema.Array(AssistantEvent.Attachment)),\n at: Schema.Finite\n})\n\n/**\n * Represents a message the user sent.\n *\n * @category models\n * @since 0.1.0\n */\nexport type UserMessage = typeof UserMessage.Type\n\n/**\n * Schema for a message the assistant sent the user, including its block if it has one.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AssistantMessage = Schema.TaggedStruct(\"AssistantMessage\", {\n id: Schema.String,\n text: Schema.String,\n at: Schema.Finite,\n block: Schema.optional(Block)\n})\n\n/**\n * Represents a message the assistant sent the user.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AssistantMessage = typeof AssistantMessage.Type\n\n/**\n * Represents one of the app's own events in the timeline: an item between the messages, in the\n * order the chat stored it.\n *\n * **Details**\n *\n * The item's `_tag` is the event's, so a match over a timeline's items takes a handler per event\n * beside `UserMessage` and `AssistantMessage`. The event, decoded with its schema, is in `event`,\n * and the item's own fields sit beside it rather than spread into it: an event may have an `id` or\n * an `at` of its own, and a class instance keeps its prototype. `id` is fixed per entry of the\n * chat's log, and `at` is when the event was stored, in epoch milliseconds.\n *\n * @category models\n * @since 0.3.0\n */\nexport type EventItem<E> = E extends { readonly _tag: infer Tag extends string }\n ? { readonly _tag: Tag; readonly id: string; readonly at: number; readonly event: E }\n : never\n\n/**\n * Schema for a tool call that waits, or waited, for the user's approval, as an item on the\n * timeline.\n *\n * **Details**\n *\n * It is only the yes or no: the assistant's own message tells the user what it asks them to\n * approve, so the item carries no params. `id` is the call's id, which the decision is for (see\n * `ToolApproval.approve`), and `tool` the tool's name, for a label. `status` is where the call stands\n * (`ToolApproval.Status`); `reason` is the user's, when they rejected it with one; `outcome` is how\n * the approved call went, once it ran. `at` is when the call started waiting, in epoch\n * milliseconds. A change updates the item in place as the call is decided and run.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport const ApprovalItem = Schema.TaggedStruct(\"ToolApproval\", {\n id: Schema.String,\n tool: Schema.String,\n status: Schema.Literals([\"pending\", \"approved\", \"rejected\", \"expired\"]),\n reason: Schema.optional(Schema.String),\n outcome: Schema.optional(AssistantEvent.ToolOutcome),\n at: Schema.Finite\n})\n\n/**\n * Represents a tool call that waits, or waited, for the user's approval, as an item on the\n * timeline.\n *\n * @category models\n * @since 0.4.0\n */\nexport type ApprovalItem = typeof ApprovalItem.Type\n\n/**\n * Represents an item in the chat's timeline: a message the user or the assistant sent, one of the\n * app's own events it shows (see {@link EventItem}), or a tool call waiting for the user's approval\n * (see {@link ApprovalItem}).\n *\n * **Example** (Showing each item of a chat)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n * import * as Match from \"effect/Match\"\n * import * as Schema from \"effect/Schema\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const line = (item: Timeline.Item<DailyBudgetReached>) =>\n * Match.valueTags(item, {\n * UserMessage: (sent) => `You: ${sent.text}`,\n * AssistantMessage: (sent) => `Assistant: ${sent.text}`,\n * DailyBudgetReached: () => \"You've reached today's budget.\"\n * })\n * ```\n *\n * @category models\n * @since 0.3.0\n */\nexport type Item<Events = never> = UserMessage | AssistantMessage | EventItem<Events> | ApprovalItem\n\n/**\n * Schema for a specialist that is working for the assistant. It holds the specialist's name and\n * when it started, in epoch milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const SpecialistWorking = Schema.Struct({\n specialist: Schema.String,\n since: Schema.Finite\n})\n\n/**\n * Represents a specialist that is working for the assistant.\n *\n * @category models\n * @since 0.1.0\n */\nexport type SpecialistWorking = typeof SpecialistWorking.Type\n\n/**\n * Schema for what is working in the chat.\n *\n * `working` is true while the assistant runs a turn, or when a turn is about to start for\n * something that arrived. `specialists` lists the specialists that are working. When the chat is\n * idle, nothing is working, even if a workflow is waiting on a timer or on the user.\n *\n * On a live subscription (`subscribe(chatId, { signals: true })`), `status` is a short line about what\n * the running turn is doing, and `typing` is true while the model writes a message to the user. Both\n * come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline\n * folded from the log alone has neither.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Activity = Schema.Struct({\n working: Schema.Boolean,\n specialists: Schema.Array(SpecialistWorking),\n status: Schema.optional(Schema.String),\n typing: Schema.Boolean\n})\n\n/**\n * Represents what is working in the chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Activity = typeof Activity.Type\n\n/**\n * Represents a chat's timeline: the chat as its user sees it, typed with the app's events it shows.\n * It holds the chat's items in order, what is working in it, whether the last turn failed, and\n * whether the chat was deleted. `sequence` is the position in the chat's log that the timeline is up to.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface Timeline<Events = never> {\n readonly sequence: number\n readonly items: ReadonlyArray<Item<Events>>\n readonly activity: Activity\n /** Whether the last turn failed with no message after it. */\n readonly failed: boolean\n /** Whether the chat was deleted. A deleted chat accepts nothing more, and its stream ends. */\n readonly deleted: boolean\n}\n\n/**\n * Represents a change to a chat's timeline, typed with the app's events it shows.\n *\n * **Details**\n *\n * A change holds each item that is new or changed (for example, a message whose block was\n * answered or closed, or a call the user approved), in full. It also holds the current activity, whether the last turn failed,\n * and whether the chat was deleted. `sequence` is the position in the chat's log that the change is up\n * to.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface Change<Events = never> {\n readonly sequence: number\n readonly items: ReadonlyArray<Item<Events>>\n readonly activity: Activity\n readonly failed: boolean\n readonly deleted: boolean\n}\n\nconst eventItem = (schema: AssistantEvent.AppEventSchema) =>\n Schema.Struct({ _tag: Schema.Literal(AppEvents.tagOf(schema)), id: Schema.String, at: Schema.Finite, event: schema })\n\nfunction makeChange<const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(\n events?: Events\n): Schema.Codec<Change<Events[number][\"Type\"]>, Schema.Json>\n// The overload states the decoded type: an item per given schema, each typed with its own event.\nfunction makeChange(events: ReadonlyArray<AssistantEvent.AppEventSchema> = []): Schema.Top {\n const AnyItem = Schema.toCodecJson(\n Schema.Union([UserMessage, AssistantMessage, ApprovalItem, ...events.map(eventItem)])\n )\n\n const decodeItem = Schema.decodeUnknownOption(AnyItem)\n const encodeItem = Schema.encodeUnknownSync(AnyItem)\n\n return Schema.Struct({\n sequence: Schema.Int,\n // An item for an event this schema doesn't name, or that doesn't decode (from a newer server, say), is left out\n // rather than failing the whole change.\n items: Schema.Array(Schema.Json).pipe(\n Schema.decodeTo(\n Schema.Array(Schema.toType(AnyItem)),\n SchemaTransformation.transform<ReadonlyArray<typeof AnyItem.Type>, ReadonlyArray<Schema.Json>>({\n decode: (json) => json.flatMap((item) => Option.toArray(decodeItem(item))),\n encode: (items) => items.map((item) => encodeItem(item))\n })\n )\n ),\n activity: Activity,\n failed: Schema.Boolean,\n deleted: Schema.Boolean\n })\n}\n\n/**\n * Creates the schema for the changes to a chat's timeline, with items for the given app events,\n * in JSON.\n *\n * **Details**\n *\n * It is the success schema of the RPC that streams a chat's timeline: name the events the chat's\n * users see, the same ones the handler passes to {@link changes} as `show`. Tool calls waiting for\n * approval are always in it, as {@link ApprovalItem}s. Each item decodes its\n * event with that event's schema, so the client gets `Change<Events>` typed with them and folds it\n * with {@link fold}, no definition needed. `Change()` carries no app events.\n *\n * A handler whose changes show an event the schema doesn't name doesn't compile.\n *\n * **Example** (An RPC that streams a chat's timeline, with the budget notice)\n *\n * ```ts\n * import { ChatId, Timeline } from \"effect-assistant\"\n * import * as Rpc from \"effect/rpc/Rpc\"\n * import * as Schema from \"effect/Schema\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const Subscribe = Rpc.make(\"Subscribe\", {\n * payload: { chatId: ChatId.ChatId },\n * success: Timeline.Change([DailyBudgetReached]),\n * stream: true\n * })\n * ```\n *\n * @category schemas\n * @since 0.3.0\n */\nexport const Change: <const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(\n events?: Events\n) => Schema.Codec<Change<Events[number][\"Type\"]>, Schema.Json> = makeChange\n\n/**\n * The timeline of a chat before anything has happened in it, with no items and nothing working.\n * Use it as the starting point when folding changes with {@link apply}.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const empty: Timeline = {\n sequence: 0,\n items: [],\n activity: { working: false, specialists: [], typing: false },\n failed: false,\n deleted: false\n}\n\n/**\n * Returns the timeline after a change.\n *\n * **Details**\n *\n * Each item in the change replaces the item with the same id, in place, and new items are added\n * after the rest. The change's activity, `failed`, and `deleted` replace the timeline's. Applying a\n * change twice changes nothing, so a client that resubscribes from the start can fold again and get\n * the same timeline.\n *\n * The timeline is typed with the change's events, as its RPC's schema decoded them (see\n * {@link Change}). To fold a stream of changes, use {@link fold}: in\n * `Stream.scan(() => Timeline.empty, Timeline.apply)`, TypeScript fixes the state's type from\n * `empty` before it sees the changes' events, so that form needs the timeline's type written out.\n *\n * **Example** (Folding changes into your own state)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n *\n * interface State<Events> {\n * readonly timeline: Timeline.Timeline<Events>\n * readonly unread: number\n * }\n *\n * const next = <Events>(state: State<Events>, change: Timeline.Change<Events>): State<Events> => ({\n * timeline: Timeline.apply(state.timeline, change),\n * unread: state.unread + change.items.length\n * })\n * ```\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const apply = <Events>(timeline: Timeline<Events>, change: Change<Events>): Timeline<Events> => {\n const changed = new Map(change.items.map((item) => [item.id, item]))\n const known = new Set(timeline.items.map((item) => item.id))\n\n return {\n sequence: Math.max(timeline.sequence, change.sequence),\n items: [\n ...timeline.items.map((item) => changed.get(item.id) ?? item),\n ...change.items.filter((item) => !known.has(item.id))\n ],\n activity: change.activity,\n failed: change.failed,\n deleted: change.deleted\n }\n}\n\n/**\n * Returns the timelines a stream of changes folds to, from {@link empty}, typed with the changes'\n * events.\n *\n * **Example** (A chat's timeline on the client)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n * import * as Schema from \"effect/Schema\"\n * import * as Stream from \"effect/Stream\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * // The stream of an RPC whose success schema is `Timeline.Change([DailyBudgetReached])`.\n * declare const changes: Stream.Stream<Timeline.Change<DailyBudgetReached>>\n *\n * const timelines = changes.pipe(Timeline.fold) // Stream<Timeline.Timeline<DailyBudgetReached>>\n * ```\n *\n * @category combinators\n * @since 0.3.0\n */\nexport const fold = <Events, E, R>(\n changes: Stream.Stream<Change<Events>, E, R>\n): Stream.Stream<Timeline<Events>, E, R> => changes.pipe(Stream.scan((): Timeline<Events> => empty, apply))\n\n/**\n * Returns whether nothing is working in the chat: no turn is running or about to start, and no\n * specialist is working.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isIdle = <Events>(timeline: Timeline<Events>): boolean =>\n !timeline.activity.working && timeline.activity.specialists.length === 0\n\ninterface AnyEventItem {\n readonly _tag: string\n readonly id: string\n readonly at: number\n readonly event: { readonly _tag: string }\n}\n\ntype AnyItem = UserMessage | AssistantMessage | AnyEventItem | ApprovalItem\n\n// What the fold below builds: the overloads that use it type its items with the events shown.\ninterface AnyChange {\n readonly sequence: number\n readonly items: ReadonlyArray<AnyItem>\n readonly activity: Activity\n readonly failed: boolean\n readonly deleted: boolean\n}\n\n/**\n * Represents the options for building a chat's timeline from its log.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface ShowOptions<Show extends ReadonlyArray<AssistantEvent.AppEventSchema>> {\n /**\n * The schemas of the app's events the chat's users see. Each becomes an item in the timeline;\n * the app's other events are left out. Defaults to none.\n */\n readonly show?: Show | undefined\n}\n\n/**\n * Represents the schemas an assistant's timeline may show: some of its own events.\n *\n * @category utility types\n * @since 0.3.0\n */\nexport type Shown<Events> = ReadonlyArray<AssistantEvent.AppEventSchema & { readonly Type: Events }>\n\nfunction snapshotWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change\nfunction snapshotWith<Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n): Change<Show[number][\"Type\"]>\nfunction snapshotWith(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n _definition?: Schemas,\n options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): AnyChange {\n const timeline = folding(options?.show ?? [])\n\n for (const entry of entries) timeline.step(entry)\n\n return timeline.snapshot\n}\n\n/**\n * Returns a chat's whole timeline as one change, built from the entries of its log.\n *\n * **When to use**\n *\n * Use it on the server for an RPC that returns a whole chat at once: its success schema is\n * {@link Change} with the same events as `show`, and the client applies it to {@link empty}.\n *\n * **Details**\n *\n * Only the app's events in `show` become items; without it, the timeline has none.\n *\n * @category constructors\n * @since 0.3.0\n */\nexport const snapshot: {\n (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change\n <Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n ): Change<Show[number][\"Type\"]>\n} = snapshotWith\n\nfunction fromEntriesWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline\nfunction fromEntriesWith<Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n): Timeline<Show[number][\"Type\"]>\nfunction fromEntriesWith(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n _definition?: Schemas,\n options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): AnyChange {\n const timeline = folding(options?.show ?? [])\n\n for (const entry of entries) timeline.step(entry)\n\n return timeline.snapshot\n}\n\n/**\n * Returns a chat's timeline, built from the entries of its log.\n *\n * **When to use**\n *\n * Use it in server-side code that reads a whole chat. A client gets the timeline as a stream from\n * {@link changes} instead, and an RPC that returns a whole chat sends a {@link snapshot}.\n *\n * **Details**\n *\n * Only the app's events in `show` become items, typed with their schemas; without it, the timeline\n * has none.\n *\n * **Example** (Building a chat's timeline from its log)\n *\n * ```ts\n * import { type ChatId, ChatLog, Timeline } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * const timelineOf = (chatId: ChatId.ChatId) =>\n * ChatLog.ChatLog.use((log) => log.read(chatId)).pipe(\n * Effect.map((entries) => Timeline.fromEntries(entries))\n * )\n * ```\n *\n * @see {@link changes} for a stream of changes instead of a whole timeline\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const fromEntries: {\n (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline\n <Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n ): Timeline<Show[number][\"Type\"]>\n} = fromEntriesWith\n\ninterface Schemas {\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n}\n\ninterface Folding {\n readonly step: (entry: AssistantEvent.AnyEntry) => AnyChange | undefined\n readonly signal: (signal: ChatSignal.ChatSignal) => AnyChange | undefined\n readonly snapshot: AnyChange\n}\n\ninterface LiveState {\n readonly status: string | undefined\n readonly typing: boolean\n}\n\nconst noLive: LiveState = { status: undefined, typing: false }\n\nconst applySignal = (live: LiveState, signal: ChatSignal.ChatSignal): LiveState =>\n Match.value(signal).pipe(\n Match.tagsExhaustive({\n Status: ({ text }): LiveState => ({ ...live, status: text }),\n TypingStarted: (): LiveState => ({ status: undefined, typing: true }),\n TypingStopped: (): LiveState => ({ ...live, typing: false })\n })\n )\n\nconst activityOf = (activity: AssistantActivity.State, live: LiveState): Activity => {\n const { status } = live\n\n const shown: Activity = {\n working: activity.turnSince !== undefined || activity.queued,\n specialists: [...activity.specialists.values()].map((run) => ({\n specialist: run.specialist,\n since: run.since\n })),\n typing: live.typing\n }\n\n return status === undefined ? shown : { ...shown, status }\n}\n\nconst sameActivity = (a: Activity, b: Activity) =>\n a.working === b.working &&\n a.status === b.status &&\n a.typing === b.typing &&\n a.specialists.length === b.specialists.length &&\n a.specialists.every((run, i) => {\n const other = b.specialists[i]\n\n return other !== undefined && run.specialist === other.specialist && run.since === other.since\n })\n\nconst folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding => {\n const shown = new Map(show.map((schema) => [AppEvents.tagOf(schema), schema]))\n let approvals: ReadonlyMap<string, ToolApproval.State> = new Map()\n let sequence = 0\n let failed = false\n let deleted = false\n let activity = AssistantActivity.empty\n let live = noLive\n let blocks: ReadonlyMap<string, BlockKit.State> = new Map()\n const answeredAt = new Map<string, number>()\n // The items in order, and the assistant's messages as stored: their blocks change as the chat goes on.\n const items = new Map<string, AnyItem>()\n const sent = new Map<string, AssistantEvent.AssistantMessage>()\n // The results a block can show, by id: a message shows one stored before it.\n const results = new Map<string, Schema.Json>()\n\n const blockOf = (message: AssistantEvent.AssistantMessage): Block | undefined => {\n if (message.block === undefined) return undefined\n\n const state = blocks.get(message.id)\n const status = state === undefined || state.open ? \"open\" : state.answer === undefined ? \"closed\" : \"answered\"\n const block: Block = { kind: message.block.kind, props: toJson(message.block.props), status }\n const { resultId } = message.block\n const result = resultId === undefined ? undefined : results.get(resultId)\n const shown = result === undefined ? block : { ...block, result }\n\n if (state?.answer === undefined) return shown\n\n const answered = { ...shown, answer: toJson(state.answer.value) }\n const at = answeredAt.get(message.id)\n\n return at === undefined ? answered : { ...answered, answeredAt: at }\n }\n\n const itemOf = (message: AssistantEvent.AssistantMessage, at: number): AssistantMessage => {\n const block = blockOf(message)\n\n return block === undefined\n ? AssistantMessage.make({ id: message.id, text: message.text, at })\n : AssistantMessage.make({ id: message.id, text: message.text, at, block })\n }\n\n const touched = (event: AssistantEvent.AssistantEvent, at: number): ReadonlyArray<string> =>\n Match.value(event).pipe(\n Match.tagsExhaustive({\n UserMessage: (message) => {\n items.set(\n message.id,\n message.attachments === undefined\n ? UserMessage.make({ id: message.id, text: message.text, at })\n : UserMessage.make({\n id: message.id,\n text: message.text,\n attachments: message.attachments,\n at\n })\n )\n failed = false\n\n return [message.id]\n },\n AssistantMessage: (message) => {\n sent.set(message.id, message)\n items.set(message.id, itemOf(message, at))\n failed = false\n\n return [message.id, ...(message.closes ?? [])]\n },\n BlockAnswer: (answer) => {\n failed = false\n\n return [answer.messageId]\n },\n BlocksClosed: (closed) => closed.messageIds,\n ApprovalRequested: () => [],\n ApprovalDecision: () => {\n failed = false\n\n return []\n },\n ApprovalsExpired: () => [],\n TurnFailed: () => {\n failed = true\n\n return []\n },\n ModelOutput: () => [],\n ToolStarted: () => [],\n ToolResult: (result) => {\n if (result.resultId !== undefined && result.outcome === \"success\") {\n results.set(result.resultId, result.full ?? result.result)\n }\n\n return []\n },\n TurnStarted: () => [],\n TurnCompleted: () => [],\n SpecialistStarted: () => [],\n SpecialistFinished: () => [],\n ChatDeleted: () => {\n deleted = true\n\n return []\n }\n })\n )\n\n // Decoded as `subscribe` streams it, or as the log stores it; one that doesn't decode is left out.\n const eventItemOf = (entry: AssistantEvent.AnyEntry): Option.Option<AnyEventItem> => {\n const schema = shown.get(entry.event._tag)\n\n if (schema === undefined) return Option.none()\n\n const event = Schema.is(schema)(entry.event) ? Option.some(entry.event) : AppEvents.decodeWith(schema, entry.event)\n\n return Option.map(event, (decoded) => ({\n _tag: decoded._tag,\n id: `app-event:${entry.sequence}`,\n at: entry.at,\n event: decoded\n }))\n }\n\n const callsOf = (event: AssistantEvent.AssistantEvent): ReadonlyArray<string> =>\n Predicate.isTagged(event, \"ApprovalsExpired\")\n ? event.callIds\n : Predicate.isTagged(event, \"ApprovalRequested\") ||\n Predicate.isTagged(event, \"ApprovalDecision\") ||\n Predicate.isTagged(event, \"ToolResult\")\n ? [event.callId]\n : []\n\n // The items of the calls this entry changed.\n const approvalItems = (event: AssistantEvent.AssistantEvent, before: ReadonlyMap<string, ToolApproval.State>) =>\n callsOf(event).flatMap((callId) => {\n const state = approvals.get(callId)\n\n if (state === undefined || state === before.get(callId)) return []\n\n const item = ApprovalItem.make({\n id: callId,\n tool: state.request.tool,\n status: state.status,\n reason: state.reason,\n outcome: state.outcome,\n at: state.at\n })\n\n items.set(callId, item)\n\n return [item]\n })\n\n // A turn's end clears what it showed, also when a signal didn't arrive.\n const settle = (event: { readonly _tag: string }) => {\n if (\n Predicate.isTagged(event, \"TurnCompleted\") ||\n Predicate.isTagged(event, \"TurnFailed\") ||\n Predicate.isTagged(event, \"ChatDeleted\")\n ) {\n live = noLive\n }\n }\n\n const signal = (received: ChatSignal.ChatSignal): AnyChange | undefined => {\n const previous = activityOf(activity, live)\n\n live = applySignal(live, received)\n\n const now = activityOf(activity, live)\n\n return sameActivity(previous, now) ? undefined : { sequence, items: [], activity: now, failed, deleted }\n }\n\n const step = (entry: AssistantEvent.AnyEntry): AnyChange | undefined => {\n const previous = { activity: activityOf(activity, live), failed, deleted }\n const { event } = entry\n\n sequence = entry.sequence\n activity = AssistantActivity.apply(activity, entry)\n settle(event)\n\n if (!AssistantEvent.isLibraryEvent(event)) {\n const now = activityOf(activity, live)\n\n return Option.match(eventItemOf(entry), {\n onNone: () =>\n sameActivity(previous.activity, now) ? undefined : { sequence, items: [], activity: now, failed, deleted },\n onSome: (item) => {\n items.set(item.id, item)\n\n return { sequence, items: [item], activity: now, failed, deleted }\n }\n })\n }\n\n blocks = BlockKit.apply(blocks, event)\n\n if (Predicate.isTagged(event, \"BlockAnswer\") && blocks.get(event.messageId)?.answer === event) {\n answeredAt.set(event.messageId, entry.at)\n }\n\n const decidedBefore = approvals\n approvals = ToolApproval.apply(approvals, entry)\n\n const changed = [...new Set(touched(event, entry.at))].flatMap((id) => {\n const message = sent.get(id)\n const current = items.get(id)\n\n if (message === undefined || current === undefined) return current === undefined ? [] : [current]\n\n const next = itemOf(message, current.at)\n items.set(id, next)\n\n return [next]\n })\n\n const all = [...changed, ...approvalItems(event, decidedBefore)]\n const now = activityOf(activity, live)\n\n return all.length === 0 &&\n failed === previous.failed &&\n deleted === previous.deleted &&\n sameActivity(previous.activity, now)\n ? undefined\n : { sequence, items: all, activity: now, failed, deleted }\n }\n\n return {\n step,\n signal,\n get snapshot() {\n return { sequence, items: [...items.values()], activity: activityOf(activity, live), failed, deleted }\n }\n }\n}\n\nconst merge = (changes: ReadonlyArray<AnyChange>): AnyChange | undefined => {\n const last = changes.at(-1)\n\n if (last === undefined) return undefined\n\n const items = new Map<string, AnyItem>()\n\n for (const change of changes) for (const item of change.items) items.set(item.id, item)\n\n return {\n sequence: last.sequence,\n items: [...items.values()],\n activity: last.activity,\n failed: last.failed,\n deleted: last.deleted\n }\n}\n\n/**\n * Represents an assistant's definition as the timeline reads it. An assistant made with\n * `Assistant.make` fits it.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Definition<Events = never> {\n /** The schemas of the assistant's events. */\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n /** The schema of the chat's entries, typed with the assistant's events: it types `show`. */\n readonly Entry: Schema.Codec<Assistant.Entry<Events>, Schema.Json>\n}\n\n/**\n * Represents the options accepted by {@link changes}.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface ChangesOptions<\n Show extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []\n> extends ShowOptions<Show> {\n /**\n * The `sequence` up to which the client already has the timeline. The result contains only the\n * changes after it. Defaults to `0`, every change.\n */\n readonly after?: number | undefined\n}\n\nfunction changesWith<E, R, Events, const Show extends Shown<Events> = readonly []>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n): Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\nfunction changesWith<E, R>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n _definition: Schemas,\n options?: ChangesOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): Stream.Stream<AnyChange, E, R> {\n const after = options?.after ?? 0\n\n return entries.pipe(\n Stream.mapAccumArray(\n () => folding(options?.show ?? []),\n (timeline, chunk) => {\n const changed = chunk.flatMap((item) => {\n if (ChatSignal.isChatSignal(item)) return Option.toArray(Option.fromUndefinedOr(timeline.signal(item)))\n\n const change = timeline.step(item)\n\n return change === undefined || item.sequence <= after ? [] : [change]\n })\n\n const merged = merge(changed)\n\n return [timeline, merged === undefined ? [] : [merged]]\n }\n )\n )\n}\n\n/**\n * Returns the stream of changes to a chat's timeline that its entries produce, for a chat client.\n *\n * **Details**\n *\n * The entries must stream from the start of the chat's log, as `assistant.subscribe(chatId)` does\n * without `after`. The fold reads every entry, because a message depends on earlier entries: its\n * block is answered or closed later. `after` only skips emitting the changes up to that `sequence`, so a\n * client that has the timeline up to a `sequence` receives only what changed since. Pass `after` here,\n * not to `subscribe`: a subscription that starts after a `sequence` gives the fold an incomplete log,\n * and the changes it produces are wrong.\n *\n * Each chunk of entries becomes one change; the stored entries, for example, arrive as one chunk.\n *\n * **Only the app's events in `show` reach the client.** Each one becomes an item between the\n * messages (see {@link EventItem}); the app's other events, like a summary of the chat for the\n * model, are left out. Without `show`, none are shown. The changes are typed with the events shown,\n * so the RPC's success schema names the same ones (`Timeline.Change([...])`), and a handler that\n * shows one the schema doesn't name doesn't compile. A timeline shows a turn as working once it\n * starts, or from the user's input.\n *\n * **Example** (Streaming a chat's timeline to a client, with the one app event its user sees)\n *\n * ```ts\n * import { Assistant, type ChatId, Timeline } from \"effect-assistant\"\n * import * as Schema from \"effect/Schema\"\n * import * as Stream from \"effect/Stream\"\n *\n * class Summary extends Schema.TaggedClass<Summary>()(\"Summary\", { text: Schema.String, throughSequence: Schema.Int }) {}\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const MyAssistant = Assistant.make(\"my-assistant\", { events: [Summary, DailyBudgetReached] })\n *\n * // The summary is for the model: only the budget notice reaches the user.\n * const watch = (chatId: ChatId.ChatId, after: number) =>\n * Stream.unwrap(\n * MyAssistant.useSync((assistant) =>\n * assistant.subscribe(chatId).pipe(Timeline.changes(MyAssistant, { show: [DailyBudgetReached], after }))\n * )\n * )\n * ```\n *\n * @see {@link fold} for folding the changes into a timeline on the client\n *\n * @category utils\n * @since 0.3.0\n */\nexport const changes: {\n <Events, const Show extends Shown<Events> = readonly []>(\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n ): <E, R>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>\n ) => Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\n <E, R, Events, const Show extends Shown<Events> = readonly []>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n ): Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\n} = dual((args) => Stream.isStream(args[0]), changesWith)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAa,cAAc,OAAO,SAAS;CAAC;CAAQ;CAAY;AAAQ,CAAC;;;;;;;;;AAkBzE,MAAa,QAAQ,OAAO,OAAO;CACjC,MAAM,OAAO;CACb,OAAO,OAAO;CACd,QAAQ;CACR,QAAQ,OAAO,SAAS,OAAO,IAAI;;CAEnC,YAAY,OAAO,SAAS,OAAO,MAAM;;CAEzC,QAAQ,OAAO,SAAS,OAAO,IAAI;AACrC,CAAC;;;;;;;;AAiBD,MAAa,cAAc,OAAO,aAAa,eAAe;CAC5D,IAAI;CACJ,MAAM,OAAO;CACb,aAAa,OAAO,SAAS,OAAO,MAAMA,UAAyB,CAAC;CACpE,IAAI,OAAO;AACb,CAAC;;;;;;;AAgBD,MAAa,mBAAmB,OAAO,aAAa,oBAAoB;CACtE,IAAI,OAAO;CACX,MAAM,OAAO;CACb,IAAI,OAAO;CACX,OAAO,OAAO,SAAS,KAAK;AAC9B,CAAC;;;;;;;;;;;;;;;;;AA6CD,MAAa,eAAe,OAAO,aAAa,gBAAgB;CAC9D,IAAI,OAAO;CACX,MAAM,OAAO;CACb,QAAQ,OAAO,SAAS;EAAC;EAAW;EAAY;EAAY;CAAS,CAAC;CACtE,QAAQ,OAAO,SAAS,OAAO,MAAM;CACrC,SAAS,OAAO,SAASC,WAA0B;CACnD,IAAI,OAAO;AACb,CAAC;;;;;;;;AA6CD,M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,IAAI;IAAG;IAAQ;GAAQ;EACvG;CACF;AACF;AAEA,MAAM,SAAS,YAA6D;CAC1E,MAAM,OAAO,QAAQ,GAAG,EAAE;CAE1B,IAAI,SAAS,KAAA,GAAW,OAAO,KAAA;CAE/B,MAAM,wBAAQ,IAAI,IAAqB;CAEvC,KAAK,MAAM,UAAU,SAAS,KAAK,MAAM,QAAQ,OAAO,OAAO,MAAM,IAAI,KAAK,IAAI,IAAI;CAEtF,OAAO;EACL,UAAU,KAAK;EACf,OAAO,CAAC,GAAG,MAAM,OAAO,CAAC;EACzB,UAAU,KAAK;EACf,QAAQ,KAAK;EACb,SAAS,KAAK;CAChB;AACF;AAqCA,SAAS,YACP,SACA,aACA,SACgC;CAChC,MAAM,QAAQ,SAAS,SAAS;CAEhC,OAAO,QAAQ,KACb,OAAO,oBACC,QAAQ,SAAS,QAAQ,CAAC,CAAC,IAChC,UAAU,UAAU;EACnB,MAAM,UAAU,MAAM,SAAS,SAAS;GACtC,IAAIC,aAAwB,IAAI,GAAG,OAAO,OAAO,QAAQ,OAAO,gBAAgB,SAAS,OAAO,IAAI,CAAC,CAAC;GAEtG,MAAM,SAAS,SAAS,KAAK,IAAI;GAEjC,OAAO,WAAW,KAAA,KAAa,KAAK,YAAY,QAAQ,CAAC,IAAI,CAAC,MAAM;EACtE,CAAC;EAED,MAAM,SAAS,MAAM,OAAO;EAE5B,OAAO,CAAC,UAAU,WAAW,KAAA,IAAY,CAAC,IAAI,CAAC,MAAM,CAAC;CACxD,CACF,CACF;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAa,UAYT,MAAM,SAAS,OAAO,SAAS,KAAK,EAAE,GAAG,WAAW"}
|
package/package.json
CHANGED
package/src/Assistant.ts
CHANGED
|
@@ -355,15 +355,18 @@ export interface Service<Events = never> {
|
|
|
355
355
|
* `show`, none by default (see `Timeline.changes`).
|
|
356
356
|
*/
|
|
357
357
|
readonly subscribe: {
|
|
358
|
-
(
|
|
358
|
+
(
|
|
359
|
+
chatId: ChatId,
|
|
360
|
+
options?: SubscribeOptions & { readonly signals?: false | undefined }
|
|
361
|
+
): Stream.Stream<Entry<Events>>
|
|
359
362
|
/**
|
|
360
|
-
* With `
|
|
363
|
+
* With `signals: true`, the stream also has the chat's signals (see `ChatSignal`): the status of
|
|
361
364
|
* what a turn is doing, and whether a message to the user is on its way. They come in order
|
|
362
365
|
* with the entries, only while the stream runs, and are never stored.
|
|
363
366
|
*/
|
|
364
367
|
(
|
|
365
368
|
chatId: ChatId,
|
|
366
|
-
options: SubscribeOptions & { readonly
|
|
369
|
+
options: SubscribeOptions & { readonly signals: true }
|
|
367
370
|
): Stream.Stream<Entry<Events> | ChatSignal.ChatSignal>
|
|
368
371
|
}
|
|
369
372
|
/**
|
|
@@ -605,18 +608,18 @@ export const make = <
|
|
|
605
608
|
|
|
606
609
|
function subscribe(
|
|
607
610
|
chatId: ChatId,
|
|
608
|
-
options?: SubscribeOptions & { readonly
|
|
611
|
+
options?: SubscribeOptions & { readonly signals?: false | undefined }
|
|
609
612
|
): Stream.Stream<Entry<OwnEvents>>
|
|
610
613
|
function subscribe(
|
|
611
614
|
chatId: ChatId,
|
|
612
|
-
options: SubscribeOptions & { readonly
|
|
615
|
+
options: SubscribeOptions & { readonly signals: true }
|
|
613
616
|
): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal>
|
|
614
617
|
function subscribe(
|
|
615
618
|
chatId: ChatId,
|
|
616
|
-
options?: SubscribeOptions & { readonly
|
|
619
|
+
options?: SubscribeOptions & { readonly signals?: boolean | undefined }
|
|
617
620
|
): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal> {
|
|
618
621
|
return engine
|
|
619
|
-
.subscribe(name, chatId, options?.after ?? 0, options?.
|
|
622
|
+
.subscribe(name, chatId, options?.after ?? 0, options?.signals === true)
|
|
620
623
|
.pipe(Stream.filterMap(Filter.fromPredicateOption(decode)))
|
|
621
624
|
}
|
|
622
625
|
|
package/src/AssistantEngine.ts
CHANGED
|
@@ -56,14 +56,14 @@ export class AssistantEngine extends Context.Service<
|
|
|
56
56
|
input: AssistantEvent.Input | AssistantEvent.StoredAppEvent
|
|
57
57
|
) => Effect.Effect<void>
|
|
58
58
|
/**
|
|
59
|
-
* Streams the chat's stored entries after the `after` sequence, then live ones. With `
|
|
59
|
+
* Streams the chat's stored entries after the `after` sequence, then live ones. With `signals`,
|
|
60
60
|
* the chat's signals too, in order with the entries.
|
|
61
61
|
*/
|
|
62
62
|
readonly subscribe: (
|
|
63
63
|
assistant: string,
|
|
64
64
|
chatId: ChatId,
|
|
65
65
|
after: number,
|
|
66
|
-
|
|
66
|
+
signals: boolean
|
|
67
67
|
) => Stream.Stream<AssistantEvent.Entry | ChatSignal.ChatSignal>
|
|
68
68
|
/**
|
|
69
69
|
* Deletes one of the assistant's chats. The chat's log records the deletion, and everything
|
|
@@ -191,12 +191,12 @@ export const layerMemory: Layer.Layer<AssistantEngine, never, ChatLog> = Layer.e
|
|
|
191
191
|
yield* RcMap.invalidate(chats, new ChatKey({ assistant, chatId }))
|
|
192
192
|
}),
|
|
193
193
|
// The subscriber holds the chat open while it streams.
|
|
194
|
-
subscribe: (assistant, chatId, after,
|
|
194
|
+
subscribe: (assistant, chatId, after, signals) =>
|
|
195
195
|
Stream.unwrap(
|
|
196
196
|
Effect.gen(function* () {
|
|
197
197
|
const chat = yield* RcMap.get(chats, new ChatKey({ assistant, chatId }))
|
|
198
198
|
|
|
199
|
-
return
|
|
199
|
+
return signals ? chat.live(after) : chat.stream(after)
|
|
200
200
|
})
|
|
201
201
|
)
|
|
202
202
|
})
|
|
@@ -208,7 +208,7 @@ interface EntityClient {
|
|
|
208
208
|
readonly subscribe: (
|
|
209
209
|
chatId: ChatId,
|
|
210
210
|
after: number,
|
|
211
|
-
|
|
211
|
+
signals: boolean
|
|
212
212
|
) => Stream.Stream<AssistantEvent.Entry | ChatSignal.ChatSignal>
|
|
213
213
|
readonly delete: (chatId: ChatId) => Effect.Effect<void>
|
|
214
214
|
}
|
|
@@ -218,7 +218,7 @@ const Submit = Rpc.make("Submit", {
|
|
|
218
218
|
}).annotate(ClusterSchema.Persisted, true)
|
|
219
219
|
|
|
220
220
|
const Subscribe = Rpc.make("Subscribe", {
|
|
221
|
-
payload: { after: Schema.Int,
|
|
221
|
+
payload: { after: Schema.Int, signals: Schema.optionalKey(Schema.Boolean) },
|
|
222
222
|
success: Schema.Union([AssistantEvent.Entry, ChatSignal.ChatSignal]),
|
|
223
223
|
stream: true
|
|
224
224
|
})
|
|
@@ -243,7 +243,7 @@ const makeClusterClient = Effect.gen(function* () {
|
|
|
243
243
|
|
|
244
244
|
const client: EntityClient = {
|
|
245
245
|
submit: (chatId, input) => makeClient(chatId).Submit({ input }, { discard: true }).pipe(Effect.orDie),
|
|
246
|
-
subscribe: (chatId, after,
|
|
246
|
+
subscribe: (chatId, after, signals) => makeClient(chatId).Subscribe({ after, signals }).pipe(Stream.orDie),
|
|
247
247
|
delete: (chatId) => makeClient(chatId).Delete().pipe(Effect.orDie)
|
|
248
248
|
}
|
|
249
249
|
|
|
@@ -262,12 +262,12 @@ const makeClusterClient = Effect.gen(function* () {
|
|
|
262
262
|
|
|
263
263
|
yield* client.submit(chatId, input)
|
|
264
264
|
}),
|
|
265
|
-
subscribe: (assistant, chatId, after,
|
|
265
|
+
subscribe: (assistant, chatId, after, signals) =>
|
|
266
266
|
Stream.unwrap(
|
|
267
267
|
Effect.gen(function* () {
|
|
268
268
|
const client = yield* clientOf(assistant)
|
|
269
269
|
|
|
270
|
-
return client.subscribe(chatId, after,
|
|
270
|
+
return client.subscribe(chatId, after, signals)
|
|
271
271
|
})
|
|
272
272
|
),
|
|
273
273
|
delete: Effect.fn("AssistantEngine.delete")(function* (assistant: string, chatId: ChatId) {
|
|
@@ -354,7 +354,7 @@ export const layerCluster: Layer.Layer<AssistantEngine, never, ChatLog | Shardin
|
|
|
354
354
|
// The turns run inside the request, so a crash leaves it unprocessed and the cluster redelivers it.
|
|
355
355
|
Submit: (request) => chat.submit(request.payload.input),
|
|
356
356
|
Subscribe: (request) =>
|
|
357
|
-
request.payload.
|
|
357
|
+
request.payload.signals === true ? chat.live(request.payload.after) : chat.stream(request.payload.after),
|
|
358
358
|
Delete: () => chat.delete
|
|
359
359
|
})
|
|
360
360
|
})
|
package/src/ChatSignal.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* status of what the assistant is doing, and whether it is writing a message to the user.
|
|
4
4
|
*
|
|
5
5
|
* Signals are never stored. They reach only the subscribers that are listening when they are sent
|
|
6
|
-
* (`assistant.subscribe(chatId, {
|
|
6
|
+
* (`assistant.subscribe(chatId, { signals: true })`), between the chat's entries and in order with
|
|
7
7
|
* them. A turn's model never reads them, compaction never sees them, and a client that loads the
|
|
8
8
|
* chat again starts without them. The turn itself shows in the log, from its `TurnStarted` to its
|
|
9
9
|
* `TurnCompleted` or `TurnFailed`.
|
package/src/Timeline.ts
CHANGED
|
@@ -66,6 +66,8 @@ export const Block = Schema.Struct({
|
|
|
66
66
|
props: Schema.Json,
|
|
67
67
|
status: BlockStatus,
|
|
68
68
|
answer: Schema.optional(Schema.Json),
|
|
69
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
70
|
+
answeredAt: Schema.optional(Schema.Finite),
|
|
69
71
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
70
72
|
result: Schema.optional(Schema.Json)
|
|
71
73
|
})
|
|
@@ -228,7 +230,7 @@ export type SpecialistWorking = typeof SpecialistWorking.Type
|
|
|
228
230
|
* something that arrived. `specialists` lists the specialists that are working. When the chat is
|
|
229
231
|
* idle, nothing is working, even if a workflow is waiting on a timer or on the user.
|
|
230
232
|
*
|
|
231
|
-
* On a live subscription (`subscribe(chatId, {
|
|
233
|
+
* On a live subscription (`subscribe(chatId, { signals: true })`), `status` is a short line about what
|
|
232
234
|
* the running turn is doing, and `typing` is true while the model writes a message to the user. Both
|
|
233
235
|
* come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline
|
|
234
236
|
* folded from the log alone has neither.
|
|
@@ -662,6 +664,7 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
|
|
|
662
664
|
let activity = AssistantActivity.empty
|
|
663
665
|
let live = noLive
|
|
664
666
|
let blocks: ReadonlyMap<string, BlockKit.State> = new Map()
|
|
667
|
+
const answeredAt = new Map<string, number>()
|
|
665
668
|
// The items in order, and the assistant's messages as stored: their blocks change as the chat goes on.
|
|
666
669
|
const items = new Map<string, AnyItem>()
|
|
667
670
|
const sent = new Map<string, AssistantEvent.AssistantMessage>()
|
|
@@ -678,7 +681,12 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
|
|
|
678
681
|
const result = resultId === undefined ? undefined : results.get(resultId)
|
|
679
682
|
const shown = result === undefined ? block : { ...block, result }
|
|
680
683
|
|
|
681
|
-
|
|
684
|
+
if (state?.answer === undefined) return shown
|
|
685
|
+
|
|
686
|
+
const answered = { ...shown, answer: toJson(state.answer.value) }
|
|
687
|
+
const at = answeredAt.get(message.id)
|
|
688
|
+
|
|
689
|
+
return at === undefined ? answered : { ...answered, answeredAt: at }
|
|
682
690
|
}
|
|
683
691
|
|
|
684
692
|
const itemOf = (message: AssistantEvent.AssistantMessage, at: number): AssistantMessage => {
|
|
@@ -845,6 +853,10 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
|
|
|
845
853
|
|
|
846
854
|
blocks = BlockKit.apply(blocks, event)
|
|
847
855
|
|
|
856
|
+
if (Predicate.isTagged(event, "BlockAnswer") && blocks.get(event.messageId)?.answer === event) {
|
|
857
|
+
answeredAt.set(event.messageId, entry.at)
|
|
858
|
+
}
|
|
859
|
+
|
|
848
860
|
const decidedBefore = approvals
|
|
849
861
|
approvals = ToolApproval.apply(approvals, entry)
|
|
850
862
|
|