effect-assistant 0.1.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (131) hide show
  1. package/README.md +1 -1
  2. package/dist/Assistant.d.ts +74 -28
  3. package/dist/Assistant.d.ts.map +1 -1
  4. package/dist/Assistant.js +11 -4
  5. package/dist/Assistant.js.map +1 -1
  6. package/dist/AssistantActivity.d.ts +10 -16
  7. package/dist/AssistantActivity.d.ts.map +1 -1
  8. package/dist/AssistantActivity.js +11 -4
  9. package/dist/AssistantActivity.js.map +1 -1
  10. package/dist/AssistantEngine.d.ts +39 -1
  11. package/dist/AssistantEngine.d.ts.map +1 -1
  12. package/dist/AssistantEngine.js +81 -28
  13. package/dist/AssistantEngine.js.map +1 -1
  14. package/dist/AssistantEvent.d.ts +52 -70
  15. package/dist/AssistantEvent.d.ts.map +1 -1
  16. package/dist/AssistantEvent.js +28 -57
  17. package/dist/AssistantEvent.js.map +1 -1
  18. package/dist/AssistantLoop.d.ts +7 -5
  19. package/dist/AssistantLoop.d.ts.map +1 -1
  20. package/dist/AssistantLoop.js +6 -3
  21. package/dist/AssistantLoop.js.map +1 -1
  22. package/dist/Block.js.map +1 -1
  23. package/dist/BlockKit.d.ts +14 -18
  24. package/dist/BlockKit.d.ts.map +1 -1
  25. package/dist/BlockKit.js +4 -7
  26. package/dist/BlockKit.js.map +1 -1
  27. package/dist/ChatLog.js +1 -1
  28. package/dist/Compaction.d.ts +8 -4
  29. package/dist/Compaction.d.ts.map +1 -1
  30. package/dist/Compaction.js +12 -15
  31. package/dist/Compaction.js.map +1 -1
  32. package/dist/CurrentChat.d.ts +2 -1
  33. package/dist/CurrentChat.d.ts.map +1 -1
  34. package/dist/CurrentChat.js.map +1 -1
  35. package/dist/Instructions.js +1 -1
  36. package/dist/Skill.d.ts +33 -0
  37. package/dist/Skill.d.ts.map +1 -1
  38. package/dist/Skill.js +27 -1
  39. package/dist/Skill.js.map +1 -1
  40. package/dist/Specialist.d.ts +4 -1
  41. package/dist/Specialist.d.ts.map +1 -1
  42. package/dist/Specialist.js.map +1 -1
  43. package/dist/Timeline.d.ts +482 -0
  44. package/dist/Timeline.d.ts.map +1 -0
  45. package/dist/Timeline.js +572 -0
  46. package/dist/Timeline.js.map +1 -0
  47. package/dist/ToolDiscovery.d.ts +4 -5
  48. package/dist/ToolDiscovery.d.ts.map +1 -1
  49. package/dist/ToolDiscovery.js +5 -4
  50. package/dist/ToolDiscovery.js.map +1 -1
  51. package/dist/ToolFailure.d.ts +1 -1
  52. package/dist/ToolFailure.js +1 -1
  53. package/dist/ToolFailure.js.map +1 -1
  54. package/dist/index.d.ts +2 -5
  55. package/dist/index.js +4 -7
  56. package/dist/internal/chat.js +11 -37
  57. package/dist/internal/chat.js.map +1 -1
  58. package/dist/internal/events.d.ts +15 -16
  59. package/dist/internal/events.d.ts.map +1 -1
  60. package/dist/internal/events.js +29 -28
  61. package/dist/internal/events.js.map +1 -1
  62. package/dist/internal/history.js +26 -58
  63. package/dist/internal/history.js.map +1 -1
  64. package/dist/internal/input.js +7 -0
  65. package/dist/internal/input.js.map +1 -0
  66. package/dist/internal/loop.d.ts +2 -2
  67. package/dist/internal/loop.d.ts.map +1 -1
  68. package/dist/internal/loop.js +21 -56
  69. package/dist/internal/loop.js.map +1 -1
  70. package/dist/internal/skills.js +6 -1
  71. package/dist/internal/skills.js.map +1 -1
  72. package/dist/internal/specialists.js +7 -7
  73. package/dist/internal/specialists.js.map +1 -1
  74. package/dist/internal/toolkit.d.ts +6 -20
  75. package/dist/internal/toolkit.d.ts.map +1 -1
  76. package/dist/internal/toolkit.js +10 -31
  77. package/dist/internal/toolkit.js.map +1 -1
  78. package/dist/internal/tools.js +2 -21
  79. package/dist/internal/tools.js.map +1 -1
  80. package/dist/internal/turns.d.ts.map +1 -1
  81. package/dist/internal/turns.js +24 -43
  82. package/dist/internal/turns.js.map +1 -1
  83. package/package.json +3 -2
  84. package/src/Assistant.ts +75 -29
  85. package/src/AssistantActivity.ts +11 -18
  86. package/src/AssistantEngine.ts +110 -43
  87. package/src/AssistantEvent.ts +46 -74
  88. package/src/AssistantLoop.ts +7 -5
  89. package/src/Block.ts +1 -1
  90. package/src/BlockKit.ts +18 -31
  91. package/src/Compaction.ts +8 -21
  92. package/src/CurrentChat.ts +2 -1
  93. package/src/Skill.ts +34 -1
  94. package/src/Specialist.ts +4 -1
  95. package/src/Timeline.ts +861 -0
  96. package/src/ToolDiscovery.ts +5 -13
  97. package/src/ToolFailure.ts +1 -1
  98. package/src/index.ts +5 -20
  99. package/src/internal/chat.ts +8 -57
  100. package/src/internal/events.ts +43 -43
  101. package/src/internal/history.ts +36 -101
  102. package/src/internal/input.ts +3 -0
  103. package/src/internal/loop.ts +31 -101
  104. package/src/internal/skills.ts +11 -0
  105. package/src/internal/specialists.ts +6 -9
  106. package/src/internal/toolkit.ts +17 -60
  107. package/src/internal/tools.ts +2 -53
  108. package/src/internal/turns.ts +37 -79
  109. package/dist/AppEvent.d.ts +0 -111
  110. package/dist/AppEvent.d.ts.map +0 -1
  111. package/dist/AppEvent.js +0 -71
  112. package/dist/AppEvent.js.map +0 -1
  113. package/dist/ChatView.d.ts +0 -459
  114. package/dist/ChatView.d.ts.map +0 -1
  115. package/dist/ChatView.js +0 -496
  116. package/dist/ChatView.js.map +0 -1
  117. package/dist/Decision.d.ts +0 -145
  118. package/dist/Decision.d.ts.map +0 -1
  119. package/dist/Decision.js +0 -178
  120. package/dist/Decision.js.map +0 -1
  121. package/dist/DecisionId.d.ts +0 -37
  122. package/dist/DecisionId.d.ts.map +0 -1
  123. package/dist/DecisionId.js +0 -44
  124. package/dist/DecisionId.js.map +0 -1
  125. package/dist/internal/decisions.js +0 -66
  126. package/dist/internal/decisions.js.map +0 -1
  127. package/src/AppEvent.ts +0 -134
  128. package/src/ChatView.ts +0 -658
  129. package/src/Decision.ts +0 -241
  130. package/src/DecisionId.ts +0 -46
  131. package/src/internal/decisions.ts +0 -131
@@ -0,0 +1,861 @@
1
+ /**
2
+ * This module provides a chat's timeline: the chat as its user sees it. A chat client receives the
3
+ * timeline and nothing else.
4
+ *
5
+ * A {@link Timeline} holds the chat's items: the messages with their blocks, and the app's own
6
+ * events it shows (each typed with its event, see {@link EventItem}). It also holds the chat's
7
+ * {@link Activity}, and whether the last turn failed or the chat was deleted. It never contains the
8
+ * model's output, tool calls or results, what the model read, or why a turn failed. The server
9
+ * streams {@link Change}s by piping the assistant's `subscribe` through {@link changes}, and the
10
+ * client folds them with {@link fold} (or {@link apply}, from {@link empty}). On the server,
11
+ * {@link fromEntries} builds a whole timeline from a chat's log, and {@link snapshot} the whole
12
+ * timeline as one change.
13
+ *
14
+ * **Only the app events in `show` reach the timeline**, and none by default: an event that is only
15
+ * for the assistant, like a summary of the chat, stays out. The RPC's schema, `Change([...])`,
16
+ * names the same events and types the client's timeline with them.
17
+ *
18
+ * @since 0.3.0
19
+ */
20
+ import { dual } from "effect/Function"
21
+ import * as Match from "effect/Match"
22
+ import * as Option from "effect/Option"
23
+ import * as Schema from "effect/Schema"
24
+ import * as SchemaTransformation from "effect/SchemaTransformation"
25
+ import * as Stream from "effect/Stream"
26
+ import type * as Assistant from "./Assistant.ts"
27
+ import * as AssistantActivity from "./AssistantActivity.ts"
28
+ import * as AssistantEvent from "./AssistantEvent.ts"
29
+ import * as BlockKit from "./BlockKit.ts"
30
+ import { InputId } from "./InputId.ts"
31
+ import * as AppEvents from "./internal/events.ts"
32
+ import { toJson } from "./internal/schema.ts"
33
+
34
+ /**
35
+ * Schema for the status of a block. A block is `"open"` while it accepts an answer, `"answered"`
36
+ * once the user has used it, and `"closed"` when it closed without an answer because the user
37
+ * answered in words or moved on.
38
+ *
39
+ * @category schemas
40
+ * @since 0.1.0
41
+ */
42
+ export const BlockStatus = Schema.Literals(["open", "answered", "closed"])
43
+
44
+ /**
45
+ * The status of a block.
46
+ *
47
+ * @category models
48
+ * @since 0.1.0
49
+ */
50
+ export type BlockStatus = typeof BlockStatus.Type
51
+
52
+ /**
53
+ * Schema for a block on an assistant's message. It holds the block's kind, its props (JSON, as
54
+ * the block's props schema encodes them), its status, and the user's answer (JSON, as the block's
55
+ * answer schema encodes it).
56
+ *
57
+ * @category schemas
58
+ * @since 0.1.0
59
+ */
60
+ export const Block = Schema.Struct({
61
+ kind: Schema.String,
62
+ props: Schema.Json,
63
+ status: BlockStatus,
64
+ answer: Schema.optional(Schema.Json)
65
+ })
66
+
67
+ /**
68
+ * Represents a block on an assistant's message.
69
+ *
70
+ * @category models
71
+ * @since 0.1.0
72
+ */
73
+ export type Block = typeof Block.Type
74
+
75
+ /**
76
+ * Schema for a message the user sent. `at` is when it was stored, in epoch
77
+ * milliseconds.
78
+ *
79
+ * @category schemas
80
+ * @since 0.1.0
81
+ */
82
+ export const UserMessage = Schema.TaggedStruct("UserMessage", {
83
+ id: InputId,
84
+ text: Schema.String,
85
+ attachments: Schema.optional(Schema.Array(AssistantEvent.Attachment)),
86
+ at: Schema.Finite
87
+ })
88
+
89
+ /**
90
+ * Represents a message the user sent.
91
+ *
92
+ * @category models
93
+ * @since 0.1.0
94
+ */
95
+ export type UserMessage = typeof UserMessage.Type
96
+
97
+ /**
98
+ * Schema for a message the assistant sent the user, including its block if it has one.
99
+ *
100
+ * @category schemas
101
+ * @since 0.1.0
102
+ */
103
+ export const AssistantMessage = Schema.TaggedStruct("AssistantMessage", {
104
+ id: Schema.String,
105
+ text: Schema.String,
106
+ at: Schema.Finite,
107
+ block: Schema.optional(Block)
108
+ })
109
+
110
+ /**
111
+ * Represents a message the assistant sent the user.
112
+ *
113
+ * @category models
114
+ * @since 0.1.0
115
+ */
116
+ export type AssistantMessage = typeof AssistantMessage.Type
117
+
118
+ /**
119
+ * Represents one of the app's own events in the timeline: an item between the messages, in the
120
+ * order the chat stored it.
121
+ *
122
+ * **Details**
123
+ *
124
+ * The item's `_tag` is the event's, so a match over a timeline's items takes a handler per event
125
+ * beside `UserMessage` and `AssistantMessage`. The event, decoded with its schema, is in `event`,
126
+ * and the item's own fields sit beside it rather than spread into it: an event may have an `id` or
127
+ * an `at` of its own, and a class instance keeps its prototype. `id` is fixed per entry of the
128
+ * chat's log, and `at` is when the event was stored, in epoch milliseconds.
129
+ *
130
+ * @category models
131
+ * @since 0.3.0
132
+ */
133
+ export type EventItem<E> = E extends { readonly _tag: infer Tag extends string }
134
+ ? { readonly _tag: Tag; readonly id: string; readonly at: number; readonly event: E }
135
+ : never
136
+
137
+ /**
138
+ * Represents an item in the chat's timeline: a message the user or the assistant sent, or one of
139
+ * the app's own events it shows (see {@link EventItem}).
140
+ *
141
+ * **Example** (Showing each item of a chat)
142
+ *
143
+ * ```ts
144
+ * import { Timeline } from "effect-assistant"
145
+ * import * as Match from "effect/Match"
146
+ * import * as Schema from "effect/Schema"
147
+ *
148
+ * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()("DailyBudgetReached", {}) {}
149
+ *
150
+ * const line = (item: Timeline.Item<DailyBudgetReached>) =>
151
+ * Match.valueTags(item, {
152
+ * UserMessage: (sent) => `You: ${sent.text}`,
153
+ * AssistantMessage: (sent) => `Assistant: ${sent.text}`,
154
+ * DailyBudgetReached: () => "You've reached today's budget."
155
+ * })
156
+ * ```
157
+ *
158
+ * @category models
159
+ * @since 0.3.0
160
+ */
161
+ export type Item<Events = never> = UserMessage | AssistantMessage | EventItem<Events>
162
+
163
+ /**
164
+ * Schema for a specialist that is working for the assistant. It holds the specialist's name and
165
+ * when it started, in epoch milliseconds.
166
+ *
167
+ * @category schemas
168
+ * @since 0.1.0
169
+ */
170
+ export const SpecialistWorking = Schema.Struct({
171
+ specialist: Schema.String,
172
+ since: Schema.Finite
173
+ })
174
+
175
+ /**
176
+ * Represents a specialist that is working for the assistant.
177
+ *
178
+ * @category models
179
+ * @since 0.1.0
180
+ */
181
+ export type SpecialistWorking = typeof SpecialistWorking.Type
182
+
183
+ /**
184
+ * Schema for what is working in the chat.
185
+ *
186
+ * `working` is true while the assistant runs a turn, or when a turn is about to start for
187
+ * something that arrived. `specialists` lists the specialists that are working. When the chat is
188
+ * idle, nothing is working, even if a workflow is waiting on a timer or on the user.
189
+ *
190
+ * @category schemas
191
+ * @since 0.1.0
192
+ */
193
+ export const Activity = Schema.Struct({
194
+ working: Schema.Boolean,
195
+ specialists: Schema.Array(SpecialistWorking)
196
+ })
197
+
198
+ /**
199
+ * Represents what is working in the chat.
200
+ *
201
+ * @category models
202
+ * @since 0.1.0
203
+ */
204
+ export type Activity = typeof Activity.Type
205
+
206
+ /**
207
+ * Represents a chat's timeline: the chat as its user sees it, typed with the app's events it shows.
208
+ * It holds the chat's items in order, what is working in it, whether the last turn failed, and
209
+ * whether the chat was deleted. `seq` is the position in the chat's log that the timeline is up to.
210
+ *
211
+ * @category models
212
+ * @since 0.3.0
213
+ */
214
+ export interface Timeline<Events = never> {
215
+ readonly seq: number
216
+ readonly items: ReadonlyArray<Item<Events>>
217
+ readonly activity: Activity
218
+ /** Whether the last turn failed with no message after it. */
219
+ readonly failed: boolean
220
+ /** Whether the chat was deleted. A deleted chat accepts nothing more, and its stream ends. */
221
+ readonly deleted: boolean
222
+ }
223
+
224
+ /**
225
+ * Represents a change to a chat's timeline, typed with the app's events it shows.
226
+ *
227
+ * **Details**
228
+ *
229
+ * A change holds each item that is new or changed (for example, a message whose block was
230
+ * answered or closed), in full. It also holds the current activity, whether the last turn failed,
231
+ * and whether the chat was deleted. `seq` is the position in the chat's log that the change is up
232
+ * to.
233
+ *
234
+ * @category models
235
+ * @since 0.3.0
236
+ */
237
+ export interface Change<Events = never> {
238
+ readonly seq: number
239
+ readonly items: ReadonlyArray<Item<Events>>
240
+ readonly activity: Activity
241
+ readonly failed: boolean
242
+ readonly deleted: boolean
243
+ }
244
+
245
+ const eventItem = (schema: AssistantEvent.AppEventSchema) =>
246
+ Schema.Struct({ _tag: Schema.Literal(AppEvents.tagOf(schema)), id: Schema.String, at: Schema.Finite, event: schema })
247
+
248
+ function makeChange<const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(
249
+ events?: Events
250
+ ): Schema.Codec<Change<Events[number]["Type"]>, Schema.Json>
251
+ // The overload states the decoded type: an item per given schema, each typed with its own event.
252
+ function makeChange(events: ReadonlyArray<AssistantEvent.AppEventSchema> = []): Schema.Top {
253
+ const AnyItem = Schema.toCodecJson(Schema.Union([UserMessage, AssistantMessage, ...events.map(eventItem)]))
254
+ const decodeItem = Schema.decodeUnknownOption(AnyItem)
255
+ const encodeItem = Schema.encodeUnknownSync(AnyItem)
256
+
257
+ return Schema.Struct({
258
+ seq: Schema.Int,
259
+ // An item for an event this schema doesn't name, or that doesn't decode (from a newer server, say), is left out
260
+ // rather than failing the whole change.
261
+ items: Schema.Array(Schema.Json).pipe(
262
+ Schema.decodeTo(
263
+ Schema.Array(Schema.toType(AnyItem)),
264
+ SchemaTransformation.transform<ReadonlyArray<typeof AnyItem.Type>, ReadonlyArray<Schema.Json>>({
265
+ decode: (json) => json.flatMap((item) => Option.toArray(decodeItem(item))),
266
+ encode: (items) => items.map((item) => encodeItem(item))
267
+ })
268
+ )
269
+ ),
270
+ activity: Activity,
271
+ failed: Schema.Boolean,
272
+ deleted: Schema.Boolean
273
+ })
274
+ }
275
+
276
+ /**
277
+ * Creates the schema for the changes to a chat's timeline, with items for the given app events,
278
+ * in JSON.
279
+ *
280
+ * **Details**
281
+ *
282
+ * It is the success schema of the RPC that streams a chat's timeline: name the events the chat's
283
+ * users see, the same ones the handler passes to {@link changes} as `show`. Each item decodes its
284
+ * event with that event's schema, so the client gets `Change<Events>` typed with them and folds it
285
+ * with {@link fold}, no definition needed. `Change()` carries no app events.
286
+ *
287
+ * A handler whose changes show an event the schema doesn't name doesn't compile.
288
+ *
289
+ * **Example** (An RPC that streams a chat's timeline, with the budget notice)
290
+ *
291
+ * ```ts
292
+ * import { ChatId, Timeline } from "effect-assistant"
293
+ * import * as Rpc from "effect/rpc/Rpc"
294
+ * import * as Schema from "effect/Schema"
295
+ *
296
+ * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()("DailyBudgetReached", {}) {}
297
+ *
298
+ * const Subscribe = Rpc.make("Subscribe", {
299
+ * payload: { chatId: ChatId.ChatId },
300
+ * success: Timeline.Change([DailyBudgetReached]),
301
+ * stream: true
302
+ * })
303
+ * ```
304
+ *
305
+ * @category schemas
306
+ * @since 0.3.0
307
+ */
308
+ export const Change: <const Events extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []>(
309
+ events?: Events
310
+ ) => Schema.Codec<Change<Events[number]["Type"]>, Schema.Json> = makeChange
311
+
312
+ /**
313
+ * The timeline of a chat before anything has happened in it, with no items and nothing working.
314
+ * Use it as the starting point when folding changes with {@link apply}.
315
+ *
316
+ * @category constructors
317
+ * @since 0.1.0
318
+ */
319
+ export const empty: Timeline = {
320
+ seq: 0,
321
+ items: [],
322
+ activity: { working: false, specialists: [] },
323
+ failed: false,
324
+ deleted: false
325
+ }
326
+
327
+ /**
328
+ * Returns the timeline after a change.
329
+ *
330
+ * **Details**
331
+ *
332
+ * Each item in the change replaces the item with the same id, in place, and new items are added
333
+ * after the rest. The change's activity, `failed`, and `deleted` replace the timeline's. Applying a
334
+ * change twice changes nothing, so a client that resubscribes from the start can fold again and get
335
+ * the same timeline.
336
+ *
337
+ * The timeline is typed with the change's events, as its RPC's schema decoded them (see
338
+ * {@link Change}). To fold a stream of changes, use {@link fold}: in
339
+ * `Stream.scan(() => Timeline.empty, Timeline.apply)`, TypeScript fixes the state's type from
340
+ * `empty` before it sees the changes' events, so that form needs the timeline's type written out.
341
+ *
342
+ * **Example** (Folding changes into your own state)
343
+ *
344
+ * ```ts
345
+ * import { Timeline } from "effect-assistant"
346
+ *
347
+ * interface State<Events> {
348
+ * readonly timeline: Timeline.Timeline<Events>
349
+ * readonly unread: number
350
+ * }
351
+ *
352
+ * const next = <Events>(state: State<Events>, change: Timeline.Change<Events>): State<Events> => ({
353
+ * timeline: Timeline.apply(state.timeline, change),
354
+ * unread: state.unread + change.items.length
355
+ * })
356
+ * ```
357
+ *
358
+ * @category combinators
359
+ * @since 0.1.0
360
+ */
361
+ export const apply = <Events>(timeline: Timeline<Events>, change: Change<Events>): Timeline<Events> => {
362
+ const changed = new Map(change.items.map((item) => [item.id, item]))
363
+ const known = new Set(timeline.items.map((item) => item.id))
364
+
365
+ return {
366
+ seq: Math.max(timeline.seq, change.seq),
367
+ items: [
368
+ ...timeline.items.map((item) => changed.get(item.id) ?? item),
369
+ ...change.items.filter((item) => !known.has(item.id))
370
+ ],
371
+ activity: change.activity,
372
+ failed: change.failed,
373
+ deleted: change.deleted
374
+ }
375
+ }
376
+
377
+ /**
378
+ * Returns the timelines a stream of changes folds to, from {@link empty}, typed with the changes'
379
+ * events.
380
+ *
381
+ * **Example** (A chat's timeline on the client)
382
+ *
383
+ * ```ts
384
+ * import { Timeline } from "effect-assistant"
385
+ * import * as Schema from "effect/Schema"
386
+ * import * as Stream from "effect/Stream"
387
+ *
388
+ * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()("DailyBudgetReached", {}) {}
389
+ *
390
+ * // The stream of an RPC whose success schema is `Timeline.Change([DailyBudgetReached])`.
391
+ * declare const changes: Stream.Stream<Timeline.Change<DailyBudgetReached>>
392
+ *
393
+ * const timelines = changes.pipe(Timeline.fold) // Stream<Timeline.Timeline<DailyBudgetReached>>
394
+ * ```
395
+ *
396
+ * @category combinators
397
+ * @since 0.3.0
398
+ */
399
+ export const fold = <Events, E, R>(
400
+ changes: Stream.Stream<Change<Events>, E, R>
401
+ ): Stream.Stream<Timeline<Events>, E, R> => changes.pipe(Stream.scan((): Timeline<Events> => empty, apply))
402
+
403
+ /**
404
+ * Returns whether nothing is working in the chat: no turn is running or about to start, and no
405
+ * specialist is working.
406
+ *
407
+ * @category guards
408
+ * @since 0.1.0
409
+ */
410
+ export const isIdle = <Events>(timeline: Timeline<Events>): boolean =>
411
+ !timeline.activity.working && timeline.activity.specialists.length === 0
412
+
413
+ interface AnyEventItem {
414
+ readonly _tag: string
415
+ readonly id: string
416
+ readonly at: number
417
+ readonly event: { readonly _tag: string }
418
+ }
419
+
420
+ // What the fold below builds: the overloads that use it type its items with the events shown.
421
+ interface AnyChange {
422
+ readonly seq: number
423
+ readonly items: ReadonlyArray<UserMessage | AssistantMessage | AnyEventItem>
424
+ readonly activity: Activity
425
+ readonly failed: boolean
426
+ readonly deleted: boolean
427
+ }
428
+
429
+ /**
430
+ * Represents the options for building a chat's timeline from its log.
431
+ *
432
+ * @category models
433
+ * @since 0.3.0
434
+ */
435
+ export interface ShowOptions<Show extends ReadonlyArray<AssistantEvent.AppEventSchema>> {
436
+ /**
437
+ * The schemas of the app's events the chat's users see. Each becomes an item in the timeline;
438
+ * the app's other events are left out. Defaults to none.
439
+ */
440
+ readonly show?: Show | undefined
441
+ }
442
+
443
+ /**
444
+ * Represents the schemas an assistant's timeline may show: some of its own events.
445
+ *
446
+ * @category utility types
447
+ * @since 0.3.0
448
+ */
449
+ export type Shown<Events> = ReadonlyArray<AssistantEvent.AppEventSchema & { readonly Type: Events }>
450
+
451
+ function snapshotWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change
452
+ function snapshotWith<Events, const Show extends Shown<Events> = readonly []>(
453
+ entries: ReadonlyArray<AssistantEvent.AnyEntry>,
454
+ definition: Definition<Events>,
455
+ options?: ShowOptions<Show>
456
+ ): Change<Show[number]["Type"]>
457
+ function snapshotWith(
458
+ entries: ReadonlyArray<AssistantEvent.AnyEntry>,
459
+ _definition?: Schemas,
460
+ options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>
461
+ ): AnyChange {
462
+ const timeline = folding(options?.show ?? [])
463
+
464
+ for (const entry of entries) timeline.step(entry)
465
+
466
+ return timeline.snapshot
467
+ }
468
+
469
+ /**
470
+ * Returns a chat's whole timeline as one change, built from the entries of its log.
471
+ *
472
+ * **When to use**
473
+ *
474
+ * Use it on the server for an RPC that returns a whole chat at once: its success schema is
475
+ * {@link Change} with the same events as `show`, and the client applies it to {@link empty}.
476
+ *
477
+ * **Details**
478
+ *
479
+ * Only the app's events in `show` become items; without it, the timeline has none.
480
+ *
481
+ * @category constructors
482
+ * @since 0.3.0
483
+ */
484
+ export const snapshot: {
485
+ (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Change
486
+ <Events, const Show extends Shown<Events> = readonly []>(
487
+ entries: ReadonlyArray<AssistantEvent.AnyEntry>,
488
+ definition: Definition<Events>,
489
+ options?: ShowOptions<Show>
490
+ ): Change<Show[number]["Type"]>
491
+ } = snapshotWith
492
+
493
+ function fromEntriesWith(entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline
494
+ function fromEntriesWith<Events, const Show extends Shown<Events> = readonly []>(
495
+ entries: ReadonlyArray<AssistantEvent.AnyEntry>,
496
+ definition: Definition<Events>,
497
+ options?: ShowOptions<Show>
498
+ ): Timeline<Show[number]["Type"]>
499
+ function fromEntriesWith(
500
+ entries: ReadonlyArray<AssistantEvent.AnyEntry>,
501
+ _definition?: Schemas,
502
+ options?: ShowOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>
503
+ ): AnyChange {
504
+ const timeline = folding(options?.show ?? [])
505
+
506
+ for (const entry of entries) timeline.step(entry)
507
+
508
+ return timeline.snapshot
509
+ }
510
+
511
+ /**
512
+ * Returns a chat's timeline, built from the entries of its log.
513
+ *
514
+ * **When to use**
515
+ *
516
+ * Use it in server-side code that reads a whole chat. A client gets the timeline as a stream from
517
+ * {@link changes} instead, and an RPC that returns a whole chat sends a {@link snapshot}.
518
+ *
519
+ * **Details**
520
+ *
521
+ * Only the app's events in `show` become items, typed with their schemas; without it, the timeline
522
+ * has none.
523
+ *
524
+ * **Example** (Building a chat's timeline from its log)
525
+ *
526
+ * ```ts
527
+ * import { type ChatId, ChatLog, Timeline } from "effect-assistant"
528
+ * import * as Effect from "effect/Effect"
529
+ *
530
+ * const timelineOf = (chatId: ChatId.ChatId) =>
531
+ * ChatLog.ChatLog.use((log) => log.read(chatId)).pipe(
532
+ * Effect.map((entries) => Timeline.fromEntries(entries))
533
+ * )
534
+ * ```
535
+ *
536
+ * @see {@link changes} for a stream of changes instead of a whole timeline
537
+ *
538
+ * @category constructors
539
+ * @since 0.1.0
540
+ */
541
+ export const fromEntries: {
542
+ (entries: ReadonlyArray<AssistantEvent.AnyEntry>): Timeline
543
+ <Events, const Show extends Shown<Events> = readonly []>(
544
+ entries: ReadonlyArray<AssistantEvent.AnyEntry>,
545
+ definition: Definition<Events>,
546
+ options?: ShowOptions<Show>
547
+ ): Timeline<Show[number]["Type"]>
548
+ } = fromEntriesWith
549
+
550
+ interface Schemas {
551
+ readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>
552
+ }
553
+
554
+ interface Folding {
555
+ readonly step: (entry: AssistantEvent.AnyEntry) => AnyChange | undefined
556
+ readonly snapshot: AnyChange
557
+ }
558
+
559
+ const activityOf = (activity: AssistantActivity.State): Activity => ({
560
+ working: activity.turnSince !== undefined || activity.queued,
561
+ specialists: [...activity.specialists.values()].map((run) => ({
562
+ specialist: run.specialist,
563
+ since: run.since
564
+ }))
565
+ })
566
+
567
+ const sameActivity = (a: Activity, b: Activity) =>
568
+ a.working === b.working &&
569
+ a.specialists.length === b.specialists.length &&
570
+ a.specialists.every((run, i) => {
571
+ const other = b.specialists[i]
572
+
573
+ return other !== undefined && run.specialist === other.specialist && run.since === other.since
574
+ })
575
+
576
+ const folding = (show: ReadonlyArray<AssistantEvent.AppEventSchema>): Folding => {
577
+ const shown = new Map(show.map((schema) => [AppEvents.tagOf(schema), schema]))
578
+ let seq = 0
579
+ let failed = false
580
+ let deleted = false
581
+ let activity = AssistantActivity.empty
582
+ let blocks: ReadonlyMap<string, BlockKit.State> = new Map()
583
+ // The items in order, and the assistant's messages as stored: their blocks change as the chat goes on.
584
+ const items = new Map<string, UserMessage | AssistantMessage | AnyEventItem>()
585
+ const sent = new Map<string, AssistantEvent.AssistantMessage>()
586
+
587
+ const blockOf = (message: AssistantEvent.AssistantMessage): Block | undefined => {
588
+ if (message.block === undefined) return undefined
589
+
590
+ const state = blocks.get(message.id)
591
+ const status = state === undefined || state.open ? "open" : state.answer === undefined ? "closed" : "answered"
592
+ const block: Block = { kind: message.block.kind, props: toJson(message.block.props), status }
593
+
594
+ return state?.answer === undefined ? block : { ...block, answer: toJson(state.answer.value) }
595
+ }
596
+
597
+ const itemOf = (message: AssistantEvent.AssistantMessage, at: number): AssistantMessage => {
598
+ const block = blockOf(message)
599
+
600
+ return block === undefined
601
+ ? AssistantMessage.make({ id: message.id, text: message.text, at })
602
+ : AssistantMessage.make({ id: message.id, text: message.text, at, block })
603
+ }
604
+
605
+ const touched = (event: AssistantEvent.AssistantEvent, at: number): ReadonlyArray<string> =>
606
+ Match.value(event).pipe(
607
+ Match.tagsExhaustive({
608
+ UserMessage: (message) => {
609
+ items.set(
610
+ message.id,
611
+ message.attachments === undefined
612
+ ? UserMessage.make({ id: message.id, text: message.text, at })
613
+ : UserMessage.make({
614
+ id: message.id,
615
+ text: message.text,
616
+ attachments: message.attachments,
617
+ at
618
+ })
619
+ )
620
+ failed = false
621
+
622
+ return [message.id]
623
+ },
624
+ AssistantMessage: (message) => {
625
+ sent.set(message.id, message)
626
+ items.set(message.id, itemOf(message, at))
627
+ failed = false
628
+
629
+ return [message.id, ...(message.closes ?? [])]
630
+ },
631
+ BlockAnswer: (answer) => {
632
+ failed = false
633
+
634
+ return [answer.messageId]
635
+ },
636
+ BlocksClosed: (closed) => closed.messageIds,
637
+ TurnFailed: () => {
638
+ failed = true
639
+
640
+ return []
641
+ },
642
+ ModelOutput: () => [],
643
+ ToolStarted: () => [],
644
+ ToolResult: () => [],
645
+ TurnStarted: () => [],
646
+ TurnCompleted: () => [],
647
+ SpecialistStarted: () => [],
648
+ SpecialistFinished: () => [],
649
+ ChatDeleted: () => {
650
+ deleted = true
651
+
652
+ return []
653
+ }
654
+ })
655
+ )
656
+
657
+ // Decoded as `subscribe` streams it, or as the log stores it; one that doesn't decode is left out.
658
+ const eventItemOf = (entry: AssistantEvent.AnyEntry): Option.Option<AnyEventItem> => {
659
+ const schema = shown.get(entry.event._tag)
660
+
661
+ if (schema === undefined) return Option.none()
662
+
663
+ const event = Schema.is(schema)(entry.event) ? Option.some(entry.event) : AppEvents.decodeWith(schema, entry.event)
664
+
665
+ return Option.map(event, (decoded) => ({
666
+ _tag: decoded._tag,
667
+ id: `app-event:${entry.seq}`,
668
+ at: entry.at,
669
+ event: decoded
670
+ }))
671
+ }
672
+
673
+ const step = (entry: AssistantEvent.AnyEntry): AnyChange | undefined => {
674
+ const before = { activity: activityOf(activity), failed, deleted }
675
+ const { event } = entry
676
+
677
+ seq = entry.seq
678
+ activity = AssistantActivity.apply(activity, entry)
679
+
680
+ if (!AssistantEvent.isLibraryEvent(event)) {
681
+ const now = activityOf(activity)
682
+
683
+ return Option.match(eventItemOf(entry), {
684
+ onNone: () =>
685
+ sameActivity(before.activity, now) ? undefined : { seq, items: [], activity: now, failed, deleted },
686
+ onSome: (item) => {
687
+ items.set(item.id, item)
688
+
689
+ return { seq, items: [item], activity: now, failed, deleted }
690
+ }
691
+ })
692
+ }
693
+
694
+ blocks = BlockKit.apply(blocks, event)
695
+
696
+ const changed = [...new Set(touched(event, entry.at))].flatMap((id) => {
697
+ const message = sent.get(id)
698
+ const current = items.get(id)
699
+
700
+ if (message === undefined || current === undefined) return current === undefined ? [] : [current]
701
+
702
+ const next = itemOf(message, current.at)
703
+ items.set(id, next)
704
+
705
+ return [next]
706
+ })
707
+
708
+ const now = activityOf(activity)
709
+
710
+ return changed.length === 0 &&
711
+ failed === before.failed &&
712
+ deleted === before.deleted &&
713
+ sameActivity(before.activity, now)
714
+ ? undefined
715
+ : { seq, items: changed, activity: now, failed, deleted }
716
+ }
717
+
718
+ return {
719
+ step,
720
+ get snapshot() {
721
+ return { seq, items: [...items.values()], activity: activityOf(activity), failed, deleted }
722
+ }
723
+ }
724
+ }
725
+
726
+ const merge = (changes: ReadonlyArray<AnyChange>): AnyChange | undefined => {
727
+ const last = changes.at(-1)
728
+
729
+ if (last === undefined) return undefined
730
+
731
+ const items = new Map<string, UserMessage | AssistantMessage | AnyEventItem>()
732
+
733
+ for (const change of changes) for (const item of change.items) items.set(item.id, item)
734
+
735
+ return {
736
+ seq: last.seq,
737
+ items: [...items.values()],
738
+ activity: last.activity,
739
+ failed: last.failed,
740
+ deleted: last.deleted
741
+ }
742
+ }
743
+
744
+ /**
745
+ * Represents an assistant's definition as the timeline reads it. An assistant made with
746
+ * `Assistant.make` fits it.
747
+ *
748
+ * @category models
749
+ * @since 0.1.0
750
+ */
751
+ export interface Definition<Events = never> {
752
+ /** The schemas of the assistant's events. */
753
+ readonly events: ReadonlyArray<AssistantEvent.AppEventSchema>
754
+ /** The schema of the chat's entries, typed with the assistant's events: it types `show`. */
755
+ readonly Entry: Schema.Codec<Assistant.Entry<Events>, Schema.Json>
756
+ }
757
+
758
+ /**
759
+ * Represents the options accepted by {@link changes}.
760
+ *
761
+ * @category models
762
+ * @since 0.3.0
763
+ */
764
+ export interface ChangesOptions<
765
+ Show extends ReadonlyArray<AssistantEvent.AppEventSchema> = readonly []
766
+ > extends ShowOptions<Show> {
767
+ /**
768
+ * The `seq` up to which the client already has the timeline. The result contains only the
769
+ * changes after it. Defaults to `0`, every change.
770
+ */
771
+ readonly after?: number | undefined
772
+ }
773
+
774
+ function changesWith<E, R, Events, const Show extends Shown<Events> = readonly []>(
775
+ entries: Stream.Stream<AssistantEvent.AnyEntry, E, R>,
776
+ definition: Definition<Events>,
777
+ options?: ChangesOptions<Show>
778
+ ): Stream.Stream<Change<Show[number]["Type"]>, E, R>
779
+ function changesWith<E, R>(
780
+ entries: Stream.Stream<AssistantEvent.AnyEntry, E, R>,
781
+ _definition: Schemas,
782
+ options?: ChangesOptions<ReadonlyArray<AssistantEvent.AppEventSchema>>
783
+ ): Stream.Stream<AnyChange, E, R> {
784
+ const after = options?.after ?? 0
785
+
786
+ return entries.pipe(
787
+ Stream.mapAccumArray(
788
+ () => folding(options?.show ?? []),
789
+ (timeline, chunk) => {
790
+ const changed = chunk.flatMap((entry) => {
791
+ const change = timeline.step(entry)
792
+
793
+ return change === undefined || entry.seq <= after ? [] : [change]
794
+ })
795
+
796
+ const merged = merge(changed)
797
+
798
+ return [timeline, merged === undefined ? [] : [merged]]
799
+ }
800
+ )
801
+ )
802
+ }
803
+
804
+ /**
805
+ * Returns the stream of changes to a chat's timeline that its entries produce, for a chat client.
806
+ *
807
+ * **Details**
808
+ *
809
+ * The entries must stream from the start of the chat's log, as `assistant.subscribe(chatId)` does
810
+ * without `after`. The fold reads every entry, because a message depends on earlier entries: its
811
+ * block is answered or closed later. `after` only skips emitting the changes up to that `seq`, so a
812
+ * client that has the timeline up to a `seq` receives only what changed since. Pass `after` here,
813
+ * not to `subscribe`: a subscription that starts after a `seq` gives the fold an incomplete log,
814
+ * and the changes it produces are wrong.
815
+ *
816
+ * Each chunk of entries becomes one change; the stored entries, for example, arrive as one chunk.
817
+ *
818
+ * **Only the app's events in `show` reach the client.** Each one becomes an item between the
819
+ * messages (see {@link EventItem}); the app's other events, like a summary of the chat for the
820
+ * model, are left out. Without `show`, none are shown. The changes are typed with the events shown,
821
+ * so the RPC's success schema names the same ones (`Timeline.Change([...])`), and a handler that
822
+ * shows one the schema doesn't name doesn't compile. A timeline shows a turn as working once it
823
+ * starts, or from the user's input.
824
+ *
825
+ * **Example** (Streaming a chat's timeline to a client, with the one app event its user sees)
826
+ *
827
+ * ```ts
828
+ * import { Assistant, type ChatId, Timeline } from "effect-assistant"
829
+ * import * as Schema from "effect/Schema"
830
+ * import * as Stream from "effect/Stream"
831
+ *
832
+ * class Summary extends Schema.TaggedClass<Summary>()("Summary", { text: Schema.String, throughSeq: Schema.Int }) {}
833
+ * class DailyBudgetReached extends Schema.TaggedClass<DailyBudgetReached>()("DailyBudgetReached", {}) {}
834
+ *
835
+ * const MyAssistant = Assistant.make("my-assistant", { events: [Summary, DailyBudgetReached] })
836
+ *
837
+ * // The summary is for the model: only the budget notice reaches the user.
838
+ * const watch = (chatId: ChatId.ChatId, after: number) =>
839
+ * Stream.unwrap(
840
+ * MyAssistant.useSync((assistant) =>
841
+ * assistant.subscribe(chatId).pipe(Timeline.changes(MyAssistant, { show: [DailyBudgetReached], after }))
842
+ * )
843
+ * )
844
+ * ```
845
+ *
846
+ * @see {@link fold} for folding the changes into a timeline on the client
847
+ *
848
+ * @category utils
849
+ * @since 0.3.0
850
+ */
851
+ export const changes: {
852
+ <Events, const Show extends Shown<Events> = readonly []>(
853
+ definition: Definition<Events>,
854
+ options?: ChangesOptions<Show>
855
+ ): <E, R>(entries: Stream.Stream<AssistantEvent.AnyEntry, E, R>) => Stream.Stream<Change<Show[number]["Type"]>, E, R>
856
+ <E, R, Events, const Show extends Shown<Events> = readonly []>(
857
+ entries: Stream.Stream<AssistantEvent.AnyEntry, E, R>,
858
+ definition: Definition<Events>,
859
+ options?: ChangesOptions<Show>
860
+ ): Stream.Stream<Change<Show[number]["Type"]>, E, R>
861
+ } = dual((args) => Stream.isStream(args[0]), changesWith)