effect-assistant 0.0.0-stage → 0.2.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 (172) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +22 -2
  3. package/dist/AppEvent.d.ts +111 -0
  4. package/dist/AppEvent.d.ts.map +1 -0
  5. package/dist/AppEvent.js +71 -0
  6. package/dist/AppEvent.js.map +1 -0
  7. package/dist/Assistant.d.ts +403 -0
  8. package/dist/Assistant.d.ts.map +1 -0
  9. package/dist/Assistant.js +126 -0
  10. package/dist/Assistant.js.map +1 -0
  11. package/dist/AssistantActivity.d.ts +85 -0
  12. package/dist/AssistantActivity.d.ts.map +1 -0
  13. package/dist/AssistantActivity.js +105 -0
  14. package/dist/AssistantActivity.js.map +1 -0
  15. package/dist/AssistantEngine.d.ts +116 -0
  16. package/dist/AssistantEngine.d.ts.map +1 -0
  17. package/dist/AssistantEngine.js +255 -0
  18. package/dist/AssistantEngine.js.map +1 -0
  19. package/dist/AssistantEvent.d.ts +551 -0
  20. package/dist/AssistantEvent.d.ts.map +1 -0
  21. package/dist/AssistantEvent.js +473 -0
  22. package/dist/AssistantEvent.js.map +1 -0
  23. package/dist/AssistantLoop.d.ts +173 -0
  24. package/dist/AssistantLoop.d.ts.map +1 -0
  25. package/dist/AssistantLoop.js +111 -0
  26. package/dist/AssistantLoop.js.map +1 -0
  27. package/dist/AssistantToolCall.d.ts +32 -0
  28. package/dist/AssistantToolCall.d.ts.map +1 -0
  29. package/dist/AssistantToolCall.js +37 -0
  30. package/dist/AssistantToolCall.js.map +1 -0
  31. package/dist/Block.d.ts +69 -0
  32. package/dist/Block.d.ts.map +1 -0
  33. package/dist/Block.js +39 -0
  34. package/dist/Block.js.map +1 -0
  35. package/dist/BlockKit.d.ts +180 -0
  36. package/dist/BlockKit.d.ts.map +1 -0
  37. package/dist/BlockKit.js +148 -0
  38. package/dist/BlockKit.js.map +1 -0
  39. package/dist/ChatId.d.ts +31 -0
  40. package/dist/ChatId.d.ts.map +1 -0
  41. package/dist/ChatId.js +36 -0
  42. package/dist/ChatId.js.map +1 -0
  43. package/dist/ChatLog.d.ts +109 -0
  44. package/dist/ChatLog.d.ts.map +1 -0
  45. package/dist/ChatLog.js +177 -0
  46. package/dist/ChatLog.js.map +1 -0
  47. package/dist/ChatView.d.ts +408 -0
  48. package/dist/ChatView.d.ts.map +1 -0
  49. package/dist/ChatView.js +443 -0
  50. package/dist/ChatView.js.map +1 -0
  51. package/dist/Chats.d.ts +110 -0
  52. package/dist/Chats.d.ts.map +1 -0
  53. package/dist/Chats.js +98 -0
  54. package/dist/Chats.js.map +1 -0
  55. package/dist/Compaction.d.ts +105 -0
  56. package/dist/Compaction.d.ts.map +1 -0
  57. package/dist/Compaction.js +126 -0
  58. package/dist/Compaction.js.map +1 -0
  59. package/dist/CurrentChat.d.ts +40 -0
  60. package/dist/CurrentChat.d.ts.map +1 -0
  61. package/dist/CurrentChat.js +33 -0
  62. package/dist/CurrentChat.js.map +1 -0
  63. package/dist/InputId.d.ts +38 -0
  64. package/dist/InputId.d.ts.map +1 -0
  65. package/dist/InputId.js +43 -0
  66. package/dist/InputId.js.map +1 -0
  67. package/dist/Instructions.d.ts +56 -0
  68. package/dist/Instructions.d.ts.map +1 -0
  69. package/dist/Instructions.js +50 -0
  70. package/dist/Instructions.js.map +1 -0
  71. package/dist/Memory.d.ts +190 -0
  72. package/dist/Memory.d.ts.map +1 -0
  73. package/dist/Memory.js +216 -0
  74. package/dist/Memory.js.map +1 -0
  75. package/dist/RunId.d.ts +41 -0
  76. package/dist/RunId.d.ts.map +1 -0
  77. package/dist/RunId.js +46 -0
  78. package/dist/RunId.js.map +1 -0
  79. package/dist/Skill.d.ts +72 -0
  80. package/dist/Skill.d.ts.map +1 -0
  81. package/dist/Skill.js +58 -0
  82. package/dist/Skill.js.map +1 -0
  83. package/dist/Specialist.d.ts +267 -0
  84. package/dist/Specialist.d.ts.map +1 -0
  85. package/dist/Specialist.js +119 -0
  86. package/dist/Specialist.js.map +1 -0
  87. package/dist/ToolDiscovery.d.ts +107 -0
  88. package/dist/ToolDiscovery.d.ts.map +1 -0
  89. package/dist/ToolDiscovery.js +140 -0
  90. package/dist/ToolDiscovery.js.map +1 -0
  91. package/dist/ToolFailure.d.ts +66 -0
  92. package/dist/ToolFailure.d.ts.map +1 -0
  93. package/dist/ToolFailure.js +79 -0
  94. package/dist/ToolFailure.js.map +1 -0
  95. package/dist/_virtual/_rolldown/runtime.js +13 -0
  96. package/dist/index.d.ts +24 -0
  97. package/dist/index.js +24 -0
  98. package/dist/internal/chat.js +177 -0
  99. package/dist/internal/chat.js.map +1 -0
  100. package/dist/internal/events.d.ts +46 -0
  101. package/dist/internal/events.d.ts.map +1 -0
  102. package/dist/internal/events.js +65 -0
  103. package/dist/internal/events.js.map +1 -0
  104. package/dist/internal/history.js +147 -0
  105. package/dist/internal/history.js.map +1 -0
  106. package/dist/internal/instructions.js +11 -0
  107. package/dist/internal/instructions.js.map +1 -0
  108. package/dist/internal/loop.d.ts +73 -0
  109. package/dist/internal/loop.d.ts.map +1 -0
  110. package/dist/internal/loop.js +131 -0
  111. package/dist/internal/loop.js.map +1 -0
  112. package/dist/internal/schema.js +14 -0
  113. package/dist/internal/schema.js.map +1 -0
  114. package/dist/internal/skills.js +28 -0
  115. package/dist/internal/skills.js.map +1 -0
  116. package/dist/internal/specialists.js +272 -0
  117. package/dist/internal/specialists.js.map +1 -0
  118. package/dist/internal/telemetry.js +85 -0
  119. package/dist/internal/telemetry.js.map +1 -0
  120. package/dist/internal/toolkit.d.ts +62 -0
  121. package/dist/internal/toolkit.d.ts.map +1 -0
  122. package/dist/internal/toolkit.js +108 -0
  123. package/dist/internal/toolkit.js.map +1 -0
  124. package/dist/internal/tools.js +113 -0
  125. package/dist/internal/tools.js.map +1 -0
  126. package/dist/internal/turns.d.ts +64 -0
  127. package/dist/internal/turns.d.ts.map +1 -0
  128. package/dist/internal/turns.js +214 -0
  129. package/dist/internal/turns.js.map +1 -0
  130. package/dist/internal/uuid.js +45 -0
  131. package/dist/internal/uuid.js.map +1 -0
  132. package/dist/internal/writer.d.ts +12 -0
  133. package/dist/internal/writer.d.ts.map +1 -0
  134. package/package.json +52 -3
  135. package/src/AppEvent.ts +134 -0
  136. package/src/Assistant.ts +589 -0
  137. package/src/AssistantActivity.ts +150 -0
  138. package/src/AssistantEngine.ts +343 -0
  139. package/src/AssistantEvent.ts +569 -0
  140. package/src/AssistantLoop.ts +209 -0
  141. package/src/AssistantToolCall.ts +40 -0
  142. package/src/Block.ts +84 -0
  143. package/src/BlockKit.ts +298 -0
  144. package/src/ChatId.ts +36 -0
  145. package/src/ChatLog.ts +247 -0
  146. package/src/ChatView.ts +587 -0
  147. package/src/Chats.ts +122 -0
  148. package/src/Compaction.ts +207 -0
  149. package/src/CurrentChat.ts +47 -0
  150. package/src/InputId.ts +43 -0
  151. package/src/Instructions.ts +72 -0
  152. package/src/Memory.ts +276 -0
  153. package/src/RunId.ts +46 -0
  154. package/src/Skill.ts +91 -0
  155. package/src/Specialist.ts +355 -0
  156. package/src/ToolDiscovery.ts +179 -0
  157. package/src/ToolFailure.ts +74 -0
  158. package/src/index.ts +120 -0
  159. package/src/internal/chat.ts +323 -0
  160. package/src/internal/events.ts +100 -0
  161. package/src/internal/history.ts +294 -0
  162. package/src/internal/instructions.ts +9 -0
  163. package/src/internal/loop.ts +274 -0
  164. package/src/internal/schema.ts +25 -0
  165. package/src/internal/skills.ts +37 -0
  166. package/src/internal/specialists.ts +410 -0
  167. package/src/internal/telemetry.ts +125 -0
  168. package/src/internal/toolkit.ts +188 -0
  169. package/src/internal/tools.ts +159 -0
  170. package/src/internal/turns.ts +410 -0
  171. package/src/internal/uuid.ts +50 -0
  172. package/src/internal/writer.ts +12 -0
@@ -0,0 +1,410 @@
1
+ import type * as LanguageModel from "effect/ai/LanguageModel"
2
+ import type * as Tool from "effect/ai/Tool"
3
+ import type * as Prompt from "effect/ai/Prompt"
4
+ import * as Cause from "effect/Cause"
5
+ import * as Context from "effect/Context"
6
+ import * as Effect from "effect/Effect"
7
+ import * as Exit from "effect/Exit"
8
+ import { identity } from "effect/Function"
9
+ import * as Option from "effect/Option"
10
+ import * as Predicate from "effect/Predicate"
11
+ import * as Schema from "effect/Schema"
12
+ import type * as Scope from "effect/Scope"
13
+ import * as Stream from "effect/Stream"
14
+ import type * as Assistant from "../Assistant.ts"
15
+ import type { ChatId } from "../ChatId.ts"
16
+ import * as AssistantEvent from "../AssistantEvent.ts"
17
+ import type * as AssistantLoop from "../AssistantLoop.ts"
18
+ import * as Loop from "./loop.ts"
19
+ import type * as BlockKit from "../BlockKit.ts"
20
+ import type { CurrentChat } from "../CurrentChat.ts"
21
+ import * as Instructions from "../Instructions.ts"
22
+ import * as Skill from "../Skill.ts"
23
+ import * as Skills from "./skills.ts"
24
+ import type * as Specialist from "../Specialist.ts"
25
+ import * as AppEvents from "./events.ts"
26
+ import * as History from "./history.ts"
27
+ import { mapText } from "./instructions.ts"
28
+ import { toJsonText } from "./schema.ts"
29
+ import * as Specialists from "./specialists.ts"
30
+ import * as Telemetry from "./telemetry.ts"
31
+ import * as Toolkits from "./toolkit.ts"
32
+ import type { Writer } from "./writer.ts"
33
+ import * as Tools from "./tools.ts"
34
+
35
+ /** @internal */
36
+ export const silentTurnMessage = "I finished without sending a reply."
37
+
38
+ /** @internal */
39
+ export const defaultReplyNudge =
40
+ "You haven't replied to the user's latest message yet. Reply now with send_user_message."
41
+
42
+ /** @internal */
43
+ export const deliveryNudge =
44
+ "You told the user you're on it, but stopped without giving them the result. Send it now with send_user_message; if part of it is still running, say what and that you'll report back. If they already have everything, call wait."
45
+
46
+ /** @internal */
47
+ export interface Definition {
48
+ readonly name: string
49
+ readonly blocks: BlockKit.BlockKit | undefined
50
+ readonly specialists: ReadonlyArray<Specialist.Any>
51
+ readonly app: AppEvents.AppEvents
52
+ }
53
+
54
+ // Once its build ran the layer's services are provided, so its streams need only what a turn provides.
55
+ /** @internal */
56
+ export type TurnHandler = (
57
+ turn: Assistant.Turn<any>
58
+ ) => Stream.Stream<AssistantLoop.Event, unknown, Assistant.TurnServices | LanguageModel.LanguageModel>
59
+
60
+ // The chat `CurrentChat` gives, with its entries typed as the assistant's decode returns them: the assistant's typed
61
+ // chat is this one, so it needs no check of its own.
62
+ /** @internal */
63
+ export interface TypedChat {
64
+ readonly chatId: ChatId
65
+ readonly entries: Effect.Effect<AppEvents.DecodedEntries>
66
+ readonly append: CurrentChat["Service"]["append"]
67
+ }
68
+
69
+ /** @internal */
70
+ export interface Registration {
71
+ readonly definition: Definition
72
+ readonly model: Context.Context<LanguageModel.LanguageModel>
73
+ readonly open: (chat: TypedChat) => Effect.Effect<TurnHandler, never, Scope.Scope | CurrentChat>
74
+ readonly specialists: ReadonlyArray<{
75
+ readonly specialist: Specialist.Any
76
+ readonly built: Specialist.Built
77
+ }>
78
+ readonly builtins: Toolkits.Tools<Assistant.TurnServices>
79
+ }
80
+
81
+ /** @internal */
82
+ export const register = Effect.fnUntraced(function* (
83
+ definition: Definition,
84
+ options: { readonly open: Registration["open"] }
85
+ ) {
86
+ const model = yield* Effect.context<LanguageModel.LanguageModel>()
87
+
88
+ const specialists = yield* Effect.forEach(
89
+ definition.specialists,
90
+ Effect.fnUntraced(function* (specialist) {
91
+ const built = yield* Effect.serviceOption(specialist.Handler)
92
+
93
+ if (Option.isNone(built)) {
94
+ return yield* Effect.die(
95
+ `No handler for the ${specialist.name} specialist: provide ${specialist.name}.toLayer.`
96
+ )
97
+ }
98
+
99
+ return { specialist, built: built.value }
100
+ })
101
+ )
102
+
103
+ const builtins = Toolkits.merge(
104
+ yield* Tools.makeMessaging(definition.blocks),
105
+ yield* Specialists.toolkit(definition.specialists)
106
+ )
107
+
108
+ const registration: Registration = {
109
+ definition,
110
+ model,
111
+ open: options.open,
112
+ specialists,
113
+ builtins
114
+ }
115
+
116
+ return registration
117
+ })
118
+
119
+ const ProviderError = Schema.Struct({ _tag: Schema.optional(Schema.String), raw: Schema.Unknown })
120
+
121
+ // Provider errors keep their response body.
122
+ const failureMessage = (cause: Cause.Cause<unknown>): string =>
123
+ Option.match(Schema.decodeUnknownOption(ProviderError)(Cause.squash(cause)), {
124
+ onNone: () => Cause.pretty(cause),
125
+ onSome: ({ _tag, raw }) => `${_tag ?? "Error"}: ${Predicate.isString(raw) ? raw : toJsonText(raw)}`
126
+ })
127
+
128
+ const lastSeq = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, otherwise: number) => entries.at(-1)?.seq ?? otherwise
129
+
130
+ const toHistory = (
131
+ viewed: ReadonlyArray<Assistant.Entry<any> | Prompt.Message>,
132
+ app: AppEvents.AppEvents
133
+ ): ReadonlyArray<Prompt.Message> => {
134
+ const out: Array<Prompt.Message> = []
135
+ let run: Array<AssistantEvent.AnyEntry> = []
136
+
137
+ const flush = () => {
138
+ out.push(...History.fromEntries(run, (event) => AppEvents.read(app, event)))
139
+ run = []
140
+ }
141
+
142
+ for (const item of viewed) {
143
+ if (isEntry(item)) run.push(item)
144
+ else {
145
+ flush()
146
+ out.push(item)
147
+ }
148
+ }
149
+
150
+ flush()
151
+
152
+ return out
153
+ }
154
+
155
+ const isEntry = (item: Assistant.Entry<any> | Prompt.Message): item is Assistant.Entry<any> =>
156
+ Predicate.hasProperty(item, "seq")
157
+
158
+ // The handler's stream can end between a step's output and its tools, or while they run. An interrupted turn (a
159
+ // shutdown) leaves its calls open instead: the next turn runs them again.
160
+ const closeOpenCalls = Effect.fnUntraced(function* (chat: Writer, startSeq: number) {
161
+ const entries = (yield* chat.entries).filter(({ seq }) => seq > startSeq)
162
+
163
+ const started = new Set(
164
+ entries.flatMap(({ event }) => (Predicate.isTagged(event, "ToolStarted") ? [event.callId] : []))
165
+ )
166
+
167
+ const open = History.unansweredCalls(History.fromEntries(entries, () => undefined))
168
+
169
+ if (open.length === 0) return
170
+
171
+ yield* chat.append(
172
+ open.map((call) =>
173
+ AssistantEvent.ToolResult.make({
174
+ callId: call.id,
175
+ tool: call.name,
176
+ outcome: "failure",
177
+ ...(started.has(call.id)
178
+ ? { result: History.mayHaveRunOutput, reason: "MayHaveRun" }
179
+ : { result: History.notRunOutput, reason: "NotRun" })
180
+ })
181
+ )
182
+ )
183
+ })
184
+
185
+ // The inputs before the turn's `TurnStarted` (at `startSeq`) woke it; past that, what its model outputs record
186
+ // reading.
187
+ const handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, startSeq: number) =>
188
+ entries.reduce(
189
+ (through, { seq, event }) =>
190
+ seq > startSeq &&
191
+ AssistantEvent.isLibraryEvent(event) &&
192
+ Predicate.isTagged(event, "ModelOutput") &&
193
+ event.seenThroughSeq !== undefined
194
+ ? Math.max(through, event.seenThroughSeq)
195
+ : through,
196
+ startSeq
197
+ )
198
+
199
+ // Fails visibly when the user's latest input got no reply; an input that arrived after what its model read gets the
200
+ // next turn, which replies.
201
+ const finishTurn = Effect.fnUntraced(function* (chat: Writer, read: number, wakes: ReadonlySet<string>) {
202
+ const entries = yield* chat.entries
203
+
204
+ const end =
205
+ History.owesReply(entries, read) && !History.unreadAfter(entries, read, wakes)
206
+ ? AssistantEvent.TurnFailed.make({ throughSeq: read, message: silentTurnMessage })
207
+ : AssistantEvent.TurnCompleted.make({ throughSeq: read })
208
+
209
+ yield* chat.append([end])
210
+ })
211
+
212
+ // Everything stored so far counts as read, so a failing input isn't retried forever.
213
+ const failTurn = Effect.fnUntraced(function* (chat: Writer, cause: Cause.Cause<unknown>) {
214
+ yield* Effect.logError("assistant turn failed", cause)
215
+
216
+ const last = lastSeq(yield* chat.entries, 0)
217
+
218
+ yield* chat.append([AssistantEvent.TurnFailed.make({ throughSeq: last, message: failureMessage(cause) })])
219
+ })
220
+
221
+ const makeTurnApi = (
222
+ registration: Registration,
223
+ chat: Writer,
224
+ startSeq: number,
225
+ checkOpen: Effect.Effect<void>
226
+ ): Assistant.Turn<any> => {
227
+ const { definition, builtins } = registration
228
+ const { app } = definition
229
+
230
+ // With how far into the chat it goes: the step records it on the model's output.
231
+ // Read before every model call: a chat the app deleted meanwhile stops here.
232
+ const history = Effect.fnUntraced(function* (view: Assistant.HistoryView<any> = identity) {
233
+ yield* checkOpen
234
+
235
+ const all = yield* chat.entries
236
+
237
+ const read: AssistantLoop.ChatHistory = {
238
+ messages: toHistory(view(AppEvents.decodeEntries(app, all)), app),
239
+ throughSeq: lastSeq(all, startSeq)
240
+ }
241
+
242
+ return read
243
+ })
244
+
245
+ const instructions = (given: string | Instructions.Resolved) =>
246
+ mapText(given, (text) => `${Instructions.protocol}\n\n${text}`)
247
+
248
+ // The loop's own prompt and tools, so the prompt stays cached, with the nudge at the end.
249
+ const replyPass = <R>(options: {
250
+ readonly instructions: Instructions.Resolved
251
+ readonly toolkit: Toolkits.Tools<R>
252
+ readonly view: Assistant.HistoryView<any>
253
+ readonly nudge: string | undefined
254
+ }) =>
255
+ Stream.unwrap(
256
+ Effect.gen(function* () {
257
+ const all = yield* chat.entries
258
+ const through = handledThrough(all, startSeq)
259
+
260
+ // Something arrived after what the loop's model read: the next turn reads it with the full loop, and replies.
261
+ if (History.unreadAfter(all, through, app.wakes)) return Stream.empty
262
+
263
+ const owed = History.owesReply(all, through)
264
+ const undelivered = !owed && History.owesDelivery(all, through)
265
+
266
+ if (!owed && !undelivered) return Stream.empty
267
+
268
+ const nudge = undelivered ? deliveryNudge : (options.nudge ?? defaultReplyNudge)
269
+
270
+ return Loop.run({
271
+ instructions: options.instructions,
272
+ // A reply that's owed can only be sent; a result it may have given may also be for nobody.
273
+ toolkit: Toolkits.runOnly(
274
+ options.toolkit,
275
+ owed ? [Tools.sendUserMessageName] : [Tools.sendUserMessageName, Tools.waitToolName],
276
+ "Not now: reply to the user with send_user_message."
277
+ ),
278
+ history: Effect.gen(function* () {
279
+ yield* checkOpen
280
+
281
+ const entries = yield* chat.entries
282
+
283
+ return {
284
+ messages: [
285
+ ...toHistory(options.view(AppEvents.decodeEntries(app, entries)), app),
286
+ History.userText(nudge)
287
+ ],
288
+ throughSeq: lastSeq(entries, startSeq)
289
+ }
290
+ }),
291
+ // A second step, for a reply after a call it was refused.
292
+ maxSteps: 2
293
+ })
294
+ })
295
+ )
296
+
297
+ const replyIfOwed = (options: Assistant.ReplyOptions) =>
298
+ replyPass({
299
+ instructions: instructions(options.instructions),
300
+ toolkit: builtins,
301
+ view: identity,
302
+ nudge: options.nudge
303
+ })
304
+
305
+ const prepare = <T extends Record<string, Tool.Any>, RS>(options: Assistant.LoopOptions<T, RS, any>) => {
306
+ const skills = options.skills ?? []
307
+
308
+ return {
309
+ system: mapText(instructions(options.instructions), (text) => Skill.withCatalog(text, skills)),
310
+ toolkit: Toolkits.merge(
311
+ Toolkits.merge(builtins, Skills.toTools(skills)),
312
+ Toolkits.fromToolkitOrEmpty(options.toolkit)
313
+ ),
314
+ view: options.history ?? identity
315
+ }
316
+ }
317
+
318
+ return {
319
+ chatId: chat.chatId,
320
+ history,
321
+ instructions,
322
+ replyIfOwed,
323
+ loop: (options) => {
324
+ const { system, toolkit, view } = prepare(options)
325
+ const twice = Toolkits.duplicateNames(toolkit)
326
+
327
+ const loop =
328
+ twice.length > 0
329
+ ? Stream.die(`Tool names used twice, like one named after a built-in: ${twice.join(", ")}`)
330
+ : Loop.run({
331
+ instructions: system,
332
+ toolkit,
333
+ history: history(view),
334
+ maxSteps: options.maxSteps ?? 16
335
+ })
336
+
337
+ return Stream.concat(loop, replyPass({ instructions: system, toolkit, view, nudge: options.replyNudge }))
338
+ }
339
+ }
340
+ }
341
+
342
+ // Every event the handler's loop emits is recorded before the loop is pulled again.
343
+ /** @internal */
344
+ export const run = Effect.fnUntraced(
345
+ function* (options: {
346
+ readonly registration: Registration
347
+ readonly handler: TurnHandler
348
+ readonly chat: Writer
349
+ readonly services: Context.Context<Assistant.TurnServices | LanguageModel.LanguageModel>
350
+ // A chat the app deleted is deleted here, and the turn stops.
351
+ readonly checkOpen: Effect.Effect<void>
352
+ }) {
353
+ const { chat } = options
354
+ const before = yield* chat.entries
355
+
356
+ yield* Telemetry.agentInput(History.unhandledInputs(before, options.registration.definition.app.wakes))
357
+
358
+ const assistant = options.registration.definition.name
359
+ const traceId = yield* Telemetry.currentTraceId
360
+
361
+ const started = yield* chat.append([
362
+ AssistantEvent.TurnStarted.make(
363
+ Option.match(traceId, {
364
+ onNone: () => ({ assistant }),
365
+ onSome: (id) => ({ assistant, traceId: id })
366
+ })
367
+ )
368
+ ])
369
+
370
+ const startSeq = lastSeq(started, 0)
371
+ const turn = makeTurnApi(options.registration, chat, startSeq, options.checkOpen)
372
+
373
+ const record = (event: AssistantLoop.Event) => chat.append([event])
374
+
375
+ yield* options.handler(turn).pipe(
376
+ Stream.runForEach(record),
377
+ Effect.onExit((exit) => (Exit.hasInterrupts(exit) ? Effect.void : closeOpenCalls(chat, startSeq))),
378
+ // A loop the app writes gets the assistant's own tools too, with this turn's services.
379
+ Effect.provideService(
380
+ Loop.TurnTools,
381
+ Option.some(Toolkits.provide(options.registration.builtins, options.services))
382
+ ),
383
+ Effect.provideContext(options.services),
384
+ Effect.matchCauseEffect({
385
+ onSuccess: Effect.fnUntraced(function* () {
386
+ const all = yield* chat.entries
387
+
388
+ yield* finishTurn(chat, handledThrough(all, startSeq), options.registration.definition.app.wakes)
389
+ }),
390
+ onFailure: (cause) => failTurn(chat, cause)
391
+ })
392
+ )
393
+
394
+ // The trace's output is what the user saw this turn, and a failure if any.
395
+ const shown = (yield* chat.entries).flatMap(({ event, seq }) =>
396
+ seq > startSeq && (Predicate.isTagged(event, "AssistantMessage") || Predicate.isTagged(event, "TurnFailed"))
397
+ ? [event]
398
+ : []
399
+ )
400
+
401
+ yield* Telemetry.agentOutput(shown)
402
+ },
403
+ (effect, options) =>
404
+ effect.pipe(
405
+ Telemetry.agentSpan(options.registration.definition.name, {
406
+ chatId: options.chat.chatId,
407
+ root: true
408
+ })
409
+ )
410
+ )
@@ -0,0 +1,50 @@
1
+ import * as Effect from "effect/Effect"
2
+ import * as Random from "effect/Random"
3
+ import * as Schema from "effect/Schema"
4
+
5
+ /** @internal */
6
+ export const Uuid = Schema.String.check(Schema.isUUID())
7
+
8
+ const hex = (bytes: ReadonlyArray<number>): string => {
9
+ const digits = bytes.map((byte) => byte.toString(16).padStart(2, "0")).join("")
10
+
11
+ return `${digits.slice(0, 8)}-${digits.slice(8, 12)}-${digits.slice(12, 16)}-${digits.slice(16, 20)}-${digits.slice(20)}`
12
+ }
13
+
14
+ // RFC 9562 version nibble and variant bits.
15
+ const format = (bytes: ReadonlyArray<number>, version: number): string => {
16
+ const out = [...bytes]
17
+
18
+ out[6] = ((out[6] ?? 0) & 0x0f) | (version << 4)
19
+ out[8] = ((out[8] ?? 0) & 0x3f) | 0x80
20
+
21
+ return hex(out)
22
+ }
23
+
24
+ // From the `Random` service, so a seeded test gets the same ids every run.
25
+ /** @internal */
26
+ export const make: Effect.Effect<string> = Effect.gen(function* () {
27
+ const bytes = yield* Effect.forEach(Array.from({ length: 16 }), () => Random.nextIntBetween(0, 255))
28
+
29
+ return format(bytes, 4)
30
+ })
31
+
32
+ const fnv1a = (key: string, round: number): number => {
33
+ let hash = 0x811c9dc5 ^ round
34
+
35
+ for (let i = 0; i < key.length; i++) hash = Math.imul(hash ^ key.charCodeAt(i), 0x01000193)
36
+
37
+ return hash >>> 0
38
+ }
39
+
40
+ // Version 8: the same key gives the same UUID. Not a secret, only unlikely to collide: four 32-bit FNV-1a hashes.
41
+ /** @internal */
42
+ export const fromKey = (key: string): string =>
43
+ format(
44
+ [0, 1, 2, 3].flatMap((round) => {
45
+ const hash = fnv1a(key, round)
46
+
47
+ return [hash >>> 24, (hash >>> 16) & 0xff, (hash >>> 8) & 0xff, hash & 0xff]
48
+ }),
49
+ 8
50
+ )
@@ -0,0 +1,12 @@
1
+ import type * as Effect from "effect/Effect"
2
+ import type * as AssistantEvent from "../AssistantEvent.ts"
3
+ import type { ChatId } from "../ChatId.ts"
4
+
5
+ /** @internal */
6
+ export interface Writer {
7
+ readonly chatId: ChatId
8
+ readonly entries: Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>
9
+ readonly append: (
10
+ events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>
11
+ ) => Effect.Effect<ReadonlyArray<AssistantEvent.Entry>>
12
+ }