effect-assistant 0.13.0 → 0.13.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/Timeline.d.ts +4 -0
- package/dist/Timeline.d.ts.map +1 -1
- package/dist/Timeline.js +11 -1
- package/dist/Timeline.js.map +1 -1
- package/dist/ToolStatus.d.ts +3 -2
- package/dist/ToolStatus.d.ts.map +1 -1
- package/dist/ToolStatus.js +3 -2
- package/dist/ToolStatus.js.map +1 -1
- package/dist/internal/loop.d.ts.map +1 -1
- package/dist/internal/loop.js +1 -1
- package/dist/internal/loop.js.map +1 -1
- package/dist/internal/summary.js +2 -1
- package/dist/internal/summary.js.map +1 -1
- package/package.json +1 -1
- package/src/Timeline.ts +13 -1
- package/src/ToolStatus.ts +4 -3
- package/src/internal/loop.ts +2 -3
- package/src/internal/summary.ts +5 -1
package/dist/Timeline.d.ts
CHANGED
|
@@ -35,6 +35,8 @@ export declare const Block: Schema.Struct<{
|
|
|
35
35
|
readonly props: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
36
36
|
readonly status: Schema.Literals<readonly ["open", "answered", "closed"]>;
|
|
37
37
|
readonly answer: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
38
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
39
|
+
readonly answeredAt: Schema.optional<Schema.Finite>;
|
|
38
40
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
39
41
|
readonly result: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
40
42
|
}>;
|
|
@@ -85,6 +87,8 @@ export declare const AssistantMessage: Schema.TaggedStruct<"AssistantMessage", {
|
|
|
85
87
|
readonly props: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
86
88
|
readonly status: Schema.Literals<readonly ["open", "answered", "closed"]>;
|
|
87
89
|
readonly answer: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
90
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
91
|
+
readonly answeredAt: Schema.optional<Schema.Finite>;
|
|
88
92
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
89
93
|
readonly result: Schema.optional<Schema.Codec<Schema.Json, Schema.Json, never, never>>;
|
|
90
94
|
}>>;
|
package/dist/Timeline.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Timeline.d.ts","names":[],"sources":["../src/Timeline.ts"],"mappings":";;;;;;;;;;;;;;;;qBA6Ca,aAAW,OAAA;;;;;;;YAQZ,qBAAqB,YAAY;;;;;;;;;qBAUhC,OAAK,OAAA
|
|
1
|
+
{"version":3,"file":"Timeline.d.ts","names":[],"sources":["../src/Timeline.ts"],"mappings":";;;;;;;;;;;;;;;;qBA6Ca,aAAW,OAAA;;;;;;;YAQZ,qBAAqB,YAAY;;;;;;;;;qBAUhC,OAAK,OAAA;;;;;;;;;;;;;;;;YAiBN,eAAe,MAAM;;;;;;;;qBASpB,aAAW,OAAA;;;;;;;;;;;;;;;;;YAaZ,qBAAqB,YAAY;;;;;;;qBAQhC,kBAAgB,OAAA;;;;;;;;;;;;;;;;;;;;;YAajB,0BAA0B,iBAAiB;;;;;;;;;;;;;;;;YAiB3C,UAAU,KAAK;WAAqB,YAAY;;WAC7C,MAAM;WAAc;WAAqB;WAAqB,OAAO;;;;;;;;;;;;;;;;;;qBAmBvE,cAAY,OAAA;;;;;;;;;;;;;;;YAgBb,sBAAsB,aAAa;;;;;;;;;;;;;;;;;;;;;;;;;;YA2BnC,KAAK,kBAAkB,cAAc,mBAAmB,UAAU,UAAU;;;;;;;;qBAS3E,mBAAiB,OAAA;;;;;;;;;;YAWlB,2BAA2B,kBAAkB;;;;;;;;;;;;;;;;qBAiB5C,UAAQ,OAAA;;;;;;;;;;;;;;;YAaT,kBAAkB,SAAS;;;;;;;;;iBAUtB,SAAS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Ae,SACvB,GAAG,GACL,SAAS,OAAO,OAAO,WAA0B,YAAuB,GAAG,OACxE,OAAO,OAAO,OAAO,uBAAuB,GAAG;GACnD,GAAG,GAAG,cAAc,aAAa,MAAM,uBACtC,SAAS,OAAO,OAAO,WAA0B,YAAuB,GAAG,IAC3E,YAAY,WAAW,SACvB,UAAU,eAAe,QACxB,OAAO,OAAO,OAAO,uBAAuB,GAAG"}
|
package/dist/Timeline.js
CHANGED
|
@@ -78,6 +78,8 @@ const Block = Schema.Struct({
|
|
|
78
78
|
props: Schema.Json,
|
|
79
79
|
status: BlockStatus,
|
|
80
80
|
answer: Schema.optional(Schema.Json),
|
|
81
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
82
|
+
answeredAt: Schema.optional(Schema.Finite),
|
|
81
83
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
82
84
|
result: Schema.optional(Schema.Json)
|
|
83
85
|
});
|
|
@@ -424,6 +426,7 @@ const folding = (show) => {
|
|
|
424
426
|
let activity = empty$1;
|
|
425
427
|
let live = noLive;
|
|
426
428
|
let blocks = /* @__PURE__ */ new Map();
|
|
429
|
+
const answeredAt = /* @__PURE__ */ new Map();
|
|
427
430
|
const items = /* @__PURE__ */ new Map();
|
|
428
431
|
const sent = /* @__PURE__ */ new Map();
|
|
429
432
|
const results = /* @__PURE__ */ new Map();
|
|
@@ -442,10 +445,16 @@ const folding = (show) => {
|
|
|
442
445
|
...block,
|
|
443
446
|
result
|
|
444
447
|
};
|
|
445
|
-
|
|
448
|
+
if (state?.answer === void 0) return shown;
|
|
449
|
+
const answered = {
|
|
446
450
|
...shown,
|
|
447
451
|
answer: toJson(state.answer.value)
|
|
448
452
|
};
|
|
453
|
+
const at = answeredAt.get(message.id);
|
|
454
|
+
return at === void 0 ? answered : {
|
|
455
|
+
...answered,
|
|
456
|
+
answeredAt: at
|
|
457
|
+
};
|
|
449
458
|
};
|
|
450
459
|
const itemOf = (message, at) => {
|
|
451
460
|
const block = blockOf(message);
|
|
@@ -585,6 +594,7 @@ const folding = (show) => {
|
|
|
585
594
|
});
|
|
586
595
|
}
|
|
587
596
|
blocks = apply$2(blocks, event);
|
|
597
|
+
if (Predicate.isTagged(event, "BlockAnswer") && blocks.get(event.messageId)?.answer === event) answeredAt.set(event.messageId, entry.at);
|
|
588
598
|
const decidedBefore = approvals;
|
|
589
599
|
approvals = apply$1(approvals, entry);
|
|
590
600
|
const all = [...[...new Set(touched(event, entry.at))].flatMap((id) => {
|
package/dist/Timeline.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Timeline.js","names":["AssistantEvent.Attachment","AssistantEvent.ToolOutcome","AppEvents.tagOf","AssistantActivity.empty","AppEvents.decodeWith","AssistantActivity.apply","AssistantEvent.isLibraryEvent","BlockKit.apply","ToolApproval.apply","ChatSignal.isChatSignal"],"sources":["../src/Timeline.ts"],"sourcesContent":["/**\n * This module provides a chat's timeline: the chat as its user sees it. A chat client receives the\n * timeline and nothing else.\n *\n * A {@link Timeline} holds the chat's items: the messages with their blocks, the app's own events\n * it shows (each typed with its event, see {@link EventItem}), and the tool calls waiting for the\n * user's approval ({@link ApprovalItem}). It also holds the chat's\n * {@link Activity}, and whether the last turn failed or the chat was deleted. It never contains the\n * model's output, tool calls or results, what the model read, or why a turn failed. The server\n * streams {@link Change}s by piping the assistant's `subscribe` through {@link changes}, and the\n * client folds them with {@link fold} (or {@link apply}, from {@link empty}). On the server,\n * {@link fromEntries} builds a whole timeline from a chat's log, and {@link snapshot} the whole\n * timeline as one change.\n *\n * **Only the app events in `show` reach the timeline**, and none by default: an event that is only\n * for the assistant, like a summary of the chat, stays out. The RPC's schema, `Change([...])`,\n * names the same events and types the client's timeline with them.\n *\n * @since 0.3.0\n */\nimport { dual } from \"effect/Function\"\nimport * as Match from \"effect/Match\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaTransformation from \"effect/SchemaTransformation\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Assistant from \"./Assistant.ts\"\nimport * as AssistantActivity from \"./AssistantActivity.ts\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport * as BlockKit from \"./BlockKit.ts\"\nimport * as ChatSignal from \"./ChatSignal.ts\"\nimport { InputId } from \"./InputId.ts\"\nimport * as AppEvents from \"./internal/events.ts\"\nimport * as ToolApproval from \"./ToolApproval.ts\"\nimport { toJson } from \"./internal/schema.ts\"\n\n/**\n * Schema for the status of a block. A block is `\"open\"` while it accepts an answer, `\"answered\"`\n * once the user has used it, and `\"closed\"` when it closed without an answer because the user\n * answered in words or moved on.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const BlockStatus = Schema.Literals([\"open\", \"answered\", \"closed\"])\n\n/**\n * The status of a block.\n *\n * @category models\n * @since 0.1.0\n */\nexport type BlockStatus = typeof BlockStatus.Type\n\n/**\n * Schema for a block on an assistant's message. It holds the block's kind, its props (JSON, as\n * the block's props schema encodes them), its status, and the user's answer (JSON, as the block's\n * answer schema encodes it).\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Block = Schema.Struct({\n kind: Schema.String,\n props: Schema.Json,\n status: BlockStatus,\n answer: Schema.optional(Schema.Json),\n /** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */\n result: Schema.optional(Schema.Json)\n})\n\n/**\n * Represents a block on an assistant's message.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Block = typeof Block.Type\n\n/**\n * Schema for a message the user sent. `at` is when it was stored, in epoch\n * milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const UserMessage = Schema.TaggedStruct(\"UserMessage\", {\n id: InputId,\n text: Schema.String,\n attachments: Schema.optional(Schema.Array(AssistantEvent.Attachment)),\n at: Schema.Finite\n})\n\n/**\n * Represents a message the user sent.\n *\n * @category models\n * @since 0.1.0\n */\nexport type UserMessage = typeof UserMessage.Type\n\n/**\n * Schema for a message the assistant sent the user, including its block if it has one.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AssistantMessage = Schema.TaggedStruct(\"AssistantMessage\", {\n id: Schema.String,\n text: Schema.String,\n at: Schema.Finite,\n block: Schema.optional(Block)\n})\n\n/**\n * Represents a message the assistant sent the user.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AssistantMessage = typeof AssistantMessage.Type\n\n/**\n * Represents one of the app's own events in the timeline: an item between the messages, in the\n * order the chat stored it.\n *\n * **Details**\n *\n * The item's `_tag` is the event's, so a match over a timeline's items takes a handler per event\n * beside `UserMessage` and `AssistantMessage`. The event, decoded with its schema, is in `event`,\n * and the item's own fields sit beside it rather than spread into it: an event may have an `id` or\n * an `at` of its own, and a class instance keeps its prototype. `id` is fixed per entry of the\n * chat's log, and `at` is when the event was stored, in epoch milliseconds.\n *\n * @category models\n * @since 0.3.0\n */\nexport type EventItem<E> = E extends { readonly _tag: infer Tag extends string }\n ? { readonly _tag: Tag; readonly id: string; readonly at: number; readonly event: E }\n : never\n\n/**\n * Schema for a tool call that waits, or waited, for the user's approval, as an item on the\n * timeline.\n *\n * **Details**\n *\n * It is only the yes or no: the assistant's own message tells the user what it asks them to\n * approve, so the item carries no params. `id` is the call's id, which the decision is for (see\n * `ToolApproval.approve`), and `tool` the tool's name, for a label. `status` is where the call stands\n * (`ToolApproval.Status`); `reason` is the user's, when they rejected it with one; `outcome` is how\n * the approved call went, once it ran. `at` is when the call started waiting, in epoch\n * milliseconds. A change updates the item in place as the call is decided and run.\n *\n * @category schemas\n * @since 0.4.0\n */\nexport const ApprovalItem = Schema.TaggedStruct(\"ToolApproval\", {\n id: Schema.String,\n tool: Schema.String,\n status: Schema.Literals([\"pending\", \"approved\", \"rejected\", \"expired\"]),\n reason: Schema.optional(Schema.String),\n outcome: Schema.optional(AssistantEvent.ToolOutcome),\n at: Schema.Finite\n})\n\n/**\n * Represents a tool call that waits, or waited, for the user's approval, as an item on the\n * timeline.\n *\n * @category models\n * @since 0.4.0\n */\nexport type ApprovalItem = typeof ApprovalItem.Type\n\n/**\n * Represents an item in the chat's timeline: a message the user or the assistant sent, one of the\n * app's own events it shows (see {@link EventItem}), or a tool call waiting for the user's approval\n * (see {@link ApprovalItem}).\n *\n * **Example** (Showing each item of a chat)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n * import * as Match from \"effect/Match\"\n * import * as Schema from \"effect/Schema\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const line = (item: Timeline.Item<DailyBudgetReached>) =>\n * Match.valueTags(item, {\n * UserMessage: (sent) => `You: ${sent.text}`,\n * AssistantMessage: (sent) => `Assistant: ${sent.text}`,\n * DailyBudgetReached: () => \"You've reached today's budget.\"\n * })\n * ```\n *\n * @category models\n * @since 0.3.0\n */\nexport type Item<Events = never> = UserMessage | AssistantMessage | EventItem<Events> | ApprovalItem\n\n/**\n * Schema for a specialist that is working for the assistant. It holds the specialist's name and\n * when it started, in epoch milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const SpecialistWorking = Schema.Struct({\n specialist: Schema.String,\n since: Schema.Finite\n})\n\n/**\n * Represents a specialist that is working for the assistant.\n *\n * @category models\n * @since 0.1.0\n */\nexport type SpecialistWorking = typeof SpecialistWorking.Type\n\n/**\n * Schema for what is working in the chat.\n *\n * `working` is true while the assistant runs a turn, or when a turn is about to start for\n * something that arrived. `specialists` lists the specialists that are working. When the chat is\n * idle, nothing is working, even if a workflow is waiting on a timer or on the user.\n *\n * On a live subscription (`subscribe(chatId, { live: true })`), `status` is a short line about what\n * the running turn is doing, and `typing` is true while the model writes a message to the user. Both\n * come from the chat's signals (see `ChatSignal`): they go when the turn ends, and a timeline\n * folded from the log alone has neither.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Activity = Schema.Struct({\n working: Schema.Boolean,\n specialists: Schema.Array(SpecialistWorking),\n status: Schema.optional(Schema.String),\n typing: Schema.Boolean\n})\n\n/**\n * Represents what is working in the chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Activity = typeof Activity.Type\n\n/**\n * Represents a chat's timeline: the chat as its user sees it, typed with the app's events it shows.\n * It holds the chat's items in order, what is working in it, whether the last turn failed, and\n * whether the chat was deleted. `sequence` is the position in the chat's log that the timeline is up to.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface Timeline<Events = never> {\n readonly sequence: number\n readonly items: ReadonlyArray<Item<Events>>\n readonly activity: Activity\n /** Whether the last turn failed with no message after it. */\n readonly failed: boolean\n /** Whether the chat was deleted. A deleted chat accepts nothing more, and its stream ends. */\n readonly deleted: boolean\n}\n\n/**\n * Represents a change to a chat's timeline, typed with the app's events it shows.\n *\n * **Details**\n *\n * A change holds each item that is new or changed (for example, a message whose block was\n * answered or closed, or a call the user approved), in full. It also holds the current activity, whether the last turn failed,\n * and whether the chat was deleted. `sequence` is the position in the chat's log that the change is up\n * to.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface Change<Events = never> {\n readonly sequence: number\n readonly items: ReadonlyArray<Item<Events>>\n readonly activity: Activity\n readonly failed: boolean\n readonly deleted: boolean\n}\n\nconst eventItem = (schema: AssistantEvent.AppEventSchema) =>\n Schema.Struct({ _tag: Schema.Literal(AppEvents.tagOf(schema)), id: Schema.String, at: Schema.Finite, event: schema })\n\nfunction makeChange<const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(\n events?: Events\n): Schema.Codec<Change<Events[number][\"Type\"]>, Schema.Json>\n// The overload states the decoded type: an item per given schema, each typed with its own event.\nfunction makeChange(events: ReadonlyArray<AssistantEvent.AppEventSchema> = []): Schema.Top {\n const AnyItem = Schema.toCodecJson(\n Schema.Union([UserMessage, AssistantMessage, ApprovalItem, ...events.map(eventItem)])\n )\n\n const decodeItem = Schema.decodeUnknownOption(AnyItem)\n const encodeItem = Schema.encodeUnknownSync(AnyItem)\n\n return Schema.Struct({\n sequence: Schema.Int,\n // An item for an event this schema doesn't name, or that doesn't decode (from a newer server, say), is left out\n // rather than failing the whole change.\n items: Schema.Array(Schema.Json).pipe(\n Schema.decodeTo(\n Schema.Array(Schema.toType(AnyItem)),\n SchemaTransformation.transform<ReadonlyArray<typeof AnyItem.Type>, ReadonlyArray<Schema.Json>>({\n decode: (json) => json.flatMap((item) => Option.toArray(decodeItem(item))),\n encode: (items) => items.map((item) => encodeItem(item))\n })\n )\n ),\n activity: Activity,\n failed: Schema.Boolean,\n deleted: Schema.Boolean\n })\n}\n\n/**\n * Creates the schema for the changes to a chat's timeline, with items for the given app events,\n * in JSON.\n *\n * **Details**\n *\n * It is the success schema of the RPC that streams a chat's timeline: name the events the chat's\n * users see, the same ones the handler passes to {@link changes} as `show`. Tool calls waiting for\n * approval are always in it, as {@link ApprovalItem}s. Each item decodes its\n * event with that event's schema, so the client gets `Change<Events>` typed with them and folds it\n * with {@link fold}, no definition needed. `Change()` carries no app events.\n *\n * A handler whose changes show an event the schema doesn't name doesn't compile.\n *\n * **Example** (An RPC that streams a chat's timeline, with the budget notice)\n *\n * ```ts\n * import { ChatId, Timeline } from \"effect-assistant\"\n * import * as Rpc from \"effect/rpc/Rpc\"\n * import * as Schema from \"effect/Schema\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const Subscribe = Rpc.make(\"Subscribe\", {\n * payload: { chatId: ChatId.ChatId },\n * success: Timeline.Change([DailyBudgetReached]),\n * stream: true\n * })\n * ```\n *\n * @category schemas\n * @since 0.3.0\n */\nexport const Change: <const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(\n events?: Events\n) => Schema.Codec<Change<Events[number][\"Type\"]>, Schema.Json> = makeChange\n\n/**\n * The timeline of a chat before anything has happened in it, with no items and nothing working.\n * Use it as the starting point when folding changes with {@link apply}.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const empty: Timeline = {\n sequence: 0,\n items: [],\n activity: { working: false, specialists: [], typing: false },\n failed: false,\n deleted: false\n}\n\n/**\n * Returns the timeline after a change.\n *\n * **Details**\n *\n * Each item in the change replaces the item with the same id, in place, and new items are added\n * after the rest. The change's activity, `failed`, and `deleted` replace the timeline's. Applying a\n * change twice changes nothing, so a client that resubscribes from the start can fold again and get\n * the same timeline.\n *\n * The timeline is typed with the change's events, as its RPC's schema decoded them (see\n * {@link Change}). To fold a stream of changes, use {@link fold}: in\n * `Stream.scan(() => Timeline.empty, Timeline.apply)`, TypeScript fixes the state's type from\n * `empty` before it sees the changes' events, so that form needs the timeline's type written out.\n *\n * **Example** (Folding changes into your own state)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n *\n * interface State<Events> {\n * readonly timeline: Timeline.Timeline<Events>\n * readonly unread: number\n * }\n *\n * const next = <Events>(state: State<Events>, change: Timeline.Change<Events>): State<Events> => ({\n * timeline: Timeline.apply(state.timeline, change),\n * unread: state.unread + change.items.length\n * })\n * ```\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const apply = <Events>(timeline: Timeline<Events>, change: Change<Events>): Timeline<Events> => {\n const changed = new Map(change.items.map((item) => [item.id, item]))\n const known = new Set(timeline.items.map((item) => item.id))\n\n return {\n sequence: Math.max(timeline.sequence, change.sequence),\n items: [\n ...timeline.items.map((item) => changed.get(item.id) ?? item),\n ...change.items.filter((item) => !known.has(item.id))\n ],\n activity: change.activity,\n failed: change.failed,\n deleted: change.deleted\n }\n}\n\n/**\n * Returns the timelines a stream of changes folds to, from {@link empty}, typed with the changes'\n * events.\n *\n * **Example** (A chat's timeline on the client)\n *\n * ```ts\n * import { Timeline } from \"effect-assistant\"\n * import * as Schema from \"effect/Schema\"\n * import * as Stream from \"effect/Stream\"\n *\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * // The stream of an RPC whose success schema is `Timeline.Change([DailyBudgetReached])`.\n * declare const changes: Stream.Stream<Timeline.Change<DailyBudgetReached>>\n *\n * const timelines = changes.pipe(Timeline.fold) // Stream<Timeline.Timeline<DailyBudgetReached>>\n * ```\n *\n * @category combinators\n * @since 0.3.0\n */\nexport const fold = <Events, E, R>(\n changes: Stream.Stream<Change<Events>, E, R>\n): Stream.Stream<Timeline<Events>, E, R> => changes.pipe(Stream.scan((): Timeline<Events> => empty, apply))\n\n/**\n * Returns whether nothing is working in the chat: no turn is running or about to start, and no\n * specialist is working.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isIdle = <Events>(timeline: Timeline<Events>): boolean =>\n !timeline.activity.working && timeline.activity.specialists.length === 0\n\ninterface AnyEventItem {\n readonly _tag: string\n readonly id: string\n readonly at: number\n readonly event: { readonly _tag: string }\n}\n\ntype AnyItem = UserMessage | AssistantMessage | AnyEventItem | ApprovalItem\n\n// What the fold below builds: the overloads that use it type its items with the events shown.\ninterface AnyChange {\n readonly sequence: number\n readonly items: ReadonlyArray<AnyItem>\n readonly activity: Activity\n readonly failed: boolean\n readonly deleted: boolean\n}\n\n/**\n * Represents the options for building a chat's timeline from its log.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface ShowOptions<Show extends ReadonlyArray<AssistantEvent.AppEventSchema>> {\n /**\n * The schemas of the app's events the chat's users see. Each becomes an item in the timeline;\n * the app's other events are left out. Defaults to none.\n */\n readonly show?: Show | undefined\n}\n\n/**\n * Represents the schemas an assistant's timeline may show: some of its own events.\n *\n * @category utility types\n * @since 0.3.0\n */\nexport type Shown<Events> = ReadonlyArray<AssistantEvent.AppEventSchema & { readonly Type: Events }>\n\nfunction snapshotWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change\nfunction snapshotWith<Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n): Change<Show[number][\"Type\"]>\nfunction snapshotWith(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n _definition?: Schemas,\n options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): AnyChange {\n const timeline = folding(options?.show ?? [])\n\n for (const entry of entries) timeline.step(entry)\n\n return timeline.snapshot\n}\n\n/**\n * Returns a chat's whole timeline as one change, built from the entries of its log.\n *\n * **When to use**\n *\n * Use it on the server for an RPC that returns a whole chat at once: its success schema is\n * {@link Change} with the same events as `show`, and the client applies it to {@link empty}.\n *\n * **Details**\n *\n * Only the app's events in `show` become items; without it, the timeline has none.\n *\n * @category constructors\n * @since 0.3.0\n */\nexport const snapshot: {\n (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change\n <Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n ): Change<Show[number][\"Type\"]>\n} = snapshotWith\n\nfunction fromEntriesWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline\nfunction fromEntriesWith<Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n): Timeline<Show[number][\"Type\"]>\nfunction fromEntriesWith(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n _definition?: Schemas,\n options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): AnyChange {\n const timeline = folding(options?.show ?? [])\n\n for (const entry of entries) timeline.step(entry)\n\n return timeline.snapshot\n}\n\n/**\n * Returns a chat's timeline, built from the entries of its log.\n *\n * **When to use**\n *\n * Use it in server-side code that reads a whole chat. A client gets the timeline as a stream from\n * {@link changes} instead, and an RPC that returns a whole chat sends a {@link snapshot}.\n *\n * **Details**\n *\n * Only the app's events in `show` become items, typed with their schemas; without it, the timeline\n * has none.\n *\n * **Example** (Building a chat's timeline from its log)\n *\n * ```ts\n * import { type ChatId, ChatLog, Timeline } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * const timelineOf = (chatId: ChatId.ChatId) =>\n * ChatLog.ChatLog.use((log) => log.read(chatId)).pipe(\n * Effect.map((entries) => Timeline.fromEntries(entries))\n * )\n * ```\n *\n * @see {@link changes} for a stream of changes instead of a whole timeline\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const fromEntries: {\n (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline\n <Events, const Show extends Shown<Events> = readonly []>(\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n definition: Definition<Events>,\n options?: ShowOptions<Show>\n ): Timeline<Show[number][\"Type\"]>\n} = fromEntriesWith\n\ninterface Schemas {\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n}\n\ninterface Folding {\n readonly step: (entry: AssistantEvent.AnyEntry) => AnyChange | undefined\n readonly signal: (signal: ChatSignal.ChatSignal) => AnyChange | undefined\n readonly snapshot: AnyChange\n}\n\ninterface LiveState {\n readonly status: string | undefined\n readonly typing: boolean\n}\n\nconst noLive: LiveState = { status: undefined, typing: false }\n\nconst applySignal = (live: LiveState, signal: ChatSignal.ChatSignal): LiveState =>\n Match.value(signal).pipe(\n Match.tagsExhaustive({\n Status: ({ text }): LiveState => ({ ...live, status: text }),\n TypingStarted: (): LiveState => ({ status: undefined, typing: true }),\n TypingStopped: (): LiveState => ({ ...live, typing: false })\n })\n )\n\nconst activityOf = (activity: AssistantActivity.State, live: LiveState): Activity => {\n const { status } = live\n\n const shown: Activity = {\n working: activity.turnSince !== undefined || activity.queued,\n specialists: [...activity.specialists.values()].map((run) => ({\n specialist: run.specialist,\n since: run.since\n })),\n typing: live.typing\n }\n\n return status === undefined ? shown : { ...shown, status }\n}\n\nconst sameActivity = (a: Activity, b: Activity) =>\n a.working === b.working &&\n a.status === b.status &&\n a.typing === b.typing &&\n a.specialists.length === b.specialists.length &&\n a.specialists.every((run, i) => {\n const other = b.specialists[i]\n\n return other !== undefined && run.specialist === other.specialist && run.since === other.since\n })\n\nconst folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding => {\n const shown = new Map(show.map((schema) => [AppEvents.tagOf(schema), schema]))\n let approvals: ReadonlyMap<string, ToolApproval.State> = new Map()\n let sequence = 0\n let failed = false\n let deleted = false\n let activity = AssistantActivity.empty\n let live = noLive\n let blocks: ReadonlyMap<string, BlockKit.State> = new Map()\n // The items in order, and the assistant's messages as stored: their blocks change as the chat goes on.\n const items = new Map<string, AnyItem>()\n const sent = new Map<string, AssistantEvent.AssistantMessage>()\n // The results a block can show, by id: a message shows one stored before it.\n const results = new Map<string, Schema.Json>()\n\n const blockOf = (message: AssistantEvent.AssistantMessage): Block | undefined => {\n if (message.block === undefined) return undefined\n\n const state = blocks.get(message.id)\n const status = state === undefined || state.open ? \"open\" : state.answer === undefined ? \"closed\" : \"answered\"\n const block: Block = { kind: message.block.kind, props: toJson(message.block.props), status }\n const { resultId } = message.block\n const result = resultId === undefined ? undefined : results.get(resultId)\n const shown = result === undefined ? block : { ...block, result }\n\n return state?.answer === undefined ? shown : { ...shown, answer: toJson(state.answer.value) }\n }\n\n const itemOf = (message: AssistantEvent.AssistantMessage, at: number): AssistantMessage => {\n const block = blockOf(message)\n\n return block === undefined\n ? AssistantMessage.make({ id: message.id, text: message.text, at })\n : AssistantMessage.make({ id: message.id, text: message.text, at, block })\n }\n\n const touched = (event: AssistantEvent.AssistantEvent, at: number): ReadonlyArray<string> =>\n Match.value(event).pipe(\n Match.tagsExhaustive({\n UserMessage: (message) => {\n items.set(\n message.id,\n message.attachments === undefined\n ? UserMessage.make({ id: message.id, text: message.text, at })\n : UserMessage.make({\n id: message.id,\n text: message.text,\n attachments: message.attachments,\n at\n })\n )\n failed = false\n\n return [message.id]\n },\n AssistantMessage: (message) => {\n sent.set(message.id, message)\n items.set(message.id, itemOf(message, at))\n failed = false\n\n return [message.id, ...(message.closes ?? [])]\n },\n BlockAnswer: (answer) => {\n failed = false\n\n return [answer.messageId]\n },\n BlocksClosed: (closed) => closed.messageIds,\n ApprovalRequested: () => [],\n ApprovalDecision: () => {\n failed = false\n\n return []\n },\n ApprovalsExpired: () => [],\n TurnFailed: () => {\n failed = true\n\n return []\n },\n ModelOutput: () => [],\n ToolStarted: () => [],\n ToolResult: (result) => {\n if (result.resultId !== undefined && result.outcome === \"success\") {\n results.set(result.resultId, result.full ?? result.result)\n }\n\n return []\n },\n TurnStarted: () => [],\n TurnCompleted: () => [],\n SpecialistStarted: () => [],\n SpecialistFinished: () => [],\n ChatDeleted: () => {\n deleted = true\n\n return []\n }\n })\n )\n\n // Decoded as `subscribe` streams it, or as the log stores it; one that doesn't decode is left out.\n const eventItemOf = (entry: AssistantEvent.AnyEntry): Option.Option<AnyEventItem> => {\n const schema = shown.get(entry.event._tag)\n\n if (schema === undefined) return Option.none()\n\n const event = Schema.is(schema)(entry.event) ? Option.some(entry.event) : AppEvents.decodeWith(schema, entry.event)\n\n return Option.map(event, (decoded) => ({\n _tag: decoded._tag,\n id: `app-event:${entry.sequence}`,\n at: entry.at,\n event: decoded\n }))\n }\n\n const callsOf = (event: AssistantEvent.AssistantEvent): ReadonlyArray<string> =>\n Predicate.isTagged(event, \"ApprovalsExpired\")\n ? event.callIds\n : Predicate.isTagged(event, \"ApprovalRequested\") ||\n Predicate.isTagged(event, \"ApprovalDecision\") ||\n Predicate.isTagged(event, \"ToolResult\")\n ? [event.callId]\n : []\n\n // The items of the calls this entry changed.\n const approvalItems = (event: AssistantEvent.AssistantEvent, before: ReadonlyMap<string, ToolApproval.State>) =>\n callsOf(event).flatMap((callId) => {\n const state = approvals.get(callId)\n\n if (state === undefined || state === before.get(callId)) return []\n\n const item = ApprovalItem.make({\n id: callId,\n tool: state.request.tool,\n status: state.status,\n reason: state.reason,\n outcome: state.outcome,\n at: state.at\n })\n\n items.set(callId, item)\n\n return [item]\n })\n\n // A turn's end clears what it showed, also when a signal didn't arrive.\n const settle = (event: { readonly _tag: string }) => {\n if (\n Predicate.isTagged(event, \"TurnCompleted\") ||\n Predicate.isTagged(event, \"TurnFailed\") ||\n Predicate.isTagged(event, \"ChatDeleted\")\n ) {\n live = noLive\n }\n }\n\n const signal = (received: ChatSignal.ChatSignal): AnyChange | undefined => {\n const previous = activityOf(activity, live)\n\n live = applySignal(live, received)\n\n const now = activityOf(activity, live)\n\n return sameActivity(previous, now) ? undefined : { sequence, items: [], activity: now, failed, deleted }\n }\n\n const step = (entry: AssistantEvent.AnyEntry): AnyChange | undefined => {\n const previous = { activity: activityOf(activity, live), failed, deleted }\n const { event } = entry\n\n sequence = entry.sequence\n activity = AssistantActivity.apply(activity, entry)\n settle(event)\n\n if (!AssistantEvent.isLibraryEvent(event)) {\n const now = activityOf(activity, live)\n\n return Option.match(eventItemOf(entry), {\n onNone: () =>\n sameActivity(previous.activity, now) ? undefined : { sequence, items: [], activity: now, failed, deleted },\n onSome: (item) => {\n items.set(item.id, item)\n\n return { sequence, items: [item], activity: now, failed, deleted }\n }\n })\n }\n\n blocks = BlockKit.apply(blocks, event)\n\n const decidedBefore = approvals\n approvals = ToolApproval.apply(approvals, entry)\n\n const changed = [...new Set(touched(event, entry.at))].flatMap((id) => {\n const message = sent.get(id)\n const current = items.get(id)\n\n if (message === undefined || current === undefined) return current === undefined ? [] : [current]\n\n const next = itemOf(message, current.at)\n items.set(id, next)\n\n return [next]\n })\n\n const all = [...changed, ...approvalItems(event, decidedBefore)]\n const now = activityOf(activity, live)\n\n return all.length === 0 &&\n failed === previous.failed &&\n deleted === previous.deleted &&\n sameActivity(previous.activity, now)\n ? undefined\n : { sequence, items: all, activity: now, failed, deleted }\n }\n\n return {\n step,\n signal,\n get snapshot() {\n return { sequence, items: [...items.values()], activity: activityOf(activity, live), failed, deleted }\n }\n }\n}\n\nconst merge = (changes: ReadonlyArray<AnyChange>): AnyChange | undefined => {\n const last = changes.at(-1)\n\n if (last === undefined) return undefined\n\n const items = new Map<string, AnyItem>()\n\n for (const change of changes) for (const item of change.items) items.set(item.id, item)\n\n return {\n sequence: last.sequence,\n items: [...items.values()],\n activity: last.activity,\n failed: last.failed,\n deleted: last.deleted\n }\n}\n\n/**\n * Represents an assistant's definition as the timeline reads it. An assistant made with\n * `Assistant.make` fits it.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Definition<Events = never> {\n /** The schemas of the assistant's events. */\n readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>\n /** The schema of the chat's entries, typed with the assistant's events: it types `show`. */\n readonly Entry: Schema.Codec<Assistant.Entry<Events>, Schema.Json>\n}\n\n/**\n * Represents the options accepted by {@link changes}.\n *\n * @category models\n * @since 0.3.0\n */\nexport interface ChangesOptions<\n Show extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []\n> extends ShowOptions<Show> {\n /**\n * The `sequence` up to which the client already has the timeline. The result contains only the\n * changes after it. Defaults to `0`, every change.\n */\n readonly after?: number | undefined\n}\n\nfunction changesWith<E, R, Events, const Show extends Shown<Events> = readonly []>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n): Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\nfunction changesWith<E, R>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n _definition: Schemas,\n options?: ChangesOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>\n): Stream.Stream<AnyChange, E, R> {\n const after = options?.after ?? 0\n\n return entries.pipe(\n Stream.mapAccumArray(\n () => folding(options?.show ?? []),\n (timeline, chunk) => {\n const changed = chunk.flatMap((item) => {\n if (ChatSignal.isChatSignal(item)) return Option.toArray(Option.fromUndefinedOr(timeline.signal(item)))\n\n const change = timeline.step(item)\n\n return change === undefined || item.sequence <= after ? [] : [change]\n })\n\n const merged = merge(changed)\n\n return [timeline, merged === undefined ? [] : [merged]]\n }\n )\n )\n}\n\n/**\n * Returns the stream of changes to a chat's timeline that its entries produce, for a chat client.\n *\n * **Details**\n *\n * The entries must stream from the start of the chat's log, as `assistant.subscribe(chatId)` does\n * without `after`. The fold reads every entry, because a message depends on earlier entries: its\n * block is answered or closed later. `after` only skips emitting the changes up to that `sequence`, so a\n * client that has the timeline up to a `sequence` receives only what changed since. Pass `after` here,\n * not to `subscribe`: a subscription that starts after a `sequence` gives the fold an incomplete log,\n * and the changes it produces are wrong.\n *\n * Each chunk of entries becomes one change; the stored entries, for example, arrive as one chunk.\n *\n * **Only the app's events in `show` reach the client.** Each one becomes an item between the\n * messages (see {@link EventItem}); the app's other events, like a summary of the chat for the\n * model, are left out. Without `show`, none are shown. The changes are typed with the events shown,\n * so the RPC's success schema names the same ones (`Timeline.Change([...])`), and a handler that\n * shows one the schema doesn't name doesn't compile. A timeline shows a turn as working once it\n * starts, or from the user's input.\n *\n * **Example** (Streaming a chat's timeline to a client, with the one app event its user sees)\n *\n * ```ts\n * import { Assistant, type ChatId, Timeline } from \"effect-assistant\"\n * import * as Schema from \"effect/Schema\"\n * import * as Stream from \"effect/Stream\"\n *\n * class Summary extends Schema.TaggedClass<Summary>()(\"Summary\", { text: Schema.String, throughSequence: Schema.Int }) {}\n * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()(\"DailyBudgetReached\", {}) {}\n *\n * const MyAssistant = Assistant.make(\"my-assistant\", { events: [Summary, DailyBudgetReached] })\n *\n * // The summary is for the model: only the budget notice reaches the user.\n * const watch = (chatId: ChatId.ChatId, after: number) =>\n * Stream.unwrap(\n * MyAssistant.useSync((assistant) =>\n * assistant.subscribe(chatId).pipe(Timeline.changes(MyAssistant, { show: [DailyBudgetReached], after }))\n * )\n * )\n * ```\n *\n * @see {@link fold} for folding the changes into a timeline on the client\n *\n * @category utils\n * @since 0.3.0\n */\nexport const changes: {\n <Events, const Show extends Shown<Events> = readonly []>(\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n ): <E, R>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>\n ) => Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\n <E, R, Events, const Show extends Shown<Events> = readonly []>(\n entries: Stream.Stream<AssistantEvent.AnyEntry | ChatSignal.ChatSignal, E, R>,\n definition: Definition<Events>,\n options?: ChangesOptions<Show>\n ): Stream.Stream<Change<Show[number][\"Type\"]>, E, R>\n} = dual((args) => Stream.isStream(args[0]), changesWith)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA6CA,MAAa,cAAc,OAAO,SAAS;CAAC;CAAQ;CAAY;AAAQ,CAAC;;;;;;;;;AAkBzE,MAAa,QAAQ,OAAO,OAAO;CACjC,MAAM,OAAO;CACb,OAAO,OAAO;CACd,QAAQ;CACR,QAAQ,OAAO,SAAS,OAAO,IAAI;;CAEnC,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,OAAO;CACpC,SAAS,OAAO;CAChB,aAAa,OAAO,MAAM,iBAAiB;CAC3C,QAAQ,OAAO,SAAS,OAAO,MAAM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ACb,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 { 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;;;;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;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiDA,MAAa,UAYT,MAAM,SAAS,OAAO,SAAS,KAAK,EAAE,GAAG,WAAW"}
|
package/dist/ToolStatus.d.ts
CHANGED
|
@@ -36,8 +36,9 @@ export declare const Described: Context.Reference<boolean>;
|
|
|
36
36
|
*
|
|
37
37
|
* **Details**
|
|
38
38
|
*
|
|
39
|
-
* The model sees
|
|
40
|
-
* writes there while the call runs.
|
|
39
|
+
* The model sees a required `description` parameter on the tool, and the chat shows what it
|
|
40
|
+
* writes there while the call runs. Required, because models leave optional parameters out; a call
|
|
41
|
+
* without it still runs, with no status. The handler gets its parameters without it. A tool that has a
|
|
41
42
|
* parameter of that name already can't be marked: the loop stops with a defect when it offers one.
|
|
42
43
|
*
|
|
43
44
|
* **Example** (A slow report with a status)
|
package/dist/ToolStatus.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolStatus.d.ts","names":[],"sources":["../src/ToolStatus.ts"],"mappings":";;;;;;KAiBK;WACM,YAAY,OAAO;WACnB,SAAS,OAAO;WAChB,SAAS,OAAO;WAChB,aAAa,KAAK;;;;;;;;qBAShB;;;;;;;qBAQA;;;;;;;qBASA,WAAS,QAAA
|
|
1
|
+
{"version":3,"file":"ToolStatus.d.ts","names":[],"sources":["../src/ToolStatus.ts"],"mappings":";;;;;;KAiBK;WACM,YAAY,OAAO;WACnB,SAAS,OAAO;WAChB,SAAS,OAAO;WAChB,aAAa,KAAK;;;;;;;;qBAShB;;;;;;;qBAQA;;;;;;;qBASA,WAAS,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAiCT,YAAa,qBAAqB,eAAe,SAAS,GAAC,MAChE,KAAK,KAAK,MAAM,QAAQ,OAC7B,KAAK,KAAK,MAAM,QAAQ;;;;;;;qBAQd,cAAW,MAAU,KAAK"}
|
package/dist/ToolStatus.js
CHANGED
|
@@ -34,8 +34,9 @@ const Described = Context.Reference("effect-assistant/ToolStatus/Described", { d
|
|
|
34
34
|
*
|
|
35
35
|
* **Details**
|
|
36
36
|
*
|
|
37
|
-
* The model sees
|
|
38
|
-
* writes there while the call runs.
|
|
37
|
+
* The model sees a required `description` parameter on the tool, and the chat shows what it
|
|
38
|
+
* writes there while the call runs. Required, because models leave optional parameters out; a call
|
|
39
|
+
* without it still runs, with no status. The handler gets its parameters without it. A tool that has a
|
|
39
40
|
* parameter of that name already can't be marked: the loop stops with a defect when it offers one.
|
|
40
41
|
*
|
|
41
42
|
* **Example** (A slow report with a status)
|
package/dist/ToolStatus.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolStatus.js","names":[],"sources":["../src/ToolStatus.ts"],"sourcesContent":["/**\n * This module provides status labels for tool calls: while a call runs, the chat shows the user a\n * short line about what the assistant is doing, like \"Checking last summer's campaign budget\".\n *\n * Mark the tools that take a while or act on something with {@link described}: workflows, reports\n * from other systems, orders, specialists. The model then sees
|
|
1
|
+
{"version":3,"file":"ToolStatus.js","names":[],"sources":["../src/ToolStatus.ts"],"sourcesContent":["/**\n * This module provides status labels for tool calls: while a call runs, the chat shows the user a\n * short line about what the assistant is doing, like \"Checking last summer's campaign budget\".\n *\n * Mark the tools that take a while or act on something with {@link described}: workflows, reports\n * from other systems, orders, specialists. The model then sees a required `description` parameter\n * on them and fills it in the chat's language. When the call starts, the chat sends the\n * description as a `ChatSignal.Status`; it shows until the next status, so it stays after the call\n * ends. The tool's handler never receives the parameter. Quick reads need no label: the chat shows its generic working state for\n * them.\n *\n * @since 0.13.0\n */\nimport type * as Tool from \"effect/ai/Tool\"\nimport * as Context from \"effect/Context\"\nimport type * as Schema from \"effect/Schema\"\n\ntype Schemas = {\n readonly parameters: Schema.Constraint\n readonly success: Schema.Constraint\n readonly failure: Schema.Constraint\n readonly failureMode: Tool.FailureMode\n}\n\n/**\n * The name of the parameter the model fills with a call's status.\n *\n * @category constants\n * @since 0.13.0\n */\nexport const parameterName = \"description\"\n\n/**\n * What the model reads about the parameter.\n *\n * @category constants\n * @since 0.13.0\n */\nexport const parameterDescription =\n \"Shown to the user while this runs: 3 to 8 plain words in the user's language about what you're doing, like \\\"Checking last summer's campaign budget\\\". No tool names, ids or code.\"\n\n/**\n * Annotation for whether a tool's calls show a status, set with {@link described}.\n *\n * @category annotations\n * @since 0.13.0\n */\nexport const Described = Context.Reference<boolean>(\"effect-assistant/ToolStatus/Described\", {\n defaultValue: () => false\n})\n\n/**\n * Marks a tool whose calls show a status while they run.\n *\n * **Details**\n *\n * The model sees a required `description` parameter on the tool, and the chat shows what it\n * writes there while the call runs. Required, because models leave optional parameters out; a call\n * without it still runs, with no status. The handler gets its parameters without it. A tool that has a\n * parameter of that name already can't be marked: the loop stops with a defect when it offers one.\n *\n * **Example** (A slow report with a status)\n *\n * ```ts\n * import { ToolStatus } from \"effect-assistant\"\n * import * as Tool from \"effect/ai/Tool\"\n * import * as Schema from \"effect/Schema\"\n *\n * export const CampaignReport = ToolStatus.described(\n * Tool.make(\"campaign_report\", {\n * description: \"The spend and results of a past campaign.\",\n * parameters: Schema.Struct({ campaignId: Schema.String }),\n * success: Schema.Struct({ spent: Schema.Finite })\n * })\n * )\n * ```\n *\n * @category annotations\n * @since 0.13.0\n */\nexport const described = <Name extends string, Config extends Schemas, R>(\n tool: Tool.Tool<Name, Config, R>\n): Tool.Tool<Name, Config, R> => tool.annotate(Described, true)\n\n/**\n * Returns whether a tool's calls show a status.\n *\n * @category guards\n * @since 0.13.0\n */\nexport const isDescribed = (tool: Tool.Any): boolean => Context.get(tool.annotations, Described)\n"],"mappings":";;;;;;;;;;;;;;;;AA8BA,MAAa,gBAAgB;;;;;;;AAQ7B,MAAa,uBACX;;;;;;;AAQF,MAAa,YAAY,QAAQ,UAAmB,yCAAyC,EAC3F,oBAAoB,MACtB,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+BD,MAAa,aACX,SAC+B,KAAK,SAAS,WAAW,IAAI;;;;;;;AAQ9D,MAAa,eAAe,SAA4B,QAAQ,IAAI,KAAK,aAAa,SAAS"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop.d.ts","names":[],"sources":["../../src/internal/loop.ts"],"mappings":";;;;;;;;;;;;;;;YA2BY,QACR,cACA,cACA,aACA;;qBAKS,eAAa,QAAA,UAAA,OAAA;WACW,UAAA,OAAO,OAAO,cAAc;;;qBAMpD,WAAS,QAAA,UAAA,OAAA,OAAA;;iBAKL;WACN,UAAU,cAAc,OAAO;WAC/B;;;iBAUM,YAAY;WAClB,uBAAuB;WACvB,UAAU,MAAe;WACzB,SAAS,OAAO,OAAO,cAAc,OAAO,WAAW;WACvD,aAAa,cAAc;;;iBAIrB,QAAQ,mBAAmB,YAAY;WAC7C;;;iBAKM;;WAEN,QAAQ;;;;;;WAMR;;;;WAIA;;;
|
|
1
|
+
{"version":3,"file":"loop.d.ts","names":[],"sources":["../../src/internal/loop.ts"],"mappings":";;;;;;;;;;;;;;;YA2BY,QACR,cACA,cACA,aACA;;qBAKS,eAAa,QAAA,UAAA,OAAA;WACW,UAAA,OAAO,OAAO,cAAc;;;qBAMpD,WAAS,QAAA,UAAA,OAAA,OAAA;;iBAKL;WACN,UAAU,cAAc,OAAO;WAC/B;;;iBAUM,YAAY;WAClB,uBAAuB;WACvB,UAAU,MAAe;WACzB,SAAS,OAAO,OAAO,cAAc,OAAO,WAAW;WACvD,aAAa,cAAc;;;iBAIrB,QAAQ,mBAAmB,YAAY;WAC7C;;;iBAKM;;WAEN,QAAQ;;;;;;WAMR;;;;WAIA;;;YAkOC,KAAK,GAAG,KAAK,KAAK;EAC5B;aAAkB,OAAO;;EACzB;aAAiB,OAAO;;EACxB,MAAM;;;qBAUK,QAAS,GAAC,OAAS,MAAI,KAAK;;qBAG5B,OAAQ,GAAC,OAAS,MAAI,OAAO,OAAO,YAAY;;qBAIhD,OAAQ,gBAAc,OAAO,OAAO,YAAY;;qBAOhD,OAAQ,GAAG,GAAG,GAAG,GAAC,SACpB,GAAC,OACH,OAAO,MAAM,OAAO,OAAO,KAAK,GAAG,IAAI,GAAG,OAChD,OAAO,OAAO,GAAG,GAAG;;qBAmBV,OAAQ,GAAG,GAAG,YAAY,YAAU,SACtC,YAAY,IAAE,OAChB,QAAQ,eAAe,OAAO,OAAO,YAAY,IAAI,IAAI,QAC/D,OAAO,OAAO,KAAK,OAAO,IAAI,QAAQ,UAAU,IAAI,cAAc,gBAAgB,IAAI;;qBA8E5E,MAAO,WAAS,SAClB,QAAQ,OAChB,OAAO,OAAO,OAAO,QAAQ,SAAS,cAAc,gBAAgB"}
|
package/dist/internal/loop.js
CHANGED
|
@@ -30,7 +30,7 @@ const readHistory = (read) => "messages" in read ? {
|
|
|
30
30
|
messages: read,
|
|
31
31
|
throughSequence: void 0
|
|
32
32
|
};
|
|
33
|
-
const statusParameter = Schema.String.annotate({ description: parameterDescription })
|
|
33
|
+
const statusParameter = Schema.String.annotate({ description: parameterDescription });
|
|
34
34
|
const withStatusParameter = (tool) => {
|
|
35
35
|
const ast = tool.parametersSchema.ast;
|
|
36
36
|
if (!isDescribed(tool) || !SchemaAST.isObjects(ast)) return tool;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"loop.js","names":["ToolStatus.parameterDescription","ToolStatus.isDescribed","ToolStatus.parameterName","Live.use","Streamed.collect","AssistantEvent.ModelPart","Telemetry.toolOutput","Telemetry.toolSpan","Toolkits.failed","Toolkits.empty","History.unansweredCalls","Telemetry.annotateModelCall"],"sources":["../../src/internal/loop.ts"],"sourcesContent":["import type * as AiError from \"effect/ai/AiError\"\nimport * as LanguageModel from \"effect/ai/LanguageModel\"\nimport * as Model from \"effect/ai/Model\"\nimport * as Prompt from \"effect/ai/Prompt\"\nimport type * as Response from \"effect/ai/Response\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Clock from \"effect/Clock\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaAST from \"effect/SchemaAST\"\nimport * as Stream from \"effect/Stream\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type * as Instructions from \"../Instructions.ts\"\nimport * as ToolStatus from \"../ToolStatus.ts\"\nimport * as History from \"./history.ts\"\nimport * as Live from \"./live.ts\"\nimport * as Streamed from \"./stream.ts\"\nimport * as Telemetry from \"./telemetry.ts\"\nimport * as Toolkits from \"./toolkit.ts\"\nimport { isTurnEnding, isUserMessage, sendUserMessageName } from \"./tools.ts\"\n\n/** @internal */\nexport type Event =\n | AssistantEvent.ModelOutput\n | AssistantEvent.ToolStarted\n | AssistantEvent.ToolResult\n | AssistantEvent.ApprovalRequested\n\n// Only a turn's loop can wait for the user's approval, and runs the calls they approved. A turn's specialists inherit\n// its context, so their runs set it back to none.\n/** @internal */\nexport const TurnApprovals = Context.Reference<\n Option.Option<{ readonly approved: Effect.Effect<ReadonlyArray<AssistantEvent.ToolCallPart>> }>\n>(\"effect-assistant/TurnApprovals\", { defaultValue: Option.none })\n\n// The assistant's own tools with the turn's services, so an app's own loop in a turn can message the user. A\n// specialist's run has none.\n/** @internal */\nexport const TurnTools = Context.Reference<Option.Option<Toolkits.Tools>>(\"effect-assistant/TurnTools\", {\n defaultValue: Option.none\n})\n\n/** @internal */\nexport interface ChatHistory {\n readonly messages: ReadonlyArray<Prompt.Message>\n readonly throughSequence: number\n}\n\nconst readHistory = (read: ReadonlyArray<Prompt.Message> | ChatHistory) =>\n \"messages\" in read\n ? { messages: read.messages, throughSequence: read.throughSequence }\n : { messages: read, throughSequence: undefined }\n\n// `AssistantLoop` takes native toolkits; turns and specialist runs come here with their tools already merged.\n/** @internal */\nexport interface StepOptions<R = never> {\n readonly instructions: string | Instructions.Resolved\n readonly toolkit?: Toolkits.Tools<R> | undefined\n readonly history: Effect.Effect<ReadonlyArray<Prompt.Message> | ChatHistory>\n readonly toolChoice?: LanguageModel.ToolChoice<string> | undefined\n}\n\n/** @internal */\nexport interface Options<R = never> extends StepOptions<R> {\n readonly maxSteps?: number | undefined\n}\n\n// Its member docs show through `AssistantLoop.StepResult`.\n/** @internal */\nexport interface StepResult {\n /** The model's output; unset when the step only ran calls a crash cut off. */\n readonly output: AssistantEvent.ModelOutput | undefined\n /**\n * Whether the model is done: it made no tool calls, one of its calls waits for the user's\n * approval, or it ended its turn (`wait`, or a message with `wait: true`) and none of the step's\n * calls failed.\n */\n readonly done: boolean\n /**\n * The history's length with this step's output and results: a longer one got something new meanwhile.\n */\n readonly historyLength: number\n}\n\n// A tool as `Tool.isUserDefined` narrows one. With `Tool.Any`, generateText's types ask for the services that encode\n// every tool's params, `unknown` for a schema of unknown type, though deferred validation encodes none.\ntype RequestTool = Tool.Tool<string, any, any>\n\nconst statusParameter = Schema.String.annotate({ description: ToolStatus.parameterDescription }).pipe(\n Schema.optionalKey\n)\n\n// What the model reads of a described tool: its parameters with the status one. Only the request has it; the call\n// runs without it (see `withoutStatus`). A record of no keys (a tool without parameters) becomes an object with it.\nconst withStatusParameter = (tool: Tool.Any): Tool.Any => {\n const ast = tool.parametersSchema.ast\n\n if (!ToolStatus.isDescribed(tool) || !SchemaAST.isObjects(ast)) return tool\n\n if (ast.propertySignatures.some((property) => property.name === ToolStatus.parameterName)) {\n throw new Error(\n `${tool.name} has a parameter named ${ToolStatus.parameterName} already, so it can't show a status: rename it.`\n )\n }\n\n const added = Schema.Struct({ [ToolStatus.parameterName]: statusParameter }).ast.propertySignatures\n\n return tool.setParameters(\n Schema.make<Schema.Top>(\n new SchemaAST.Objects(\n [...ast.propertySignatures, ...added],\n ast.indexSignatures.filter((index) => !SchemaAST.isNever(index.type)),\n ast.annotations\n )\n )\n )\n}\n\n// The loop runs the calls itself, after storing each as started, so the model call runs none. It also decides which\n// calls wait for approval: the model call would ask for approvals of its own.\nconst requestToolkit = (definitions: ReadonlyArray<Tool.Any>): Toolkit.WithHandler<Record<string, RequestTool>> => ({\n tools: Object.fromEntries(\n definitions.map((tool) => {\n const requested = withStatusParameter(tool)\n\n return [\n tool.name,\n requested.needsApproval === undefined || requested.needsApproval === false\n ? requested\n : requested.setNeedsApproval(false)\n ]\n })\n ),\n handle: () => Effect.succeed(Stream.empty)\n})\n\n// The model starts a message to the user: a `send_user_message` call, or text of its own, which the reply pass turns\n// into one.\nconst startsMessage = (part: Response.AnyPart) =>\n part.type === \"text-start\" || (part.type === \"tool-params-start\" && part.name === sendUserMessageName)\n\n// Validation is deferred: a call to a tool that isn't in the toolkit (one in the history the turn no longer offers),\n// or with params that don't fit its schema, would otherwise fail the whole model call. The loop runs it instead, and\n// the model reads why it failed.\n// Streamed, so the chat can show the user that a message is on its way while the model writes it.\nconst generate = (\n prompt: Prompt.Prompt,\n definitions: ReadonlyArray<Tool.Any>,\n toolChoice: LanguageModel.ToolChoice<string> | undefined\n): Effect.Effect<ReadonlyArray<Response.AnyPart>, AiError.AiError, LanguageModel.LanguageModel> =>\n Stream.suspend(() =>\n LanguageModel.streamText({\n prompt,\n toolkit: requestToolkit(definitions),\n toolChoice,\n disableToolCallResolution: true,\n toolCallValidation: \"deferred\"\n })\n ).pipe(\n Stream.tap((part) => (startsMessage(part) ? Live.use((live) => live.typing(true)) : Effect.void)),\n Stream.runCollect,\n Effect.map(Streamed.collect)\n )\n\nconst decodePart = Schema.decodeUnknownOption(AssistantEvent.ModelPart)\n\nconst modelParts = (content: ReadonlyArray<Response.AnyPart>) =>\n content.flatMap((part) =>\n Option.toArray(decodePart(part)).filter((decoded) => !(decoded.type === \"tool-call\" && decoded.providerExecuted))\n )\n\nconst toolCalls = (parts: ReadonlyArray<AssistantEvent.ModelPart>): ReadonlyArray<AssistantEvent.ToolCallPart> =>\n parts.flatMap((part) => (part.type === \"tool-call\" ? [part] : []))\n\nconst decodeParams = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.Json))\n\nconst isDescribedCall = <R>(tools: Toolkits.Tools<R>, call: AssistantEvent.ToolCallPart) =>\n tools.definitions.some((tool) => tool.name === call.name && ToolStatus.isDescribed(tool))\n\n// The status the model wrote for a described tool's call, and the call as the tool's handler gets it.\nconst splitStatus = (call: AssistantEvent.ToolCallPart): readonly [string | undefined, AssistantEvent.ToolCallPart] => {\n const params = decodeParams(call.params)\n\n if (Option.isNone(params) || !Object.hasOwn(params.value, ToolStatus.parameterName)) return [undefined, call]\n\n const { [ToolStatus.parameterName]: written, ...rest } = params.value\n const status = Predicate.isString(written) ? written.trim() : \"\"\n\n return [status === \"\" ? undefined : status, { ...call, params: rest }]\n}\n\n// A call's status shows when it starts; a message's typing stops once the message is stored.\nconst runCall = Effect.fnUntraced(function* <R>(tools: Toolkits.Tools<R>, call: AssistantEvent.ToolCallPart) {\n const [status, run] = isDescribedCall(tools, call) ? splitStatus(call) : [undefined, call]\n\n const result = yield* Effect.gen(function* () {\n if (status !== undefined) yield* Live.use((live) => live.callStarted(call.id, status))\n\n const result = yield* tools.run(run)\n\n yield* Telemetry.toolOutput(result.result)\n\n return result\n }).pipe(\n Telemetry.toolSpan(call),\n Effect.ensuring(\n Live.use((live) =>\n Effect.andThen(live.callEnded(call.id), call.name === sendUserMessageName ? live.typing(false) : Effect.void)\n )\n )\n )\n\n return AssistantEvent.ToolResult.make({ callId: call.id, tool: call.name, ...result })\n})\n\n// A call that needs approval waits for the user in a turn. A specialist's run can't ask them, so its call fails.\nconst awaitApproval = Effect.fnUntraced(function* (call: AssistantEvent.ToolCallPart) {\n if (Option.isNone(yield* TurnApprovals)) {\n return AssistantEvent.ToolResult.make({\n callId: call.id,\n tool: call.name,\n ...Toolkits.failed(\n `${call.name} needs the user's approval, and only the assistant can ask for it. Don't run it: say in your answer what needs approving, with the details.`,\n \"NeedsApproval\"\n )\n })\n }\n\n return AssistantEvent.ApprovalRequested.make({ callId: call.id, tool: call.name, params: call.params })\n})\n\ninterface Pending {\n readonly call: AssistantEvent.ToolCallPart\n /** The user approved it: it runs without asking again. */\n readonly approved: boolean\n}\n\ninterface Ran {\n /** One of the calls failed, so the model has to read the results. */\n readonly failed: boolean\n /** One of the calls waits for the user's approval, so the turn ends. */\n readonly waiting: boolean\n}\n\n// The approval shows the call, not what it does: the user learns that from the assistant's message beside it.\nconst unexplained = (call: AssistantEvent.ToolCallPart) =>\n AssistantEvent.ToolResult.make({\n callId: call.id,\n tool: call.name,\n ...Toolkits.failed(\n `Not sent for approval: the user would see buttons without knowing what they approve. In one step, send them a message with send_user_message saying what ${call.name} will do (what, to whom, how many), and call ${call.name} again.`,\n \"ApprovalNeedsMessage\"\n )\n })\n\n// Every `ToolStarted` is stored before any call runs; a call that waits for approval doesn't start.\nconst runCalls = <R, S, E, R2>(\n tools: Toolkits.Tools<R>,\n pending: ReadonlyArray<Pending>,\n history: ReadonlyArray<Prompt.Message>,\n then: (ran: Ran) => Stream.Stream<Step<never, S>, E, R2>\n): Stream.Stream<Step<Event, S>, E, R | R2> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const waits = yield* Effect.forEach(pending, ({ call, approved }) =>\n approved ? Effect.succeed(false) : tools.needsApproval(call, history)\n )\n\n const started = pending.flatMap(({ call }, i) =>\n waits[i] === true ? [] : [value(AssistantEvent.ToolStarted.make({ callId: call.id, tool: call.name }))]\n )\n\n return Stream.fromIterable(started).pipe(\n Stream.concat(\n Stream.unwrap(\n Effect.gen(function* () {\n const explained = pending.some(({ call }) => isUserMessage(call))\n\n // Text that became no message, or a message that failed, stops the typing too.\n const done = yield* Effect.forEach(\n pending,\n ({ call }, i): Effect.Effect<Event, never, R> =>\n waits[i] !== true\n ? runCall(tools, call)\n : explained\n ? awaitApproval(call)\n : Effect.succeed(unexplained(call)),\n { concurrency: \"unbounded\" }\n ).pipe(Effect.ensuring(Live.use((live) => live.typing(false))))\n\n return Stream.fromIterable(done.map(value)).pipe(\n Stream.concat(\n then({\n failed: done.some(isFailure),\n waiting: done.some((event) => Predicate.isTagged(event, \"ApprovalRequested\"))\n })\n )\n )\n })\n )\n )\n )\n })\n )\n\nconst isFailure = (event: Event) => Predicate.isTagged(event, \"ToolResult\") && event.outcome === \"failure\"\n\n/** @internal */\nexport type Step<A, S> = Data.TaggedEnum<{\n Value: { readonly value: A }\n Next: { readonly state: S }\n Stop: Record<never, never>\n}>\n\ninterface StepDefinition extends Data.TaggedEnum.WithGenerics<2> {\n readonly taggedEnum: Step<this[\"A\"], this[\"B\"]>\n}\n\nconst Steps = Data.taggedEnum<StepDefinition>()\n\n/** @internal */\nexport const value = <A>(value: A): Step<A, never> => Steps.Value({ value })\n\n/** @internal */\nexport const next = <S>(state: S): Stream.Stream<Step<never, S>> => Stream.succeed(Steps.Next({ state }))\n\n/** @internal */\n// oxlint-disable-next-line no-unnecessary-type-parameters -- `stop<number>()` types a loop's state where inference can't.\nexport const stop = <S = never>(): Stream.Stream<Step<never, S>> => Stream.succeed(Steps.Stop())\n\nconst isValue = <A, S>(step: Step<A, S>): step is Data.TaggedEnum.Value<Step<A, S>, \"Value\"> =>\n Predicate.isTagged(step, \"Value\")\n\n// A body that ends without `next` or `stop` stops too.\n/** @internal */\nexport const loop = <S, A, E, R>(\n initial: S,\n body: (state: S) => Stream.Stream<Step<A, S>, E, R>\n): Stream.Stream<A, E, R> => {\n const go = (state: S): Stream.Stream<A, E, R> =>\n Stream.suspend(() => {\n let after: Option.Option<S> = Option.none()\n\n return body(state).pipe(\n Stream.tap((step) =>\n Effect.sync(() => (after = Predicate.isTagged(step, \"Next\") ? Option.some(step.state) : after))\n ),\n Stream.filter(isValue),\n Stream.map((step) => step.value),\n Stream.concat(Stream.suspend(() => Option.match(after, { onNone: () => Stream.empty, onSome: go })))\n )\n })\n\n return go(initial)\n}\n\n/** @internal */\nexport const step = <R, S, E2 = never, R2 = never>(\n options: StepOptions<R>,\n then: (result: StepResult) => Stream.Stream<Step<never, S>, E2, R2>\n): Stream.Stream<Step<Event, S>, AiError.AiError | E2, LanguageModel.LanguageModel | R | R2> => {\n const toolkit = options.toolkit ?? Toolkits.empty\n const instructions = Predicate.isString(options.instructions) ? { text: options.instructions } : options.instructions\n\n const after = (result: StepResult) => Stream.suspend(() => then(result))\n\n return Stream.unwrap(\n Effect.gen(function* () {\n const { messages: history, throughSequence } = readHistory(yield* options.history)\n // Calls a crash cut off, with no result: they run again, with the same ids, before the model goes on.\n const cutOff = History.unansweredCalls(history)\n const approvals = yield* TurnApprovals\n\n // Calls the user approved: they run as the model made them, with the same ids, before the model goes on. Not in\n // a loop without their tools.\n const approved = Option.isNone(approvals)\n ? []\n : (yield* approvals.value.approved).filter(\n (call) =>\n toolkit.definitions.some((tool) => tool.name === call.name) && !cutOff.some((cut) => cut.id === call.id)\n )\n\n if (cutOff.length > 0 || approved.length > 0) {\n const pending = [\n ...cutOff.map((call) => ({ call, approved: false })),\n ...approved.map((call) => ({ call, approved: true }))\n ]\n\n return runCalls(toolkit, pending, history, ({ waiting }) =>\n after({ output: undefined, done: waiting, historyLength: history.length + pending.length })\n )\n }\n\n const prompt = Prompt.fromMessages([Prompt.systemMessage({ content: instructions.text }), ...history])\n const name = yield* Effect.serviceOption(Model.ModelName)\n const started = yield* Clock.currentTimeMillis\n\n const content = yield* generate(prompt, toolkit.definitions, options.toolChoice).pipe(\n Telemetry.annotateModelCall(instructions.attributes)\n )\n\n const metadata = content.find((part) => part.type === \"response-metadata\")\n const finish = content.find((part) => part.type === \"finish\")\n\n const output = AssistantEvent.ModelOutput.make({\n parts: modelParts(content),\n seenThroughSequence: throughSequence,\n model: metadata?.modelId ?? Option.getOrUndefined(name),\n responseId: metadata?.id,\n usage: finish?.usage,\n durationMillis: (yield* Clock.currentTimeMillis) - started\n })\n\n const calls = toolCalls(output.parts)\n const historyLength = history.length + Prompt.fromResponseParts(output.parts).content.length + calls.length\n\n // A failed call doesn't end the turn: a message that failed never reached the user, so the model reads why. A call\n // that waits for approval does: the turn waits for the user.\n return Stream.make(value(output)).pipe(\n Stream.concat(\n runCalls(\n toolkit,\n calls.map((call) => ({ call, approved: false })),\n history,\n ({ failed, waiting }) =>\n after({\n output,\n done: calls.length === 0 || waiting || (!failed && calls.some(isTurnEnding)),\n historyLength\n })\n )\n )\n )\n })\n )\n}\n\n/** @internal */\nexport const run = <R = never>(\n options: Options<R>\n): Stream.Stream<Event, AiError.AiError, LanguageModel.LanguageModel | R> => {\n const maxSteps = options.maxSteps ?? 16\n\n // Done: stop, unless something arrived while the model was working; then it reads that first.\n const afterDone = (steps: number, historyLength: number) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const read = yield* options.history\n\n return readHistory(read).messages.length > historyLength ? next(steps) : stop<number>()\n })\n )\n\n return loop(0, (steps: number) =>\n step(options, (result) => {\n const taken = result.output === undefined ? steps : steps + 1\n\n if (taken >= maxSteps) return stop<number>()\n\n return result.done ? afterDone(taken, result.historyLength) : next(taken)\n })\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,gBAAgB,QAAQ,UAEnC,kCAAkC,EAAE,cAAc,OAAO,KAAK,CAAC;;AAKjE,MAAa,YAAY,QAAQ,UAAyC,8BAA8B,EACtG,cAAc,OAAO,KACvB,CAAC;AAQD,MAAM,eAAe,SACnB,cAAc,OACV;CAAE,UAAU,KAAK;CAAU,iBAAiB,KAAK;AAAgB,IACjE;CAAE,UAAU;CAAM,iBAAiB,KAAA;AAAU;AAqCnD,MAAM,kBAAkB,OAAO,OAAO,SAAS,EAAE,aAAaA,qBAAgC,CAAC,CAAC,CAAC,KAC/F,OAAO,WACT;AAIA,MAAM,uBAAuB,SAA6B;CACxD,MAAM,MAAM,KAAK,iBAAiB;CAElC,IAAI,CAACC,YAAuB,IAAI,KAAK,CAAC,UAAU,UAAU,GAAG,GAAG,OAAO;CAEvE,IAAI,IAAI,mBAAmB,MAAM,aAAa,SAAS,SAAS,aAAwB,GACtF,MAAM,IAAI,MACR,GAAG,KAAK,KAAK,yBAAyBC,cAAyB,gDACjE;CAGF,MAAM,QAAQ,OAAO,OAAO,GAAGA,gBAA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qB;EACrD,CAAC;EAED,MAAM,QAAQ,UAAU,OAAO,KAAK;EACpC,MAAM,gBAAgB,QAAQ,SAAS,OAAO,kBAAkB,OAAO,KAAK,CAAC,CAAC,QAAQ,SAAS,MAAM;EAIrG,OAAO,OAAO,KAAK,MAAM,MAAM,CAAC,CAAC,CAAC,KAChC,OAAO,OACL,SACE,SACA,MAAM,KAAK,UAAU;GAAE;GAAM,UAAU;EAAM,EAAE,GAC/C,UACC,EAAE,QAAQ,cACT,MAAM;GACJ;GACA,MAAM,MAAM,WAAW,KAAK,WAAY,CAAC,UAAU,MAAM,KAAK,YAAY;GAC1E;EACF,CAAC,CACL,CACF,CACF;CACF,CAAC,CACH;AACF;;AAGA,MAAa,OACX,YAC2E;CAC3E,MAAM,WAAW,QAAQ,YAAY;CAGrC,MAAM,aAAa,OAAe,kBAChC,OAAO,OACL,OAAO,IAAI,aAAa;EACtB,MAAM,OAAO,OAAO,QAAQ;EAE5B,OAAO,YAAY,IAAI,CAAC,CAAC,SAAS,SAAS,gBAAgB,KAAK,KAAK,IAAI,KAAa;CACxF,CAAC,CACH;CAEF,OAAO,KAAK,IAAI,UACd,KAAK,UAAU,WAAW;EACxB,MAAM,QAAQ,OAAO,WAAW,KAAA,IAAY,QAAQ,QAAQ;EAE5D,IAAI,SAAS,UAAU,OAAO,KAAa;EAE3C,OAAO,OAAO,OAAO,UAAU,OAAO,OAAO,aAAa,IAAI,KAAK,KAAK;CAC1E,CAAC,CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"loop.js","names":["ToolStatus.parameterDescription","ToolStatus.isDescribed","ToolStatus.parameterName","Live.use","Streamed.collect","AssistantEvent.ModelPart","Telemetry.toolOutput","Telemetry.toolSpan","Toolkits.failed","Toolkits.empty","History.unansweredCalls","Telemetry.annotateModelCall"],"sources":["../../src/internal/loop.ts"],"sourcesContent":["import type * as AiError from \"effect/ai/AiError\"\nimport * as LanguageModel from \"effect/ai/LanguageModel\"\nimport * as Model from \"effect/ai/Model\"\nimport * as Prompt from \"effect/ai/Prompt\"\nimport type * as Response from \"effect/ai/Response\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Clock from \"effect/Clock\"\nimport * as Context from \"effect/Context\"\nimport * as Data from \"effect/Data\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as SchemaAST from \"effect/SchemaAST\"\nimport * as Stream from \"effect/Stream\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type * as Instructions from \"../Instructions.ts\"\nimport * as ToolStatus from \"../ToolStatus.ts\"\nimport * as History from \"./history.ts\"\nimport * as Live from \"./live.ts\"\nimport * as Streamed from \"./stream.ts\"\nimport * as Telemetry from \"./telemetry.ts\"\nimport * as Toolkits from \"./toolkit.ts\"\nimport { isTurnEnding, isUserMessage, sendUserMessageName } from \"./tools.ts\"\n\n/** @internal */\nexport type Event =\n | AssistantEvent.ModelOutput\n | AssistantEvent.ToolStarted\n | AssistantEvent.ToolResult\n | AssistantEvent.ApprovalRequested\n\n// Only a turn's loop can wait for the user's approval, and runs the calls they approved. A turn's specialists inherit\n// its context, so their runs set it back to none.\n/** @internal */\nexport const TurnApprovals = Context.Reference<\n Option.Option<{ readonly approved: Effect.Effect<ReadonlyArray<AssistantEvent.ToolCallPart>> }>\n>(\"effect-assistant/TurnApprovals\", { defaultValue: Option.none })\n\n// The assistant's own tools with the turn's services, so an app's own loop in a turn can message the user. A\n// specialist's run has none.\n/** @internal */\nexport const TurnTools = Context.Reference<Option.Option<Toolkits.Tools>>(\"effect-assistant/TurnTools\", {\n defaultValue: Option.none\n})\n\n/** @internal */\nexport interface ChatHistory {\n readonly messages: ReadonlyArray<Prompt.Message>\n readonly throughSequence: number\n}\n\nconst readHistory = (read: ReadonlyArray<Prompt.Message> | ChatHistory) =>\n \"messages\" in read\n ? { messages: read.messages, throughSequence: read.throughSequence }\n : { messages: read, throughSequence: undefined }\n\n// `AssistantLoop` takes native toolkits; turns and specialist runs come here with their tools already merged.\n/** @internal */\nexport interface StepOptions<R = never> {\n readonly instructions: string | Instructions.Resolved\n readonly toolkit?: Toolkits.Tools<R> | undefined\n readonly history: Effect.Effect<ReadonlyArray<Prompt.Message> | ChatHistory>\n readonly toolChoice?: LanguageModel.ToolChoice<string> | undefined\n}\n\n/** @internal */\nexport interface Options<R = never> extends StepOptions<R> {\n readonly maxSteps?: number | undefined\n}\n\n// Its member docs show through `AssistantLoop.StepResult`.\n/** @internal */\nexport interface StepResult {\n /** The model's output; unset when the step only ran calls a crash cut off. */\n readonly output: AssistantEvent.ModelOutput | undefined\n /**\n * Whether the model is done: it made no tool calls, one of its calls waits for the user's\n * approval, or it ended its turn (`wait`, or a message with `wait: true`) and none of the step's\n * calls failed.\n */\n readonly done: boolean\n /**\n * The history's length with this step's output and results: a longer one got something new meanwhile.\n */\n readonly historyLength: number\n}\n\n// A tool as `Tool.isUserDefined` narrows one. With `Tool.Any`, generateText's types ask for the services that encode\n// every tool's params, `unknown` for a schema of unknown type, though deferred validation encodes none.\ntype RequestTool = Tool.Tool<string, any, any>\n\n// Required in what the model reads, so it writes one with every call; a call without it still runs.\nconst statusParameter = Schema.String.annotate({ description: ToolStatus.parameterDescription })\n\n// What the model reads of a described tool: its parameters with the status one. Only the request has it; the call\n// runs without it (see `withoutStatus`). A record of no keys (a tool without parameters) becomes an object with it.\nconst withStatusParameter = (tool: Tool.Any): Tool.Any => {\n const ast = tool.parametersSchema.ast\n\n if (!ToolStatus.isDescribed(tool) || !SchemaAST.isObjects(ast)) return tool\n\n if (ast.propertySignatures.some((property) => property.name === ToolStatus.parameterName)) {\n throw new Error(\n `${tool.name} has a parameter named ${ToolStatus.parameterName} already, so it can't show a status: rename it.`\n )\n }\n\n const added = Schema.Struct({ [ToolStatus.parameterName]: statusParameter }).ast.propertySignatures\n\n return tool.setParameters(\n Schema.make<Schema.Top>(\n new SchemaAST.Objects(\n [...ast.propertySignatures, ...added],\n ast.indexSignatures.filter((index) => !SchemaAST.isNever(index.type)),\n ast.annotations\n )\n )\n )\n}\n\n// The loop runs the calls itself, after storing each as started, so the model call runs none. It also decides which\n// calls wait for approval: the model call would ask for approvals of its own.\nconst requestToolkit = (definitions: ReadonlyArray<Tool.Any>): Toolkit.WithHandler<Record<string, RequestTool>> => ({\n tools: Object.fromEntries(\n definitions.map((tool) => {\n const requested = withStatusParameter(tool)\n\n return [\n tool.name,\n requested.needsApproval === undefined || requested.needsApproval === false\n ? requested\n : requested.setNeedsApproval(false)\n ]\n })\n ),\n handle: () => Effect.succeed(Stream.empty)\n})\n\n// The model starts a message to the user: a `send_user_message` call, or text of its own, which the reply pass turns\n// into one.\nconst startsMessage = (part: Response.AnyPart) =>\n part.type === \"text-start\" || (part.type === \"tool-params-start\" && part.name === sendUserMessageName)\n\n// Validation is deferred: a call to a tool that isn't in the toolkit (one in the history the turn no longer offers),\n// or with params that don't fit its schema, would otherwise fail the whole model call. The loop runs it instead, and\n// the model reads why it failed.\n// Streamed, so the chat can show the user that a message is on its way while the model writes it.\nconst generate = (\n prompt: Prompt.Prompt,\n definitions: ReadonlyArray<Tool.Any>,\n toolChoice: LanguageModel.ToolChoice<string> | undefined\n): Effect.Effect<ReadonlyArray<Response.AnyPart>, AiError.AiError, LanguageModel.LanguageModel> =>\n Stream.suspend(() =>\n LanguageModel.streamText({\n prompt,\n toolkit: requestToolkit(definitions),\n toolChoice,\n disableToolCallResolution: true,\n toolCallValidation: \"deferred\"\n })\n ).pipe(\n Stream.tap((part) => (startsMessage(part) ? Live.use((live) => live.typing(true)) : Effect.void)),\n Stream.runCollect,\n Effect.map(Streamed.collect)\n )\n\nconst decodePart = Schema.decodeUnknownOption(AssistantEvent.ModelPart)\n\nconst modelParts = (content: ReadonlyArray<Response.AnyPart>) =>\n content.flatMap((part) =>\n Option.toArray(decodePart(part)).filter((decoded) => !(decoded.type === \"tool-call\" && decoded.providerExecuted))\n )\n\nconst toolCalls = (parts: ReadonlyArray<AssistantEvent.ModelPart>): ReadonlyArray<AssistantEvent.ToolCallPart> =>\n parts.flatMap((part) => (part.type === \"tool-call\" ? [part] : []))\n\nconst decodeParams = Schema.decodeUnknownOption(Schema.Record(Schema.String, Schema.Json))\n\nconst isDescribedCall = <R>(tools: Toolkits.Tools<R>, call: AssistantEvent.ToolCallPart) =>\n tools.definitions.some((tool) => tool.name === call.name && ToolStatus.isDescribed(tool))\n\n// The status the model wrote for a described tool's call, and the call as the tool's handler gets it.\nconst splitStatus = (call: AssistantEvent.ToolCallPart): readonly [string | undefined, AssistantEvent.ToolCallPart] => {\n const params = decodeParams(call.params)\n\n if (Option.isNone(params) || !Object.hasOwn(params.value, ToolStatus.parameterName)) return [undefined, call]\n\n const { [ToolStatus.parameterName]: written, ...rest } = params.value\n const status = Predicate.isString(written) ? written.trim() : \"\"\n\n return [status === \"\" ? undefined : status, { ...call, params: rest }]\n}\n\n// A call's status shows when it starts; a message's typing stops once the message is stored.\nconst runCall = Effect.fnUntraced(function* <R>(tools: Toolkits.Tools<R>, call: AssistantEvent.ToolCallPart) {\n const [status, run] = isDescribedCall(tools, call) ? splitStatus(call) : [undefined, call]\n\n const result = yield* Effect.gen(function* () {\n if (status !== undefined) yield* Live.use((live) => live.callStarted(call.id, status))\n\n const result = yield* tools.run(run)\n\n yield* Telemetry.toolOutput(result.result)\n\n return result\n }).pipe(\n Telemetry.toolSpan(call),\n Effect.ensuring(\n Live.use((live) =>\n Effect.andThen(live.callEnded(call.id), call.name === sendUserMessageName ? live.typing(false) : Effect.void)\n )\n )\n )\n\n return AssistantEvent.ToolResult.make({ callId: call.id, tool: call.name, ...result })\n})\n\n// A call that needs approval waits for the user in a turn. A specialist's run can't ask them, so its call fails.\nconst awaitApproval = Effect.fnUntraced(function* (call: AssistantEvent.ToolCallPart) {\n if (Option.isNone(yield* TurnApprovals)) {\n return AssistantEvent.ToolResult.make({\n callId: call.id,\n tool: call.name,\n ...Toolkits.failed(\n `${call.name} needs the user's approval, and only the assistant can ask for it. Don't run it: say in your answer what needs approving, with the details.`,\n \"NeedsApproval\"\n )\n })\n }\n\n return AssistantEvent.ApprovalRequested.make({ callId: call.id, tool: call.name, params: call.params })\n})\n\ninterface Pending {\n readonly call: AssistantEvent.ToolCallPart\n /** The user approved it: it runs without asking again. */\n readonly approved: boolean\n}\n\ninterface Ran {\n /** One of the calls failed, so the model has to read the results. */\n readonly failed: boolean\n /** One of the calls waits for the user's approval, so the turn ends. */\n readonly waiting: boolean\n}\n\n// The approval shows the call, not what it does: the user learns that from the assistant's message beside it.\nconst unexplained = (call: AssistantEvent.ToolCallPart) =>\n AssistantEvent.ToolResult.make({\n callId: call.id,\n tool: call.name,\n ...Toolkits.failed(\n `Not sent for approval: the user would see buttons without knowing what they approve. In one step, send them a message with send_user_message saying what ${call.name} will do (what, to whom, how many), and call ${call.name} again.`,\n \"ApprovalNeedsMessage\"\n )\n })\n\n// Every `ToolStarted` is stored before any call runs; a call that waits for approval doesn't start.\nconst runCalls = <R, S, E, R2>(\n tools: Toolkits.Tools<R>,\n pending: ReadonlyArray<Pending>,\n history: ReadonlyArray<Prompt.Message>,\n then: (ran: Ran) => Stream.Stream<Step<never, S>, E, R2>\n): Stream.Stream<Step<Event, S>, E, R | R2> =>\n Stream.unwrap(\n Effect.gen(function* () {\n const waits = yield* Effect.forEach(pending, ({ call, approved }) =>\n approved ? Effect.succeed(false) : tools.needsApproval(call, history)\n )\n\n const started = pending.flatMap(({ call }, i) =>\n waits[i] === true ? [] : [value(AssistantEvent.ToolStarted.make({ callId: call.id, tool: call.name }))]\n )\n\n return Stream.fromIterable(started).pipe(\n Stream.concat(\n Stream.unwrap(\n Effect.gen(function* () {\n const explained = pending.some(({ call }) => isUserMessage(call))\n\n // Text that became no message, or a message that failed, stops the typing too.\n const done = yield* Effect.forEach(\n pending,\n ({ call }, i): Effect.Effect<Event, never, R> =>\n waits[i] !== true\n ? runCall(tools, call)\n : explained\n ? awaitApproval(call)\n : Effect.succeed(unexplained(call)),\n { concurrency: \"unbounded\" }\n ).pipe(Effect.ensuring(Live.use((live) => live.typing(false))))\n\n return Stream.fromIterable(done.map(value)).pipe(\n Stream.concat(\n then({\n failed: done.some(isFailure),\n waiting: done.some((event) => Predicate.isTagged(event, \"ApprovalRequested\"))\n })\n )\n )\n })\n )\n )\n )\n })\n )\n\nconst isFailure = (event: Event) => Predicate.isTagged(event, \"ToolResult\") && event.outcome === \"failure\"\n\n/** @internal */\nexport type Step<A, S> = Data.TaggedEnum<{\n Value: { readonly value: A }\n Next: { readonly state: S }\n Stop: Record<never, never>\n}>\n\ninterface StepDefinition extends Data.TaggedEnum.WithGenerics<2> {\n readonly taggedEnum: Step<this[\"A\"], this[\"B\"]>\n}\n\nconst Steps = Data.taggedEnum<StepDefinition>()\n\n/** @internal */\nexport const value = <A>(value: A): Step<A, never> => Steps.Value({ value })\n\n/** @internal */\nexport const next = <S>(state: S): Stream.Stream<Step<never, S>> => Stream.succeed(Steps.Next({ state }))\n\n/** @internal */\n// oxlint-disable-next-line no-unnecessary-type-parameters -- `stop<number>()` types a loop's state where inference can't.\nexport const stop = <S = never>(): Stream.Stream<Step<never, S>> => Stream.succeed(Steps.Stop())\n\nconst isValue = <A, S>(step: Step<A, S>): step is Data.TaggedEnum.Value<Step<A, S>, \"Value\"> =>\n Predicate.isTagged(step, \"Value\")\n\n// A body that ends without `next` or `stop` stops too.\n/** @internal */\nexport const loop = <S, A, E, R>(\n initial: S,\n body: (state: S) => Stream.Stream<Step<A, S>, E, R>\n): Stream.Stream<A, E, R> => {\n const go = (state: S): Stream.Stream<A, E, R> =>\n Stream.suspend(() => {\n let after: Option.Option<S> = Option.none()\n\n return body(state).pipe(\n Stream.tap((step) =>\n Effect.sync(() => (after = Predicate.isTagged(step, \"Next\") ? Option.some(step.state) : after))\n ),\n Stream.filter(isValue),\n Stream.map((step) => step.value),\n Stream.concat(Stream.suspend(() => Option.match(after, { onNone: () => Stream.empty, onSome: go })))\n )\n })\n\n return go(initial)\n}\n\n/** @internal */\nexport const step = <R, S, E2 = never, R2 = never>(\n options: StepOptions<R>,\n then: (result: StepResult) => Stream.Stream<Step<never, S>, E2, R2>\n): Stream.Stream<Step<Event, S>, AiError.AiError | E2, LanguageModel.LanguageModel | R | R2> => {\n const toolkit = options.toolkit ?? Toolkits.empty\n const instructions = Predicate.isString(options.instructions) ? { text: options.instructions } : options.instructions\n\n const after = (result: StepResult) => Stream.suspend(() => then(result))\n\n return Stream.unwrap(\n Effect.gen(function* () {\n const { messages: history, throughSequence } = readHistory(yield* options.history)\n // Calls a crash cut off, with no result: they run again, with the same ids, before the model goes on.\n const cutOff = History.unansweredCalls(history)\n const approvals = yield* TurnApprovals\n\n // Calls the user approved: they run as the model made them, with the same ids, before the model goes on. Not in\n // a loop without their tools.\n const approved = Option.isNone(approvals)\n ? []\n : (yield* approvals.value.approved).filter(\n (call) =>\n toolkit.definitions.some((tool) => tool.name === call.name) && !cutOff.some((cut) => cut.id === call.id)\n )\n\n if (cutOff.length > 0 || approved.length > 0) {\n const pending = [\n ...cutOff.map((call) => ({ call, approved: false })),\n ...approved.map((call) => ({ call, approved: true }))\n ]\n\n return runCalls(toolkit, pending, history, ({ waiting }) =>\n after({ output: undefined, done: waiting, historyLength: history.length + pending.length })\n )\n }\n\n const prompt = Prompt.fromMessages([Prompt.systemMessage({ content: instructions.text }), ...history])\n const name = yield* Effect.serviceOption(Model.ModelName)\n const started = yield* Clock.currentTimeMillis\n\n const content = yield* generate(prompt, toolkit.definitions, options.toolChoice).pipe(\n Telemetry.annotateModelCall(instructions.attributes)\n )\n\n const metadata = content.find((part) => part.type === \"response-metadata\")\n const finish = content.find((part) => part.type === \"finish\")\n\n const output = AssistantEvent.ModelOutput.make({\n parts: modelParts(content),\n seenThroughSequence: throughSequence,\n model: metadata?.modelId ?? Option.getOrUndefined(name),\n responseId: metadata?.id,\n usage: finish?.usage,\n durationMillis: (yield* Clock.currentTimeMillis) - started\n })\n\n const calls = toolCalls(output.parts)\n const historyLength = history.length + Prompt.fromResponseParts(output.parts).content.length + calls.length\n\n // A failed call doesn't end the turn: a message that failed never reached the user, so the model reads why. A call\n // that waits for approval does: the turn waits for the user.\n return Stream.make(value(output)).pipe(\n Stream.concat(\n runCalls(\n toolkit,\n calls.map((call) => ({ call, approved: false })),\n history,\n ({ failed, waiting }) =>\n after({\n output,\n done: calls.length === 0 || waiting || (!failed && calls.some(isTurnEnding)),\n historyLength\n })\n )\n )\n )\n })\n )\n}\n\n/** @internal */\nexport const run = <R = never>(\n options: Options<R>\n): Stream.Stream<Event, AiError.AiError, LanguageModel.LanguageModel | R> => {\n const maxSteps = options.maxSteps ?? 16\n\n // Done: stop, unless something arrived while the model was working; then it reads that first.\n const afterDone = (steps: number, historyLength: number) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const read = yield* options.history\n\n return readHistory(read).messages.length > historyLength ? next(steps) : stop<number>()\n })\n )\n\n return loop(0, (steps: number) =>\n step(options, (result) => {\n const taken = result.output === undefined ? steps : steps + 1\n\n if (taken >= maxSteps) return stop<number>()\n\n return result.done ? afterDone(taken, result.historyLength) : next(taken)\n })\n )\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAoCA,MAAa,gBAAgB,QAAQ,UAEnC,kCAAkC,EAAE,cAAc,OAAO,KAAK,CAAC;;AAKjE,MAAa,YAAY,QAAQ,UAAyC,8BAA8B,EACtG,cAAc,OAAO,KACvB,CAAC;AAQD,MAAM,eAAe,SACnB,cAAc,OACV;CAAE,UAAU,KAAK;CAAU,iBAAiB,KAAK;AAAgB,IACjE;CAAE,UAAU;CAAM,iBAAiB,KAAA;AAAU;AAsCnD,MAAM,kBAAkB,OAAO,OAAO,SAAS,EAAE,aAAaA,qBAAgC,CAAC;AAI/F,MAAM,uBAAuB,SAA6B;CACxD,MAAM,MAAM,KAAK,iBAAiB;CAElC,IAAI,CAACC,YAAuB,IAAI,KAAK,CAAC,UAAU,UAAU,GAAG,GAAG,OAAO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SAAA,YAAoC,KAAK;GAC7C,OAAO,WAAW,OAAO;GACzB,qBAAqB;GACrB,OAAO,UAAU,WAAW,OAAO,eAAe,IAAI;GACtD,YAAY,UAAU;GACtB,OAAO,QAAQ;GACf,iBAAiB,OAAO,MAAM,qBAAqB;EACrD,CAAC;EAED,MAAM,QAAQ,UAAU,OAAO,KAAK;EACpC,MAAM,gBAAgB,QAAQ,SAAS,OAAO,kBAAkB,OAAO,KAAK,CAAC,CAAC,QAAQ,SAAS,MAAM;EAIrG,OAAO,OAAO,KAAK,MAAM,MAAM,CAAC,CAAC,CAAC,KAChC,OAAO,OACL,SACE,SACA,MAAM,KAAK,UAAU;GAAE;GAAM,UAAU;EAAM,EAAE,GAC/C,UACC,EAAE,QAAQ,cACT,MAAM;GACJ;GACA,MAAM,MAAM,WAAW,KAAK,WAAY,CAAC,UAAU,MAAM,KAAK,YAAY;GAC1E;EACF,CAAC,CACL,CACF,CACF;CACF,CAAC,CACH;AACF;;AAGA,MAAa,OACX,YAC2E;CAC3E,MAAM,WAAW,QAAQ,YAAY;CAGrC,MAAM,aAAa,OAAe,kBAChC,OAAO,OACL,OAAO,IAAI,aAAa;EACtB,MAAM,OAAO,OAAO,QAAQ;EAE5B,OAAO,YAAY,IAAI,CAAC,CAAC,SAAS,SAAS,gBAAgB,KAAK,KAAK,IAAI,KAAa;CACxF,CAAC,CACH;CAEF,OAAO,KAAK,IAAI,UACd,KAAK,UAAU,WAAW;EACxB,MAAM,QAAQ,OAAO,WAAW,KAAA,IAAY,QAAQ,QAAQ;EAE5D,IAAI,SAAS,UAAU,OAAO,KAAa;EAE3C,OAAO,OAAO,OAAO,UAAU,OAAO,OAAO,aAAa,IAAI,KAAK,KAAK;CAC1E,CAAC,CACH;AACF"}
|
package/dist/internal/summary.js
CHANGED
|
@@ -43,6 +43,7 @@ const workingSinceMessage = (entries) => {
|
|
|
43
43
|
return message === -1 || entries.slice(message + 1).some(({ event }) => isWork(event));
|
|
44
44
|
};
|
|
45
45
|
const MAX_CHECK_MILLIS = 500;
|
|
46
|
+
const MIN_CHECK_MILLIS = 100;
|
|
46
47
|
/** @internal */
|
|
47
48
|
const run = Effect.fnUntraced(function* (summary, live, chat) {
|
|
48
49
|
const summarized = yield* Ref.make(-1);
|
|
@@ -57,7 +58,7 @@ const run = Effect.fnUntraced(function* (summary, live, chat) {
|
|
|
57
58
|
const written = yield* summary.summarize(transcript(entries));
|
|
58
59
|
yield* Ref.set(summarized, through);
|
|
59
60
|
if (Option.isSome(written)) yield* live.summarized(written.value);
|
|
60
|
-
}).pipe(Effect.repeat(Schedule.spaced(Math.min(MAX_CHECK_MILLIS, after / 2, staleAfter / 2))));
|
|
61
|
+
}).pipe(Effect.repeat(Schedule.spaced(Math.max(MIN_CHECK_MILLIS, Math.min(MAX_CHECK_MILLIS, after / 2, staleAfter / 2)))));
|
|
61
62
|
});
|
|
62
63
|
//#endregion
|
|
63
64
|
export { run, transcript };
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"summary.js","names":["AssistantEvent.isLibraryEvent","History.fromEntries"],"sources":["../../src/internal/summary.ts"],"sourcesContent":["import type * as Prompt from \"effect/ai/Prompt\"\nimport * as Clock from \"effect/Clock\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type * as StatusSummary from \"../StatusSummary.ts\"\nimport * as History from \"./history.ts\"\nimport * as Live from \"./live.ts\"\nimport { toJsonText } from \"./schema.ts\"\nimport type { Writer } from \"./writer.ts\"\n\nconst MAX_LINE = 300\n\nconst MAX_MESSAGES = 12\n\nconst clip = (text: string) => (text.length > MAX_LINE ? `${text.slice(0, MAX_LINE)}…` : text)\n\nconst assistantLines = (part: Prompt.AssistantMessagePart): ReadonlyArray<string> => {\n switch (part.type) {\n case \"text\":\n return [`Assistant: ${clip(part.text)}`]\n case \"tool-call\":\n return [`Assistant runs ${part.name} ${clip(toJsonText(part.params))}`]\n default:\n return []\n }\n}\n\nconst lines = (message: Prompt.Message): ReadonlyArray<string> => {\n switch (message.role) {\n case \"system\":\n return []\n case \"user\":\n return message.content.flatMap((part) => (part.type === \"text\" ? [`User: ${clip(part.text)}`] : []))\n case \"assistant\":\n return message.content.flatMap(assistantLines)\n case \"tool\":\n return message.content.flatMap((part) =>\n part.type === \"tool-result\"\n ? [`Result of ${part.name}: ${clip(Predicate.isString(part.result) ? part.result : toJsonText(part.result))}`]\n : []\n )\n }\n}\n\n// The calls started and not answered yet: what the assistant is doing right now.\nconst runningCalls = (entries: ReadonlyArray<AssistantEvent.AnyEntry>) => {\n const events = entries.flatMap(({ event }) => (AssistantEvent.isLibraryEvent(event) ? [event] : []))\n const answered = new Set(events.flatMap((event) => (Predicate.isTagged(event, \"ToolResult\") ? [event.callId] : [])))\n\n return events.flatMap((event) =>\n Predicate.isTagged(event, \"ToolStarted\") && !answered.has(event.callId) ? [event.tool] : []\n )\n}\n\n// The latest messages, as plain lines, and what still runs: the summary's model gets no tools, so no tool call parts.\n/** @internal */\nexport const transcript = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): string => {\n const running = runningCalls(entries)\n const lastLines = History.fromEntries(entries).slice(-MAX_MESSAGES).flatMap(lines)\n\n return [...lastLines, ...(running.length === 0 ? [] : [`Running now: ${running.join(\", \")}`])].join(\"\\n\")\n}\n\nconst lastSequence = (entries: ReadonlyArray<AssistantEvent.AnyEntry>) => entries.at(-1)?.sequence ?? 0\n\nconst isWork = (event: { readonly _tag: string }) =>\n Predicate.isTagged(event, \"TurnStarted\") ||\n Predicate.isTagged(event, \"ModelOutput\") ||\n Predicate.isTagged(event, \"ToolStarted\")\n\n// After a message the user is up to date: a summary shows again only for work the model started since, not for what a\n// handler does after its reply (a compaction, say).\nconst workingSinceMessage = (entries: ReadonlyArray<AssistantEvent.AnyEntry>) => {\n const message = entries.findLastIndex(({ event }) => Predicate.isTagged(event, \"AssistantMessage\"))\n\n return message === -1 || entries.slice(message + 1).some(({ event }) => isWork(event))\n}\n\nconst MAX_CHECK_MILLIS = 500\n\n// A line for a turn that shows nothing for a while, or whose line hasn't changed for longer: never while a described\n// call says what runs, or the model writes to the user, and only after something new happened.\n/** @internal */\nexport const run = Effect.fnUntraced(function* (\n summary: StatusSummary.StatusSummary[\"Service\"],\n live: Live.Live,\n chat: Writer\n) {\n const summarized = yield* Ref.make(-1)\n const after = Duration.toMillis(summary.after)\n const staleAfter = Duration.toMillis(summary.staleAfter)\n\n const tick = Effect.gen(function* () {\n const current = yield* live.state\n const entries = yield* chat.entries\n const through = lastSequence(entries)\n const waited = (yield* Clock.currentTimeMillis) - current.shownAt\n\n if (\n current.typing ||\n current.running.length > 0 ||\n waited < (current.shown === undefined ? after : staleAfter) ||\n through === (yield* Ref.get(summarized)) ||\n !workingSinceMessage(entries)\n ) {\n return\n }\n\n const written = yield* summary.summarize(transcript(entries))\n\n yield* Ref.set(summarized, through)\n\n if (Option.isSome(written)) yield* live.summarized(written.value)\n })\n\n // Often enough that a line is filled or refreshed close to when it's due.\n yield* tick.pipe(Effect.repeat(Schedule.spaced(Math.min(MAX_CHECK_MILLIS, after / 2, staleAfter / 2))))\n})\n"],"mappings":";;;;;;;;;;;AAeA,MAAM,WAAW;AAIjB,MAAM,QAAQ,SAAkB,KAAK,SAAS,WAAW,GAAG,KAAK,MAAM,GAAG,QAAQ,EAAE,KAAK;AAEzF,MAAM,kBAAkB,SAA6D;CACnF,QAAQ,KAAK,MAAb;EACE,KAAK,QACH,OAAO,CAAC,cAAc,KAAK,KAAK,IAAI,GAAG;EACzC,KAAK,aACH,OAAO,CAAC,kBAAkB,KAAK,KAAK,GAAG,KAAK,WAAW,KAAK,MAAM,CAAC,GAAG;EACxE,SACE,OAAO,CAAC;CACZ;AACF;AAEA,MAAM,SAAS,YAAmD;CAChE,QAAQ,QAAQ,MAAhB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zC,MAAM,uBAAuB,YAAoD;CAC/E,MAAM,UAAU,QAAQ,eAAe,EAAE,YAAY,UAAU,SAAS,OAAO,kBAAkB,CAAC;CAElG,OAAO,YAAY,MAAM,QAAQ,MAAM,UAAU,CAAC,CAAC,CAAC,MAAM,EAAE,YAAY,OAAO,KAAK,CAAC;AACvF;AAEA,MAAM,mBAAmB;;AAKzB,MAAa,MAAM,OAAO,WAAW,WACnC,SACA,MACA,MACA;CACA,MAAM,aAAa,OAAO,IAAI,KAAK,EAAE;CACrC,MAAM,QAAQ,SAAS,SAAS,QAAQ,KAAK;CAC7C,MAAM,aAAa,SAAS,SAAS,QAAQ,UAAU;CA0BvD,OAxBa,OAAO,IAAI,aAAa;EACnC,MAAM,UAAU,OAAO,KAAK;EAC5B,MAAM,UAAU,OAAO,KAAK;EAC5B,MAAM,UAAU,aAAa,OAAO;EACpC,MAAM,UAAU,OAAO,MAAM,qBAAqB,QAAQ;EAE1D,IACE,QAAQ,UACR,QAAQ,QAAQ,SAAS,KACzB,UAAU,QAAQ,UAAU,KAAA,IAAY,QAAQ,eAChD,aAAa,OAAO,IAAI,IAAI,UAAU,MACtC,CAAC,oBAAoB,OAAO,GAE5B;EAGF,MAAM,UAAU,OAAO,QAAQ,UAAU,WAAW,OAAO,CAAC;EAE5D,OAAO,IAAI,IAAI,YAAY,OAAO;EAElC,IAAI,OAAO,OAAO,OAAO,GAAG,OAAO,KAAK,WAAW,QAAQ,KAAK;CAClE,CAGU,CAAC,CAAC,
|
|
1
|
+
{"version":3,"file":"summary.js","names":["AssistantEvent.isLibraryEvent","History.fromEntries"],"sources":["../../src/internal/summary.ts"],"sourcesContent":["import type * as Prompt from \"effect/ai/Prompt\"\nimport * as Clock from \"effect/Clock\"\nimport * as Duration from \"effect/Duration\"\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Ref from \"effect/Ref\"\nimport * as Schedule from \"effect/Schedule\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type * as StatusSummary from \"../StatusSummary.ts\"\nimport * as History from \"./history.ts\"\nimport * as Live from \"./live.ts\"\nimport { toJsonText } from \"./schema.ts\"\nimport type { Writer } from \"./writer.ts\"\n\nconst MAX_LINE = 300\n\nconst MAX_MESSAGES = 12\n\nconst clip = (text: string) => (text.length > MAX_LINE ? `${text.slice(0, MAX_LINE)}…` : text)\n\nconst assistantLines = (part: Prompt.AssistantMessagePart): ReadonlyArray<string> => {\n switch (part.type) {\n case \"text\":\n return [`Assistant: ${clip(part.text)}`]\n case \"tool-call\":\n return [`Assistant runs ${part.name} ${clip(toJsonText(part.params))}`]\n default:\n return []\n }\n}\n\nconst lines = (message: Prompt.Message): ReadonlyArray<string> => {\n switch (message.role) {\n case \"system\":\n return []\n case \"user\":\n return message.content.flatMap((part) => (part.type === \"text\" ? [`User: ${clip(part.text)}`] : []))\n case \"assistant\":\n return message.content.flatMap(assistantLines)\n case \"tool\":\n return message.content.flatMap((part) =>\n part.type === \"tool-result\"\n ? [`Result of ${part.name}: ${clip(Predicate.isString(part.result) ? part.result : toJsonText(part.result))}`]\n : []\n )\n }\n}\n\n// The calls started and not answered yet: what the assistant is doing right now.\nconst runningCalls = (entries: ReadonlyArray<AssistantEvent.AnyEntry>) => {\n const events = entries.flatMap(({ event }) => (AssistantEvent.isLibraryEvent(event) ? [event] : []))\n const answered = new Set(events.flatMap((event) => (Predicate.isTagged(event, \"ToolResult\") ? [event.callId] : [])))\n\n return events.flatMap((event) =>\n Predicate.isTagged(event, \"ToolStarted\") && !answered.has(event.callId) ? [event.tool] : []\n )\n}\n\n// The latest messages, as plain lines, and what still runs: the summary's model gets no tools, so no tool call parts.\n/** @internal */\nexport const transcript = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): string => {\n const running = runningCalls(entries)\n const lastLines = History.fromEntries(entries).slice(-MAX_MESSAGES).flatMap(lines)\n\n return [...lastLines, ...(running.length === 0 ? [] : [`Running now: ${running.join(\", \")}`])].join(\"\\n\")\n}\n\nconst lastSequence = (entries: ReadonlyArray<AssistantEvent.AnyEntry>) => entries.at(-1)?.sequence ?? 0\n\nconst isWork = (event: { readonly _tag: string }) =>\n Predicate.isTagged(event, \"TurnStarted\") ||\n Predicate.isTagged(event, \"ModelOutput\") ||\n Predicate.isTagged(event, \"ToolStarted\")\n\n// After a message the user is up to date: a summary shows again only for work the model started since, not for what a\n// handler does after its reply (a compaction, say).\nconst workingSinceMessage = (entries: ReadonlyArray<AssistantEvent.AnyEntry>) => {\n const message = entries.findLastIndex(({ event }) => Predicate.isTagged(event, \"AssistantMessage\"))\n\n return message === -1 || entries.slice(message + 1).some(({ event }) => isWork(event))\n}\n\nconst MAX_CHECK_MILLIS = 500\n\nconst MIN_CHECK_MILLIS = 100\n\n// A line for a turn that shows nothing for a while, or whose line hasn't changed for longer: never while a described\n// call says what runs, or the model writes to the user, and only after something new happened.\n/** @internal */\nexport const run = Effect.fnUntraced(function* (\n summary: StatusSummary.StatusSummary[\"Service\"],\n live: Live.Live,\n chat: Writer\n) {\n const summarized = yield* Ref.make(-1)\n const after = Duration.toMillis(summary.after)\n const staleAfter = Duration.toMillis(summary.staleAfter)\n\n const tick = Effect.gen(function* () {\n const current = yield* live.state\n const entries = yield* chat.entries\n const through = lastSequence(entries)\n const waited = (yield* Clock.currentTimeMillis) - current.shownAt\n\n if (\n current.typing ||\n current.running.length > 0 ||\n waited < (current.shown === undefined ? after : staleAfter) ||\n through === (yield* Ref.get(summarized)) ||\n !workingSinceMessage(entries)\n ) {\n return\n }\n\n const written = yield* summary.summarize(transcript(entries))\n\n yield* Ref.set(summarized, through)\n\n if (Option.isSome(written)) yield* live.summarized(written.value)\n })\n\n // Often enough that a line is filled or refreshed close to when it's due.\n yield* tick.pipe(\n Effect.repeat(Schedule.spaced(Math.max(MIN_CHECK_MILLIS, Math.min(MAX_CHECK_MILLIS, after / 2, staleAfter / 2))))\n )\n})\n"],"mappings":";;;;;;;;;;;AAeA,MAAM,W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AAO;EAElC,IAAI,OAAO,OAAO,OAAO,GAAG,OAAO,KAAK,WAAW,QAAQ,KAAK;CAClE,CAGU,CAAC,CAAC,KACV,OAAO,OAAO,SAAS,OAAO,KAAK,IAAI,kBAAkB,KAAK,IAAI,kBAAkB,QAAQ,GAAG,aAAa,CAAC,CAAC,CAAC,CAAC,CAClH;AACF,CAAC"}
|
package/package.json
CHANGED
package/src/Timeline.ts
CHANGED
|
@@ -66,6 +66,8 @@ export const Block = Schema.Struct({
|
|
|
66
66
|
props: Schema.Json,
|
|
67
67
|
status: BlockStatus,
|
|
68
68
|
answer: Schema.optional(Schema.Json),
|
|
69
|
+
/** When the user answered, in epoch milliseconds, once the block is answered. */
|
|
70
|
+
answeredAt: Schema.optional(Schema.Finite),
|
|
69
71
|
/** For a block that shows a tool's result (`Block.fromToolResult`): the result, as the tool's success schema encodes it. */
|
|
70
72
|
result: Schema.optional(Schema.Json)
|
|
71
73
|
})
|
|
@@ -662,6 +664,7 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
|
|
|
662
664
|
let activity = AssistantActivity.empty
|
|
663
665
|
let live = noLive
|
|
664
666
|
let blocks: ReadonlyMap<string, BlockKit.State> = new Map()
|
|
667
|
+
const answeredAt = new Map<string, number>()
|
|
665
668
|
// The items in order, and the assistant's messages as stored: their blocks change as the chat goes on.
|
|
666
669
|
const items = new Map<string, AnyItem>()
|
|
667
670
|
const sent = new Map<string, AssistantEvent.AssistantMessage>()
|
|
@@ -678,7 +681,12 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
|
|
|
678
681
|
const result = resultId === undefined ? undefined : results.get(resultId)
|
|
679
682
|
const shown = result === undefined ? block : { ...block, result }
|
|
680
683
|
|
|
681
|
-
|
|
684
|
+
if (state?.answer === undefined) return shown
|
|
685
|
+
|
|
686
|
+
const answered = { ...shown, answer: toJson(state.answer.value) }
|
|
687
|
+
const at = answeredAt.get(message.id)
|
|
688
|
+
|
|
689
|
+
return at === undefined ? answered : { ...answered, answeredAt: at }
|
|
682
690
|
}
|
|
683
691
|
|
|
684
692
|
const itemOf = (message: AssistantEvent.AssistantMessage, at: number): AssistantMessage => {
|
|
@@ -845,6 +853,10 @@ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding =>
|
|
|
845
853
|
|
|
846
854
|
blocks = BlockKit.apply(blocks, event)
|
|
847
855
|
|
|
856
|
+
if (Predicate.isTagged(event, "BlockAnswer") && blocks.get(event.messageId)?.answer === event) {
|
|
857
|
+
answeredAt.set(event.messageId, entry.at)
|
|
858
|
+
}
|
|
859
|
+
|
|
848
860
|
const decidedBefore = approvals
|
|
849
861
|
approvals = ToolApproval.apply(approvals, entry)
|
|
850
862
|
|
package/src/ToolStatus.ts
CHANGED
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* short line about what the assistant is doing, like "Checking last summer's campaign budget".
|
|
4
4
|
*
|
|
5
5
|
* Mark the tools that take a while or act on something with {@link described}: workflows, reports
|
|
6
|
-
* from other systems, orders, specialists. The model then sees
|
|
6
|
+
* from other systems, orders, specialists. The model then sees a required `description` parameter
|
|
7
7
|
* on them and fills it in the chat's language. When the call starts, the chat sends the
|
|
8
8
|
* description as a `ChatSignal.Status`; it shows until the next status, so it stays after the call
|
|
9
9
|
* ends. The tool's handler never receives the parameter. Quick reads need no label: the chat shows its generic working state for
|
|
@@ -54,8 +54,9 @@ export const Described = Context.Reference<boolean>("effect-assistant/ToolStatus
|
|
|
54
54
|
*
|
|
55
55
|
* **Details**
|
|
56
56
|
*
|
|
57
|
-
* The model sees
|
|
58
|
-
* writes there while the call runs.
|
|
57
|
+
* The model sees a required `description` parameter on the tool, and the chat shows what it
|
|
58
|
+
* writes there while the call runs. Required, because models leave optional parameters out; a call
|
|
59
|
+
* without it still runs, with no status. The handler gets its parameters without it. A tool that has a
|
|
59
60
|
* parameter of that name already can't be marked: the loop stops with a defect when it offers one.
|
|
60
61
|
*
|
|
61
62
|
* **Example** (A slow report with a status)
|
package/src/internal/loop.ts
CHANGED
|
@@ -91,9 +91,8 @@ export interface StepResult {
|
|
|
91
91
|
// every tool's params, `unknown` for a schema of unknown type, though deferred validation encodes none.
|
|
92
92
|
type RequestTool = Tool.Tool<string, any, any>
|
|
93
93
|
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
)
|
|
94
|
+
// Required in what the model reads, so it writes one with every call; a call without it still runs.
|
|
95
|
+
const statusParameter = Schema.String.annotate({ description: ToolStatus.parameterDescription })
|
|
97
96
|
|
|
98
97
|
// What the model reads of a described tool: its parameters with the status one. Only the request has it; the call
|
|
99
98
|
// runs without it (see `withoutStatus`). A record of no keys (a tool without parameters) becomes an object with it.
|
package/src/internal/summary.ts
CHANGED
|
@@ -83,6 +83,8 @@ const workingSinceMessage = (entries: ReadonlyArray<AssistantEvent.AnyEntry>) =>
|
|
|
83
83
|
|
|
84
84
|
const MAX_CHECK_MILLIS = 500
|
|
85
85
|
|
|
86
|
+
const MIN_CHECK_MILLIS = 100
|
|
87
|
+
|
|
86
88
|
// A line for a turn that shows nothing for a while, or whose line hasn't changed for longer: never while a described
|
|
87
89
|
// call says what runs, or the model writes to the user, and only after something new happened.
|
|
88
90
|
/** @internal */
|
|
@@ -119,5 +121,7 @@ export const run = Effect.fnUntraced(function* (
|
|
|
119
121
|
})
|
|
120
122
|
|
|
121
123
|
// Often enough that a line is filled or refreshed close to when it's due.
|
|
122
|
-
yield* tick.pipe(
|
|
124
|
+
yield* tick.pipe(
|
|
125
|
+
Effect.repeat(Schedule.spaced(Math.max(MIN_CHECK_MILLIS, Math.min(MAX_CHECK_MILLIS, after / 2, staleAfter / 2))))
|
|
126
|
+
)
|
|
123
127
|
})
|