effect-assistant 0.13.2 → 0.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (47) hide show
  1. package/dist/Assistant.d.ts +5 -4
  2. package/dist/Assistant.d.ts.map +1 -1
  3. package/dist/Assistant.js +2 -2
  4. package/dist/Assistant.js.map +1 -1
  5. package/dist/AssistantActivity.d.ts +5 -4
  6. package/dist/AssistantActivity.d.ts.map +1 -1
  7. package/dist/AssistantActivity.js +0 -11
  8. package/dist/AssistantActivity.js.map +1 -1
  9. package/dist/AssistantEngine.d.ts +2 -2
  10. package/dist/AssistantEngine.d.ts.map +1 -1
  11. package/dist/AssistantEngine.js +8 -8
  12. package/dist/AssistantEngine.js.map +1 -1
  13. package/dist/AssistantEvent.d.ts +5 -4
  14. package/dist/AssistantEvent.d.ts.map +1 -1
  15. package/dist/AssistantEvent.js +3 -3
  16. package/dist/AssistantEvent.js.map +1 -1
  17. package/dist/ChatLog.js +4 -4
  18. package/dist/ChatLog.js.map +1 -1
  19. package/dist/ChatSignal.js +1 -1
  20. package/dist/ChatSignal.js.map +1 -1
  21. package/dist/Memory.d.ts +1 -1
  22. package/dist/Memory.js +2 -2
  23. package/dist/StatusSummary.d.ts +1 -1
  24. package/dist/StatusSummary.js +1 -1
  25. package/dist/Timeline.d.ts +21 -18
  26. package/dist/Timeline.d.ts.map +1 -1
  27. package/dist/Timeline.js +17 -15
  28. package/dist/Timeline.js.map +1 -1
  29. package/dist/ToolApproval.d.ts +3 -2
  30. package/dist/ToolApproval.d.ts.map +1 -1
  31. package/dist/ToolApproval.js +0 -13
  32. package/dist/ToolApproval.js.map +1 -1
  33. package/dist/internal/history.js +5 -3
  34. package/dist/internal/history.js.map +1 -1
  35. package/dist/internal/live.js +1 -1
  36. package/dist/internal/loop.js +1 -1
  37. package/dist/internal/summary.js +1 -1
  38. package/package.json +1 -1
  39. package/src/Assistant.ts +13 -9
  40. package/src/AssistantActivity.ts +5 -4
  41. package/src/AssistantEngine.ts +10 -10
  42. package/src/AssistantEvent.ts +5 -4
  43. package/src/ChatLog.ts +4 -4
  44. package/src/ChatSignal.ts +1 -1
  45. package/src/Timeline.ts +29 -21
  46. package/src/ToolApproval.ts +3 -2
  47. package/src/internal/history.ts +5 -3
@@ -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 /** 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, { 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 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,MAAa,oBAAoB,OAAO,OAAO;CAC7C,YAAY,OAAO;CACnB,OAAO,OAAO;AAChB,CAAC;;;;;;;;;;;;;;;;AAyBD,MAAa,WAAW,OAAO,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I,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"}
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 * as DateTime from \"effect/DateTime\"\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, once the block is answered. Encodes as epoch milliseconds. */\n answeredAt: Schema.optional(Schema.DateTimeUtcFromMillis),\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, a UTC `DateTime` that encodes\n * as epoch 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.DateTimeUtcFromMillis\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. `at` is\n * when it was stored, a UTC `DateTime` that encodes as epoch milliseconds.\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.DateTimeUtcFromMillis,\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, a UTC `DateTime` that encodes as epoch\n * 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: DateTime.Utc; 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, a UTC `DateTime` that\n * encodes as epoch 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.DateTimeUtcFromMillis\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, a UTC `DateTime` that encodes as epoch milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const SpecialistWorking = Schema.Struct({\n specialist: Schema.String,\n since: Schema.DateTimeUtcFromMillis\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({\n _tag: Schema.Literal(AppEvents.tagOf(schema)),\n id: Schema.String,\n at: Schema.DateTimeUtcFromMillis,\n event: schema\n })\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: DateTime.Utc\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 && DateTime.Equivalence(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, DateTime.Utc>()\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: DateTime.Utc): 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: DateTime.Utc): 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"],"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O;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"}
@@ -2,6 +2,7 @@ import { AnyEntry, ApprovalDecision, ApprovalRequested, AssistantEvent_d_exports
2
2
  import { CurrentChat } from "./CurrentChat.js";
3
3
  import { InputId, InputId_d_exports } from "./InputId.js";
4
4
  import * as Effect from "effect/Effect";
5
+ import * as DateTime from "effect/DateTime";
5
6
  declare namespace ToolApproval_d_exports {
6
7
  export { State, Status, apply, approve, closeStale, decisionId, fromEntries, reject, staleApprovals };
7
8
  }
@@ -21,8 +22,8 @@ export type Status = "pending" | "approved" | "rejected" | "expired";
21
22
  */
22
23
  export interface State {
23
24
  readonly request: ApprovalRequested;
24
- /** When the call started waiting, in epoch milliseconds. */
25
- readonly at: number;
25
+ /** When the call started waiting. */
26
+ readonly at: DateTime.Utc;
26
27
  readonly status: Status;
27
28
  /** The user's reason, when they rejected it with one. */
28
29
  readonly reason: string | undefined;
@@ -1 +1 @@
1
- {"version":3,"file":"ToolApproval.d.ts","names":[],"sources":["../src/ToolApproval.ts"],"mappings":";;;;;;;;;;;;;;YA0BY;;;;;;;iBAQK;WACN,SAAS;;WAET;WACA,QAAQ;;WAER;;WAEA,SAAS;;;;;;;;;;;;;qBAmBP,QAAK,QACR,oBAAoB,QAAM,OAC3B,aACN,oBAAoB;;;;;;;qBA0DV,cAAW,SAAa,cAAc,cAA2B,oBAAoB;;;;;;;qBASrF,aAAU,mBAAqB;;;;;;;;;;;;;;;;;;;;;;qBAuB/B,UAAO;WAAyB;MAAe;;;;;;;;;;qBAY/C,SAAM;WACI;GAAY;WACZ;MACpB;;;;;;;;;;;;qBAqBU,iBAAc,SAChB,cAAc,WAAwB;WAC3B;MACnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAkDU,aAAU;WAAsD;MAK3E,OAAA,oBAAA"}
1
+ {"version":3,"file":"ToolApproval.d.ts","names":[],"sources":["../src/ToolApproval.ts"],"mappings":";;;;;;;;;;;;;;;YA2BY;;;;;;;iBAQK;WACN,SAAS;;WAET,IAAI,SAAS;WACb,QAAQ;;WAER;;WAEA,SAAS;;;;;;;;;;;;;qBAmBP,QAAK,QACR,oBAAoB,QAAM,OAC3B,aACN,oBAAoB;;;;;;;qBA0DV,cAAW,SAAa,cAAc,cAA2B,oBAAoB;;;;;;;qBASrF,aAAU,mBAAqB;;;;;;;;;;;;;;;;;;;;;;qBAuB/B,UAAO;WAAyB;MAAe;;;;;;;;;;qBAY/C,SAAM;WACI;GAAY;WACZ;MACpB;;;;;;;;;;;;qBAqBU,iBAAc,SAChB,cAAc,WAAwB;WAC3B;MACnB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAkDU,aAAU;WAAsD;MAK3E,OAAA,oBAAA"}
@@ -5,19 +5,6 @@ import { CurrentChat } from "./CurrentChat.js";
5
5
  import * as Effect from "effect/Effect";
6
6
  import * as Predicate from "effect/Predicate";
7
7
  //#region src/ToolApproval.ts
8
- /**
9
- * Tool calls that wait for the user's approval.
10
- *
11
- * A tool made with Effect's `needsApproval` doesn't run when the model calls it in a turn: the
12
- * call waits ({@link AssistantEvent.ApprovalRequested}), the turn ends, and the chat's timeline
13
- * shows it to the user. Their decision, built with {@link approve} or {@link reject} and submitted
14
- * like a message, wakes a turn: an approved call runs then, with its params and id, and a rejected
15
- * one doesn't. A call the user moved on from expires ({@link closeStale}, like `BlockKit.closeStale`). On the timeline, every
16
- * call is an item with its tool's name and where it stands: only the yes or no, since the
17
- * assistant's message says what it asks.
18
- *
19
- * @since 0.4.0
20
- */
21
8
  var ToolApproval_exports = /* @__PURE__ */ __exportAll({
22
9
  apply: () => apply,
23
10
  approve: () => approve,
@@ -1 +1 @@
1
- {"version":3,"file":"ToolApproval.js","names":["AssistantEvent.isLibraryEvent","InputId.fromKey"],"sources":["../src/ToolApproval.ts"],"sourcesContent":["/**\n * Tool calls that wait for the user's approval.\n *\n * A tool made with Effect's `needsApproval` doesn't run when the model calls it in a turn: the\n * call waits ({@link AssistantEvent.ApprovalRequested}), the turn ends, and the chat's timeline\n * shows it to the user. Their decision, built with {@link approve} or {@link reject} and submitted\n * like a message, wakes a turn: an approved call runs then, with its params and id, and a rejected\n * one doesn't. A call the user moved on from expires ({@link closeStale}, like `BlockKit.closeStale`). On the timeline, every\n * call is an item with its tool's name and where it stands: only the yes or no, since the\n * assistant's message says what it asks.\n *\n * @since 0.4.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport { CurrentChat } from \"./CurrentChat.ts\"\nimport * as InputId from \"./InputId.ts\"\n\n/**\n * Represents where a call that waits for approval stands: `\"pending\"` until the user decides,\n * then `\"approved\"` or `\"rejected\"`, or `\"expired\"` when the user moved on.\n *\n * @category models\n * @since 0.4.0\n */\nexport type Status = \"pending\" | \"approved\" | \"rejected\" | \"expired\"\n\n/**\n * Represents a tool call that waited, or waits, for the user's approval.\n *\n * @category models\n * @since 0.4.0\n */\nexport interface State {\n readonly request: AssistantEvent.ApprovalRequested\n /** When the call started waiting, in epoch milliseconds. */\n readonly at: number\n readonly status: Status\n /** The user's reason, when they rejected it with one. */\n readonly reason: string | undefined\n /** How the approved call went, once it ran. */\n readonly outcome: AssistantEvent.ToolOutcome | undefined\n}\n\nconst decided = (state: State, decision: AssistantEvent.ApprovalDecision): State =>\n decision.reason === undefined\n ? { ...state, status: decision.decision }\n : { ...state, status: decision.decision, reason: decision.reason }\n\n/**\n * Returns the approvals after one more entry. Fold a chat's entries in order, or use\n * {@link fromEntries}.\n *\n * **Details**\n *\n * The first of a call's decision and its expiry counts: anything after it changes nothing.\n *\n * @category combinators\n * @since 0.4.0\n */\nexport const apply = (\n states: ReadonlyMap<string, State>,\n entry: AssistantEvent.AnyEntry\n): ReadonlyMap<string, State> => {\n const { event } = entry\n\n if (!AssistantEvent.isLibraryEvent(event)) return states\n\n if (Predicate.isTagged(event, \"ApprovalRequested\")) {\n return states.has(event.callId)\n ? states\n : new Map(states).set(event.callId, {\n request: event,\n at: entry.at,\n status: \"pending\",\n reason: undefined,\n outcome: undefined\n })\n }\n\n if (Predicate.isTagged(event, \"ApprovalDecision\")) {\n const state = states.get(event.callId)\n\n return state === undefined || state.status !== \"pending\"\n ? states\n : new Map(states).set(event.callId, decided(state, event))\n }\n\n if (Predicate.isTagged(event, \"ApprovalsExpired\")) {\n const expired = event.callIds.flatMap((callId) => {\n const state = states.get(callId)\n\n return state === undefined || state.status !== \"pending\" ? [] : [{ ...state, status: \"expired\" as const }]\n })\n\n if (expired.length === 0) return states\n\n const next = new Map(states)\n\n for (const state of expired) next.set(state.request.callId, state)\n\n return next\n }\n\n if (Predicate.isTagged(event, \"ToolResult\")) {\n const state = states.get(event.callId)\n\n return state === undefined || state.status !== \"approved\"\n ? states\n : new Map(states).set(event.callId, { ...state, outcome: event.outcome })\n }\n\n return states\n}\n\n/**\n * Returns every call that waited for approval in a chat, by call id, with where it stands.\n *\n * @category constructors\n * @since 0.4.0\n */\nexport const fromEntries = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlyMap<string, State> =>\n entries.reduce(apply, new Map<string, State>())\n\n/**\n * The id of a decision on a call: the same for every decision on it, so the chat stores one.\n *\n * @category utils\n * @since 0.4.0\n */\nexport const decisionId = (callId: string): InputId.InputId => InputId.fromKey(`approval:${callId}`)\n\n/**\n * Returns the input that approves a call waiting for the user's approval, to submit like a\n * message. `approval` is the call's item on the chat's timeline, or anything with the call's id.\n *\n * **Example** (Approve and reject buttons on the client)\n *\n * ```tsx\n * import { ToolApproval } from \"effect-assistant\"\n *\n * const buttons = (approval: { readonly id: string; readonly status: ToolApproval.Status }) =>\n * approval.status === \"pending\" ? (\n * <>\n * <button onClick={() => submit(ToolApproval.approve(approval))}>Approve</button>\n * <button onClick={() => submit(ToolApproval.reject(approval, { reason: \"Not this week\" }))}>Reject</button>\n * </>\n * ) : null\n * ```\n *\n * @category constructors\n * @since 0.4.0\n */\nexport const approve = (approval: { readonly id: string }): AssistantEvent.ApprovalDecision =>\n AssistantEvent.ApprovalDecision.make({ id: decisionId(approval.id), callId: approval.id, decision: \"approved\" })\n\n/**\n * Returns the input that rejects a call waiting for the user's approval, with an optional short\n * reason the model reads.\n *\n * @see {@link approve} for an example\n *\n * @category constructors\n * @since 0.4.0\n */\nexport const reject = (\n approval: { readonly id: string },\n options?: { readonly reason?: string | undefined }\n): AssistantEvent.ApprovalDecision =>\n options?.reason === undefined\n ? AssistantEvent.ApprovalDecision.make({ id: decisionId(approval.id), callId: approval.id, decision: \"rejected\" })\n : AssistantEvent.ApprovalDecision.make({\n id: decisionId(approval.id),\n callId: approval.id,\n decision: \"rejected\",\n reason: options.reason\n })\n\n/**\n * Returns the ids of the calls still waiting for approval after the user typed the given number\n * of messages without deciding them.\n *\n * **Details**\n *\n * These are the calls {@link closeStale} closes.\n *\n * @category utils\n * @since 0.4.0\n */\nexport const staleApprovals = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n options: { readonly messages: number }\n): ReadonlyArray<string> => {\n const states = fromEntries(entries)\n\n return [...states.values()].flatMap((state) => {\n if (state.status !== \"pending\") return []\n\n const requested = entries.findIndex(\n ({ event }) =>\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"ApprovalRequested\") &&\n event.callId === state.request.callId\n )\n\n const typed = entries.slice(requested + 1).filter(({ event }) => Predicate.isTagged(event, \"UserMessage\")).length\n\n return typed >= options.messages ? [state.request.callId] : []\n })\n}\n\n/**\n * Closes the calls the user moved on from, which still wait for approval after the given number\n * of typed messages: they expire, and won't run.\n *\n * **Details**\n *\n * Run it from a turn, before or after its loop, like `BlockKit.closeStale`. It records an\n * `ApprovalsExpired` event: the timeline shows the calls as expired, the model reads that they\n * weren't approved, and a decision that arrives later isn't stored.\n *\n * **Example** (Closing calls the user moved on from, and stale blocks, every turn)\n *\n * ```ts\n * import { BlockKit, ToolApproval } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * const MyAssistantLive = MyAssistant.toLayer(\n * Effect.fn(function* (turn) {\n * yield* BlockKit.closeStale({ messages: 10 })\n * yield* ToolApproval.closeStale({ messages: 10 })\n *\n * return turn.run({ instructions, toolkit: MyTools })\n * })\n * )\n * ```\n *\n * @see {@link staleApprovals} for the calls it closes\n *\n * @category utils\n * @since 0.4.0\n */\nexport const closeStale = Effect.fn(function* (options: { readonly messages: number }) {\n const chat = yield* CurrentChat\n const stale = staleApprovals(yield* chat.entries, options)\n\n if (stale.length > 0) yield* chat.append(AssistantEvent.ApprovalsExpired.make({ callIds: stale }))\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAM,WAAW,OAAc,aAC7B,SAAS,WAAW,KAAA,IAChB;CAAE,GAAG;CAAO,QAAQ,SAAS;AAAS,IACtC;CAAE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AAS,GAAG,OAAO,KAAK,OAAA,iBAAuC,KAAK,EAAE,SAAS,MAAM,CAAC,CAAC;AACnG,CAAC"}
1
+ {"version":3,"file":"ToolApproval.js","names":["AssistantEvent.isLibraryEvent","InputId.fromKey"],"sources":["../src/ToolApproval.ts"],"sourcesContent":["/**\n * Tool calls that wait for the user's approval.\n *\n * A tool made with Effect's `needsApproval` doesn't run when the model calls it in a turn: the\n * call waits ({@link AssistantEvent.ApprovalRequested}), the turn ends, and the chat's timeline\n * shows it to the user. Their decision, built with {@link approve} or {@link reject} and submitted\n * like a message, wakes a turn: an approved call runs then, with its params and id, and a rejected\n * one doesn't. A call the user moved on from expires ({@link closeStale}, like `BlockKit.closeStale`). On the timeline, every\n * call is an item with its tool's name and where it stands: only the yes or no, since the\n * assistant's message says what it asks.\n *\n * @since 0.4.0\n */\nimport type * as DateTime from \"effect/DateTime\"\nimport * as Effect from \"effect/Effect\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport { CurrentChat } from \"./CurrentChat.ts\"\nimport * as InputId from \"./InputId.ts\"\n\n/**\n * Represents where a call that waits for approval stands: `\"pending\"` until the user decides,\n * then `\"approved\"` or `\"rejected\"`, or `\"expired\"` when the user moved on.\n *\n * @category models\n * @since 0.4.0\n */\nexport type Status = \"pending\" | \"approved\" | \"rejected\" | \"expired\"\n\n/**\n * Represents a tool call that waited, or waits, for the user's approval.\n *\n * @category models\n * @since 0.4.0\n */\nexport interface State {\n readonly request: AssistantEvent.ApprovalRequested\n /** When the call started waiting. */\n readonly at: DateTime.Utc\n readonly status: Status\n /** The user's reason, when they rejected it with one. */\n readonly reason: string | undefined\n /** How the approved call went, once it ran. */\n readonly outcome: AssistantEvent.ToolOutcome | undefined\n}\n\nconst decided = (state: State, decision: AssistantEvent.ApprovalDecision): State =>\n decision.reason === undefined\n ? { ...state, status: decision.decision }\n : { ...state, status: decision.decision, reason: decision.reason }\n\n/**\n * Returns the approvals after one more entry. Fold a chat's entries in order, or use\n * {@link fromEntries}.\n *\n * **Details**\n *\n * The first of a call's decision and its expiry counts: anything after it changes nothing.\n *\n * @category combinators\n * @since 0.4.0\n */\nexport const apply = (\n states: ReadonlyMap<string, State>,\n entry: AssistantEvent.AnyEntry\n): ReadonlyMap<string, State> => {\n const { event } = entry\n\n if (!AssistantEvent.isLibraryEvent(event)) return states\n\n if (Predicate.isTagged(event, \"ApprovalRequested\")) {\n return states.has(event.callId)\n ? states\n : new Map(states).set(event.callId, {\n request: event,\n at: entry.at,\n status: \"pending\",\n reason: undefined,\n outcome: undefined\n })\n }\n\n if (Predicate.isTagged(event, \"ApprovalDecision\")) {\n const state = states.get(event.callId)\n\n return state === undefined || state.status !== \"pending\"\n ? states\n : new Map(states).set(event.callId, decided(state, event))\n }\n\n if (Predicate.isTagged(event, \"ApprovalsExpired\")) {\n const expired = event.callIds.flatMap((callId) => {\n const state = states.get(callId)\n\n return state === undefined || state.status !== \"pending\" ? [] : [{ ...state, status: \"expired\" as const }]\n })\n\n if (expired.length === 0) return states\n\n const next = new Map(states)\n\n for (const state of expired) next.set(state.request.callId, state)\n\n return next\n }\n\n if (Predicate.isTagged(event, \"ToolResult\")) {\n const state = states.get(event.callId)\n\n return state === undefined || state.status !== \"approved\"\n ? states\n : new Map(states).set(event.callId, { ...state, outcome: event.outcome })\n }\n\n return states\n}\n\n/**\n * Returns every call that waited for approval in a chat, by call id, with where it stands.\n *\n * @category constructors\n * @since 0.4.0\n */\nexport const fromEntries = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlyMap<string, State> =>\n entries.reduce(apply, new Map<string, State>())\n\n/**\n * The id of a decision on a call: the same for every decision on it, so the chat stores one.\n *\n * @category utils\n * @since 0.4.0\n */\nexport const decisionId = (callId: string): InputId.InputId => InputId.fromKey(`approval:${callId}`)\n\n/**\n * Returns the input that approves a call waiting for the user's approval, to submit like a\n * message. `approval` is the call's item on the chat's timeline, or anything with the call's id.\n *\n * **Example** (Approve and reject buttons on the client)\n *\n * ```tsx\n * import { ToolApproval } from \"effect-assistant\"\n *\n * const buttons = (approval: { readonly id: string; readonly status: ToolApproval.Status }) =>\n * approval.status === \"pending\" ? (\n * <>\n * <button onClick={() => submit(ToolApproval.approve(approval))}>Approve</button>\n * <button onClick={() => submit(ToolApproval.reject(approval, { reason: \"Not this week\" }))}>Reject</button>\n * </>\n * ) : null\n * ```\n *\n * @category constructors\n * @since 0.4.0\n */\nexport const approve = (approval: { readonly id: string }): AssistantEvent.ApprovalDecision =>\n AssistantEvent.ApprovalDecision.make({ id: decisionId(approval.id), callId: approval.id, decision: \"approved\" })\n\n/**\n * Returns the input that rejects a call waiting for the user's approval, with an optional short\n * reason the model reads.\n *\n * @see {@link approve} for an example\n *\n * @category constructors\n * @since 0.4.0\n */\nexport const reject = (\n approval: { readonly id: string },\n options?: { readonly reason?: string | undefined }\n): AssistantEvent.ApprovalDecision =>\n options?.reason === undefined\n ? AssistantEvent.ApprovalDecision.make({ id: decisionId(approval.id), callId: approval.id, decision: \"rejected\" })\n : AssistantEvent.ApprovalDecision.make({\n id: decisionId(approval.id),\n callId: approval.id,\n decision: \"rejected\",\n reason: options.reason\n })\n\n/**\n * Returns the ids of the calls still waiting for approval after the user typed the given number\n * of messages without deciding them.\n *\n * **Details**\n *\n * These are the calls {@link closeStale} closes.\n *\n * @category utils\n * @since 0.4.0\n */\nexport const staleApprovals = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n options: { readonly messages: number }\n): ReadonlyArray<string> => {\n const states = fromEntries(entries)\n\n return [...states.values()].flatMap((state) => {\n if (state.status !== \"pending\") return []\n\n const requested = entries.findIndex(\n ({ event }) =>\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"ApprovalRequested\") &&\n event.callId === state.request.callId\n )\n\n const typed = entries.slice(requested + 1).filter(({ event }) => Predicate.isTagged(event, \"UserMessage\")).length\n\n return typed >= options.messages ? [state.request.callId] : []\n })\n}\n\n/**\n * Closes the calls the user moved on from, which still wait for approval after the given number\n * of typed messages: they expire, and won't run.\n *\n * **Details**\n *\n * Run it from a turn, before or after its loop, like `BlockKit.closeStale`. It records an\n * `ApprovalsExpired` event: the timeline shows the calls as expired, the model reads that they\n * weren't approved, and a decision that arrives later isn't stored.\n *\n * **Example** (Closing calls the user moved on from, and stale blocks, every turn)\n *\n * ```ts\n * import { BlockKit, ToolApproval } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * const MyAssistantLive = MyAssistant.toLayer(\n * Effect.fn(function* (turn) {\n * yield* BlockKit.closeStale({ messages: 10 })\n * yield* ToolApproval.closeStale({ messages: 10 })\n *\n * return turn.run({ instructions, toolkit: MyTools })\n * })\n * )\n * ```\n *\n * @see {@link staleApprovals} for the calls it closes\n *\n * @category utils\n * @since 0.4.0\n */\nexport const closeStale = Effect.fn(function* (options: { readonly messages: number }) {\n const chat = yield* CurrentChat\n const stale = staleApprovals(yield* chat.entries, options)\n\n if (stale.length > 0) yield* chat.append(AssistantEvent.ApprovalsExpired.make({ callIds: stale }))\n})\n"],"mappings":";;;;;;;;;;;;;;;;AA8CA,MAAM,WAAW,OAAc,aAC7B,SAAS,WAAW,KAAA,IAChB;CAAE,GAAG;CAAO,QAAQ,SAAS;AAAS,IACtC;CAAE,GAAG;CAAO,QAAQ,SAAS;CAAU,QAAQ,SAAS;AAAO;;;;;;;;;;;;AAarE,MAAa,SACX,QACA,UAC+B;CAC/B,MAAM,EAAE,UAAU;CAElB,IAAI,CAACA,eAA8B,KAAK,GAAG,OAAO;CAElD,IAAI,UAAU,SAAS,OAAO,mBAAmB,GAC/C,OAAO,OAAO,IAAI,MAAM,MAAM,IAC1B,SACA,IAAI,IAAI,MAAM,CAAC,CAAC,IAAI,MAAM,QAAQ;EAChC,SAAS;EACT,IAAI,MAAM;EACV,QAAQ;EACR,QAAQ,KAAA;EACR,SAAS,KAAA;CACX,CAAC;CAGP,IAAI,UAAU,SAAS,OAAO,kBAAkB,GAAG;EACjD,MAA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AU;AAAW,CAAC,IAAA,iBAC/E,KAAK;CACnC,IAAI,WAAW,SAAS,EAAE;CAC1B,QAAQ,SAAS;CACjB,UAAU;CACV,QAAQ,QAAQ;AAClB,CAAC;;;;;;;;;;;;AAaP,MAAa,kBACX,SACA,YAC0B;CAG1B,OAAO,CAAC,GAFO,YAAY,OAEX,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,SAAS,UAAU;EAC7C,IAAI,MAAM,WAAW,WAAW,OAAO,CAAC;EAExC,MAAM,YAAY,QAAQ,WACvB,EAAE,YACDD,eAA8B,KAAK,KACnC,UAAU,SAAS,OAAO,mBAAmB,KAC7C,MAAM,WAAW,MAAM,QAAQ,MACnC;EAIA,OAFc,QAAQ,MAAM,YAAY,CAAC,CAAC,CAAC,QAAQ,EAAE,YAAY,UAAU,SAAS,OAAO,aAAa,CAAC,CAAC,CAAC,UAE3F,QAAQ,WAAW,CAAC,MAAM,QAAQ,MAAM,IAAI,CAAC;CAC/D,CAAC;AACH;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,aAAa,OAAO,GAAG,WAAW,SAAwC;CACrF,MAAM,OAAO,OAAO;CACpB,MAAM,QAAQ,eAAe,OAAO,KAAK,SAAS,OAAO;CAEzD,IAAI,MAAM,SAAS,GAAG,OAAO,KAAK,OAAA,iBAAuC,KAAK,EAAE,SAAS,MAAM,CAAC,CAAC;AACnG,CAAC"}
@@ -5,7 +5,9 @@ import * as Option from "effect/Option";
5
5
  import * as Predicate from "effect/Predicate";
6
6
  import * as Schema from "effect/Schema";
7
7
  import * as Response from "effect/ai/Response";
8
+ import * as DateTime from "effect/DateTime";
8
9
  import * as Prompt from "effect/ai/Prompt";
10
+ import * as Duration from "effect/Duration";
9
11
  import * as Match from "effect/Match";
10
12
  //#region src/internal/history.ts
11
13
  /** @internal */
@@ -33,8 +35,8 @@ const unansweredCalls = (history) => {
33
35
  const notRunOutput = "Not run: the turn ended before this call ran.";
34
36
  /** @internal */
35
37
  const mayHaveRunOutput = "Stopped: the turn ended while this call ran. It may have done its work; check before doing it again.";
36
- const ago = (millis) => {
37
- const seconds = Math.max(0, Math.round(millis / 1e3));
38
+ const ago = (duration) => {
39
+ const seconds = Math.max(0, Math.round(Duration.toSeconds(duration)));
38
40
  return seconds < 90 ? `${seconds} seconds` : `${Math.round(seconds / 60)} minutes`;
39
41
  };
40
42
  const finishedText = (entries, index, finished) => {
@@ -45,7 +47,7 @@ const finishedText = (entries, index, finished) => {
45
47
  const wrote = (started === void 0 ? [] : entries.slice(from + 1, index)).some(({ event }) => Predicate.isTagged(event, "UserMessage"));
46
48
  const lines = [
47
49
  "A report from a specialist you started. The user hasn't seen it.",
48
- started === void 0 ? `You started it for: ${finished.goal}` : `You started it ${ago(at.at - started.at)} ago for: ${finished.goal}`,
50
+ started === void 0 ? `You started it for: ${finished.goal}` : `You started it ${ago(DateTime.distance(started.at, at.at))} ago for: ${finished.goal}`,
49
51
  wrote ? "The user has written since you started it." : "The user hasn't written since you started it.",
50
52
  Match.value(finished.status).pipe(Match.when("answered", () => `Report:\n${finished.report ?? ""}`), Match.when("failed", () => `It failed: ${finished.error ?? ""}`), Match.when("cut_off", () => "A restart cut it off before it finished. Spawn it again if it's still needed."), Match.when("stopped", () => "You stopped it."), Match.exhaustive)
51
53
  ];
@@ -1 +1 @@
1
- {"version":3,"file":"history.js","names":["AssistantEvent.isLibraryEvent","AssistantEvent.textWithAttachments","AssistantEvent.isInput","AssistantEvent.isAppInput","AssistantEvent.isTurnEnd","AssistantEvent.isWaking","AssistantEvent.isUserInput","Uuid.fromKey"],"sources":["../../src/internal/history.ts"],"sourcesContent":["import * as Prompt from \"effect/ai/Prompt\"\nimport * as Response from \"effect/ai/Response\"\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 AssistantEvent from \"../AssistantEvent.ts\"\nimport { toJson, toJsonText } from \"./schema.ts\"\nimport * as Uuid from \"./uuid.ts\"\n\n/** @internal */\nexport const userText = (text: string): Prompt.UserMessage =>\n Prompt.userMessage({ content: [Prompt.textPart({ text })] })\n\n/** @internal */\nexport const toolMessage = (result: AssistantEvent.ToolResult): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: result.callId,\n name: result.tool,\n isFailure: result.outcome === \"failure\",\n result: result.result,\n providerExecuted: false\n })\n ]\n })\n\n// A call with no result is one a crash cut off.\n/** @internal */\nexport const unansweredCalls = (history: ReadonlyArray<Prompt.Message>): ReadonlyArray<AssistantEvent.ToolCallPart> => {\n const answered = new Set(\n history.flatMap((message) =>\n message.role === \"tool\" ? message.content.flatMap((part) => (part.type === \"tool-result\" ? [part.id] : [])) : []\n )\n )\n\n return history.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.flatMap((part) =>\n part.type === \"tool-call\" && !part.providerExecuted && !answered.has(part.id)\n ? [\n Response.makePart(\"tool-call\", {\n id: part.id,\n name: part.name,\n params: toJson(part.params),\n providerExecuted: false,\n metadata: part.options\n })\n ]\n : []\n )\n : []\n )\n}\n\n/** @internal */\nexport const notRunOutput = \"Not run: the turn ended before this call ran.\"\n\n/** @internal */\nexport const mayHaveRunOutput =\n \"Stopped: the turn ended while this call ran. It may have done its work; check before doing it again.\"\n\nconst ago = (millis: number) => {\n const seconds = Math.max(0, Math.round(millis / 1000))\n\n return seconds < 90 ? `${seconds} seconds` : `${Math.round(seconds / 60)} minutes`\n}\n\nconst finishedText = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n index: number,\n finished: AssistantEvent.SpecialistFinished\n) => {\n const at = entries[index]!\n\n const isStart = ({ event }: AssistantEvent.AnyEntry) =>\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"SpecialistStarted\") &&\n event.runId === finished.runId\n\n const from = entries.slice(0, index).findLastIndex(isStart)\n const started = from === -1 ? undefined : entries[from]\n const since = started === undefined ? [] : entries.slice(from + 1, index)\n const wrote = since.some(({ event }) => Predicate.isTagged(event, \"UserMessage\"))\n\n const lines = [\n \"A report from a specialist you started. The user hasn't seen it.\",\n started === undefined\n ? `You started it for: ${finished.goal}`\n : `You started it ${ago(at.at - started.at)} ago for: ${finished.goal}`,\n wrote ? \"The user has written since you started it.\" : \"The user hasn't written since you started it.\",\n Match.value(finished.status).pipe(\n Match.when(\"answered\", () => `Report:\\n${finished.report ?? \"\"}`),\n Match.when(\"failed\", () => `It failed: ${finished.error ?? \"\"}`),\n Match.when(\"cut_off\", () => \"A restart cut it off before it finished. Spawn it again if it's still needed.\"),\n Match.when(\"stopped\", () => \"You stopped it.\"),\n Match.exhaustive\n )\n ]\n\n return `<specialist name=\"${finished.specialist}\" run=\"${finished.runId}\" status=\"${finished.status}\">\\n${lines.join(\n \"\\n\"\n )}\\n</specialist>`\n}\n\nconst answerText = (answer: AssistantEvent.BlockAnswer) =>\n `<answer message=\"${answer.messageId}\" kind=\"${answer.kind}\">\\nThe user answered with the block on your message ${answer.messageId}.\\n${toJsonText(answer.value)}\\n</answer>`\n\nconst resultText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe result of a call from earlier in this chat.\\n${toJsonText(result.result)}\\n</result>`\n\n/** @internal */\nexport const awaitingApprovalOutput =\n \"Waiting for the user's approval: they see this call and approve or reject it. Its outcome arrives later in this chat; don't call it again meanwhile.\"\n\nconst awaitingText = (request: AssistantEvent.ApprovalRequested) =>\n `<approval tool=\"${request.tool}\" call=\"${request.callId}\" status=\"pending\">\\nYour call to ${request.tool} from earlier in this chat waits for the user's approval.\\n${toJsonText(request.params)}\\n</approval>`\n\nconst approvedText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe user approved your call to ${result.tool} from earlier in this chat, and it ran.\\n${toJsonText(result.result)}\\n</result>`\n\nconst rejectedText = (decision: AssistantEvent.ApprovalDecision, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${decision.callId}\" decision=\"rejected\">\\nThe user rejected your call to ${tool}; it didn't run.${decision.reason === undefined ? \"\" : `\\nTheir reason: ${decision.reason}`}\\n</approval>`\n\nconst expiredText = (callId: string, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${callId}\" status=\"expired\">\\nThe user moved on without approving your call to ${tool}; it didn't run.\\n</approval>`\n\nconst awaitingMessage = (request: AssistantEvent.ApprovalRequested): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: request.callId,\n name: request.tool,\n isFailure: false,\n result: awaitingApprovalOutput,\n providerExecuted: false\n })\n ]\n })\n\nconst isEntry = (item: AssistantEvent.AnyEntry | Prompt.Message): item is AssistantEvent.AnyEntry =>\n Predicate.hasProperty(item, \"sequence\")\n\n// In the order the model saw the entries, not the order they were stored. A message a history view put in stands\n// where it is, right after the entry before it, and waits like an input for a call's result or for the model's next\n// read; the app's own events reach the model only as such messages.\n/** @internal */\nexport const fromEntries = (\n items: ReadonlyArray<AssistantEvent.AnyEntry | Prompt.Message>\n): ReadonlyArray<Prompt.Message> => {\n const entries = items.filter(isEntry)\n const history: Array<Prompt.Message> = []\n const held: Array<Prompt.Message> = []\n const open = new Set<string>()\n const called = new Set<string>()\n // Calls that waited for approval: the placeholder answered them, so what came of them later is an input.\n const requests = new Map<string, AssistantEvent.ApprovalRequested>()\n const toolOf = (callId: string) => requests.get(callId)?.tool ?? \"a tool\"\n\n const flushIfClosed = () => {\n if (open.size === 0) history.push(...held.splice(0))\n }\n\n const nextSeen = (from: number) => {\n const next = entries.slice(from + 1).find(({ event }) => Predicate.isTagged(event, \"ModelOutput\"))?.event\n\n return next !== undefined && AssistantEvent.isLibraryEvent(next) && Predicate.isTagged(next, \"ModelOutput\")\n ? next.seenThroughSequence\n : undefined\n }\n\n // `index` is the last entry at or before the item, and `sequence` where the item stands.\n const input = (index: number, sequence: number, item: Prompt.Message) => {\n const seen = nextSeen(index)\n\n if (open.size > 0 || (seen !== undefined && seen < sequence)) held.push(item)\n else history.push(item)\n }\n\n let index = -1\n\n for (const item of items) {\n if (!isEntry(item)) {\n input(index, (entries[index]?.sequence ?? 0) + 0.5, item)\n\n continue\n }\n\n index += 1\n\n const { event, sequence } = item\n const at = index\n\n if (!AssistantEvent.isLibraryEvent(event)) continue\n\n Match.value(event).pipe(\n Match.tagsExhaustive({\n UserMessage: (message) =>\n input(at, sequence, userText(AssistantEvent.textWithAttachments(message.text, message.attachments))),\n BlockAnswer: (answer) => input(at, sequence, userText(answerText(answer))),\n ModelOutput: (output) => {\n history.push(...Prompt.fromResponseParts(output.parts).content)\n\n for (const part of output.parts) {\n if (part.type === \"tool-call\") {\n open.add(part.id)\n called.add(part.id)\n }\n }\n\n flushIfClosed()\n },\n ToolResult: (result) => {\n if (requests.has(result.callId)) return input(at, sequence, userText(approvedText(result)))\n\n // A view that starts after the call (since a summary, say) keeps its result as text: a tool result needs its\n // call right before it.\n if (!called.has(result.callId)) return input(at, sequence, userText(resultText(result)))\n\n history.push(toolMessage(result))\n open.delete(result.callId)\n flushIfClosed()\n },\n AssistantMessage: () => undefined,\n ToolStarted: () => undefined,\n TurnStarted: () => undefined,\n TurnCompleted: () => undefined,\n TurnFailed: () => undefined,\n SpecialistFinished: (finished) => input(at, sequence, userText(finishedText(entries, at, finished))),\n // Every run starts in a call of the model's own (a spawn or a follow-up), whose result says so.\n SpecialistStarted: () => undefined,\n BlocksClosed: () => undefined,\n // The call's result, for the provider's pairing; what the user decides comes later.\n ApprovalRequested: (request) => {\n requests.set(request.callId, request)\n\n if (!called.has(request.callId)) return input(at, sequence, userText(awaitingText(request)))\n\n history.push(awaitingMessage(request))\n open.delete(request.callId)\n flushIfClosed()\n },\n // An approved call's result says so.\n ApprovalDecision: (decision) =>\n decision.decision === \"rejected\"\n ? input(at, sequence, userText(rejectedText(decision, toolOf(decision.callId))))\n : undefined,\n ApprovalsExpired: (expired) =>\n expired.callIds.forEach((callId) => input(at, sequence, userText(expiredText(callId, toolOf(callId))))),\n ChatDeleted: () => undefined\n })\n )\n }\n\n return [...history, ...held]\n}\n\n/** @internal */\nexport const isInput = (event: { readonly _tag: string }): boolean =>\n AssistantEvent.isInput(event) || AssistantEvent.isAppInput(event)\n\n/** @internal */\nexport const handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): number => {\n const last = entries.findLast(({ event }) => AssistantEvent.isTurnEnd(event))?.event\n\n return last !== undefined && AssistantEvent.isTurnEnd(last) ? last.throughSequence : 0\n}\n\n// A run the assistant stopped isn't an input here: it wakes nothing.\n/** @internal */\nexport const unhandledInputs = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>\n): ReadonlyArray<{ readonly _tag: string }> => {\n const seen = handledThrough(entries)\n\n return entries.flatMap(({ event, sequence }) =>\n sequence > seen && isInput(event) && !(AssistantEvent.isInput(event) && !AssistantEvent.isWaking(event))\n ? [event]\n : []\n )\n}\n\n/** @internal */\nexport const needsTurn = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): boolean =>\n unhandledInputs(entries).length > 0\n\n// A failure the user was shown counts as a reply, and so does a call they're asked to approve.\n/** @internal */\nexport const owesReply = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n return (\n latest !== undefined &&\n !entries.some(\n ({ event, sequence }) =>\n sequence > latest.sequence &&\n (Predicate.isTagged(event, \"AssistantMessage\") ||\n Predicate.isTagged(event, \"TurnFailed\") ||\n Predicate.isTagged(event, \"ApprovalRequested\"))\n )\n )\n}\n\nconst sentToWaitOn = Schema.decodeUnknownOption(Schema.Struct({ wait: Schema.Literal(false) }))\n\n// Messages sent with `wait: false` are progress while the model kept working, like \"On it\".\nconst progressMessages = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlySet<string> =>\n new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"ModelOutput\")\n ? event.parts.flatMap((part) =>\n part.type === \"tool-call\" && part.name === \"send_user_message\" && Option.isSome(sentToWaitOn(part.params))\n ? [Uuid.fromKey(`message:${part.id}`)]\n : []\n )\n : []\n )\n )\n\n// The model said it was on it and stopped without the result: its last message since the user's latest input was\n// progress. An earlier message may have answered something else, such as an input that came before. A specialist still\n// working doesn't count, since its report is what comes next.\n/** @internal */\nexport const owesDelivery = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n if (latest === undefined) return false\n\n const after = entries.flatMap(({ sequence, event }) =>\n sequence > latest.sequence && AssistantEvent.isLibraryEvent(event) ? [event] : []\n )\n\n const last = after.findLast((event) => Predicate.isTagged(event, \"AssistantMessage\"))\n const progress = progressMessages(entries)\n const started = after.flatMap((event) => (Predicate.isTagged(event, \"SpecialistStarted\") ? [event.runId] : []))\n\n const finished = new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"SpecialistFinished\") ? [event.runId] : []\n )\n )\n\n // A call waiting for the user's approval is what comes next, like a specialist's report.\n return (\n last !== undefined &&\n last.block === undefined &&\n progress.has(last.id) &&\n !after.some((event) => Predicate.isTagged(event, \"TurnFailed\") || Predicate.isTagged(event, \"ApprovalRequested\")) &&\n started.every((runId) => finished.has(runId))\n )\n}\n\n/** @internal */\nexport const unreadAfter = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean =>\n entries.some(({ event, sequence }) => sequence > throughSequence && isInput(event))\n"],"mappings":";;;;;;;;;;;AAWA,MAAa,YAAY,SACvB,OAAO,YAAY,EAAE,SAAS,CAAC,OAAO,SAAS,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;;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M,UAAU,UAAU,SAAS,OAAO,YAAY,KAAK,UAAU,SAAS,OAAO,mBAAmB,CAAC,KAChH,QAAQ,OAAO,UAAU,SAAS,IAAI,KAAK,CAAC;AAEhD;;AAGA,MAAa,eAAe,SAAiD,oBAC3E,QAAQ,MAAM,EAAE,OAAO,eAAe,WAAW,mBAAmB,QAAQ,KAAK,CAAC"}
1
+ {"version":3,"file":"history.js","names":["AssistantEvent.isLibraryEvent","AssistantEvent.textWithAttachments","AssistantEvent.isInput","AssistantEvent.isAppInput","AssistantEvent.isTurnEnd","AssistantEvent.isWaking","AssistantEvent.isUserInput","Uuid.fromKey"],"sources":["../../src/internal/history.ts"],"sourcesContent":["import * as Prompt from \"effect/ai/Prompt\"\nimport * as Response from \"effect/ai/Response\"\nimport * as DateTime from \"effect/DateTime\"\nimport * as Duration from \"effect/Duration\"\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 AssistantEvent from \"../AssistantEvent.ts\"\nimport { toJson, toJsonText } from \"./schema.ts\"\nimport * as Uuid from \"./uuid.ts\"\n\n/** @internal */\nexport const userText = (text: string): Prompt.UserMessage =>\n Prompt.userMessage({ content: [Prompt.textPart({ text })] })\n\n/** @internal */\nexport const toolMessage = (result: AssistantEvent.ToolResult): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: result.callId,\n name: result.tool,\n isFailure: result.outcome === \"failure\",\n result: result.result,\n providerExecuted: false\n })\n ]\n })\n\n// A call with no result is one a crash cut off.\n/** @internal */\nexport const unansweredCalls = (history: ReadonlyArray<Prompt.Message>): ReadonlyArray<AssistantEvent.ToolCallPart> => {\n const answered = new Set(\n history.flatMap((message) =>\n message.role === \"tool\" ? message.content.flatMap((part) => (part.type === \"tool-result\" ? [part.id] : [])) : []\n )\n )\n\n return history.flatMap((message) =>\n message.role === \"assistant\"\n ? message.content.flatMap((part) =>\n part.type === \"tool-call\" && !part.providerExecuted && !answered.has(part.id)\n ? [\n Response.makePart(\"tool-call\", {\n id: part.id,\n name: part.name,\n params: toJson(part.params),\n providerExecuted: false,\n metadata: part.options\n })\n ]\n : []\n )\n : []\n )\n}\n\n/** @internal */\nexport const notRunOutput = \"Not run: the turn ended before this call ran.\"\n\n/** @internal */\nexport const mayHaveRunOutput =\n \"Stopped: the turn ended while this call ran. It may have done its work; check before doing it again.\"\n\nconst ago = (duration: Duration.Duration) => {\n const seconds = Math.max(0, Math.round(Duration.toSeconds(duration)))\n\n return seconds < 90 ? `${seconds} seconds` : `${Math.round(seconds / 60)} minutes`\n}\n\nconst finishedText = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n index: number,\n finished: AssistantEvent.SpecialistFinished\n) => {\n const at = entries[index]!\n\n const isStart = ({ event }: AssistantEvent.AnyEntry) =>\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"SpecialistStarted\") &&\n event.runId === finished.runId\n\n const from = entries.slice(0, index).findLastIndex(isStart)\n const started = from === -1 ? undefined : entries[from]\n const since = started === undefined ? [] : entries.slice(from + 1, index)\n const wrote = since.some(({ event }) => Predicate.isTagged(event, \"UserMessage\"))\n\n const lines = [\n \"A report from a specialist you started. The user hasn't seen it.\",\n started === undefined\n ? `You started it for: ${finished.goal}`\n : `You started it ${ago(DateTime.distance(started.at, at.at))} ago for: ${finished.goal}`,\n wrote ? \"The user has written since you started it.\" : \"The user hasn't written since you started it.\",\n Match.value(finished.status).pipe(\n Match.when(\"answered\", () => `Report:\\n${finished.report ?? \"\"}`),\n Match.when(\"failed\", () => `It failed: ${finished.error ?? \"\"}`),\n Match.when(\"cut_off\", () => \"A restart cut it off before it finished. Spawn it again if it's still needed.\"),\n Match.when(\"stopped\", () => \"You stopped it.\"),\n Match.exhaustive\n )\n ]\n\n return `<specialist name=\"${finished.specialist}\" run=\"${finished.runId}\" status=\"${finished.status}\">\\n${lines.join(\n \"\\n\"\n )}\\n</specialist>`\n}\n\nconst answerText = (answer: AssistantEvent.BlockAnswer) =>\n `<answer message=\"${answer.messageId}\" kind=\"${answer.kind}\">\\nThe user answered with the block on your message ${answer.messageId}.\\n${toJsonText(answer.value)}\\n</answer>`\n\nconst resultText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe result of a call from earlier in this chat.\\n${toJsonText(result.result)}\\n</result>`\n\n/** @internal */\nexport const awaitingApprovalOutput =\n \"Waiting for the user's approval: they see this call and approve or reject it. Its outcome arrives later in this chat; don't call it again meanwhile.\"\n\nconst awaitingText = (request: AssistantEvent.ApprovalRequested) =>\n `<approval tool=\"${request.tool}\" call=\"${request.callId}\" status=\"pending\">\\nYour call to ${request.tool} from earlier in this chat waits for the user's approval.\\n${toJsonText(request.params)}\\n</approval>`\n\nconst approvedText = (result: AssistantEvent.ToolResult) =>\n `<result tool=\"${result.tool}\" call=\"${result.callId}\" outcome=\"${result.outcome}\">\\nThe user approved your call to ${result.tool} from earlier in this chat, and it ran.\\n${toJsonText(result.result)}\\n</result>`\n\nconst rejectedText = (decision: AssistantEvent.ApprovalDecision, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${decision.callId}\" decision=\"rejected\">\\nThe user rejected your call to ${tool}; it didn't run.${decision.reason === undefined ? \"\" : `\\nTheir reason: ${decision.reason}`}\\n</approval>`\n\nconst expiredText = (callId: string, tool: string) =>\n `<approval tool=\"${tool}\" call=\"${callId}\" status=\"expired\">\\nThe user moved on without approving your call to ${tool}; it didn't run.\\n</approval>`\n\nconst awaitingMessage = (request: AssistantEvent.ApprovalRequested): Prompt.ToolMessage =>\n Prompt.toolMessage({\n content: [\n Prompt.toolResultPart({\n id: request.callId,\n name: request.tool,\n isFailure: false,\n result: awaitingApprovalOutput,\n providerExecuted: false\n })\n ]\n })\n\nconst isEntry = (item: AssistantEvent.AnyEntry | Prompt.Message): item is AssistantEvent.AnyEntry =>\n Predicate.hasProperty(item, \"sequence\")\n\n// In the order the model saw the entries, not the order they were stored. A message a history view put in stands\n// where it is, right after the entry before it, and waits like an input for a call's result or for the model's next\n// read; the app's own events reach the model only as such messages.\n/** @internal */\nexport const fromEntries = (\n items: ReadonlyArray<AssistantEvent.AnyEntry | Prompt.Message>\n): ReadonlyArray<Prompt.Message> => {\n const entries = items.filter(isEntry)\n const history: Array<Prompt.Message> = []\n const held: Array<Prompt.Message> = []\n const open = new Set<string>()\n const called = new Set<string>()\n // Calls that waited for approval: the placeholder answered them, so what came of them later is an input.\n const requests = new Map<string, AssistantEvent.ApprovalRequested>()\n const toolOf = (callId: string) => requests.get(callId)?.tool ?? \"a tool\"\n\n const flushIfClosed = () => {\n if (open.size === 0) history.push(...held.splice(0))\n }\n\n const nextSeen = (from: number) => {\n const next = entries.slice(from + 1).find(({ event }) => Predicate.isTagged(event, \"ModelOutput\"))?.event\n\n return next !== undefined && AssistantEvent.isLibraryEvent(next) && Predicate.isTagged(next, \"ModelOutput\")\n ? next.seenThroughSequence\n : undefined\n }\n\n // `index` is the last entry at or before the item, and `sequence` where the item stands.\n const input = (index: number, sequence: number, item: Prompt.Message) => {\n const seen = nextSeen(index)\n\n if (open.size > 0 || (seen !== undefined && seen < sequence)) held.push(item)\n else history.push(item)\n }\n\n let index = -1\n\n for (const item of items) {\n if (!isEntry(item)) {\n input(index, (entries[index]?.sequence ?? 0) + 0.5, item)\n\n continue\n }\n\n index += 1\n\n const { event, sequence } = item\n const at = index\n\n if (!AssistantEvent.isLibraryEvent(event)) continue\n\n Match.value(event).pipe(\n Match.tagsExhaustive({\n UserMessage: (message) =>\n input(at, sequence, userText(AssistantEvent.textWithAttachments(message.text, message.attachments))),\n BlockAnswer: (answer) => input(at, sequence, userText(answerText(answer))),\n ModelOutput: (output) => {\n history.push(...Prompt.fromResponseParts(output.parts).content)\n\n for (const part of output.parts) {\n if (part.type === \"tool-call\") {\n open.add(part.id)\n called.add(part.id)\n }\n }\n\n flushIfClosed()\n },\n ToolResult: (result) => {\n if (requests.has(result.callId)) return input(at, sequence, userText(approvedText(result)))\n\n // A view that starts after the call (since a summary, say) keeps its result as text: a tool result needs its\n // call right before it.\n if (!called.has(result.callId)) return input(at, sequence, userText(resultText(result)))\n\n history.push(toolMessage(result))\n open.delete(result.callId)\n flushIfClosed()\n },\n AssistantMessage: () => undefined,\n ToolStarted: () => undefined,\n TurnStarted: () => undefined,\n TurnCompleted: () => undefined,\n TurnFailed: () => undefined,\n SpecialistFinished: (finished) => input(at, sequence, userText(finishedText(entries, at, finished))),\n // Every run starts in a call of the model's own (a spawn or a follow-up), whose result says so.\n SpecialistStarted: () => undefined,\n BlocksClosed: () => undefined,\n // The call's result, for the provider's pairing; what the user decides comes later.\n ApprovalRequested: (request) => {\n requests.set(request.callId, request)\n\n if (!called.has(request.callId)) return input(at, sequence, userText(awaitingText(request)))\n\n history.push(awaitingMessage(request))\n open.delete(request.callId)\n flushIfClosed()\n },\n // An approved call's result says so.\n ApprovalDecision: (decision) =>\n decision.decision === \"rejected\"\n ? input(at, sequence, userText(rejectedText(decision, toolOf(decision.callId))))\n : undefined,\n ApprovalsExpired: (expired) =>\n expired.callIds.forEach((callId) => input(at, sequence, userText(expiredText(callId, toolOf(callId))))),\n ChatDeleted: () => undefined\n })\n )\n }\n\n return [...history, ...held]\n}\n\n/** @internal */\nexport const isInput = (event: { readonly _tag: string }): boolean =>\n AssistantEvent.isInput(event) || AssistantEvent.isAppInput(event)\n\n/** @internal */\nexport const handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): number => {\n const last = entries.findLast(({ event }) => AssistantEvent.isTurnEnd(event))?.event\n\n return last !== undefined && AssistantEvent.isTurnEnd(last) ? last.throughSequence : 0\n}\n\n// A run the assistant stopped isn't an input here: it wakes nothing.\n/** @internal */\nexport const unhandledInputs = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>\n): ReadonlyArray<{ readonly _tag: string }> => {\n const seen = handledThrough(entries)\n\n return entries.flatMap(({ event, sequence }) =>\n sequence > seen && isInput(event) && !(AssistantEvent.isInput(event) && !AssistantEvent.isWaking(event))\n ? [event]\n : []\n )\n}\n\n/** @internal */\nexport const needsTurn = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): boolean =>\n unhandledInputs(entries).length > 0\n\n// A failure the user was shown counts as a reply, and so does a call they're asked to approve.\n/** @internal */\nexport const owesReply = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n return (\n latest !== undefined &&\n !entries.some(\n ({ event, sequence }) =>\n sequence > latest.sequence &&\n (Predicate.isTagged(event, \"AssistantMessage\") ||\n Predicate.isTagged(event, \"TurnFailed\") ||\n Predicate.isTagged(event, \"ApprovalRequested\"))\n )\n )\n}\n\nconst sentToWaitOn = Schema.decodeUnknownOption(Schema.Struct({ wait: Schema.Literal(false) }))\n\n// Messages sent with `wait: false` are progress while the model kept working, like \"On it\".\nconst progressMessages = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlySet<string> =>\n new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"ModelOutput\")\n ? event.parts.flatMap((part) =>\n part.type === \"tool-call\" && part.name === \"send_user_message\" && Option.isSome(sentToWaitOn(part.params))\n ? [Uuid.fromKey(`message:${part.id}`)]\n : []\n )\n : []\n )\n )\n\n// The model said it was on it and stopped without the result: its last message since the user's latest input was\n// progress. An earlier message may have answered something else, such as an input that came before. A specialist still\n// working doesn't count, since its report is what comes next.\n/** @internal */\nexport const owesDelivery = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean => {\n const latest = entries.findLast(\n ({ event, sequence }) =>\n sequence <= throughSequence && AssistantEvent.isInput(event) && AssistantEvent.isUserInput(event)\n )\n\n if (latest === undefined) return false\n\n const after = entries.flatMap(({ sequence, event }) =>\n sequence > latest.sequence && AssistantEvent.isLibraryEvent(event) ? [event] : []\n )\n\n const last = after.findLast((event) => Predicate.isTagged(event, \"AssistantMessage\"))\n const progress = progressMessages(entries)\n const started = after.flatMap((event) => (Predicate.isTagged(event, \"SpecialistStarted\") ? [event.runId] : []))\n\n const finished = new Set(\n entries.flatMap(({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"SpecialistFinished\") ? [event.runId] : []\n )\n )\n\n // A call waiting for the user's approval is what comes next, like a specialist's report.\n return (\n last !== undefined &&\n last.block === undefined &&\n progress.has(last.id) &&\n !after.some((event) => Predicate.isTagged(event, \"TurnFailed\") || Predicate.isTagged(event, \"ApprovalRequested\")) &&\n started.every((runId) => finished.has(runId))\n )\n}\n\n/** @internal */\nexport const unreadAfter = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, throughSequence: number): boolean =>\n entries.some(({ event, sequence }) => sequence > throughSequence && isInput(event))\n"],"mappings":";;;;;;;;;;;;;AAaA,MAAa,YAAY,SACvB,OAAO,YAAY,EAAE,SAAS,CAAC,OAAO,SAAS,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;;AAG7D,MAAa,eAAe,WAC1B,OAAO,YAAY,EACjB,SAAS,CACP,OAAO,eAAe;CACpB,IAAI,OAAO;CACX,MAAM,OAAO;CACb,WAAW,OAAO,YAAY;CAC9B,QAAQ,OAAO;CACf,kBAAkB;AACpB,CAAC,CACH,EACF,CAAC;;AAIH,MAAa,mBAAmB,YAAuF;CACrH,MAAM,WAAW,IAAI,IACnB,QAAQ,SAAS,YACf,QAAQ,SAAS,SAAS,QAAQ,QAAQ,SAAS,SAAU,KAAK,SAAS,gBAAgB,CAAC,KAAK,EAAE,IAAI,CAAC,CAAE,IAAI,CAAC,CACjH,CACF;CAEA,OAAO,QAAQ,SAAS,YACtB,QAAQ,SAAS,cACb,QAAQ,QAAQ,SAAS,SACvB,KAAK,SAAS,eAAe,CAAC,KAAK,oBAAoB,CAAC,SAA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;;AAMF,MAAa,gBAAgB,SAAiD,oBAAqC;CACjH,MAAM,SAAS,QAAQ,UACpB,EAAE,OAAO,eACR,YAAY,mBAAmBL,UAAuB,KAAK,KAAKI,YAA2B,KAAK,CACpG;CAEA,IAAI,WAAW,KAAA,GAAW,OAAO;CAEjC,MAAM,QAAQ,QAAQ,SAAS,EAAE,UAAU,YACzC,WAAW,OAAO,YAAYN,eAA8B,KAAK,IAAI,CAAC,KAAK,IAAI,CAAC,CAClF;CAEA,MAAM,OAAO,MAAM,UAAU,UAAU,UAAU,SAAS,OAAO,kBAAkB,CAAC;CACpF,MAAM,WAAW,iBAAiB,OAAO;CACzC,MAAM,UAAU,MAAM,SAAS,UAAW,UAAU,SAAS,OAAO,mBAAmB,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAAE;CAE9G,MAAM,WAAW,IAAI,IACnB,QAAQ,SAAS,EAAE,YACjBA,eAA8B,KAAK,KAAK,UAAU,SAAS,OAAO,oBAAoB,IAAI,CAAC,MAAM,KAAK,IAAI,CAAC,CAC7G,CACF;CAGA,OACE,SAAS,KAAA,KACT,KAAK,UAAU,KAAA,KACf,SAAS,IAAI,KAAK,EAAE,KACpB,CAAC,MAAM,MAAM,UAAU,UAAU,SAAS,OAAO,YAAY,KAAK,UAAU,SAAS,OAAO,mBAAmB,CAAC,KAChH,QAAQ,OAAO,UAAU,SAAS,IAAI,KAAK,CAAC;AAEhD;;AAGA,MAAa,eAAe,SAAiD,oBAC3E,QAAQ,MAAM,EAAE,OAAO,eAAe,WAAW,mBAAmB,QAAQ,KAAK,CAAC"}
@@ -2,8 +2,8 @@ import { Status, TypingStarted, TypingStopped } from "../ChatSignal.js";
2
2
  import * as Context from "effect/Context";
3
3
  import * as Effect from "effect/Effect";
4
4
  import * as Option from "effect/Option";
5
- import * as Clock from "effect/Clock";
6
5
  import * as SynchronizedRef from "effect/SynchronizedRef";
6
+ import * as Clock from "effect/Clock";
7
7
  //#region src/internal/live.ts
8
8
  /** @internal */
9
9
  const TurnLive = Context.Reference("effect-assistant/TurnLive", { defaultValue: Option.none });
@@ -13,11 +13,11 @@ import * as Predicate from "effect/Predicate";
13
13
  import * as Schema from "effect/Schema";
14
14
  import * as Stream from "effect/Stream";
15
15
  import * as Data from "effect/Data";
16
- import * as Clock from "effect/Clock";
17
16
  import * as Model from "effect/ai/Model";
18
17
  import * as Prompt from "effect/ai/Prompt";
19
18
  import * as SchemaAST from "effect/SchemaAST";
20
19
  import * as LanguageModel from "effect/ai/LanguageModel";
20
+ import * as Clock from "effect/Clock";
21
21
  //#region src/internal/loop.ts
22
22
  /** @internal */
23
23
  const TurnApprovals = Context.Reference("effect-assistant/TurnApprovals", { defaultValue: Option.none });
@@ -4,9 +4,9 @@ import { fromEntries } from "./history.js";
4
4
  import * as Effect from "effect/Effect";
5
5
  import * as Option from "effect/Option";
6
6
  import * as Predicate from "effect/Predicate";
7
- import * as Clock from "effect/Clock";
8
7
  import * as Ref from "effect/Ref";
9
8
  import * as Duration from "effect/Duration";
9
+ import * as Clock from "effect/Clock";
10
10
  import * as Schedule from "effect/Schedule";
11
11
  //#region src/internal/summary.ts
12
12
  const MAX_LINE = 300;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "effect-assistant",
3
- "version": "0.13.2",
3
+ "version": "0.15.0",
4
4
  "description": "A colleague assistant on Effect: an append-only event log per chat, an interruptible agent loop, specialists, skills, and UI blocks",
5
5
  "license": "MIT",
6
6
  "repository": {
package/src/Assistant.ts CHANGED
@@ -17,6 +17,7 @@ import type * as Prompt from "effect/ai/Prompt"
17
17
  import type * as Tool from "effect/ai/Tool"
18
18
  import type * as Toolkit from "effect/ai/Toolkit"
19
19
  import * as Context from "effect/Context"
20
+ import type * as DateTime from "effect/DateTime"
20
21
  import * as Effect from "effect/Effect"
21
22
  import * as Filter from "effect/Filter"
22
23
  import * as Layer from "effect/Layer"
@@ -139,7 +140,7 @@ export type HistoryView<Events = never> = (
139
140
  export interface Entry<Events = never> {
140
141
  readonly chatId: ChatId
141
142
  readonly sequence: number
142
- readonly at: number
143
+ readonly at: DateTime.Utc
143
144
  readonly event: AssistantEvent.AssistantEvent | Events
144
145
  }
145
146
 
@@ -355,15 +356,18 @@ export interface Service<Events = never> {
355
356
  * `show`, none by default (see `Timeline.changes`).
356
357
  */
357
358
  readonly subscribe: {
358
- (chatId: ChatId, options?: SubscribeOptions & { readonly live?: false | undefined }): Stream.Stream<Entry<Events>>
359
+ (
360
+ chatId: ChatId,
361
+ options?: SubscribeOptions & { readonly signals?: false | undefined }
362
+ ): Stream.Stream<Entry<Events>>
359
363
  /**
360
- * With `live: true`, the stream also has the chat's signals (see `ChatSignal`): the status of
364
+ * With `signals: true`, the stream also has the chat's signals (see `ChatSignal`): the status of
361
365
  * what a turn is doing, and whether a message to the user is on its way. They come in order
362
366
  * with the entries, only while the stream runs, and are never stored.
363
367
  */
364
368
  (
365
369
  chatId: ChatId,
366
- options: SubscribeOptions & { readonly live: true }
370
+ options: SubscribeOptions & { readonly signals: true }
367
371
  ): Stream.Stream<Entry<Events> | ChatSignal.ChatSignal>
368
372
  }
369
373
  /**
@@ -505,7 +509,7 @@ function entrySchema(events: ReadonlyArray<AssistantEvent.AppEventSchema>): Sche
505
509
  Schema.Struct({
506
510
  chatId: ChatId,
507
511
  sequence: Schema.Int,
508
- at: Schema.Finite,
512
+ at: Schema.DateTimeUtcFromMillis,
509
513
  event: Schema.Union([AssistantEvent.AssistantEvent, ...events])
510
514
  })
511
515
  )
@@ -605,18 +609,18 @@ export const make = <
605
609
 
606
610
  function subscribe(
607
611
  chatId: ChatId,
608
- options?: SubscribeOptions & { readonly live?: false | undefined }
612
+ options?: SubscribeOptions & { readonly signals?: false | undefined }
609
613
  ): Stream.Stream<Entry<OwnEvents>>
610
614
  function subscribe(
611
615
  chatId: ChatId,
612
- options: SubscribeOptions & { readonly live: true }
616
+ options: SubscribeOptions & { readonly signals: true }
613
617
  ): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal>
614
618
  function subscribe(
615
619
  chatId: ChatId,
616
- options?: SubscribeOptions & { readonly live?: boolean | undefined }
620
+ options?: SubscribeOptions & { readonly signals?: boolean | undefined }
617
621
  ): Stream.Stream<Entry<OwnEvents> | ChatSignal.ChatSignal> {
618
622
  return engine
619
- .subscribe(name, chatId, options?.after ?? 0, options?.live === true)
623
+ .subscribe(name, chatId, options?.after ?? 0, options?.signals === true)
620
624
  .pipe(Stream.filterMap(Filter.fromPredicateOption(decode)))
621
625
  }
622
626