effect-assistant 0.0.0-stage → 0.1.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 (185) 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 +614 -0
  20. package/dist/AssistantEvent.d.ts.map +1 -0
  21. package/dist/AssistantEvent.js +523 -0
  22. package/dist/AssistantEvent.js.map +1 -0
  23. package/dist/AssistantLoop.d.ts +171 -0
  24. package/dist/AssistantLoop.d.ts.map +1 -0
  25. package/dist/AssistantLoop.js +108 -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 +184 -0
  36. package/dist/BlockKit.d.ts.map +1 -0
  37. package/dist/BlockKit.js +151 -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 +459 -0
  48. package/dist/ChatView.d.ts.map +1 -0
  49. package/dist/ChatView.js +496 -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 +133 -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/Decision.d.ts +145 -0
  64. package/dist/Decision.d.ts.map +1 -0
  65. package/dist/Decision.js +178 -0
  66. package/dist/Decision.js.map +1 -0
  67. package/dist/DecisionId.d.ts +37 -0
  68. package/dist/DecisionId.d.ts.map +1 -0
  69. package/dist/DecisionId.js +44 -0
  70. package/dist/DecisionId.js.map +1 -0
  71. package/dist/InputId.d.ts +38 -0
  72. package/dist/InputId.d.ts.map +1 -0
  73. package/dist/InputId.js +43 -0
  74. package/dist/InputId.js.map +1 -0
  75. package/dist/Instructions.d.ts +56 -0
  76. package/dist/Instructions.d.ts.map +1 -0
  77. package/dist/Instructions.js +50 -0
  78. package/dist/Instructions.js.map +1 -0
  79. package/dist/Memory.d.ts +190 -0
  80. package/dist/Memory.d.ts.map +1 -0
  81. package/dist/Memory.js +216 -0
  82. package/dist/Memory.js.map +1 -0
  83. package/dist/RunId.d.ts +41 -0
  84. package/dist/RunId.d.ts.map +1 -0
  85. package/dist/RunId.js +46 -0
  86. package/dist/RunId.js.map +1 -0
  87. package/dist/Skill.d.ts +72 -0
  88. package/dist/Skill.d.ts.map +1 -0
  89. package/dist/Skill.js +58 -0
  90. package/dist/Skill.js.map +1 -0
  91. package/dist/Specialist.d.ts +267 -0
  92. package/dist/Specialist.d.ts.map +1 -0
  93. package/dist/Specialist.js +119 -0
  94. package/dist/Specialist.js.map +1 -0
  95. package/dist/ToolDiscovery.d.ts +108 -0
  96. package/dist/ToolDiscovery.d.ts.map +1 -0
  97. package/dist/ToolDiscovery.js +139 -0
  98. package/dist/ToolDiscovery.js.map +1 -0
  99. package/dist/ToolFailure.d.ts +66 -0
  100. package/dist/ToolFailure.d.ts.map +1 -0
  101. package/dist/ToolFailure.js +79 -0
  102. package/dist/ToolFailure.js.map +1 -0
  103. package/dist/_virtual/_rolldown/runtime.js +13 -0
  104. package/dist/index.d.ts +26 -0
  105. package/dist/index.js +26 -0
  106. package/dist/internal/chat.js +202 -0
  107. package/dist/internal/chat.js.map +1 -0
  108. package/dist/internal/decisions.js +66 -0
  109. package/dist/internal/decisions.js.map +1 -0
  110. package/dist/internal/events.d.ts +46 -0
  111. package/dist/internal/events.d.ts.map +1 -0
  112. package/dist/internal/events.js +65 -0
  113. package/dist/internal/events.js.map +1 -0
  114. package/dist/internal/history.js +185 -0
  115. package/dist/internal/history.js.map +1 -0
  116. package/dist/internal/instructions.js +11 -0
  117. package/dist/internal/instructions.js.map +1 -0
  118. package/dist/internal/loop.d.ts +73 -0
  119. package/dist/internal/loop.d.ts.map +1 -0
  120. package/dist/internal/loop.js +166 -0
  121. package/dist/internal/loop.js.map +1 -0
  122. package/dist/internal/schema.js +14 -0
  123. package/dist/internal/schema.js.map +1 -0
  124. package/dist/internal/skills.js +28 -0
  125. package/dist/internal/skills.js.map +1 -0
  126. package/dist/internal/specialists.js +273 -0
  127. package/dist/internal/specialists.js.map +1 -0
  128. package/dist/internal/telemetry.js +85 -0
  129. package/dist/internal/telemetry.js.map +1 -0
  130. package/dist/internal/toolkit.d.ts +76 -0
  131. package/dist/internal/toolkit.d.ts.map +1 -0
  132. package/dist/internal/toolkit.js +129 -0
  133. package/dist/internal/toolkit.js.map +1 -0
  134. package/dist/internal/tools.js +132 -0
  135. package/dist/internal/tools.js.map +1 -0
  136. package/dist/internal/turns.d.ts +64 -0
  137. package/dist/internal/turns.d.ts.map +1 -0
  138. package/dist/internal/turns.js +221 -0
  139. package/dist/internal/turns.js.map +1 -0
  140. package/dist/internal/uuid.js +45 -0
  141. package/dist/internal/uuid.js.map +1 -0
  142. package/dist/internal/writer.d.ts +12 -0
  143. package/dist/internal/writer.d.ts.map +1 -0
  144. package/package.json +51 -3
  145. package/src/AppEvent.ts +134 -0
  146. package/src/Assistant.ts +589 -0
  147. package/src/AssistantActivity.ts +150 -0
  148. package/src/AssistantEngine.ts +343 -0
  149. package/src/AssistantEvent.ts +635 -0
  150. package/src/AssistantLoop.ts +207 -0
  151. package/src/AssistantToolCall.ts +40 -0
  152. package/src/Block.ts +84 -0
  153. package/src/BlockKit.ts +311 -0
  154. package/src/ChatId.ts +36 -0
  155. package/src/ChatLog.ts +247 -0
  156. package/src/ChatView.ts +658 -0
  157. package/src/Chats.ts +122 -0
  158. package/src/Compaction.ts +224 -0
  159. package/src/CurrentChat.ts +47 -0
  160. package/src/Decision.ts +241 -0
  161. package/src/DecisionId.ts +46 -0
  162. package/src/InputId.ts +43 -0
  163. package/src/Instructions.ts +72 -0
  164. package/src/Memory.ts +276 -0
  165. package/src/RunId.ts +46 -0
  166. package/src/Skill.ts +91 -0
  167. package/src/Specialist.ts +355 -0
  168. package/src/ToolDiscovery.ts +187 -0
  169. package/src/ToolFailure.ts +74 -0
  170. package/src/index.ts +130 -0
  171. package/src/internal/chat.ts +372 -0
  172. package/src/internal/decisions.ts +131 -0
  173. package/src/internal/events.ts +100 -0
  174. package/src/internal/history.ts +366 -0
  175. package/src/internal/instructions.ts +9 -0
  176. package/src/internal/loop.ts +344 -0
  177. package/src/internal/schema.ts +25 -0
  178. package/src/internal/skills.ts +37 -0
  179. package/src/internal/specialists.ts +414 -0
  180. package/src/internal/telemetry.ts +125 -0
  181. package/src/internal/toolkit.ts +231 -0
  182. package/src/internal/tools.ts +210 -0
  183. package/src/internal/turns.ts +429 -0
  184. package/src/internal/uuid.ts +50 -0
  185. package/src/internal/writer.ts +12 -0
@@ -0,0 +1,150 @@
1
+ /**
2
+ * This module provides functions that determine what is working in a chat right now, read from
3
+ * the chat's log.
4
+ *
5
+ * A {@link State} records whether the assistant is running a turn or is about to start one,
6
+ * and which specialist runs are working. Fold a chat's entries into it with {@link apply}, or
7
+ * build it from a list of entries with {@link fromEntries}, then check it with
8
+ * {@link isWorking}.
9
+ *
10
+ * @since 0.1.0
11
+ */
12
+ import * as Match from "effect/Match"
13
+ import * as Predicate from "effect/Predicate"
14
+ import * as AssistantEvent from "./AssistantEvent.ts"
15
+ import type { RunId } from "./RunId.ts"
16
+
17
+ /**
18
+ * Represents a specialist run that is working.
19
+ *
20
+ * @category models
21
+ * @since 0.1.0
22
+ */
23
+ export interface SpecialistRun {
24
+ readonly runId: RunId
25
+ readonly specialist: string
26
+ /** The goal the run is working on. */
27
+ readonly goal: string
28
+ /** When the run started, in epoch milliseconds. */
29
+ readonly since: number
30
+ }
31
+
32
+ /**
33
+ * Represents what is working in a chat.
34
+ *
35
+ * @category models
36
+ * @since 0.1.0
37
+ */
38
+ export interface State {
39
+ /** When the running turn started, in epoch milliseconds, or `undefined` when no turn runs. */
40
+ readonly turnSince: number | undefined
41
+ /**
42
+ * Whether an input arrived that no finished turn has read. When this is true, a turn is about
43
+ * to start.
44
+ */
45
+ readonly queued: boolean
46
+ /** The `seq` of the newest input. */
47
+ readonly lastInputSeq: number
48
+ /** Specialist runs that are working, by run id. */
49
+ readonly specialists: ReadonlyMap<RunId, SpecialistRun>
50
+ }
51
+
52
+ /**
53
+ * The activity of a chat with an empty log, where nothing is working.
54
+ *
55
+ * @category constructors
56
+ * @since 0.1.0
57
+ */
58
+ export const empty: State = {
59
+ turnSince: undefined,
60
+ queued: false,
61
+ lastInputSeq: 0,
62
+ specialists: new Map()
63
+ }
64
+
65
+ const withoutRun = (activity: State, runId: RunId): State => {
66
+ if (!activity.specialists.has(runId)) return activity
67
+
68
+ const specialists = new Map(activity.specialists)
69
+ specialists.delete(runId)
70
+
71
+ return { ...activity, specialists }
72
+ }
73
+
74
+ /**
75
+ * Represents the options for folding a chat's entries into its activity.
76
+ *
77
+ * @category models
78
+ * @since 0.1.0
79
+ */
80
+ export interface Options {
81
+ /**
82
+ * The tags of the app's events that wake a turn (see `AppEvent`). These events count as inputs
83
+ * too. Defaults to none.
84
+ */
85
+ readonly wakes?: ReadonlySet<string> | undefined
86
+ }
87
+
88
+ /**
89
+ * Returns the activity after one more entry. Fold a chat's entries in order, or use
90
+ * {@link fromEntries}.
91
+ *
92
+ * @category combinators
93
+ * @since 0.1.0
94
+ */
95
+ export const apply = (activity: State, entry: AssistantEvent.AnyEntry, options?: Options): State => {
96
+ const event = entry.event
97
+
98
+ if (!AssistantEvent.isLibraryEvent(event)) {
99
+ return options?.wakes?.has(event._tag) === true ? { ...activity, queued: true, lastInputSeq: entry.seq } : activity
100
+ }
101
+
102
+ if (AssistantEvent.isInput(event)) {
103
+ // A finished run's report is an input, and ends the run.
104
+ const current = Predicate.isTagged(event, "SpecialistFinished") ? withoutRun(activity, event.runId) : activity
105
+
106
+ return AssistantEvent.isWaking(event) ? { ...current, queued: true, lastInputSeq: entry.seq } : current
107
+ }
108
+
109
+ return Match.value(event).pipe(
110
+ Match.tag("TurnStarted", (): State => ({ ...activity, turnSince: entry.at })),
111
+ // Turns run one at a time, so an end closes whichever turn is open, also one a restart cut off.
112
+ Match.tag("TurnCompleted", "TurnFailed", (ended): State => ({
113
+ ...activity,
114
+ turnSince: undefined,
115
+ queued: activity.lastInputSeq > ended.throughSeq
116
+ })),
117
+ Match.tag("SpecialistStarted", (started): State => ({
118
+ ...activity,
119
+ specialists: new Map(activity.specialists).set(started.runId, {
120
+ runId: started.runId,
121
+ specialist: started.specialist,
122
+ goal: started.goal,
123
+ since: entry.at
124
+ })
125
+ })),
126
+ // Deleting a chat stops everything in it, and nothing starts again.
127
+ Match.tag("ChatDeleted", (): State => ({ ...empty, lastInputSeq: activity.lastInputSeq })),
128
+ Match.orElse(() => activity)
129
+ )
130
+ }
131
+
132
+ /**
133
+ * Returns what is working in a chat after the given entries, folded in order from
134
+ * {@link empty}.
135
+ *
136
+ * @category constructors
137
+ * @since 0.1.0
138
+ */
139
+ export const fromEntries = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, options?: Options): State =>
140
+ entries.reduce((activity, entry) => apply(activity, entry, options), empty)
141
+
142
+ /**
143
+ * Returns whether anything is working: a turn that is running or about to start, or a specialist
144
+ * run.
145
+ *
146
+ * @category guards
147
+ * @since 0.1.0
148
+ */
149
+ export const isWorking = (activity: State): boolean =>
150
+ activity.turnSince !== undefined || activity.queued || activity.specialists.size > 0
@@ -0,0 +1,343 @@
1
+ /**
2
+ * This module provides the `AssistantEngine` service, which runs assistants' chats, and its two
3
+ * implementations.
4
+ *
5
+ * An assistant's `toLayer` registers the assistant with the engine, and the assistant's `submit`
6
+ * and `subscribe` go through it. Pick one engine for the app, as with a workflow engine.
7
+ * {@link layerMemory} runs chats in the process, for tests and single-process apps.
8
+ * {@link layerCluster} runs each chat as a cluster entity, so a turn cut off by a crash resumes.
9
+ *
10
+ * @since 0.1.0
11
+ */
12
+ import * as ClusterSchema from "effect/cluster/ClusterSchema"
13
+ import * as Entity from "effect/cluster/Entity"
14
+ import * as Sharding from "effect/cluster/Sharding"
15
+ import * as Context from "effect/Context"
16
+ import * as Data from "effect/Data"
17
+ import * as Effect from "effect/Effect"
18
+ import * as Exit from "effect/Exit"
19
+ import * as Layer from "effect/Layer"
20
+ import * as MutableHashMap from "effect/MutableHashMap"
21
+ import * as Option from "effect/Option"
22
+ import * as Predicate from "effect/Predicate"
23
+ import * as RcMap from "effect/RcMap"
24
+ import * as Rpc from "effect/rpc/Rpc"
25
+ import * as Schema from "effect/Schema"
26
+ import * as Scope from "effect/Scope"
27
+ import * as Stream from "effect/Stream"
28
+ import * as AssistantEvent from "./AssistantEvent.ts"
29
+ import { ChatId } from "./ChatId.ts"
30
+ import { ChatLog } from "./ChatLog.ts"
31
+ import * as Chat from "./internal/chat.ts"
32
+ import * as History from "./internal/history.ts"
33
+ import type * as Turns from "./internal/turns.ts"
34
+
35
+ /**
36
+ * Service that runs assistants' chats. An assistant's `toLayer` registers the assistant with it,
37
+ * and the assistant's `submit` and `subscribe` use it.
38
+ *
39
+ * @category services
40
+ * @since 0.1.0
41
+ */
42
+ export class AssistantEngine extends Context.Service<
43
+ AssistantEngine,
44
+ {
45
+ /** Registers an assistant for as long as the scope is open. */
46
+ readonly register: (registration: Turns.Registration) => Effect.Effect<void, never, Scope.Scope>
47
+ /**
48
+ * Stores an input in one of the assistant's chats. The assistant works on it in the
49
+ * background.
50
+ */
51
+ readonly submit: (
52
+ assistant: string,
53
+ chatId: ChatId,
54
+ input: AssistantEvent.Input | AssistantEvent.StoredAppEvent
55
+ ) => Effect.Effect<void>
56
+ /** Streams the chat's stored entries after the `after` seq, then live ones. */
57
+ readonly subscribe: (assistant: string, chatId: ChatId, after: number) => Stream.Stream<AssistantEvent.Entry>
58
+ /**
59
+ * Deletes one of the assistant's chats. The chat's log records the deletion, and everything
60
+ * that works in the chat stops.
61
+ */
62
+ readonly delete: (assistant: string, chatId: ChatId) => Effect.Effect<void>
63
+ }
64
+ >()("effect-assistant/AssistantEngine") {}
65
+
66
+ class ChatKey extends Data.Class<{ readonly assistant: string; readonly chatId: ChatId }> {}
67
+
68
+ const notRegistered = (assistant: string) =>
69
+ Effect.die(`The ${assistant} assistant isn't registered: provide its toLayer.`)
70
+
71
+ /**
72
+ * Layer that runs chats in the current process. Each chat's turns run as fibers, one at a time.
73
+ *
74
+ * **Details**
75
+ *
76
+ * With `ChatLog.layerSql`, the engine resumes chats at startup. When an assistant registers, the
77
+ * engine finds the chats that assistant was working on when the process stopped (a turn cut off
78
+ * partway, or an input that no turn read) and runs a turn for each. Run this engine in one process
79
+ * only, because two processes would run the same chat and write its log at the same time.
80
+ *
81
+ * **Example** (Running chats in memory)
82
+ *
83
+ * ```ts
84
+ * import { Assistant, AssistantEngine, ChatLog } from "effect-assistant"
85
+ * import type * as LanguageModel from "effect/ai/LanguageModel"
86
+ * import * as Layer from "effect/Layer"
87
+ *
88
+ * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>
89
+ *
90
+ * const MyAssistant = Assistant.make("my-assistant")
91
+ *
92
+ * const AppLive = MyAssistant.toLayer((turn) => turn.loop({ instructions: "Be brief." })).pipe(
93
+ * Layer.provide(ModelLive),
94
+ * Layer.provideMerge(AssistantEngine.layerMemory),
95
+ * Layer.provideMerge(ChatLog.layerMemory)
96
+ * )
97
+ * ```
98
+ *
99
+ * @see {@link layerCluster} for running each chat as a cluster entity
100
+ *
101
+ * @category layers
102
+ * @since 0.1.0
103
+ */
104
+ export const layerMemory: Layer.Layer<AssistantEngine, never, ChatLog> = Layer.effect(
105
+ AssistantEngine,
106
+ Effect.gen(function* () {
107
+ const context = yield* Effect.context<ChatLog>()
108
+ const log = yield* ChatLog
109
+ const registered = new Map<string, Turns.Registration>()
110
+ // A chat's keep-alive: a hold on its entry, so it stays open while runs or turns work in the background.
111
+ const held = MutableHashMap.empty<ChatKey, Scope.Closeable>()
112
+
113
+ // One entry per open chat, like a cluster entity: opened when used, closed five minutes after the last use.
114
+ const chats: RcMap.RcMap<ChatKey, Chat.Chat> = yield* RcMap.make({
115
+ lookup: Effect.fnUntraced(function* (key: ChatKey) {
116
+ const registration = registered.get(key.assistant)
117
+
118
+ if (registration === undefined) return yield* notRegistered(key.assistant)
119
+
120
+ return yield* Chat.make({
121
+ registration,
122
+ chatId: key.chatId,
123
+ keepAlive: (enabled) => keepAlive(key, enabled)
124
+ }).pipe(Effect.provide(context))
125
+ }),
126
+ idleTimeToLive: "5 minutes"
127
+ })
128
+
129
+ // On: a hold on the chat's entry, in a scope of its own. Off: closing that scope lets the entry go idle.
130
+ const keepAlive = Effect.fnUntraced(function* (key: ChatKey, enabled: boolean) {
131
+ if (enabled) {
132
+ const scope = yield* Scope.make()
133
+
134
+ yield* Effect.provideService(RcMap.get(chats, key), Scope.Scope, scope)
135
+
136
+ return MutableHashMap.set(held, key, scope)
137
+ }
138
+
139
+ const scope = MutableHashMap.get(held, key)
140
+
141
+ MutableHashMap.remove(held, key)
142
+
143
+ if (Option.isSome(scope)) yield* Scope.close(scope.value, Exit.void)
144
+ })
145
+
146
+ const withChat = Effect.fnUntraced(function* <A>(
147
+ assistant: string,
148
+ chatId: ChatId,
149
+ f: (chat: Chat.Chat) => Effect.Effect<A>
150
+ ) {
151
+ const chat = yield* RcMap.get(chats, new ChatKey({ assistant, chatId }))
152
+
153
+ return yield* f(chat)
154
+ }, Effect.scoped)
155
+
156
+ // A chat owes a turn when its last turn was cut off, or an input came after.
157
+ const resumeAll = Effect.fnUntraced(function* (registration: Turns.Registration) {
158
+ const { name, app } = registration.definition
159
+
160
+ for (const chatId of yield* log.unfinished) {
161
+ const entries = yield* log.read(chatId)
162
+
163
+ const lastTurn = entries.findLast(({ event }) => Predicate.isTagged(event, "TurnStarted"))?.event
164
+ const ours = Predicate.isTagged(lastTurn, "TurnStarted") && lastTurn.assistant === name
165
+
166
+ if (ours && History.needsTurn(entries, app.wakes)) yield* withChat(name, chatId, (chat) => chat.resume)
167
+ }
168
+ })
169
+
170
+ return AssistantEngine.of({
171
+ register: Effect.fn("AssistantEngine.register")(function* (registration: Turns.Registration) {
172
+ registered.set(registration.definition.name, registration)
173
+ // Chats this assistant was working on when the process stopped: pick them up again.
174
+ yield* Effect.forkScoped(resumeAll(registration))
175
+ }),
176
+ submit: (assistant, chatId, input) => withChat(assistant, chatId, (chat) => chat.submitInBackground(input)),
177
+ // The chat deletes itself, so a chat that's open stops; the entry goes, and the next open finds it deleted.
178
+ delete: Effect.fn("AssistantEngine.delete")(function* (assistant: string, chatId: ChatId) {
179
+ yield* withChat(assistant, chatId, (chat) => chat.delete)
180
+ yield* RcMap.invalidate(chats, new ChatKey({ assistant, chatId }))
181
+ }),
182
+ // The subscriber holds the chat open while it streams.
183
+ subscribe: (assistant, chatId, after) =>
184
+ Stream.unwrap(
185
+ Effect.gen(function* () {
186
+ const chat = yield* RcMap.get(chats, new ChatKey({ assistant, chatId }))
187
+
188
+ return chat.stream(after)
189
+ })
190
+ )
191
+ })
192
+ })
193
+ )
194
+
195
+ interface EntityClient {
196
+ readonly submit: (chatId: ChatId, input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) => Effect.Effect<void>
197
+ readonly subscribe: (chatId: ChatId, after: number) => Stream.Stream<AssistantEvent.Entry>
198
+ readonly delete: (chatId: ChatId) => Effect.Effect<void>
199
+ }
200
+
201
+ const Submit = Rpc.make("Submit", {
202
+ payload: { input: Schema.Union([AssistantEvent.Input, AssistantEvent.StoredAppEvent]) }
203
+ }).annotate(ClusterSchema.Persisted, true)
204
+
205
+ const Subscribe = Rpc.make("Subscribe", {
206
+ payload: { after: Schema.Int },
207
+ success: AssistantEvent.Entry,
208
+ stream: true
209
+ })
210
+
211
+ const Delete = Rpc.make("Delete")
212
+
213
+ const chatEntity = (assistant: string) => Entity.make(`Assistant/${assistant}`, [Submit, Subscribe, Delete])
214
+
215
+ /**
216
+ * Layer that runs chats as cluster entities, one entity per chat, keyed by chat id.
217
+ *
218
+ * **Details**
219
+ *
220
+ * The layer requires `Sharding`. Use a `SingleRunner` for one process with SQL storage, a runner
221
+ * of the app's cluster, or `TestRunner` in tests.
222
+ *
223
+ * **Example** (Running chats on a single runner with Postgres)
224
+ *
225
+ * ```ts
226
+ * import * as NodeCrypto from "@effect/platform-node/NodeCrypto"
227
+ * import * as PgClient from "@effect/sql-pg/PgClient"
228
+ * import { Assistant, AssistantEngine, ChatLog } from "effect-assistant"
229
+ * import type * as LanguageModel from "effect/ai/LanguageModel"
230
+ * import * as SingleRunner from "effect/cluster/SingleRunner"
231
+ * import * as Config from "effect/Config"
232
+ * import * as Layer from "effect/Layer"
233
+ *
234
+ * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>
235
+ *
236
+ * const MyAssistant = Assistant.make("my-assistant")
237
+ *
238
+ * const AppLive = MyAssistant.toLayer((turn) => turn.loop({ instructions: "Be brief." })).pipe(
239
+ * Layer.provide(ModelLive),
240
+ * Layer.provideMerge(AssistantEngine.layerCluster),
241
+ * Layer.provideMerge(
242
+ * Layer.merge(
243
+ * ChatLog.layerSql,
244
+ * SingleRunner.layer({ runnerStorage: "sql" }).pipe(Layer.provide(NodeCrypto.layer))
245
+ * )
246
+ * ),
247
+ * Layer.provide(PgClient.layerConfig({ url: Config.Redacted("DATABASE_URL") }))
248
+ * )
249
+ * ```
250
+ *
251
+ * @see {@link layerMemory} for running chats in one process
252
+ *
253
+ * @category layers
254
+ * @since 0.1.0
255
+ */
256
+ export const layerCluster: Layer.Layer<AssistantEngine, never, ChatLog | Sharding.Sharding> = Layer.effect(
257
+ AssistantEngine,
258
+ Effect.gen(function* () {
259
+ const context = yield* Effect.context<ChatLog | Sharding.Sharding>()
260
+ const sharding = yield* Sharding.Sharding
261
+ const clients = new Map<string, EntityClient>()
262
+
263
+ const register = Effect.fnUntraced(function* (registration: Turns.Registration) {
264
+ const ChatEntity = chatEntity(registration.definition.name)
265
+
266
+ const handlers = Effect.gen(function* () {
267
+ const address = yield* Entity.CurrentAddress
268
+ const chatId = yield* Schema.decodeUnknownEffect(ChatId)(address.entityId).pipe(Effect.orDie)
269
+ // The entity's own: `Entity.keepAlive` needs its address and keep-alive latch, which is in there too.
270
+ const entityContext = yield* Effect.context<Entity.CurrentAddress | Sharding.Sharding>()
271
+
272
+ const keepAlive = (enabled: boolean) =>
273
+ Entity.keepAlive(enabled).pipe(
274
+ Effect.provide(entityContext),
275
+ Effect.catchCause((cause) => Effect.logWarning("assistant chat keep-alive failed", cause))
276
+ )
277
+
278
+ // A keep-alive left on from before a restart (by a run cut off) has done its job: it started the entity.
279
+ yield* keepAlive(false)
280
+
281
+ const chat = yield* Chat.make({ registration, chatId, keepAlive })
282
+ yield* chat.resume
283
+
284
+ return ChatEntity.of({
285
+ // The turns run inside the request, so a crash leaves it unprocessed and the cluster redelivers it.
286
+ Submit: (request) => chat.submit(request.payload.input),
287
+ Subscribe: (request) => chat.stream(request.payload.after),
288
+ Delete: () => chat.delete
289
+ })
290
+ })
291
+
292
+ yield* sharding.registerEntity(ChatEntity, handlers.pipe(Effect.provide(context)), {
293
+ maxIdleTime: "5 minutes",
294
+ concurrency: "unbounded"
295
+ })
296
+ })
297
+
298
+ // Made on first use, so a process that registers no assistant can still reach its chats.
299
+ const clientOf = Effect.fnUntraced(function* (assistant: string) {
300
+ const known = clients.get(assistant)
301
+
302
+ if (known !== undefined) return known
303
+
304
+ const makeClient = yield* chatEntity(assistant).client.pipe(Effect.provide(context))
305
+
306
+ const client: EntityClient = {
307
+ submit: (chatId, input) => makeClient(chatId).Submit({ input }, { discard: true }).pipe(Effect.orDie),
308
+ subscribe: (chatId, after) => makeClient(chatId).Subscribe({ after }).pipe(Stream.orDie),
309
+ delete: (chatId) => makeClient(chatId).Delete().pipe(Effect.orDie)
310
+ }
311
+
312
+ clients.set(assistant, client)
313
+
314
+ return client
315
+ })
316
+
317
+ return AssistantEngine.of({
318
+ register: (registration) => register(registration).pipe(Effect.provide(context)),
319
+ submit: Effect.fn("AssistantEngine.submit")(function* (
320
+ assistant: string,
321
+ chatId: ChatId,
322
+ input: AssistantEvent.Input | AssistantEvent.StoredAppEvent
323
+ ) {
324
+ const client = yield* clientOf(assistant)
325
+
326
+ yield* client.submit(chatId, input)
327
+ }),
328
+ subscribe: (assistant, chatId, after) =>
329
+ Stream.unwrap(
330
+ Effect.gen(function* () {
331
+ const client = yield* clientOf(assistant)
332
+
333
+ return client.subscribe(chatId, after)
334
+ })
335
+ ),
336
+ delete: Effect.fn("AssistantEngine.delete")(function* (assistant: string, chatId: ChatId) {
337
+ const client = yield* clientOf(assistant)
338
+
339
+ yield* client.delete(chatId)
340
+ })
341
+ })
342
+ })
343
+ )