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,126 @@
1
+ import { __exportAll } from "./_virtual/_rolldown/runtime.js";
2
+ import { ChatId } from "./ChatId.js";
3
+ import { AssistantEvent, isInput } from "./AssistantEvent.js";
4
+ import { Chats } from "./Chats.js";
5
+ import { decodeEntry, encode, make as make$1 } from "./internal/events.js";
6
+ import { register } from "./internal/turns.js";
7
+ import { AssistantEngine } from "./AssistantEngine.js";
8
+ import * as Predicate from "effect/Predicate";
9
+ import * as Context from "effect/Context";
10
+ import * as Effect from "effect/Effect";
11
+ import * as Filter from "effect/Filter";
12
+ import * as Layer from "effect/Layer";
13
+ import * as Schema from "effect/Schema";
14
+ import * as Stream from "effect/Stream";
15
+ //#region src/Assistant.ts
16
+ var Assistant_exports = /* @__PURE__ */ __exportAll({
17
+ isAssistant: () => isAssistant,
18
+ make: () => make
19
+ });
20
+ const TypeId = "~effect-assistant/Assistant";
21
+ const toStream = (result) => Effect.isEffect(result) ? Stream.unwrap(result) : result;
22
+ /**
23
+ * Returns `true` when the value is an assistant's definition, created with {@link make}.
24
+ *
25
+ * @category guards
26
+ * @since 0.1.0
27
+ */
28
+ const isAssistant = (u) => Predicate.hasProperty(u, TypeId);
29
+ function entrySchema(events) {
30
+ return Schema.toCodecJson(Schema.Struct({
31
+ chatId: ChatId,
32
+ seq: Schema.Int,
33
+ at: Schema.Finite,
34
+ event: Schema.Union([AssistantEvent, ...events.map((event) => event.schema)])
35
+ }));
36
+ }
37
+ /**
38
+ * Creates an assistant definition from its name, its UI blocks, its specialists, and the app's own
39
+ * events it stores (see `AppEvent`).
40
+ *
41
+ * **Details**
42
+ *
43
+ * The definition holds no code that runs turns. Provide a handler with its `toLayer`, then yield
44
+ * the definition to get the assistant's {@link Service}.
45
+ *
46
+ * **Example** (Defining an assistant and submitting a message)
47
+ *
48
+ * ```ts
49
+ * import { Assistant, AssistantEvent, ChatId } from "effect-assistant"
50
+ * import * as Effect from "effect/Effect"
51
+ *
52
+ * export const MyAssistant = Assistant.make("my-assistant")
53
+ *
54
+ * const program = Effect.gen(function* () {
55
+ * const assistant = yield* MyAssistant
56
+ * const chatId = yield* ChatId.make()
57
+ *
58
+ * yield* assistant.submit(chatId, AssistantEvent.UserMessage.make({ text: "Weather in Oslo?" }))
59
+ * })
60
+ * ```
61
+ *
62
+ * @see {@link Assistant} for the definition's members
63
+ * @see {@link Service} for what `yield* MyAssistant` returns
64
+ *
65
+ * @category constructors
66
+ * @since 0.1.0
67
+ */
68
+ const make = (name, options) => {
69
+ const events = options?.events ?? [];
70
+ const definition = {
71
+ name,
72
+ blocks: options?.blocks,
73
+ specialists: options?.specialists ?? [],
74
+ app: make$1(events)
75
+ };
76
+ const Key = Context.Service(`effect-assistant/Assistant/${name}`);
77
+ const stored = (input) => isInput(input) ? Effect.succeed(input) : encode(definition.app, input);
78
+ const ChatKey = Context.Service(`effect-assistant/Assistant/${name}/Chat`);
79
+ const makeService = Effect.gen(function* () {
80
+ const engine = yield* AssistantEngine;
81
+ const chats = yield* Chats;
82
+ return Key.of({
83
+ submit: Effect.fn("Assistant.submit")(function* (chatId, input) {
84
+ yield* chats.get(chatId);
85
+ yield* engine.submit(name, chatId, yield* stored(input));
86
+ }),
87
+ subscribe: (chatId, options) => engine.subscribe(name, chatId, options?.after ?? 0).pipe(Stream.filterMap(Filter.fromPredicateOption((entry) => decodeEntry(definition.app, entry)))),
88
+ delete: (chatId) => engine.delete(name, chatId)
89
+ });
90
+ });
91
+ function toLayer(build) {
92
+ return Layer.effect(Key, Effect.gen(function* () {
93
+ const context = yield* Effect.context();
94
+ const registration = yield* register(definition, { open: (typed) => Effect.gen(function* () {
95
+ const chat = ChatKey.of({
96
+ chatId: typed.chatId,
97
+ entries: typed.entries,
98
+ append: typed.append
99
+ });
100
+ const handler = Effect.isEffect(build) ? yield* Effect.provideService(build, ChatKey, chat) : build;
101
+ return (turn) => Stream.provideContext(toStream(handler(turn)), context).pipe(Stream.provideService(ChatKey, chat));
102
+ }).pipe(Effect.provideContext(context), Effect.orDie) });
103
+ yield* (yield* AssistantEngine).register(registration);
104
+ return yield* makeService;
105
+ }));
106
+ }
107
+ const named = Object.defineProperty(Key, "name", {
108
+ value: name,
109
+ writable: true
110
+ });
111
+ return Object.assign(named, {
112
+ [TypeId]: TypeId,
113
+ name,
114
+ blocks: options?.blocks,
115
+ specialists: options?.specialists ?? [],
116
+ events,
117
+ toLayer,
118
+ layerClient: Layer.effect(Key, makeService),
119
+ Chat: ChatKey,
120
+ Entry: entrySchema(events)
121
+ });
122
+ };
123
+ //#endregion
124
+ export { Assistant_exports, isAssistant, make };
125
+
126
+ //# sourceMappingURL=Assistant.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"Assistant.js","names":["AssistantEvent.AssistantEvent","AppEvents.make","AssistantEvent.isInput","AppEvents.encode","Chats.Chats","AppEvents.decodeEntry","Turns.register"],"sources":["../src/Assistant.ts"],"sourcesContent":["/**\n * This module provides `Assistant.make`, which defines an assistant that works in a chat the way a\n * colleague does: the user messages it, it works in the background with the app's tools, and it\n * messages the user back.\n *\n * A definition is what the rest of an app imports. Yielding it (`yield* MyAssistant`) returns the\n * assistant's {@link Service}, which submits inputs to chats and streams them back. Its `toLayer`\n * registers the handler that runs each {@link Turn} with the `AssistantEngine`, and its\n * `layerClient` provides the service without a handler. Code that runs inside a chat reads and\n * extends that chat through the definition's {@link Chat} key.\n *\n * @since 0.1.0\n */\nimport type * as AiError from \"effect/ai/AiError\"\nimport type * as LanguageModel from \"effect/ai/LanguageModel\"\nimport type * as Prompt from \"effect/ai/Prompt\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Filter from \"effect/Filter\"\nimport * as Layer from \"effect/Layer\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as AppEvent from \"./AppEvent.ts\"\nimport { AssistantEngine } from \"./AssistantEngine.ts\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport type * as AssistantLoop from \"./AssistantLoop.ts\"\nimport type * as BlockKit from \"./BlockKit.ts\"\nimport { ChatId } from \"./ChatId.ts\"\nimport * as Chats from \"./Chats.ts\"\nimport type { CurrentChat } from \"./CurrentChat.ts\"\nimport type * as Instructions from \"./Instructions.ts\"\nimport * as AppEvents from \"./internal/events.ts\"\nimport * as Turns from \"./internal/turns.ts\"\nimport type { Skill } from \"./Skill.ts\"\nimport type * as Specialist from \"./Specialist.ts\"\n\nconst TypeId = \"~effect-assistant/Assistant\" as const\n\n/**\n * Represents the services that a turn provides to its tools, its loop, and its specialists. These\n * are the turn's chat (`CurrentChat`) and the chat's specialist runner (`Specialist.Runner`).\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type TurnServices = CurrentChat | Specialist.Runner\n\n/**\n * Represents the options accepted by `turn.loop`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface LoopOptions<T extends Record<string, Tool.Any> = Record<never, never>, RS = never, Events = never> {\n /** The assistant's role and rules. The loop places `Instructions.protocol` before them. */\n readonly instructions: string | Instructions.Resolved\n /**\n * Tools the model can use in addition to the assistant's own. This is an `effect/ai` toolkit,\n * and its handlers come from the layer. Combine several toolkits with `Toolkit.merge`, for\n * example `Memory.Tools` or a `ToolDiscovery.make(...)` toolkit together with your own.\n */\n readonly toolkit?: Toolkit.Toolkit<T> | undefined\n /**\n * Playbooks the model can follow. The prompt lists them as a catalog, and the model loads one\n * with `load_skill` when a task matches it.\n */\n readonly skills?: ReadonlyArray<Skill<RS>> | undefined\n /** The maximum number of model calls per turn. Defaults to 16. */\n readonly maxSteps?: number | undefined\n /** The message the reply pass gives the model when the turn would end without a reply. */\n readonly replyNudge?: string | undefined\n /**\n * Selects which of the chat's entries the model reads, for example only those since the last\n * summary. Defaults to all entries.\n */\n readonly history?: HistoryView<Events> | undefined\n}\n\n/**\n * Represents a function that selects which of a chat's entries the model reads, and what else it\n * reads with them.\n *\n * **Details**\n *\n * The function receives the chat's entries and returns, in order, a mix of entries and\n * `Prompt.Message`s. The model reads the returned entries the same way it reads the full history,\n * and reads each prompt message unchanged.\n *\n * @category models\n * @since 0.1.0\n */\nexport type HistoryView<Events = never> = (\n entries: ReadonlyArray<Entry<Events>>\n) => ReadonlyArray<Entry<Events> | Prompt.Message>\n\n/**\n * Represents an entry in a chat's log, with the assistant's own events decoded to their types.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Entry<Events = never> {\n readonly chatId: ChatId\n readonly seq: number\n readonly at: number\n readonly event: AssistantEvent.AssistantEvent | Events\n}\n\n/**\n * Represents the options accepted by `turn.replyIfOwed`.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ReplyOptions {\n /** The assistant's instructions, as passed to `turn.loop`. `Instructions.protocol` is added. */\n readonly instructions: string | Instructions.Resolved\n /**\n * The message given to the model after the history. Defaults to a message saying that it\n * hasn't replied yet and should reply now.\n */\n readonly nudge?: string | undefined\n}\n\n/**\n * Represents one turn, as the assistant's handler receives it.\n *\n * `Events` is the type of the app's own events that the assistant registered with its `events`\n * option.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Turn<Events = never> {\n readonly chatId: ChatId\n /**\n * Returns the model's history, built from the chat's entries (all of them, or those a view\n * keeps), together with how far into the chat it reaches.\n *\n * Read it before every model call, as the loop does. Each step records how far its model call\n * read, and the turn ends once it has handled what the model saw. An input that arrived after\n * that is handled by the next turn.\n */\n readonly history: (view?: HistoryView<Events>) => Effect.Effect<AssistantLoop.ChatHistory>\n /**\n * Returns the full system prompt for the given instructions. It contains\n * `Instructions.protocol`, the instructions, and the specialist runs that are working now.\n */\n readonly instructions: (instructions: string | Instructions.Resolved) => Instructions.Resolved\n /**\n * Runs the agent loop over the chat. The loop uses `Instructions.protocol`, the assistant's own\n * tools, and the instructions, tools, and skills in `options`. Every step is a tool call, and\n * the loop ends with `replyIfOwed`.\n */\n readonly loop: <T extends Record<string, Tool.Any> = Record<never, never>, RS = never>(\n options: LoopOptions<T, RS, Events>\n ) => Stream.Stream<\n AssistantLoop.Event,\n AiError.AiError,\n LanguageModel.LanguageModel | TurnServices | AssistantLoop.ToolkitServices<T> | RS\n >\n /**\n * Runs one more pass when the turn would otherwise end without a reply to the user's latest\n * message. In this pass the model can only reply.\n *\n * The stream is empty when no reply is owed, or when an input arrived that the next turn will\n * read. `loop` runs this pass with its own prompt and tools, so the pass reuses the cached\n * prompt.\n */\n readonly replyIfOwed: (\n options: ReplyOptions\n ) => Stream.Stream<AssistantLoop.Event, AiError.AiError, LanguageModel.LanguageModel | TurnServices>\n}\n\n/**\n * Represents an assistant's handler, which runs a turn and returns it as a stream of the loop's\n * events.\n *\n * The handler may return the stream directly or from an Effect. `R` is the services the stream\n * requires, and `RE` is the services the Effect requires.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Handler<R = never, RE = R, Events = never> = (\n turn: Turn<Events>\n) =>\n | Stream.Stream<AssistantLoop.Event, unknown, R>\n | Effect.Effect<Stream.Stream<AssistantLoop.Event, unknown, R>, unknown, RE>\n\n/**\n * Computes the services an assistant's handler needs beyond those its turns provide (the turn\n * services and `LanguageModel`) and its tools' handlers (which its layer requires). These are the\n * services that its build Effect must require.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type HandlerServices<R> = Exclude<R, TurnServices | LanguageModel.LanguageModel | Tool.Handler<string>>\n\nconst toStream = <R, RE>(\n result:\n | Stream.Stream<AssistantLoop.Event, unknown, R>\n | Effect.Effect<Stream.Stream<AssistantLoop.Event, unknown, R>, unknown, RE>\n): Stream.Stream<AssistantLoop.Event, unknown, R | RE> => (Effect.isEffect(result) ? Stream.unwrap(result) : result)\n\n/**\n * Identifies an assistant's service in a context. Each assistant has its own identifier, keyed by\n * its name.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Identifier<Name extends string> {\n readonly \"~effect-assistant/Assistant\": Name\n}\n\n/**\n * Identifies, in a context, the chat that an assistant's turns run in.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface ChatIdentifier<Name extends string> {\n readonly \"~effect-assistant/Assistant/Chat\": Name\n}\n\n/**\n * Represents the chat that a turn of this assistant runs in, typed with the assistant's events.\n *\n * Use `yield* MyAssistant.Chat` in the handler, in the handler's build, or in a tool that its\n * turns run. Code that doesn't know the assistant uses `CurrentChat` instead.\n *\n * @see {@link CurrentChat} for the same chat without the assistant's event types\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Chat<Events = never> {\n readonly chatId: ChatId\n /**\n * The chat's entries so far, in order. They include the library's events and the assistant's\n * own events, typed.\n */\n readonly entries: Effect.Effect<ReadonlyArray<Entry<Events>>>\n /**\n * Appends events after the chat's last entry and sends them to the chat's subscribers. The\n * events can be the library's or the assistant's own, such as a summary. An event that wakes a\n * turn is handled by the next turn.\n */\n append(...events: ReadonlyArray<AssistantEvent.AssistantEvent | Events>): Effect.Effect<void>\n}\n\n/**\n * Represents the service that `yield* MyAssistant` returns. It gives code outside a chat, such as\n * a server or a workflow, access to the assistant's chats. Code that runs inside a chat uses\n * `CurrentChat` instead.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Service<Events = never> {\n /**\n * Stores an input or one of the assistant's own events, then returns. Examples are a user's\n * message or block answer, a workflow's progress, or the draft the user opened. The assistant\n * works on events that wake a turn in the background.\n *\n * Fails with `GetChatError` when the app's `Chats` service reports that the chat can't be used,\n * because the app doesn't know the chat or has deleted it.\n */\n // Method syntax: a service for these events is one for any (`Service<any>`), for helpers over assistants.\n submit(chatId: ChatId, input: AssistantEvent.Input | Events): Effect.Effect<void, Chats.GetChatError>\n /**\n * Streams the chat's stored entries, then live ones, with the assistant's own events decoded.\n * A reader that already has the earlier entries passes `after` and receives only the entries\n * after that `seq`.\n *\n * For a chat client, pipe the whole log into `ChatView.updates(MyAssistant, { after })`, which\n * streams the chat as its user sees it. Its `after` goes there, not here: the view of a message\n * depends on earlier entries.\n */\n readonly subscribe: (\n chatId: ChatId,\n options?: { readonly after?: number | undefined }\n ) => Stream.Stream<Entry<Events>>\n /**\n * Deletes a chat by storing a `ChatDeleted` event and stopping everything that works in it.\n *\n * **Details**\n *\n * A turn or specialist run working in the chat stops, and subscribers' streams end with the\n * `ChatDeleted` event. After that the chat stores nothing more: a later input, a run's report,\n * or a workflow's event for it is dropped without an error. The log is kept, and removing it is\n * up to the app. Deleting a chat a second time does nothing.\n *\n * When the app's `Chats` service reports a chat as deleted, the assistant deletes it in the same\n * way the next time it checks. It checks before an input is stored and before each model call.\n */\n readonly delete: (chatId: ChatId) => Effect.Effect<void>\n}\n\n/**\n * Represents an assistant's definition.\n *\n * The definition holds what callers and the UI need to know about the assistant, builds its\n * handler's layer, and is the key of its service (`yield* MyAssistant`). `Events` is the type of\n * the app's own events that the assistant registered.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Assistant<\n Name extends string = string,\n Specs extends Specialist.Any = never,\n Events = never\n> extends Context.Service<Identifier<Name>, Service<Events>> {\n readonly [TypeId]: typeof TypeId\n readonly name: Name\n readonly blocks: BlockKit.BlockKit | undefined\n /** The specialists the assistant can hand work to. */\n readonly specialists: ReadonlyArray<Specs>\n /** The app's own events the assistant registered. */\n readonly events: ReadonlyArray<AppEvent.Any>\n /**\n * Creates a layer that registers the assistant's handler with the engine and provides the\n * assistant's service.\n *\n * **Details**\n *\n * `build` is the handler, or an Effect that returns it. The handler may use the turn services,\n * `LanguageModel`, its tools' handlers (which the layer then requires), and services that its\n * build Effect required (see `Specialist.CheckServices`). The layer requires the\n * `AssistantEngine`, the `LanguageModel`, and each specialist's handler\n * (`Research.toLayer(...)`).\n *\n * **Example** (Providing an assistant's handler)\n *\n * ```ts\n * import { Assistant, AssistantEngine, ChatLog } from \"effect-assistant\"\n * import type * as LanguageModel from \"effect/ai/LanguageModel\"\n * import * as Layer from \"effect/Layer\"\n *\n * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const MyAssistantLive = MyAssistant.toLayer((turn) =>\n * turn.loop({ instructions: \"You help a small team. Be brief.\" })\n * )\n *\n * const AppLive = MyAssistantLive.pipe(\n * Layer.provide(ModelLive),\n * Layer.provideMerge(AssistantEngine.layerMemory),\n * Layer.provideMerge(ChatLog.layerMemory)\n * )\n * ```\n */\n readonly toLayer: <R = never, RE = never, E = never, RX = never>(\n build: (Handler<R, RE, Events> | Effect.Effect<Handler<R, RE, Events>, E, RX>) &\n Specialist.CheckServices<Exclude<HandlerServices<R | RE>, RX | ChatIdentifier<Name>>>\n ) => Layer.Layer<\n Identifier<Name>,\n never,\n | AssistantEngine\n | LanguageModel.LanguageModel\n | Specialist.HandlerOf<Specs>\n | Exclude<RX, Scope.Scope | CurrentChat | ChatIdentifier<Name>>\n | Specialist.ToolHandlers<R | RE>\n >\n /**\n * A layer that provides the assistant's service without its handler.\n *\n * **When to use**\n *\n * Use it in a process that submits to chats that another process runs, such as a web server in\n * front of a cluster.\n *\n * **Example** (Serving clients in front of a cluster)\n *\n * ```ts\n * import { Assistant, AssistantEngine } from \"effect-assistant\"\n * import * as Layer from \"effect/Layer\"\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * // Requires `ChatLog` and `Sharding`. The cluster's runners run the chats.\n * const MyAssistantClient = MyAssistant.layerClient.pipe(\n * Layer.provide(AssistantEngine.layerCluster)\n * )\n * ```\n */\n readonly layerClient: Layer.Layer<Identifier<Name>, never, AssistantEngine>\n /**\n * The key of the chat that the assistant's turns run in, typed with its events. See\n * {@link Chat}.\n */\n readonly Chat: Context.Service<ChatIdentifier<Name>, Chat<Events>>\n /** A schema that encodes the chat's entries to JSON, including the assistant's own events. */\n readonly Entry: Schema.Codec<Entry<Events>, Schema.Json>\n}\n\n/**\n * Represents any assistant, for use in generic constraints.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type Any = Assistant<any, any, any>\n\n/**\n * Returns `true` when the value is an assistant's definition, created with {@link make}.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isAssistant = (u: unknown): u is Any => Predicate.hasProperty(u, TypeId)\n\nfunction entrySchema<E>(events: ReadonlyArray<AppEvent.Any>): Schema.Codec<Entry<E>, Schema.Json>\n// The overload states the decoded type: the library's events, or one of these schemas' types.\nfunction entrySchema(events: ReadonlyArray<AppEvent.Any>): Schema.Top {\n return Schema.toCodecJson(\n Schema.Struct({\n chatId: ChatId,\n seq: Schema.Int,\n at: Schema.Finite,\n event: Schema.Union([AssistantEvent.AssistantEvent, ...events.map((event) => event.schema)])\n })\n )\n}\n\n/**\n * Creates an assistant definition from its name, its UI blocks, its specialists, and the app's own\n * events it stores (see `AppEvent`).\n *\n * **Details**\n *\n * The definition holds no code that runs turns. Provide a handler with its `toLayer`, then yield\n * the definition to get the assistant's {@link Service}.\n *\n * **Example** (Defining an assistant and submitting a message)\n *\n * ```ts\n * import { Assistant, AssistantEvent, ChatId } from \"effect-assistant\"\n * import * as Effect from \"effect/Effect\"\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\")\n *\n * const program = Effect.gen(function* () {\n * const assistant = yield* MyAssistant\n * const chatId = yield* ChatId.make()\n *\n * yield* assistant.submit(chatId, AssistantEvent.UserMessage.make({ text: \"Weather in Oslo?\" }))\n * })\n * ```\n *\n * @see {@link Assistant} for the definition's members\n * @see {@link Service} for what `yield* MyAssistant` returns\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <\n const Name extends string,\n const Specs extends ReadonlyArray<Specialist.Any> = readonly [],\n const Events extends ReadonlyArray<AppEvent.Any> = readonly []\n>(\n name: Name,\n options?: {\n /** UI blocks the assistant can add to its messages. */\n readonly blocks?: BlockKit.BlockKit | undefined\n /**\n * The specialists the assistant can hand work to. Each specialist's `toLayer` must be\n * provided to the assistant's layer.\n */\n readonly specialists?: Specs | undefined\n /**\n * The app's own events, each created with `AppEvent.make(schema, { wakes, render })`.\n * `submit` and the chat's `append` store them, and the chat's `entries` read them back,\n * decoded. Events that wake a turn are inputs, and the model reads each event that has a\n * `render`.\n */\n readonly events?: Events | undefined\n }\n): Assistant<Name, Specs[number], AppEvent.Type<Events[number]>> => {\n const events = options?.events ?? []\n\n const definition: Turns.Definition = {\n name,\n blocks: options?.blocks,\n specialists: options?.specialists ?? [],\n app: AppEvents.make(events)\n }\n\n type OwnEvents = AppEvent.Type<Events[number]>\n\n const Key = Context.Service<Identifier<Name>, Service<OwnEvents>>(`effect-assistant/Assistant/${name}`)\n\n // The app's own events go to the engine encoded, as they're stored; the library's go unchanged.\n const stored = (\n input: AssistantEvent.Input | OwnEvents\n ): Effect.Effect<AssistantEvent.Input | AssistantEvent.StoredAppEvent> =>\n AssistantEvent.isInput(input) ? Effect.succeed(input) : AppEvents.encode(definition.app, input)\n\n const ChatKey = Context.Service<ChatIdentifier<Name>, Chat<OwnEvents>>(`effect-assistant/Assistant/${name}/Chat`)\n\n // On the engine and the app's `Chats` the layer was given, so every caller sees the same ones.\n const makeService = Effect.gen(function* () {\n const engine = yield* AssistantEngine\n const chats = yield* Chats.Chats\n\n return Key.of({\n submit: Effect.fn(\"Assistant.submit\")(function* (chatId: ChatId, input: AssistantEvent.Input | OwnEvents) {\n // Checked here, where the caller can handle it: the chat checks again when it stores the input.\n yield* chats.get(chatId)\n yield* engine.submit(name, chatId, yield* stored(input))\n }),\n subscribe: (chatId, options) =>\n engine\n .subscribe(name, chatId, options?.after ?? 0)\n .pipe(\n Stream.filterMap(\n Filter.fromPredicateOption((entry: AssistantEvent.Entry) => AppEvents.decodeEntry(definition.app, entry))\n )\n ),\n delete: (chatId) => engine.delete(name, chatId)\n })\n })\n\n // The signature checks what the handler uses (`CheckServices`); the layer's services, which the build\n // required, are provided to it and to every turn's stream, so what's left is the turn services.\n function toLayer<R = never, RE = never, E = never, RX = never>(\n build: (Handler<R, RE, OwnEvents> | Effect.Effect<Handler<R, RE, OwnEvents>, E, RX>) &\n Specialist.CheckServices<Exclude<HandlerServices<R | RE>, RX | ChatIdentifier<Name>>>\n ): Layer.Layer<\n Identifier<Name>,\n never,\n | AssistantEngine\n | LanguageModel.LanguageModel\n | Specialist.HandlerOf<Specs[number]>\n | Exclude<RX, Scope.Scope | CurrentChat | ChatIdentifier<Name>>\n | Specialist.ToolHandlers<R | RE>\n >\n function toLayer(\n build: Handler<any, any, any> | Effect.Effect<Handler<any, any, any>, unknown, any>\n ): Layer.Layer<Identifier<Name>, never, any> {\n return Layer.effect(\n Key,\n Effect.gen(function* () {\n const context = yield* Effect.context()\n\n const registration = yield* Turns.register(definition, {\n // The build runs per chat activation, in the chat; here it only keeps the layer's services for it.\n open: (typed) =>\n Effect.gen(function* () {\n // The chat's entries are already decoded with this assistant's events.\n const chat = ChatKey.of({ chatId: typed.chatId, entries: typed.entries, append: typed.append })\n const handler = Effect.isEffect(build) ? yield* Effect.provideService(build, ChatKey, chat) : build\n\n return (turn: Turn<any>) =>\n Stream.provideContext(toStream(handler(turn)), context).pipe(Stream.provideService(ChatKey, chat))\n }).pipe(Effect.provideContext(context), Effect.orDie)\n })\n\n yield* (yield* AssistantEngine).register(registration)\n\n return yield* makeService\n })\n )\n }\n\n // The key is a function, whose own `name` is read-only: the assistant's name replaces it.\n const named = Object.defineProperty(Key, \"name\", { value: name, writable: true })\n\n return Object.assign(named, {\n [TypeId]: TypeId,\n name,\n blocks: options?.blocks,\n specialists: options?.specialists ?? [],\n events,\n toLayer,\n layerClient: Layer.effect(Key, makeService),\n Chat: ChatKey,\n Entry: entrySchema<OwnEvents>(events)\n })\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAwCA,MAAM,SAAS;AAoKf,MAAM,YACJ,WAGyD,OAAO,SAAS,MAAM,IAAI,OAAO,OAAO,MAAM,IAAI;;;;;;;AAmN7G,MAAa,eAAe,MAAyB,UAAU,YAAY,GAAG,MAAM;AAIpF,SAAS,YAAY,QAAiD;CACpE,OAAO,OAAO,YACZ,OAAO,OAAO;EACZ,QAAQ;EACR,KAAK,OAAO;EACZ,IAAI,OAAO;EACX,OAAO,OAAO,MAAM,CAACA,gBAA+B,GAAG,OAAO,KAAK,UAAU,MAAM,MAAM,CAAC,CAAC;CAC7F,CAAC,CACH;AACF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCA,MAAa,QAKX,MACA,YAgBkE;CAClE,MAAM,SAAS,SAAS,UAAU,CAAC;CAEnC,MAAM,aAA+B;EACnC;EACA,QAAQ,SAAS;EACjB,aAAa,SAAS,eAAe,CAAC;EACtC,KAAKC,OAAe,MAAM;CAC5B;CAIA,MAAM,MAAM,QAAQ,QAA8C,8BAA8B,MAAM;CAGtG,MAAM,UACJ,UAEAC,QAAuB,KAAK,IAAI,OAAO,QAAQ,KAAK,IAAIC,OAAiB,WAAW,KAAK,KAAK;CAEhG,MAAM,UAAU,QAAQ,QAA+C,8BAA8B,KAAK,MAAM;CAGhH,MAAM,cAAc,OAAO,IAAI,aAAa;EAC1C,MAAM,SAAS,OAAO;EACtB,MAAM,QAAQ,OAAOC;EAErB,OAAO,IAAI,GAAG;GACZ,QAAQ,OAAO,GAAG,kBAAkB,CAAC,CAAC,WAAW,QAAgB,OAAyC;IAExG,OAAO,MAAM,IAAI,MAAM;IACvB,OAAO,OAAO,OAAO,MAAM,QAAQ,OAAO,OAAO,KAAK,CAAC;GACzD,CAAC;GACD,YAAY,QAAQ,YAClB,OACG,UAAU,MAAM,QAAQ,SAAS,SAAS,CAAC,CAAC,CAC5C,KACC,OAAO,UACL,OAAO,qBAAqB,UAAgCC,YAAsB,WAAW,KAAK,KAAK,CAAC,CAC1G,CACF;GACJ,SAAS,WAAW,OAAO,OAAO,MAAM,MAAM;EAChD,CAAC;CACH,CAAC;CAgBD,SAAS,QACP,OAC2C;EAC3C,OAAO,MAAM,OACX,KACA,OAAO,IAAI,aAAa;GACtB,MAAM,UAAU,OAAO,OAAO,QAAQ;GAEtC,MAAM,eAAe,OAAOC,SAAe,YAAY,EAErD,OAAO,UACL,OAAO,IAAI,aAAa;IAEtB,MAAM,OAAO,QAAQ,GAAG;KAAE,QAAQ,MAAM;KAAQ,SAAS,MAAM;KAAS,QAAQ,MAAM;IAAO,CAAC;IAC9F,MAAM,UAAU,OAAO,SAAS,KAAK,IAAI,OAAO,OAAO,eAAe,OAAO,SAAS,IAAI,IAAI;IAE9F,QAAQ,SACN,OAAO,eAAe,SAAS,QAAQ,IAAI,CAAC,GAAG,OAAO,CAAC,CAAC,KAAK,OAAO,eAAe,SAAS,IAAI,CAAC;GACrG,CAAC,CAAC,CAAC,KAAK,OAAO,eAAe,OAAO,GAAG,OAAO,KAAK,EACxD,CAAC;GAED,QAAQ,OAAO,gBAAA,CAAiB,SAAS,YAAY;GAErD,OAAO,OAAO;EAChB,CAAC,CACH;CACF;CAGA,MAAM,QAAQ,OAAO,eAAe,KAAK,QAAQ;EAAE,OAAO;EAAM,UAAU;CAAK,CAAC;CAEhF,OAAO,OAAO,OAAO,OAAO;GACzB,SAAS;EACV;EACA,QAAQ,SAAS;EACjB,aAAa,SAAS,eAAe,CAAC;EACtC;EACA;EACA,aAAa,MAAM,OAAO,KAAK,WAAW;EAC1C,MAAM;EACN,OAAO,YAAuB,MAAM;CACtC,CAAC;AACH"}
@@ -0,0 +1,85 @@
1
+ import { AnyEntry, AssistantEvent_d_exports } from "./AssistantEvent.js";
2
+ import { RunId } from "./RunId.js";
3
+ declare namespace AssistantActivity_d_exports {
4
+ export { Options, SpecialistRun, State, apply, empty, fromEntries, isWorking };
5
+ }
6
+ /**
7
+ * Represents a specialist run that is working.
8
+ *
9
+ * @category models
10
+ * @since 0.1.0
11
+ */
12
+ export interface SpecialistRun {
13
+ readonly runId: RunId;
14
+ readonly specialist: string;
15
+ /** The goal the run is working on. */
16
+ readonly goal: string;
17
+ /** When the run started, in epoch milliseconds. */
18
+ readonly since: number;
19
+ }
20
+ /**
21
+ * Represents what is working in a chat.
22
+ *
23
+ * @category models
24
+ * @since 0.1.0
25
+ */
26
+ export interface State {
27
+ /** When the running turn started, in epoch milliseconds, or `undefined` when no turn runs. */
28
+ readonly turnSince: number | undefined;
29
+ /**
30
+ * Whether an input arrived that no finished turn has read. When this is true, a turn is about
31
+ * to start.
32
+ */
33
+ readonly queued: boolean;
34
+ /** The `seq` of the newest input. */
35
+ readonly lastInputSeq: number;
36
+ /** Specialist runs that are working, by run id. */
37
+ readonly specialists: ReadonlyMap<RunId, SpecialistRun>;
38
+ }
39
+ /**
40
+ * The activity of a chat with an empty log, where nothing is working.
41
+ *
42
+ * @category constructors
43
+ * @since 0.1.0
44
+ */
45
+ export declare const empty: State;
46
+ /**
47
+ * Represents the options for folding a chat's entries into its activity.
48
+ *
49
+ * @category models
50
+ * @since 0.1.0
51
+ */
52
+ export interface Options {
53
+ /**
54
+ * The tags of the app's events that wake a turn (see `AppEvent`). These events count as inputs
55
+ * too. Defaults to none.
56
+ */
57
+ readonly wakes?: ReadonlySet<string> | undefined;
58
+ }
59
+ /**
60
+ * Returns the activity after one more entry. Fold a chat's entries in order, or use
61
+ * {@link fromEntries}.
62
+ *
63
+ * @category combinators
64
+ * @since 0.1.0
65
+ */
66
+ export declare const apply: (activity: State, entry: AnyEntry, options?: Options) => State;
67
+ /**
68
+ * Returns what is working in a chat after the given entries, folded in order from
69
+ * {@link empty}.
70
+ *
71
+ * @category constructors
72
+ * @since 0.1.0
73
+ */
74
+ export declare const fromEntries: (entries: ReadonlyArray<AnyEntry>, options?: Options) => State;
75
+ /**
76
+ * Returns whether anything is working: a turn that is running or about to start, or a specialist
77
+ * run.
78
+ *
79
+ * @category guards
80
+ * @since 0.1.0
81
+ */
82
+ export declare const isWorking: (activity: State) => boolean;
83
+ //#endregion
84
+ export { AssistantActivity_d_exports };
85
+ //# sourceMappingURL=AssistantActivity.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AssistantActivity.d.ts","names":[],"sources":["../src/AssistantActivity.ts"],"mappings":";;;;;;;;;;;iBAsBiB;WACN,OAAO;WACP;;WAEA;;WAEA;;;;;;;;iBASM;;WAEN;;;;;WAKA;;WAEA;;WAEA,aAAa,YAAY,OAAO;;;;;;;;qBAS9B,OAAO;;;;;;;iBAsBH;;;;;WAKN,QAAQ;;;;;;;;;qBAUN,QAAK,UAAc,OAAK,OAAS,UAAuB,UAAY,YAAU;;;;;;;;qBA4C9E,cAAW,SAAa,cAAc,WAAwB,UAAY,YAAU;;;;;;;;qBAUpF,YAAS,UAAc"}
@@ -0,0 +1,105 @@
1
+ import { __exportAll } from "./_virtual/_rolldown/runtime.js";
2
+ import { isInput, isLibraryEvent, isWaking } from "./AssistantEvent.js";
3
+ import * as Predicate from "effect/Predicate";
4
+ import * as Match from "effect/Match";
5
+ //#region src/AssistantActivity.ts
6
+ /**
7
+ * This module provides functions that determine what is working in a chat right now, read from
8
+ * the chat's log.
9
+ *
10
+ * A {@link State} records whether the assistant is running a turn or is about to start one,
11
+ * and which specialist runs are working. Fold a chat's entries into it with {@link apply}, or
12
+ * build it from a list of entries with {@link fromEntries}, then check it with
13
+ * {@link isWorking}.
14
+ *
15
+ * @since 0.1.0
16
+ */
17
+ var AssistantActivity_exports = /* @__PURE__ */ __exportAll({
18
+ apply: () => apply,
19
+ empty: () => empty,
20
+ fromEntries: () => fromEntries,
21
+ isWorking: () => isWorking
22
+ });
23
+ /**
24
+ * The activity of a chat with an empty log, where nothing is working.
25
+ *
26
+ * @category constructors
27
+ * @since 0.1.0
28
+ */
29
+ const empty = {
30
+ turnSince: void 0,
31
+ queued: false,
32
+ lastInputSeq: 0,
33
+ specialists: /* @__PURE__ */ new Map()
34
+ };
35
+ const withoutRun = (activity, runId) => {
36
+ if (!activity.specialists.has(runId)) return activity;
37
+ const specialists = new Map(activity.specialists);
38
+ specialists.delete(runId);
39
+ return {
40
+ ...activity,
41
+ specialists
42
+ };
43
+ };
44
+ /**
45
+ * Returns the activity after one more entry. Fold a chat's entries in order, or use
46
+ * {@link fromEntries}.
47
+ *
48
+ * @category combinators
49
+ * @since 0.1.0
50
+ */
51
+ const apply = (activity, entry, options) => {
52
+ const event = entry.event;
53
+ if (!isLibraryEvent(event)) return options?.wakes?.has(event._tag) === true ? {
54
+ ...activity,
55
+ queued: true,
56
+ lastInputSeq: entry.seq
57
+ } : activity;
58
+ if (isInput(event)) {
59
+ const current = Predicate.isTagged(event, "SpecialistFinished") ? withoutRun(activity, event.runId) : activity;
60
+ return isWaking(event) ? {
61
+ ...current,
62
+ queued: true,
63
+ lastInputSeq: entry.seq
64
+ } : current;
65
+ }
66
+ return Match.value(event).pipe(Match.tag("TurnStarted", () => ({
67
+ ...activity,
68
+ turnSince: entry.at
69
+ })), Match.tag("TurnCompleted", "TurnFailed", (ended) => ({
70
+ ...activity,
71
+ turnSince: void 0,
72
+ queued: activity.lastInputSeq > ended.throughSeq
73
+ })), Match.tag("SpecialistStarted", (started) => ({
74
+ ...activity,
75
+ specialists: new Map(activity.specialists).set(started.runId, {
76
+ runId: started.runId,
77
+ specialist: started.specialist,
78
+ goal: started.goal,
79
+ since: entry.at
80
+ })
81
+ })), Match.tag("ChatDeleted", () => ({
82
+ ...empty,
83
+ lastInputSeq: activity.lastInputSeq
84
+ })), Match.orElse(() => activity));
85
+ };
86
+ /**
87
+ * Returns what is working in a chat after the given entries, folded in order from
88
+ * {@link empty}.
89
+ *
90
+ * @category constructors
91
+ * @since 0.1.0
92
+ */
93
+ const fromEntries = (entries, options) => entries.reduce((activity, entry) => apply(activity, entry, options), empty);
94
+ /**
95
+ * Returns whether anything is working: a turn that is running or about to start, or a specialist
96
+ * run.
97
+ *
98
+ * @category guards
99
+ * @since 0.1.0
100
+ */
101
+ const isWorking = (activity) => activity.turnSince !== void 0 || activity.queued || activity.specialists.size > 0;
102
+ //#endregion
103
+ export { AssistantActivity_exports, apply, empty, fromEntries, isWorking };
104
+
105
+ //# sourceMappingURL=AssistantActivity.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AssistantActivity.js","names":["AssistantEvent.isLibraryEvent","AssistantEvent.isInput","AssistantEvent.isWaking"],"sources":["../src/AssistantActivity.ts"],"sourcesContent":["/**\n * This module provides functions that determine what is working in a chat right now, read from\n * the chat's log.\n *\n * A {@link State} records whether the assistant is running a turn or is about to start one,\n * and which specialist runs are working. Fold a chat's entries into it with {@link apply}, or\n * build it from a list of entries with {@link fromEntries}, then check it with\n * {@link isWorking}.\n *\n * @since 0.1.0\n */\nimport * as Match from \"effect/Match\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport type { RunId } from \"./RunId.ts\"\n\n/**\n * Represents a specialist run that is working.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface SpecialistRun {\n readonly runId: RunId\n readonly specialist: string\n /** The goal the run is working on. */\n readonly goal: string\n /** When the run started, in epoch milliseconds. */\n readonly since: number\n}\n\n/**\n * Represents what is working in a chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface State {\n /** When the running turn started, in epoch milliseconds, or `undefined` when no turn runs. */\n readonly turnSince: number | undefined\n /**\n * Whether an input arrived that no finished turn has read. When this is true, a turn is about\n * to start.\n */\n readonly queued: boolean\n /** The `seq` of the newest input. */\n readonly lastInputSeq: number\n /** Specialist runs that are working, by run id. */\n readonly specialists: ReadonlyMap<RunId, SpecialistRun>\n}\n\n/**\n * The activity of a chat with an empty log, where nothing is working.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const empty: State = {\n turnSince: undefined,\n queued: false,\n lastInputSeq: 0,\n specialists: new Map()\n}\n\nconst withoutRun = (activity: State, runId: RunId): State => {\n if (!activity.specialists.has(runId)) return activity\n\n const specialists = new Map(activity.specialists)\n specialists.delete(runId)\n\n return { ...activity, specialists }\n}\n\n/**\n * Represents the options for folding a chat's entries into its activity.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Options {\n /**\n * The tags of the app's events that wake a turn (see `AppEvent`). These events count as inputs\n * too. Defaults to none.\n */\n readonly wakes?: ReadonlySet<string> | undefined\n}\n\n/**\n * Returns the activity after one more entry. Fold a chat's entries in order, or use\n * {@link fromEntries}.\n *\n * @category combinators\n * @since 0.1.0\n */\nexport const apply = (activity: State, entry: AssistantEvent.AnyEntry, options?: Options): State => {\n const event = entry.event\n\n if (!AssistantEvent.isLibraryEvent(event)) {\n return options?.wakes?.has(event._tag) === true ? { ...activity, queued: true, lastInputSeq: entry.seq } : activity\n }\n\n if (AssistantEvent.isInput(event)) {\n // A finished run's report is an input, and ends the run.\n const current = Predicate.isTagged(event, \"SpecialistFinished\") ? withoutRun(activity, event.runId) : activity\n\n return AssistantEvent.isWaking(event) ? { ...current, queued: true, lastInputSeq: entry.seq } : current\n }\n\n return Match.value(event).pipe(\n Match.tag(\"TurnStarted\", (): State => ({ ...activity, turnSince: entry.at })),\n // Turns run one at a time, so an end closes whichever turn is open, also one a restart cut off.\n Match.tag(\"TurnCompleted\", \"TurnFailed\", (ended): State => ({\n ...activity,\n turnSince: undefined,\n queued: activity.lastInputSeq > ended.throughSeq\n })),\n Match.tag(\"SpecialistStarted\", (started): State => ({\n ...activity,\n specialists: new Map(activity.specialists).set(started.runId, {\n runId: started.runId,\n specialist: started.specialist,\n goal: started.goal,\n since: entry.at\n })\n })),\n // Deleting a chat stops everything in it, and nothing starts again.\n Match.tag(\"ChatDeleted\", (): State => ({ ...empty, lastInputSeq: activity.lastInputSeq })),\n Match.orElse(() => activity)\n )\n}\n\n/**\n * Returns what is working in a chat after the given entries, folded in order from\n * {@link empty}.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const fromEntries = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, options?: Options): State =>\n entries.reduce((activity, entry) => apply(activity, entry, options), empty)\n\n/**\n * Returns whether anything is working: a turn that is running or about to start, or a specialist\n * run.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isWorking = (activity: State): boolean =>\n activity.turnSince !== undefined || activity.queued || activity.specialists.size > 0\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyDA,MAAa,QAAe;CAC1B,WAAW,KAAA;CACX,QAAQ;CACR,cAAc;CACd,6BAAa,IAAI,IAAI;AACvB;AAEA,MAAM,cAAc,UAAiB,UAAwB;CAC3D,IAAI,CAAC,SAAS,YAAY,IAAI,KAAK,GAAG,OAAO;CAE7C,MAAM,cAAc,IAAI,IAAI,SAAS,WAAW;CAChD,YAAY,OAAO,KAAK;CAExB,OAAO;EAAE,GAAG;EAAU;CAAY;AACpC;;;;;;;;AAuBA,MAAa,SAAS,UAAiB,OAAgC,YAA6B;CAClG,MAAM,QAAQ,MAAM;CAEpB,IAAI,CAACA,eAA8B,KAAK,GACtC,OAAO,SAAS,OAAO,IAAI,MAAM,IAAI,MAAM,OAAO;EAAE,GAAG;EAAU,QAAQ;EAAM,cAAc,MAAM;CAAI,IAAI;CAG7G,IAAIC,QAAuB,KAAK,GAAG;EAEjC,MAAM,UAAU,UAAU,SAAS,OAAO,oBAAoB,IAAI,WAAW,UAAU,MAAM,KAAK,IAAI;EAEtG,OAAOC,SAAwB,KAAK,IAAI;GAAE,GAAG;GAAS,QAAQ;GAAM,cAAc,MAAM;EAAI,IAAI;CAClG;CAEA,OAAO,MAAM,MAAM,KAAK,CAAC,CAAC,KACxB,MAAM,IAAI,sBAA6B;EAAE,GAAG;EAAU,WAAW,MAAM;CAAG,EAAE,GAE5E,MAAM,IAAI,iBAAiB,eAAe,WAAkB;EAC1D,GAAG;EACH,WAAW,KAAA;EACX,QAAQ,SAAS,eAAe,MAAM;CACxC,EAAE,GACF,MAAM,IAAI,sBAAsB,aAAoB;EAClD,GAAG;EACH,aAAa,IAAI,IAAI,SAAS,WAAW,CAAC,CAAC,IAAI,QAAQ,OAAO;GAC5D,OAAO,QAAQ;GACf,YAAY,QAAQ;GACpB,MAAM,QAAQ;GACd,OAAO,MAAM;EACf,CAAC;CACH,EAAE,GAEF,MAAM,IAAI,sBAA6B;EAAE,GAAG;EAAO,cAAc,SAAS;CAAa,EAAE,GACzF,MAAM,aAAa,QAAQ,CAC7B;AACF;;;;;;;;AASA,MAAa,eAAe,SAAiD,YAC3E,QAAQ,QAAQ,UAAU,UAAU,MAAM,UAAU,OAAO,OAAO,GAAG,KAAK;;;;;;;;AAS5E,MAAa,aAAa,aACxB,SAAS,cAAc,KAAA,KAAa,SAAS,UAAU,SAAS,YAAY,OAAO"}
@@ -0,0 +1,116 @@
1
+ import { ChatId } from "./ChatId.js";
2
+ import { AssistantEvent_d_exports, Entry, Input, StoredAppEvent } from "./AssistantEvent.js";
3
+ import { ChatLog } from "./ChatLog.js";
4
+ import { Registration, turns_d_exports } from "./internal/turns.js";
5
+ import * as Context from "effect/Context";
6
+ import * as Effect from "effect/Effect";
7
+ import * as Layer from "effect/Layer";
8
+ import * as Stream from "effect/Stream";
9
+ import * as Sharding from "effect/cluster/Sharding";
10
+ import * as Scope from "effect/Scope";
11
+ declare namespace AssistantEngine_d_exports {
12
+ export { AssistantEngine, layerCluster, layerMemory };
13
+ }
14
+ declare const AssistantEngine_base: Context.ServiceClass<AssistantEngine, "effect-assistant/AssistantEngine", {
15
+ /** Registers an assistant for as long as the scope is open. */
16
+ readonly register: (registration: Registration) => Effect.Effect<void, never, Scope.Scope>;
17
+ /**
18
+ * Stores an input in one of the assistant's chats. The assistant works on it in the
19
+ * background.
20
+ */
21
+ readonly submit: (assistant: string, chatId: ChatId, input: Input | StoredAppEvent) => Effect.Effect<void>;
22
+ /** Streams the chat's stored entries after the `after` seq, then live ones. */
23
+ readonly subscribe: (assistant: string, chatId: ChatId, after: number) => Stream.Stream<Entry>;
24
+ /**
25
+ * Deletes one of the assistant's chats. The chat's log records the deletion, and everything
26
+ * that works in the chat stops.
27
+ */
28
+ readonly delete: (assistant: string, chatId: ChatId) => Effect.Effect<void>;
29
+ }>;
30
+ /**
31
+ * Service that runs assistants' chats. An assistant's `toLayer` registers the assistant with it,
32
+ * and the assistant's `submit` and `subscribe` use it.
33
+ *
34
+ * @category services
35
+ * @since 0.1.0
36
+ */
37
+ export declare class AssistantEngine extends AssistantEngine_base {}
38
+ /**
39
+ * Layer that runs chats in the current process. Each chat's turns run as fibers, one at a time.
40
+ *
41
+ * **Details**
42
+ *
43
+ * With `ChatLog.layerSql`, the engine resumes chats at startup. When an assistant registers, the
44
+ * engine finds the chats that assistant was working on when the process stopped (a turn cut off
45
+ * partway, or an input that no turn read) and runs a turn for each. Run this engine in one process
46
+ * only, because two processes would run the same chat and write its log at the same time.
47
+ *
48
+ * **Example** (Running chats in memory)
49
+ *
50
+ * ```ts
51
+ * import { Assistant, AssistantEngine, ChatLog } from "effect-assistant"
52
+ * import type * as LanguageModel from "effect/ai/LanguageModel"
53
+ * import * as Layer from "effect/Layer"
54
+ *
55
+ * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>
56
+ *
57
+ * const MyAssistant = Assistant.make("my-assistant")
58
+ *
59
+ * const AppLive = MyAssistant.toLayer((turn) => turn.loop({ instructions: "Be brief." })).pipe(
60
+ * Layer.provide(ModelLive),
61
+ * Layer.provideMerge(AssistantEngine.layerMemory),
62
+ * Layer.provideMerge(ChatLog.layerMemory)
63
+ * )
64
+ * ```
65
+ *
66
+ * @see {@link layerCluster} for running each chat as a cluster entity
67
+ *
68
+ * @category layers
69
+ * @since 0.1.0
70
+ */
71
+ export declare const layerMemory: Layer.Layer<AssistantEngine, never, ChatLog>;
72
+ /**
73
+ * Layer that runs chats as cluster entities, one entity per chat, keyed by chat id.
74
+ *
75
+ * **Details**
76
+ *
77
+ * The layer requires `Sharding`. Use a `SingleRunner` for one process with SQL storage, a runner
78
+ * of the app's cluster, or `TestRunner` in tests.
79
+ *
80
+ * **Example** (Running chats on a single runner with Postgres)
81
+ *
82
+ * ```ts
83
+ * import * as NodeCrypto from "@effect/platform-node/NodeCrypto"
84
+ * import * as PgClient from "@effect/sql-pg/PgClient"
85
+ * import { Assistant, AssistantEngine, ChatLog } from "effect-assistant"
86
+ * import type * as LanguageModel from "effect/ai/LanguageModel"
87
+ * import * as SingleRunner from "effect/cluster/SingleRunner"
88
+ * import * as Config from "effect/Config"
89
+ * import * as Layer from "effect/Layer"
90
+ *
91
+ * declare const ModelLive: Layer.Layer<LanguageModel.LanguageModel>
92
+ *
93
+ * const MyAssistant = Assistant.make("my-assistant")
94
+ *
95
+ * const AppLive = MyAssistant.toLayer((turn) => turn.loop({ instructions: "Be brief." })).pipe(
96
+ * Layer.provide(ModelLive),
97
+ * Layer.provideMerge(AssistantEngine.layerCluster),
98
+ * Layer.provideMerge(
99
+ * Layer.merge(
100
+ * ChatLog.layerSql,
101
+ * SingleRunner.layer({ runnerStorage: "sql" }).pipe(Layer.provide(NodeCrypto.layer))
102
+ * )
103
+ * ),
104
+ * Layer.provide(PgClient.layerConfig({ url: Config.Redacted("DATABASE_URL") }))
105
+ * )
106
+ * ```
107
+ *
108
+ * @see {@link layerMemory} for running chats in one process
109
+ *
110
+ * @category layers
111
+ * @since 0.1.0
112
+ */
113
+ export declare const layerCluster: Layer.Layer<AssistantEngine, never, ChatLog | Sharding.Sharding>;
114
+ //#endregion
115
+ export { AssistantEngine_d_exports };
116
+ //# sourceMappingURL=AssistantEngine.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"AssistantEngine.d.ts","names":[],"sources":["../src/AssistantEngine.ts"],"mappings":";;;;;;;;;;;;;;;WA6CuB,WAAC,cAAc,iBAAuB,OAAO,oBAAoB,MAAM;;;;;WAKzE,SACf,mBACA,QAAQ,QACR,OAAO,QAAuB,mBAC3B,OAAO;;WAEQ,YAAC,mBAAmB,QAAQ,QAAQ,kBAAkB,OAAO,OAAO;;;;;WAKvE,SAAC,mBAAmB,QAAQ,WAAW,OAAO;;;;;;;;;qBApBtD,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA8DxB,aAAa,MAAM,MAAM,wBAAwB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAwJjD,cAAc,MAAM,MAAM,wBAAwB,UAAU,SAAS"}