effect-assistant 0.1.0 → 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.
- package/README.md +1 -1
- package/dist/AssistantEvent.d.ts +3 -66
- package/dist/AssistantEvent.d.ts.map +1 -1
- package/dist/AssistantEvent.js +1 -51
- package/dist/AssistantEvent.js.map +1 -1
- package/dist/AssistantLoop.d.ts +7 -5
- package/dist/AssistantLoop.d.ts.map +1 -1
- package/dist/AssistantLoop.js +6 -3
- package/dist/AssistantLoop.js.map +1 -1
- package/dist/Block.js.map +1 -1
- package/dist/BlockKit.d.ts +11 -15
- package/dist/BlockKit.d.ts.map +1 -1
- package/dist/BlockKit.js +3 -6
- package/dist/BlockKit.js.map +1 -1
- package/dist/ChatView.d.ts +7 -58
- package/dist/ChatView.d.ts.map +1 -1
- package/dist/ChatView.js +15 -68
- package/dist/ChatView.js.map +1 -1
- package/dist/Compaction.d.ts +2 -2
- package/dist/Compaction.d.ts.map +1 -1
- package/dist/Compaction.js +6 -13
- package/dist/Compaction.js.map +1 -1
- package/dist/ToolDiscovery.d.ts +4 -5
- package/dist/ToolDiscovery.d.ts.map +1 -1
- package/dist/ToolDiscovery.js +5 -4
- package/dist/ToolDiscovery.js.map +1 -1
- package/dist/ToolFailure.d.ts +1 -1
- package/dist/ToolFailure.js +1 -1
- package/dist/ToolFailure.js.map +1 -1
- package/dist/index.d.ts +1 -3
- package/dist/index.js +3 -5
- package/dist/internal/chat.js +6 -31
- package/dist/internal/chat.js.map +1 -1
- package/dist/internal/history.js +2 -40
- package/dist/internal/history.js.map +1 -1
- package/dist/internal/loop.d.ts +2 -2
- package/dist/internal/loop.d.ts.map +1 -1
- package/dist/internal/loop.js +20 -55
- package/dist/internal/loop.js.map +1 -1
- package/dist/internal/specialists.js +2 -3
- package/dist/internal/specialists.js.map +1 -1
- package/dist/internal/toolkit.d.ts +6 -20
- package/dist/internal/toolkit.d.ts.map +1 -1
- package/dist/internal/toolkit.js +10 -31
- package/dist/internal/toolkit.js.map +1 -1
- package/dist/internal/tools.js +1 -20
- package/dist/internal/tools.js.map +1 -1
- package/dist/internal/turns.d.ts.map +1 -1
- package/dist/internal/turns.js +2 -9
- package/dist/internal/turns.js.map +1 -1
- package/package.json +3 -2
- package/src/AssistantEvent.ts +0 -66
- package/src/AssistantLoop.ts +7 -5
- package/src/Block.ts +1 -1
- package/src/BlockKit.ts +12 -25
- package/src/ChatView.ts +10 -81
- package/src/Compaction.ts +2 -19
- package/src/ToolDiscovery.ts +5 -13
- package/src/ToolFailure.ts +1 -1
- package/src/index.ts +0 -10
- package/src/internal/chat.ts +4 -53
- package/src/internal/history.ts +2 -74
- package/src/internal/loop.ts +31 -101
- package/src/internal/specialists.ts +3 -7
- package/src/internal/toolkit.ts +17 -60
- package/src/internal/tools.ts +2 -53
- package/src/internal/turns.ts +7 -26
- package/dist/Decision.d.ts +0 -145
- package/dist/Decision.d.ts.map +0 -1
- package/dist/Decision.js +0 -178
- package/dist/Decision.js.map +0 -1
- package/dist/DecisionId.d.ts +0 -37
- package/dist/DecisionId.d.ts.map +0 -1
- package/dist/DecisionId.js +0 -44
- package/dist/DecisionId.js.map +0 -1
- package/dist/internal/decisions.js +0 -66
- package/dist/internal/decisions.js.map +0 -1
- package/src/Decision.ts +0 -241
- package/src/DecisionId.ts +0 -46
- package/src/internal/decisions.ts +0 -131
package/README.md
CHANGED
|
@@ -4,7 +4,7 @@ A chat assistant on [Effect](https://effect.website) that behaves like a
|
|
|
4
4
|
colleague. It keeps an append-only event log per chat, runs an
|
|
5
5
|
interruptible agent loop over it, and talks to the user only through a
|
|
6
6
|
`send_user_message` tool. It also supports specialists, skills, UI blocks,
|
|
7
|
-
|
|
7
|
+
memory, and compaction. It runs in memory or as one Effect
|
|
8
8
|
Cluster entity per chat.
|
|
9
9
|
|
|
10
10
|
```bash
|
package/dist/AssistantEvent.d.ts
CHANGED
|
@@ -2,7 +2,7 @@ import { ChatId } from "./ChatId.js";
|
|
|
2
2
|
import * as Schema from "effect/Schema";
|
|
3
3
|
import * as Response from "effect/ai/Response";
|
|
4
4
|
declare namespace AssistantEvent_d_exports {
|
|
5
|
-
export { AnyEntry, AppTag, AssistantEvent, AssistantMessage, Attachment, BlockAnswer, BlocksClosed,
|
|
5
|
+
export { AnyEntry, AppTag, AssistantEvent, AssistantMessage, Attachment, BlockAnswer, BlocksClosed, ChatDeleted, Entry, Input, MessageBlock, ModelOutput, ModelPart, SpecialistFinished, SpecialistStarted, StoredAppEvent, ToolCallPart, ToolOutcome, ToolResult, ToolStarted, TurnCompleted, TurnFailed, TurnStarted, UserInput, UserMessage, assistantTexts, attachmentLine, formatSize, isInput, isLibraryEvent, isTurnEnd, isUserInput, isWaking, maxAttachments, textWithAttachments };
|
|
6
6
|
}
|
|
7
7
|
/**
|
|
8
8
|
* Schema for a file the user attached to a message, kept by reference.
|
|
@@ -116,69 +116,6 @@ declare const SpecialistFinished_base: Schema.Class<SpecialistFinished, Schema.T
|
|
|
116
116
|
* @since 0.1.0
|
|
117
117
|
*/
|
|
118
118
|
export declare class SpecialistFinished extends SpecialistFinished_base {}
|
|
119
|
-
/**
|
|
120
|
-
* Schema for how the user decided, either `"approved"` or `"declined"`.
|
|
121
|
-
*
|
|
122
|
-
* @category schemas
|
|
123
|
-
* @since 0.1.0
|
|
124
|
-
*/
|
|
125
|
-
export declare const DecisionOutcome: Schema.Literals<readonly ["approved", "declined"]>;
|
|
126
|
-
/**
|
|
127
|
-
* Represents how the user decided.
|
|
128
|
-
*
|
|
129
|
-
* @category models
|
|
130
|
-
* @since 0.1.0
|
|
131
|
-
*/
|
|
132
|
-
export type DecisionOutcome = typeof DecisionOutcome.Type;
|
|
133
|
-
/**
|
|
134
|
-
* Schema for the origin of a decision that a tool call waits for.
|
|
135
|
-
*
|
|
136
|
-
* It holds the call as the model wrote it. Approving the decision runs exactly this call.
|
|
137
|
-
*
|
|
138
|
-
* @category schemas
|
|
139
|
-
* @since 0.1.0
|
|
140
|
-
*/
|
|
141
|
-
export declare const CallOrigin: Schema.TaggedStruct<"Call", {
|
|
142
|
-
readonly callId: Schema.String;
|
|
143
|
-
readonly tool: Schema.String;
|
|
144
|
-
readonly params: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
145
|
-
}>;
|
|
146
|
-
/**
|
|
147
|
-
* Represents the origin of a decision that a tool call waits for.
|
|
148
|
-
*
|
|
149
|
-
* @category models
|
|
150
|
-
* @since 0.1.0
|
|
151
|
-
*/
|
|
152
|
-
export type CallOrigin = typeof CallOrigin.Type;
|
|
153
|
-
declare const DecisionRequested_base: Schema.Class<DecisionRequested, Schema.TaggedStruct<"DecisionRequested", {
|
|
154
|
-
readonly id: Schema.brand<Schema.TemplateLiteral<readonly ["decision:", Schema.String]>, "~effect-assistant/DecisionId">;
|
|
155
|
-
readonly origin: Schema.TaggedStruct<"Call", {
|
|
156
|
-
readonly callId: Schema.String;
|
|
157
|
-
readonly tool: Schema.String;
|
|
158
|
-
readonly params: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
159
|
-
}>;
|
|
160
|
-
}>, {}>;
|
|
161
|
-
/**
|
|
162
|
-
* Represents a request for the user to decide something, by approving or declining it.
|
|
163
|
-
*
|
|
164
|
-
* @category schemas
|
|
165
|
-
* @since 0.1.0
|
|
166
|
-
*/
|
|
167
|
-
export declare class DecisionRequested extends DecisionRequested_base {}
|
|
168
|
-
declare const DecisionResolved_base: Schema.Class<DecisionResolved, Schema.TaggedStruct<"DecisionResolved", {
|
|
169
|
-
readonly id: Schema.brand<Schema.TemplateLiteral<readonly ["decision:", Schema.String]>, "~effect-assistant/DecisionId">;
|
|
170
|
-
readonly outcome: Schema.Literals<readonly ["approved", "declined"]>;
|
|
171
|
-
readonly answer: Schema.brand<Schema.String, "~effect-assistant/InputId">;
|
|
172
|
-
}>, {}>;
|
|
173
|
-
/**
|
|
174
|
-
* Represents a decision the user made by answering a decision block for it.
|
|
175
|
-
*
|
|
176
|
-
* `answer` is the id of that `BlockAnswer`. An approved call runs at the turn's next step.
|
|
177
|
-
*
|
|
178
|
-
* @category schemas
|
|
179
|
-
* @since 0.1.0
|
|
180
|
-
*/
|
|
181
|
-
export declare class DecisionResolved extends DecisionResolved_base {}
|
|
182
119
|
/**
|
|
183
120
|
* Schema for every input `Assistant.submit` accepts.
|
|
184
121
|
*
|
|
@@ -476,7 +413,7 @@ export declare class BlocksClosed extends BlocksClosed_base {}
|
|
|
476
413
|
* @category schemas
|
|
477
414
|
* @since 0.1.0
|
|
478
415
|
*/
|
|
479
|
-
export declare const AssistantEvent: Schema.Union<readonly [typeof UserMessage, typeof BlockAnswer, typeof AssistantMessage, typeof ModelOutput, typeof ToolStarted, typeof ToolResult, typeof TurnStarted, typeof TurnCompleted, typeof TurnFailed, typeof SpecialistStarted, typeof SpecialistFinished, typeof BlocksClosed, typeof
|
|
416
|
+
export declare const AssistantEvent: Schema.Union<readonly [typeof UserMessage, typeof BlockAnswer, typeof AssistantMessage, typeof ModelOutput, typeof ToolStarted, typeof ToolResult, typeof TurnStarted, typeof TurnCompleted, typeof TurnFailed, typeof SpecialistStarted, typeof SpecialistFinished, typeof BlocksClosed, typeof ChatDeleted]>;
|
|
480
417
|
/**
|
|
481
418
|
* Represents an event the library defines.
|
|
482
419
|
*
|
|
@@ -554,7 +491,7 @@ export declare const Entry: Schema.Struct<{
|
|
|
554
491
|
readonly chatId: Schema.brand<Schema.TemplateLiteral<readonly ["chat:", Schema.String]>, "~effect-assistant/ChatId">;
|
|
555
492
|
readonly seq: Schema.Int;
|
|
556
493
|
readonly at: Schema.Finite;
|
|
557
|
-
readonly event: Schema.Union<readonly [Schema.Union<readonly [typeof UserMessage, typeof BlockAnswer, typeof AssistantMessage, typeof ModelOutput, typeof ToolStarted, typeof ToolResult, typeof TurnStarted, typeof TurnCompleted, typeof TurnFailed, typeof SpecialistStarted, typeof SpecialistFinished, typeof BlocksClosed, typeof
|
|
494
|
+
readonly event: Schema.Union<readonly [Schema.Union<readonly [typeof UserMessage, typeof BlockAnswer, typeof AssistantMessage, typeof ModelOutput, typeof ToolStarted, typeof ToolResult, typeof TurnStarted, typeof TurnCompleted, typeof TurnFailed, typeof SpecialistStarted, typeof SpecialistFinished, typeof BlocksClosed, typeof ChatDeleted]>, Schema.StructWithRest<Schema.Struct<{
|
|
558
495
|
readonly _tag: Schema.brand<Schema.String, "~effect-assistant/AppTag">;
|
|
559
496
|
}>, readonly [Schema.$Record<Schema.String, Schema.Codec<Schema.Json, Schema.Json, never, never>>]>]>;
|
|
560
497
|
}>;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantEvent.d.ts","names":[],"sources":["../src/AssistantEvent.ts"],"mappings":";;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"AssistantEvent.d.ts","names":[],"sources":["../src/AssistantEvent.ts"],"mappings":";;;;;;;;;;;;;;qBAyBa,YAAU,OAAA;;;;;;;;;;;;;;;qBAgBV;;;;;;;YAQD,oBAAoB,WAAW;;;;;;;qBAQ9B,aAAU;;;;;;;;;qBAiBV,iBAAc,YAAgB;;;;;;;qBAS9B,sBAAmB,cAAgB,aAAe,cAAc;;;;;;;;;;;;;;;;;;;;;qBAchE,oBAAoB;;;;;;;;;;;;;;;;qBAepB,oBAAoB;;;;;;;;;;;;;;;;;;;;;qBAgBpB,2BAA2B;;;;;;;qBAkB3B,OAAK,OAAA,uBAAA,oBAAA,oBAAA;;;;;;;YAQN,eAAe,MAAM;;;;;;;;;;qBAWpB,WAAS,OAAA,uBAAA,oBAAA;;;;;;;YAQV,mBAAmB,UAAU;;;;;;;;;;;;qBAS5B,qBAAqB;;;;;;;;;;;;;;;qBAYrB,yBAAyB;;;;;;;;;;qBAiBzB,cAAY,OAAA;;;;;;;;;;;;;;;YAWb,sBAAsB,aAAa;;;;;;;;;;qBAWlC,WAAS,OAAA,gBAAA,OAAA;;;;;;;;;;;;;;;;;;;;;;;;;YAQV,mBAAmB,UAAU;;;;;;;;;;;;;;;;;;;;;;;;;;;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
|
|
4
3
|
import { InputId, make } from "./InputId.js";
|
|
5
4
|
import { RunId } from "./RunId.js";
|
|
6
5
|
import * as Predicate from "effect/Predicate";
|
|
@@ -24,11 +23,7 @@ var AssistantEvent_exports = /* @__PURE__ */ __exportAll({
|
|
|
24
23
|
Attachment: () => Attachment,
|
|
25
24
|
BlockAnswer: () => BlockAnswer,
|
|
26
25
|
BlocksClosed: () => BlocksClosed,
|
|
27
|
-
CallOrigin: () => CallOrigin,
|
|
28
26
|
ChatDeleted: () => ChatDeleted,
|
|
29
|
-
DecisionOutcome: () => DecisionOutcome,
|
|
30
|
-
DecisionRequested: () => DecisionRequested,
|
|
31
|
-
DecisionResolved: () => DecisionResolved,
|
|
32
27
|
Entry: () => Entry,
|
|
33
28
|
Input: () => Input,
|
|
34
29
|
MessageBlock: () => MessageBlock,
|
|
@@ -159,49 +154,6 @@ var SpecialistFinished = class extends Schema.TaggedClass()("SpecialistFinished"
|
|
|
159
154
|
error: Schema.optional(Schema.String)
|
|
160
155
|
}) {};
|
|
161
156
|
/**
|
|
162
|
-
* Schema for how the user decided, either `"approved"` or `"declined"`.
|
|
163
|
-
*
|
|
164
|
-
* @category schemas
|
|
165
|
-
* @since 0.1.0
|
|
166
|
-
*/
|
|
167
|
-
const DecisionOutcome = Schema.Literals(["approved", "declined"]);
|
|
168
|
-
/**
|
|
169
|
-
* Schema for the origin of a decision that a tool call waits for.
|
|
170
|
-
*
|
|
171
|
-
* It holds the call as the model wrote it. Approving the decision runs exactly this call.
|
|
172
|
-
*
|
|
173
|
-
* @category schemas
|
|
174
|
-
* @since 0.1.0
|
|
175
|
-
*/
|
|
176
|
-
const CallOrigin = Schema.TaggedStruct("Call", {
|
|
177
|
-
callId: Schema.String,
|
|
178
|
-
tool: Schema.String,
|
|
179
|
-
params: Schema.Json
|
|
180
|
-
});
|
|
181
|
-
/**
|
|
182
|
-
* Represents a request for the user to decide something, by approving or declining it.
|
|
183
|
-
*
|
|
184
|
-
* @category schemas
|
|
185
|
-
* @since 0.1.0
|
|
186
|
-
*/
|
|
187
|
-
var DecisionRequested = class extends Schema.TaggedClass()("DecisionRequested", {
|
|
188
|
-
id: DecisionId,
|
|
189
|
-
origin: CallOrigin
|
|
190
|
-
}) {};
|
|
191
|
-
/**
|
|
192
|
-
* Represents a decision the user made by answering a decision block for it.
|
|
193
|
-
*
|
|
194
|
-
* `answer` is the id of that `BlockAnswer`. An approved call runs at the turn's next step.
|
|
195
|
-
*
|
|
196
|
-
* @category schemas
|
|
197
|
-
* @since 0.1.0
|
|
198
|
-
*/
|
|
199
|
-
var DecisionResolved = class extends Schema.TaggedClass()("DecisionResolved", {
|
|
200
|
-
id: DecisionId,
|
|
201
|
-
outcome: DecisionOutcome,
|
|
202
|
-
answer: InputId
|
|
203
|
-
}) {};
|
|
204
|
-
/**
|
|
205
157
|
* Schema for every input `Assistant.submit` accepts.
|
|
206
158
|
*
|
|
207
159
|
* @category schemas
|
|
@@ -428,8 +380,6 @@ const AssistantEvent = Schema.Union([
|
|
|
428
380
|
SpecialistStarted,
|
|
429
381
|
SpecialistFinished,
|
|
430
382
|
BlocksClosed,
|
|
431
|
-
DecisionRequested,
|
|
432
|
-
DecisionResolved,
|
|
433
383
|
ChatDeleted
|
|
434
384
|
]);
|
|
435
385
|
const libraryTags = new Set(AssistantEvent.members.map((member) => member.fields._tag.schema.literal));
|
|
@@ -518,6 +468,6 @@ const isTurnEnd = (event) => Predicate.isTagged(event, "TurnCompleted") || Predi
|
|
|
518
468
|
*/
|
|
519
469
|
const assistantTexts = (entries) => entries.flatMap(({ event }) => isLibraryEvent(event) && Predicate.isTagged(event, "AssistantMessage") ? [event.text] : []);
|
|
520
470
|
//#endregion
|
|
521
|
-
export { AppTag, AssistantEvent, AssistantEvent_exports, AssistantMessage, Attachment, BlockAnswer, BlocksClosed,
|
|
471
|
+
export { AppTag, AssistantEvent, AssistantEvent_exports, AssistantMessage, Attachment, BlockAnswer, BlocksClosed, ChatDeleted, Entry, Input, MessageBlock, ModelOutput, ModelPart, SpecialistFinished, SpecialistStarted, StoredAppEvent, ToolCallPart, ToolOutcome, ToolResult, ToolStarted, TurnCompleted, TurnFailed, TurnStarted, UserInput, UserMessage, assistantTexts, attachmentLine, formatSize, isInput, isLibraryEvent, isTurnEnd, isUserInput, isWaking, maxAttachments, textWithAttachments };
|
|
522
472
|
|
|
523
473
|
//# sourceMappingURL=AssistantEvent.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantEvent.js","names":["makeInputId"],"sources":["../src/AssistantEvent.ts"],"sourcesContent":["/**\n * Defines the events that can happen in a chat.\n *\n * A chat is an append-only log of these events, and the log is the source of truth. A chat client\n * receives the part of the log its user sees (`ChatView`), and the model's history is rebuilt\n * from the log before every model call. Besides the library's events ({@link AssistantEvent}), a\n * log holds the application's own events ({@link StoredAppEvent}).\n *\n * @since 0.1.0\n */\nimport * as Response from \"effect/ai/Response\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport { ChatId } from \"./ChatId.ts\"\nimport { DecisionId } from \"./DecisionId.ts\"\nimport { InputId, make as makeInputId } from \"./InputId.ts\"\nimport { RunId } from \"./RunId.ts\"\n\n/**\n * Schema for a file the user attached to a message, kept by reference.\n *\n * The file itself is stored elsewhere, so the log never holds its bytes.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Attachment = Schema.Struct({\n fileId: Schema.String.check(Schema.isMaxLength(64)),\n name: Schema.String.check(Schema.isMaxLength(255)),\n mediaType: Schema.String.check(Schema.isMaxLength(127)),\n /** In bytes. */\n size: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))\n})\n\n/**\n * The maximum number of files one message can carry.\n *\n * Each attached file is a line in every prompt after the message.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const maxAttachments = 10\n\n/**\n * Represents a file the user attached to a message.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Attachment = typeof Attachment.Type\n\n/**\n * Formats a byte count for people and the model, such as `2.1 MB`.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const formatSize = (bytes: number): string =>\n bytes < 1024\n ? `${bytes} B`\n : bytes < 1024 * 1024\n ? `${(bytes / 1024).toFixed(1)} KB`\n : bytes < 1024 * 1024 * 1024\n ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n : `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`\n\n/**\n * Returns the line the model reads for an attachment.\n *\n * The line names the file and never holds its content.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const attachmentLine = (attachment: Attachment): string =>\n `[attached: ${attachment.name}, ${attachment.mediaType}, ${formatSize(attachment.size)}, id ${attachment.fileId}]`\n\n/**\n * Returns a message's text followed by a line for each attached file.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const textWithAttachments = (text: string, attachments: ReadonlyArray<Attachment> | undefined): string =>\n attachments === undefined || attachments.length === 0\n ? text\n : [text, ...attachments.map(attachmentLine)].filter((part) => part.length > 0).join(\"\\n\")\n\n/**\n * Represents text the user typed, and the files they attached.\n *\n * `id` defaults to a new one. Pass the client's own id so that a retried send stores the message\n * once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class UserMessage extends Schema.TaggedClass<UserMessage>()(\"UserMessage\", {\n id: InputId.pipe(Schema.withConstructorDefault(makeInputId())),\n text: Schema.String,\n attachments: Schema.optional(Schema.Array(Attachment).check(Schema.isMaxLength(maxAttachments)))\n}) {}\n\n/**\n * Represents the user's answer to a block.\n *\n * It holds the id of the message the block was on, and the value in the block's answer schema\n * (in its JSON form). A chat UI shows it inside the block rather than as a message.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlockAnswer extends Schema.TaggedClass<BlockAnswer>()(\"BlockAnswer\", {\n id: InputId,\n messageId: Schema.String,\n kind: Schema.String,\n value: Schema.Unknown\n}) {}\n\n/**\n * Represents a specialist run that finished working on a brief.\n *\n * Unless the assistant stopped the run, it is an input, and a turn reads its report and decides\n * what to tell the user. Its id is fixed per run and brief, so it is stored once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistFinished extends Schema.TaggedClass<SpecialistFinished>()(\"SpecialistFinished\", {\n id: InputId,\n runId: RunId,\n specialist: Schema.String,\n /** Which brief this answers: 1 for the first, then one more per follow-up. */\n brief: Schema.Int,\n goal: Schema.String,\n status: Schema.Literals([\"answered\", \"failed\", \"stopped\", \"cut_off\"]),\n report: Schema.optional(Schema.String),\n error: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Schema for how the user decided, either `\"approved\"` or `\"declined\"`.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const DecisionOutcome = Schema.Literals([\"approved\", \"declined\"])\n\n/**\n * Represents how the user decided.\n *\n * @category models\n * @since 0.1.0\n */\nexport type DecisionOutcome = typeof DecisionOutcome.Type\n\n/**\n * Schema for the origin of a decision that a tool call waits for.\n *\n * It holds the call as the model wrote it. Approving the decision runs exactly this call.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const CallOrigin = Schema.TaggedStruct(\"Call\", {\n callId: Schema.String,\n tool: Schema.String,\n params: Schema.Json\n})\n\n/**\n * Represents the origin of a decision that a tool call waits for.\n *\n * @category models\n * @since 0.1.0\n */\nexport type CallOrigin = typeof CallOrigin.Type\n\n/**\n * Represents a request for the user to decide something, by approving or declining it.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class DecisionRequested extends Schema.TaggedClass<DecisionRequested>()(\"DecisionRequested\", {\n id: DecisionId,\n origin: CallOrigin\n}) {}\n\n/**\n * Represents a decision the user made by answering a decision block for it.\n *\n * `answer` is the id of that `BlockAnswer`. An approved call runs at the turn's next step.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class DecisionResolved extends Schema.TaggedClass<DecisionResolved>()(\"DecisionResolved\", {\n id: DecisionId,\n outcome: DecisionOutcome,\n answer: InputId\n}) {}\n\n/**\n * Schema for every input `Assistant.submit` accepts.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Input = Schema.Union([UserMessage, BlockAnswer, SpecialistFinished])\n\n/**\n * Represents an input to an assistant.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Input = typeof Input.Type\n\n/**\n * Schema for the inputs from the chat's user, which are messages and block answers.\n *\n * A turn owes each one a reply. It is also what a chat client usually may submit, since the app's\n * events come from the server.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const UserInput = Schema.Union([UserMessage, BlockAnswer])\n\n/**\n * Represents an input from the chat's user.\n *\n * @category models\n * @since 0.1.0\n */\nexport type UserInput = typeof UserInput.Type\n\n/**\n * Represents the UI shown with a message, as a block kind from the assistant's `BlockKit` and its\n * props.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class MessageBlock extends Schema.Class<MessageBlock>(\"effect-assistant/MessageBlock\")({\n kind: Schema.String,\n props: Schema.Unknown\n}) {}\n\n/**\n * Represents a message the assistant sent the user with `send_user_message`, optionally with a\n * block.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class AssistantMessage extends Schema.TaggedClass<AssistantMessage>()(\"AssistantMessage\", {\n id: Schema.String,\n text: Schema.String,\n block: Schema.optional(MessageBlock),\n /** Earlier messages whose block the user answered by typing instead. Their blocks close. */\n closes: Schema.optional(Schema.Array(Schema.String))\n}) {}\n\n/**\n * Schema for a tool call the model made.\n *\n * It is `effect/ai`'s tool call part (`Response.ToolCallPart`) for any tool, with its params in\n * JSON, as the model wrote them.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolCallPart = Schema.Struct({\n ...Response.ToolCallPart(\"\", Schema.Json).fields,\n name: Schema.String\n}).annotate({ identifier: \"ToolCallPart\" })\n\n/**\n * Represents a tool call the model made.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolCallPart = typeof ToolCallPart.Type\n\n/**\n * Schema for what the log keeps of a model call.\n *\n * It uses `effect/ai`'s response parts for text, reasoning (with the provider's metadata, such as\n * a thinking block's signature), and tool calls.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ModelPart = Schema.Union([Response.TextPart, Response.ReasoningPart, ToolCallPart])\n\n/**\n * Represents a part of a model call's output.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ModelPart = typeof ModelPart.Type\n\n/**\n * Represents what one model call wrote, as response parts for text, reasoning, and tool calls.\n *\n * `Prompt.fromResponseParts` turns the parts into history.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ModelOutput extends Schema.TaggedClass<ModelOutput>()(\"ModelOutput\", {\n parts: Schema.Array(ModelPart),\n /**\n * The last entry the model had read when it wrote this. Inputs after it\n * arrived while the model was working. A turn has handled what its\n * outputs had read.\n */\n seenThroughSeq: Schema.optional(Schema.Int),\n /** The model that wrote it, as the provider's id for it or the name the context gave it. */\n model: Schema.optional(Schema.String),\n /** The provider's id for the response, when it gives one. */\n responseId: Schema.optional(Schema.String),\n /** The call's token usage, with input (including the cache's reads and writes) and output. */\n usage: Schema.optional(Response.Usage),\n /** How long the call took, in milliseconds. */\n durationMillis: Schema.optional(Schema.Finite)\n}) {}\n\n/**\n * Represents a tool call that is about to run.\n *\n * It is stored before the tool runs, so after a crash the log says which calls may have done\n * something. Those calls run again with the same call id (see `AssistantToolCall`).\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolStarted extends Schema.TaggedClass<ToolStarted>()(\"ToolStarted\", {\n callId: Schema.String,\n tool: Schema.String\n}) {}\n\n/**\n * Schema for how a tool call went, either `\"success\"` or `\"failure\"`, which the model reads as an\n * error.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolOutcome = Schema.Literals([\"success\", \"failure\"])\n\n/**\n * Represents how a tool call went.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolOutcome = typeof ToolOutcome.Type\n\n/**\n * Represents the result of one tool call, as the model reads it.\n *\n * It holds the tool's success or failure in its encoded (JSON) form, and which of the two it is. A\n * failure includes its reason when it has one, which is a `ToolFailure`'s `reason` or the\n * failure's tag.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolResult extends Schema.TaggedClass<ToolResult>()(\"ToolResult\", {\n callId: Schema.String,\n tool: Schema.String,\n outcome: ToolOutcome,\n result: Schema.Json,\n reason: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents the start of a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnStarted extends Schema.TaggedClass<TurnStarted>()(\"TurnStarted\", {\n /** The assistant that runs it. */\n assistant: Schema.String,\n /**\n * The id of the turn's trace, when a tracer records it (not Effect's own, which exports nothing).\n */\n traceId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents a turn that finished.\n *\n * `throughSeq` is the last entry the turn read. Inputs after it still need a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnCompleted extends Schema.TaggedClass<TurnCompleted>()(\"TurnCompleted\", {\n throughSeq: Schema.Int\n}) {}\n\n/**\n * Represents a turn that failed.\n *\n * `throughSeq` covers everything stored when the turn failed, so a failing input isn't retried\n * forever.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnFailed extends Schema.TaggedClass<TurnFailed>()(\"TurnFailed\", {\n throughSeq: Schema.Int,\n message: Schema.String\n}) {}\n\n/**\n * Represents a specialist run that started working, either spawned or continued by a follow-up\n * message.\n *\n * The model doesn't see it, since the call that started the run says so, and the run's report\n * arrives as a {@link SpecialistFinished}.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistStarted extends Schema.TaggedClass<SpecialistStarted>()(\"SpecialistStarted\", {\n runId: RunId,\n specialist: Schema.String,\n /** The goal it's working on. */\n goal: Schema.String\n}) {}\n\n/**\n * Represents the deletion of a chat.\n *\n * The chat stores nothing after it, the work running in the chat stopped, and its subscribers'\n * streams end here. Its log stays.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ChatDeleted extends Schema.TaggedClass<ChatDeleted>()(\"ChatDeleted\", {}) {}\n\n/**\n * Represents blocks that closed without an answer, like the ones `BlockKit.closeStale` closes\n * from a turn once the user moved on.\n *\n * The model doesn't see it.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlocksClosed extends Schema.TaggedClass<BlocksClosed>()(\"BlocksClosed\", {\n messageIds: Schema.Array(Schema.String)\n}) {}\n\n/**\n * Schema for every event the library defines.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AssistantEvent = Schema.Union([\n UserMessage,\n BlockAnswer,\n AssistantMessage,\n ModelOutput,\n ToolStarted,\n ToolResult,\n TurnStarted,\n TurnCompleted,\n TurnFailed,\n SpecialistStarted,\n SpecialistFinished,\n BlocksClosed,\n DecisionRequested,\n DecisionResolved,\n ChatDeleted\n])\n\n/**\n * Represents an event the library defines.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AssistantEvent = typeof AssistantEvent.Type\n\nconst libraryTags: ReadonlySet<string> = new Set(\n AssistantEvent.members.map((member) => member.fields._tag.schema.literal)\n)\n\n/**\n * Schema for the tag of one of the application's own events.\n *\n * It accepts any tag but the library's, and it is branded, so narrowing an entry's event to one\n * of the library's events (`Predicate.isTagged(event, \"UserMessage\")`) never leaves an app event\n * in.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AppTag = Schema.String.pipe(Schema.brand(\"~effect-assistant/AppTag\"))\n\n/**\n * Schema for one of the application's own events as it is stored, with its `_tag` and its fields\n * in JSON.\n *\n * An assistant made with `events: [AppEvent.make(Summary)]` decodes it to a `Summary` in\n * `CurrentChat`'s `entries` and in its `subscribe`.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const StoredAppEvent = Schema.StructWithRest(Schema.Struct({ _tag: AppTag }), [\n Schema.Record(Schema.String, Schema.Json)\n]).check(Schema.makeFilter((event) => !libraryTags.has(event._tag) || `${event._tag} is one of the library's events`))\n\n/**\n * Represents one of the application's own events, as it is stored.\n *\n * @category models\n * @since 0.1.0\n */\nexport type StoredAppEvent = typeof StoredAppEvent.Type\n\n/**\n * Returns whether an event is one of the library's, not one of the app's own.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isLibraryEvent = (event: { readonly _tag: string }): event is AssistantEvent => libraryTags.has(event._tag)\n\n/**\n * Represents a chat's entry with any event in it, either the library's or the application's own\n * (decoded or not).\n *\n * The folds over a chat take this type, so a client's typed entries fit too.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AnyEntry {\n readonly chatId: ChatId\n readonly seq: number\n readonly at: number\n readonly event: { readonly _tag: string }\n}\n\n/**\n * Schema for a stored event with its position in the chat.\n *\n * `seq` starts at 1 and has no gaps. `at` is the time the event was stored, in epoch\n * milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Entry = Schema.Struct({\n chatId: ChatId,\n seq: Schema.Int,\n at: Schema.Finite,\n event: Schema.Union([AssistantEvent, StoredAppEvent])\n})\n\n/**\n * Represents a stored event with its position in the chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Entry = typeof Entry.Type\n\n/**\n * Returns whether an event is one of the library's inputs, which are a user message, a block\n * answer, or a finished specialist run.\n *\n * The application's events that wake a turn are inputs too, but only their assistant knows which\n * (see `AppEvent`).\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isInput = (event: { readonly _tag: string }): event is Input =>\n Predicate.isTagged(event, \"UserMessage\") ||\n Predicate.isTagged(event, \"BlockAnswer\") ||\n Predicate.isTagged(event, \"SpecialistFinished\")\n\n/**\n * Returns whether an input starts a turn, which every input does except a run the assistant\n * stopped itself.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isWaking = (input: Input): boolean =>\n !(Predicate.isTagged(input, \"SpecialistFinished\") && input.status === \"stopped\")\n\n/**\n * Returns whether an input came from the chat's user, and so is owed a reply.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isUserInput = (input: Input): input is UserInput =>\n Predicate.isTagged(input, \"UserMessage\") || Predicate.isTagged(input, \"BlockAnswer\")\n\n/**\n * Returns whether an event ends a turn, and so says how far the assistant has read.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isTurnEnd = (event: { readonly _tag: string }): event is TurnCompleted | TurnFailed =>\n Predicate.isTagged(event, \"TurnCompleted\") || Predicate.isTagged(event, \"TurnFailed\")\n\n/**\n * Returns the text of every message the user was shown, in order.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const assistantTexts = (entries: ReadonlyArray<AnyEntry>): ReadonlyArray<string> =>\n entries.flatMap(({ event }) =>\n isLibraryEvent(event) && Predicate.isTagged(event, \"AssistantMessage\") ? [event.text] : []\n )\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAa,aAAa,OAAO,OAAO;CACtC,QAAQ,OAAO,OAAO,MAAM,OAAO,YAAY,EAAE,CAAC;CAClD,MAAM,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC;CACjD,WAAW,OAAO,OAAO,MAAM,OAAO,YAAY,GAAG,CAAC;;CAEtD,MAAM,OAAO,OAAO,MAAM,OAAO,uBAAuB,CAAC,CAAC;AAC5D,CAAC;;;;;;;;;AAUD,MAAa,iBAAiB;;;;;;;AAgB9B,MAAa,cAAc,UACzB,QAAQ,OACJ,GAAG,MAAM,MACT,QAAQ,UACN,IAAI,QAAQ,KAAA,CAAM,QAAQ,CAAC,EAAE,OAC7B,QAAQ,aACN,IAAI,QAAS,QAAA,CAAc,QAAQ,CAAC,EAAE,OACtC,IAAI,QAAS,WAAA,CAAqB,QAAQ,CAAC,EAAE;;;;;;;;;AAUvD,MAAa,kBAAkB,eAC7B,cAAc,WAAW,KAAK,IAAI,WAAW,UAAU,IAAI,WAAW,WAAW,IAAI,EAAE,OAAO,WAAW,OAAO;;;;;;;AAQlH,MAAa,uBAAuB,MAAc,gBAChD,gBAAgB,KAAA,KAAa,YAAY,WAAW,IAChD,OACA,CAAC,MAAM,GAAG,YAAY,IAAI,cAAc,CAAC,CAAC,CAAC,QAAQ,SAAS,KAAK,SAAS,CAAC,CAAC,CAAC,KAAK,IAAI;;;;;;;;;;AAW5F,IAAa,cAAb,cAAiC,OAAO,YAAyB,CAAC,CAAC,eAAe;CAChF,IAAI,QAAQ,KAAK,O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,OAAO,eAAe,OAAO,OAAO,EAAE,MAAM,OAAO,CAAC,GAAG,CACnF,OAAO,OAAO,OAAO,QAAQ,OAAO,IAAI,CAC1C,CAAC,CAAC,CAAC,MAAM,OAAO,YAAY,UAAU,CAAC,YAAY,IAAI,MAAM,IAAI,KAAK,GAAG,MAAM,KAAK,gCAAgC,CAAC;;;;;;;AAgBrH,MAAa,kBAAkB,UAA8D,YAAY,IAAI,MAAM,IAAI;;;;;;;;;;AA2BvH,MAAa,QAAQ,OAAO,OAAO;CACjC,QAAQ;CACR,KAAK,OAAO;CACZ,IAAI,OAAO;CACX,OAAO,OAAO,MAAM,CAAC,gBAAgB,cAAc,CAAC;AACtD,CAAC;;;;;;;;;;;AAoBD,MAAa,WAAW,UACtB,UAAU,SAAS,OAAO,aAAa,KACvC,UAAU,SAAS,OAAO,aAAa,KACvC,UAAU,SAAS,OAAO,oBAAoB;;;;;;;;AAShD,MAAa,YAAY,UACvB,EAAE,UAAU,SAAS,OAAO,oBAAoB,KAAK,MAAM,WAAW;;;;;;;AAQxE,MAAa,eAAe,UAC1B,UAAU,SAAS,OAAO,aAAa,KAAK,UAAU,SAAS,OAAO,aAAa;;;;;;;AAQrF,MAAa,aAAa,UACxB,UAAU,SAAS,OAAO,eAAe,KAAK,UAAU,SAAS,OAAO,YAAY;;;;;;;AAQtF,MAAa,kBAAkB,YAC7B,QAAQ,SAAS,EAAE,YACjB,eAAe,KAAK,KAAK,UAAU,SAAS,OAAO,kBAAkB,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,CAC3F"}
|
|
1
|
+
{"version":3,"file":"AssistantEvent.js","names":["makeInputId"],"sources":["../src/AssistantEvent.ts"],"sourcesContent":["/**\n * Defines the events that can happen in a chat.\n *\n * A chat is an append-only log of these events, and the log is the source of truth. A chat client\n * receives the part of the log its user sees (`ChatView`), and the model's history is rebuilt\n * from the log before every model call. Besides the library's events ({@link AssistantEvent}), a\n * log holds the application's own events ({@link StoredAppEvent}).\n *\n * @since 0.1.0\n */\nimport * as Response from \"effect/ai/Response\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport { ChatId } from \"./ChatId.ts\"\nimport { InputId, make as makeInputId } from \"./InputId.ts\"\nimport { RunId } from \"./RunId.ts\"\n\n/**\n * Schema for a file the user attached to a message, kept by reference.\n *\n * The file itself is stored elsewhere, so the log never holds its bytes.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Attachment = Schema.Struct({\n fileId: Schema.String.check(Schema.isMaxLength(64)),\n name: Schema.String.check(Schema.isMaxLength(255)),\n mediaType: Schema.String.check(Schema.isMaxLength(127)),\n /** In bytes. */\n size: Schema.Finite.check(Schema.isGreaterThanOrEqualTo(0))\n})\n\n/**\n * The maximum number of files one message can carry.\n *\n * Each attached file is a line in every prompt after the message.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const maxAttachments = 10\n\n/**\n * Represents a file the user attached to a message.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Attachment = typeof Attachment.Type\n\n/**\n * Formats a byte count for people and the model, such as `2.1 MB`.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const formatSize = (bytes: number): string =>\n bytes < 1024\n ? `${bytes} B`\n : bytes < 1024 * 1024\n ? `${(bytes / 1024).toFixed(1)} KB`\n : bytes < 1024 * 1024 * 1024\n ? `${(bytes / (1024 * 1024)).toFixed(1)} MB`\n : `${(bytes / (1024 * 1024 * 1024)).toFixed(1)} GB`\n\n/**\n * Returns the line the model reads for an attachment.\n *\n * The line names the file and never holds its content.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const attachmentLine = (attachment: Attachment): string =>\n `[attached: ${attachment.name}, ${attachment.mediaType}, ${formatSize(attachment.size)}, id ${attachment.fileId}]`\n\n/**\n * Returns a message's text followed by a line for each attached file.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const textWithAttachments = (text: string, attachments: ReadonlyArray<Attachment> | undefined): string =>\n attachments === undefined || attachments.length === 0\n ? text\n : [text, ...attachments.map(attachmentLine)].filter((part) => part.length > 0).join(\"\\n\")\n\n/**\n * Represents text the user typed, and the files they attached.\n *\n * `id` defaults to a new one. Pass the client's own id so that a retried send stores the message\n * once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class UserMessage extends Schema.TaggedClass<UserMessage>()(\"UserMessage\", {\n id: InputId.pipe(Schema.withConstructorDefault(makeInputId())),\n text: Schema.String,\n attachments: Schema.optional(Schema.Array(Attachment).check(Schema.isMaxLength(maxAttachments)))\n}) {}\n\n/**\n * Represents the user's answer to a block.\n *\n * It holds the id of the message the block was on, and the value in the block's answer schema\n * (in its JSON form). A chat UI shows it inside the block rather than as a message.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlockAnswer extends Schema.TaggedClass<BlockAnswer>()(\"BlockAnswer\", {\n id: InputId,\n messageId: Schema.String,\n kind: Schema.String,\n value: Schema.Unknown\n}) {}\n\n/**\n * Represents a specialist run that finished working on a brief.\n *\n * Unless the assistant stopped the run, it is an input, and a turn reads its report and decides\n * what to tell the user. Its id is fixed per run and brief, so it is stored once.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistFinished extends Schema.TaggedClass<SpecialistFinished>()(\"SpecialistFinished\", {\n id: InputId,\n runId: RunId,\n specialist: Schema.String,\n /** Which brief this answers: 1 for the first, then one more per follow-up. */\n brief: Schema.Int,\n goal: Schema.String,\n status: Schema.Literals([\"answered\", \"failed\", \"stopped\", \"cut_off\"]),\n report: Schema.optional(Schema.String),\n error: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Schema for every input `Assistant.submit` accepts.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Input = Schema.Union([UserMessage, BlockAnswer, SpecialistFinished])\n\n/**\n * Represents an input to an assistant.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Input = typeof Input.Type\n\n/**\n * Schema for the inputs from the chat's user, which are messages and block answers.\n *\n * A turn owes each one a reply. It is also what a chat client usually may submit, since the app's\n * events come from the server.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const UserInput = Schema.Union([UserMessage, BlockAnswer])\n\n/**\n * Represents an input from the chat's user.\n *\n * @category models\n * @since 0.1.0\n */\nexport type UserInput = typeof UserInput.Type\n\n/**\n * Represents the UI shown with a message, as a block kind from the assistant's `BlockKit` and its\n * props.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class MessageBlock extends Schema.Class<MessageBlock>(\"effect-assistant/MessageBlock\")({\n kind: Schema.String,\n props: Schema.Unknown\n}) {}\n\n/**\n * Represents a message the assistant sent the user with `send_user_message`, optionally with a\n * block.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class AssistantMessage extends Schema.TaggedClass<AssistantMessage>()(\"AssistantMessage\", {\n id: Schema.String,\n text: Schema.String,\n block: Schema.optional(MessageBlock),\n /** Earlier messages whose block the user answered by typing instead. Their blocks close. */\n closes: Schema.optional(Schema.Array(Schema.String))\n}) {}\n\n/**\n * Schema for a tool call the model made.\n *\n * It is `effect/ai`'s tool call part (`Response.ToolCallPart`) for any tool, with its params in\n * JSON, as the model wrote them.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolCallPart = Schema.Struct({\n ...Response.ToolCallPart(\"\", Schema.Json).fields,\n name: Schema.String\n}).annotate({ identifier: \"ToolCallPart\" })\n\n/**\n * Represents a tool call the model made.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolCallPart = typeof ToolCallPart.Type\n\n/**\n * Schema for what the log keeps of a model call.\n *\n * It uses `effect/ai`'s response parts for text, reasoning (with the provider's metadata, such as\n * a thinking block's signature), and tool calls.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ModelPart = Schema.Union([Response.TextPart, Response.ReasoningPart, ToolCallPart])\n\n/**\n * Represents a part of a model call's output.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ModelPart = typeof ModelPart.Type\n\n/**\n * Represents what one model call wrote, as response parts for text, reasoning, and tool calls.\n *\n * `Prompt.fromResponseParts` turns the parts into history.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ModelOutput extends Schema.TaggedClass<ModelOutput>()(\"ModelOutput\", {\n parts: Schema.Array(ModelPart),\n /**\n * The last entry the model had read when it wrote this. Inputs after it\n * arrived while the model was working. A turn has handled what its\n * outputs had read.\n */\n seenThroughSeq: Schema.optional(Schema.Int),\n /** The model that wrote it, as the provider's id for it or the name the context gave it. */\n model: Schema.optional(Schema.String),\n /** The provider's id for the response, when it gives one. */\n responseId: Schema.optional(Schema.String),\n /** The call's token usage, with input (including the cache's reads and writes) and output. */\n usage: Schema.optional(Response.Usage),\n /** How long the call took, in milliseconds. */\n durationMillis: Schema.optional(Schema.Finite)\n}) {}\n\n/**\n * Represents a tool call that is about to run.\n *\n * It is stored before the tool runs, so after a crash the log says which calls may have done\n * something. Those calls run again with the same call id (see `AssistantToolCall`).\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolStarted extends Schema.TaggedClass<ToolStarted>()(\"ToolStarted\", {\n callId: Schema.String,\n tool: Schema.String\n}) {}\n\n/**\n * Schema for how a tool call went, either `\"success\"` or `\"failure\"`, which the model reads as an\n * error.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const ToolOutcome = Schema.Literals([\"success\", \"failure\"])\n\n/**\n * Represents how a tool call went.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ToolOutcome = typeof ToolOutcome.Type\n\n/**\n * Represents the result of one tool call, as the model reads it.\n *\n * It holds the tool's success or failure in its encoded (JSON) form, and which of the two it is. A\n * failure includes its reason when it has one, which is a `ToolFailure`'s `reason` or the\n * failure's tag.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ToolResult extends Schema.TaggedClass<ToolResult>()(\"ToolResult\", {\n callId: Schema.String,\n tool: Schema.String,\n outcome: ToolOutcome,\n result: Schema.Json,\n reason: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents the start of a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnStarted extends Schema.TaggedClass<TurnStarted>()(\"TurnStarted\", {\n /** The assistant that runs it. */\n assistant: Schema.String,\n /**\n * The id of the turn's trace, when a tracer records it (not Effect's own, which exports nothing).\n */\n traceId: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Represents a turn that finished.\n *\n * `throughSeq` is the last entry the turn read. Inputs after it still need a turn.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnCompleted extends Schema.TaggedClass<TurnCompleted>()(\"TurnCompleted\", {\n throughSeq: Schema.Int\n}) {}\n\n/**\n * Represents a turn that failed.\n *\n * `throughSeq` covers everything stored when the turn failed, so a failing input isn't retried\n * forever.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class TurnFailed extends Schema.TaggedClass<TurnFailed>()(\"TurnFailed\", {\n throughSeq: Schema.Int,\n message: Schema.String\n}) {}\n\n/**\n * Represents a specialist run that started working, either spawned or continued by a follow-up\n * message.\n *\n * The model doesn't see it, since the call that started the run says so, and the run's report\n * arrives as a {@link SpecialistFinished}.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class SpecialistStarted extends Schema.TaggedClass<SpecialistStarted>()(\"SpecialistStarted\", {\n runId: RunId,\n specialist: Schema.String,\n /** The goal it's working on. */\n goal: Schema.String\n}) {}\n\n/**\n * Represents the deletion of a chat.\n *\n * The chat stores nothing after it, the work running in the chat stopped, and its subscribers'\n * streams end here. Its log stays.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class ChatDeleted extends Schema.TaggedClass<ChatDeleted>()(\"ChatDeleted\", {}) {}\n\n/**\n * Represents blocks that closed without an answer, like the ones `BlockKit.closeStale` closes\n * from a turn once the user moved on.\n *\n * The model doesn't see it.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport class BlocksClosed extends Schema.TaggedClass<BlocksClosed>()(\"BlocksClosed\", {\n messageIds: Schema.Array(Schema.String)\n}) {}\n\n/**\n * Schema for every event the library defines.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AssistantEvent = Schema.Union([\n UserMessage,\n BlockAnswer,\n AssistantMessage,\n ModelOutput,\n ToolStarted,\n ToolResult,\n TurnStarted,\n TurnCompleted,\n TurnFailed,\n SpecialistStarted,\n SpecialistFinished,\n BlocksClosed,\n ChatDeleted\n])\n\n/**\n * Represents an event the library defines.\n *\n * @category models\n * @since 0.1.0\n */\nexport type AssistantEvent = typeof AssistantEvent.Type\n\nconst libraryTags: ReadonlySet<string> = new Set(\n AssistantEvent.members.map((member) => member.fields._tag.schema.literal)\n)\n\n/**\n * Schema for the tag of one of the application's own events.\n *\n * It accepts any tag but the library's, and it is branded, so narrowing an entry's event to one\n * of the library's events (`Predicate.isTagged(event, \"UserMessage\")`) never leaves an app event\n * in.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const AppTag = Schema.String.pipe(Schema.brand(\"~effect-assistant/AppTag\"))\n\n/**\n * Schema for one of the application's own events as it is stored, with its `_tag` and its fields\n * in JSON.\n *\n * An assistant made with `events: [AppEvent.make(Summary)]` decodes it to a `Summary` in\n * `CurrentChat`'s `entries` and in its `subscribe`.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const StoredAppEvent = Schema.StructWithRest(Schema.Struct({ _tag: AppTag }), [\n Schema.Record(Schema.String, Schema.Json)\n]).check(Schema.makeFilter((event) => !libraryTags.has(event._tag) || `${event._tag} is one of the library's events`))\n\n/**\n * Represents one of the application's own events, as it is stored.\n *\n * @category models\n * @since 0.1.0\n */\nexport type StoredAppEvent = typeof StoredAppEvent.Type\n\n/**\n * Returns whether an event is one of the library's, not one of the app's own.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isLibraryEvent = (event: { readonly _tag: string }): event is AssistantEvent => libraryTags.has(event._tag)\n\n/**\n * Represents a chat's entry with any event in it, either the library's or the application's own\n * (decoded or not).\n *\n * The folds over a chat take this type, so a client's typed entries fit too.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface AnyEntry {\n readonly chatId: ChatId\n readonly seq: number\n readonly at: number\n readonly event: { readonly _tag: string }\n}\n\n/**\n * Schema for a stored event with its position in the chat.\n *\n * `seq` starts at 1 and has no gaps. `at` is the time the event was stored, in epoch\n * milliseconds.\n *\n * @category schemas\n * @since 0.1.0\n */\nexport const Entry = Schema.Struct({\n chatId: ChatId,\n seq: Schema.Int,\n at: Schema.Finite,\n event: Schema.Union([AssistantEvent, StoredAppEvent])\n})\n\n/**\n * Represents a stored event with its position in the chat.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Entry = typeof Entry.Type\n\n/**\n * Returns whether an event is one of the library's inputs, which are a user message, a block\n * answer, or a finished specialist run.\n *\n * The application's events that wake a turn are inputs too, but only their assistant knows which\n * (see `AppEvent`).\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isInput = (event: { readonly _tag: string }): event is Input =>\n Predicate.isTagged(event, \"UserMessage\") ||\n Predicate.isTagged(event, \"BlockAnswer\") ||\n Predicate.isTagged(event, \"SpecialistFinished\")\n\n/**\n * Returns whether an input starts a turn, which every input does except a run the assistant\n * stopped itself.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isWaking = (input: Input): boolean =>\n !(Predicate.isTagged(input, \"SpecialistFinished\") && input.status === \"stopped\")\n\n/**\n * Returns whether an input came from the chat's user, and so is owed a reply.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isUserInput = (input: Input): input is UserInput =>\n Predicate.isTagged(input, \"UserMessage\") || Predicate.isTagged(input, \"BlockAnswer\")\n\n/**\n * Returns whether an event ends a turn, and so says how far the assistant has read.\n *\n * @category guards\n * @since 0.1.0\n */\nexport const isTurnEnd = (event: { readonly _tag: string }): event is TurnCompleted | TurnFailed =>\n Predicate.isTagged(event, \"TurnCompleted\") || Predicate.isTagged(event, \"TurnFailed\")\n\n/**\n * Returns the text of every message the user was shown, in order.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const assistantTexts = (entries: ReadonlyArray<AnyEntry>): ReadonlyArray<string> =>\n entries.flatMap(({ event }) =>\n isLibraryEvent(event) && Predicate.isTagged(event, \"AssistantMessage\") ? [event.text] : []\n )\n"],"mapp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Ae,UAC1B,UAAU,SAAS,OAAO,aAAa,KAAK,UAAU,SAAS,OAAO,aAAa;;;;;;;AAQrF,MAAa,aAAa,UACxB,UAAU,SAAS,OAAO,eAAe,KAAK,UAAU,SAAS,OAAO,YAAY;;;;;;;AAQtF,MAAa,kBAAkB,YAC7B,QAAQ,SAAS,EAAE,YACjB,eAAe,KAAK,KAAK,UAAU,SAAS,OAAO,kBAAkB,IAAI,CAAC,MAAM,IAAI,IAAI,CAAC,CAC3F"}
|
package/dist/AssistantLoop.d.ts
CHANGED
|
@@ -15,8 +15,7 @@ declare namespace AssistantLoop_d_exports {
|
|
|
15
15
|
* Represents what the loop emits.
|
|
16
16
|
*
|
|
17
17
|
* For each model call, the loop emits the call's output. Then, for each of its tool calls, it
|
|
18
|
-
* emits a `ToolStarted` before the call runs and the call's result
|
|
19
|
-
* a call that waits for the user's decision.
|
|
18
|
+
* emits a `ToolStarted` before the call runs and the call's result.
|
|
20
19
|
*
|
|
21
20
|
* @category models
|
|
22
21
|
* @since 0.1.0
|
|
@@ -127,9 +126,12 @@ export interface Options<T extends Record<string, Tool.Any> = NoTools> extends S
|
|
|
127
126
|
* **Details**
|
|
128
127
|
*
|
|
129
128
|
* The step calls the model with the current history and emits its `ModelOutput`. It then runs
|
|
130
|
-
* the output's tool calls and emits a `ToolStarted` and a `ToolResult` for each
|
|
131
|
-
*
|
|
132
|
-
*
|
|
129
|
+
* the output's tool calls and emits a `ToolStarted` and a `ToolResult` for each. `then` receives
|
|
130
|
+
* the step's result and decides what comes next, with `AssistantLoop.next(state)` or
|
|
131
|
+
* `AssistantLoop.stop()`.
|
|
132
|
+
*
|
|
133
|
+
* A tool with Effect's `needsApproval` set fails the loop before the model is called: the
|
|
134
|
+
* library doesn't run calls that wait for approval (see the guide on involving the user).
|
|
133
135
|
*
|
|
134
136
|
* @category constructors
|
|
135
137
|
* @since 0.1.0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantLoop.d.ts","names":[],"sources":["../src/AssistantLoop.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"AssistantLoop.d.ts","names":[],"sources":["../src/AssistantLoop.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;YAkCY,QAAQ;;;;;;;;;YAUR,cAAc;;;;;;;YAQd,aAAa;;;;;;;YAQb,KAAK,GAAG,KAAK,OAAU,GAAG;;;;;;;qBAQzB,cAAK;;;;;;;qBAQL,aAAI;;;;;;;qBAQJ,aAAI;;;;;;;;;;qBAWJ,aAAI;KAEZ,UAAU;;;;;;;;YASH,gBAAgB,UAAU,eAAe,KAAK,QAAQ,KAAK,YAAY,KAAK,aAAsB;;;;;;;iBAQ7F,YAAY,UAAU,eAAe,KAAK,OAAO;;WAEvD,uBAAuB;;;;;WAKvB,UAAU,QAAQ,QAAQ;;;;;;WAM1B,SAAS,OAAO,OAAO,cAAc,OAAO,WAAW;;;;;WAKvD,aAAa,cAAc;;;;;;;;iBASrB,QAAQ,UAAU,eAAe,KAAK,OAAO,iBAAiB,YAAY;;WAEhF;;;;;;;;;;;;;;;;;;qBA0BE,OAAQ,UAAU,eAAe,KAAK,OAAO,SAAS,WAAW,YAAY,YAAU,SACzF,YAAY,IAAE,OAChB,QAAQ,eAAe,OAAO,OAAO,YAAY,IAAI,IAAI,QAC/D,OAAO,OAAO,KAAK,OAAO,IAAI,QAAQ,UAAU,IAAI,cAAc,gBAAgB,gBAAgB,KAAK;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAiC7F,MAAO,UAAU,eAAe,KAAK,OAAO,SAAO,SACrD,QAAQ,OAChB,OAAO,OAAO,OAAO,QAAQ,SAAS,cAAc,gBAAgB,gBAAgB"}
|
package/dist/AssistantLoop.js
CHANGED
|
@@ -57,9 +57,12 @@ const toolsOf = (toolkit) => Effect.map(TurnTools, (turn) => {
|
|
|
57
57
|
* **Details**
|
|
58
58
|
*
|
|
59
59
|
* The step calls the model with the current history and emits its `ModelOutput`. It then runs
|
|
60
|
-
* the output's tool calls and emits a `ToolStarted` and a `ToolResult` for each
|
|
61
|
-
*
|
|
62
|
-
*
|
|
60
|
+
* the output's tool calls and emits a `ToolStarted` and a `ToolResult` for each. `then` receives
|
|
61
|
+
* the step's result and decides what comes next, with `AssistantLoop.next(state)` or
|
|
62
|
+
* `AssistantLoop.stop()`.
|
|
63
|
+
*
|
|
64
|
+
* A tool with Effect's `needsApproval` set fails the loop before the model is called: the
|
|
65
|
+
* library doesn't run calls that wait for approval (see the guide on involving the user).
|
|
63
66
|
*
|
|
64
67
|
* @category constructors
|
|
65
68
|
* @since 0.1.0
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"AssistantLoop.js","names":["Loop.value","Loop.next","Loop.stop","Loop.loop","Loop.TurnTools","Toolkits.empty","Toolkits.fromToolkit","Toolkits.merge","Loop.step","Loop.run"],"sources":["../src/AssistantLoop.ts"],"sourcesContent":["/**\n * Runs the agent loop, which calls the model, runs its tool calls, and repeats.\n *\n * Most handlers use `turn.loop` or `run.loop`. This module is for a loop of your own: {@link run}\n * runs the loop until the model is done, and {@link step} is one step, as a body for\n * {@link loop}.\n *\n * Tools are a native toolkit (`effect/ai/Toolkit`) whose handlers come from the handler's layer.\n * In a turn, the assistant's own tools (`send_user_message`, `wait`, and the specialist tools)\n * are added to them.\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 Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Instructions from \"./Instructions.ts\"\nimport * as Loop from \"./internal/loop.ts\"\nimport * as Toolkits from \"./internal/toolkit.ts\"\n\n/**\n * Represents what the loop emits.\n *\n * For each model call, the loop emits the call's output. Then, for each of its tool calls, it\n * emits a `ToolStarted` before the call runs and the call's result
|
|
1
|
+
{"version":3,"file":"AssistantLoop.js","names":["Loop.value","Loop.next","Loop.stop","Loop.loop","Loop.TurnTools","Toolkits.empty","Toolkits.fromToolkit","Toolkits.merge","Loop.step","Loop.run"],"sources":["../src/AssistantLoop.ts"],"sourcesContent":["/**\n * Runs the agent loop, which calls the model, runs its tool calls, and repeats.\n *\n * Most handlers use `turn.loop` or `run.loop`. This module is for a loop of your own: {@link run}\n * runs the loop until the model is done, and {@link step} is one step, as a body for\n * {@link loop}.\n *\n * Tools are a native toolkit (`effect/ai/Toolkit`) whose handlers come from the handler's layer.\n * In a turn, the assistant's own tools (`send_user_message`, `wait`, and the specialist tools)\n * are added to them.\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 Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Instructions from \"./Instructions.ts\"\nimport * as Loop from \"./internal/loop.ts\"\nimport * as Toolkits from \"./internal/toolkit.ts\"\n\n/**\n * Represents what the loop emits.\n *\n * For each model call, the loop emits the call's output. Then, for each of its tool calls, it\n * emits a `ToolStarted` before the call runs and the call's result.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Event = Loop.Event\n\n/**\n * Represents a chat's history as the model reads it.\n *\n * It holds the messages, and the last `seq` of the chat they cover.\n *\n * @category models\n * @since 0.1.0\n */\nexport type ChatHistory = Loop.ChatHistory\n\n/**\n * Represents how a step went, for deciding what comes next.\n *\n * @category models\n * @since 0.1.0\n */\nexport type StepResult = Loop.StepResult\n\n/**\n * Represents what a loop body emits, which is either a value or what to do next.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Step<A, S> = Loop.Step<A, S>\n\n/**\n * Emits a value from a loop body.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const value = Loop.value\n\n/**\n * Ends a loop body's step and continues the loop with the given state.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const next = Loop.next\n\n/**\n * Ends the loop.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const stop = Loop.stop\n\n/**\n * Runs a loop body from an initial state.\n *\n * It emits the body's values, and runs the body again with the state it passes to `next`, until\n * the body calls `stop`.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const loop = Loop.loop\n\ntype NoTools = Record<never, never>\n\n/**\n * Extracts the services a toolkit's tools need when they run, which are their handlers and the\n * services those handlers use.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type ToolkitServices<T extends Record<string, Tool.Any>> = Tool.HandlersFor<T> | Toolkits.ToolServices<T>\n\n/**\n * Represents the options for {@link step}.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface StepOptions<T extends Record<string, Tool.Any> = NoTools> {\n /** The full system prompt, like `turn.instructions(text)`, optionally with span attributes. */\n readonly instructions: string | Instructions.Resolved\n /**\n * The tools the model can call, in addition to the assistant's own tools in a turn. Their\n * handlers come from the layer.\n */\n readonly toolkit?: Toolkit.Toolkit<T> | undefined\n /**\n * The current history, read at the start of the step. It is either messages, or a chat's\n * history (`turn.history()`), whose `throughSeq` the step's `ModelOutput` records as how far\n * the model had read.\n */\n readonly history: Effect.Effect<ReadonlyArray<Prompt.Message> | ChatHistory>\n /**\n * Defaults to `\"auto\"`, where a step without a tool call ends the loop. Forcing a call\n * (`\"required\"`, or a tool by name) is refused by newer models, and with extended thinking.\n */\n readonly toolChoice?: LanguageModel.ToolChoice<string> | undefined\n}\n\n/**\n * Represents the options for {@link run}.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Options<T extends Record<string, Tool.Any> = NoTools> extends StepOptions<T> {\n /** The model calls allowed. Defaults to 16. */\n readonly maxSteps?: number | undefined\n}\n\nconst toolsOf = <T extends Record<string, Tool.Any>>(toolkit: Toolkit.Toolkit<T> | undefined) =>\n Effect.map(Loop.TurnTools, (turn) => {\n const own = toolkit === undefined ? Toolkits.empty : Toolkits.fromToolkit(toolkit)\n\n return Option.match(turn, { onNone: () => own, onSome: (builtins) => Toolkits.merge(builtins, own) })\n })\n\n/**\n * Runs one step of the agent loop, as a body for {@link loop}.\n *\n * **Details**\n *\n * The step calls the model with the current history and emits its `ModelOutput`. It then runs\n * the output's tool calls and emits a `ToolStarted` and a `ToolResult` for each. `then` receives\n * the step's result and decides what comes next, with `AssistantLoop.next(state)` or\n * `AssistantLoop.stop()`.\n *\n * A tool with Effect's `needsApproval` set fails the loop before the model is called: the\n * library doesn't run calls that wait for approval (see the guide on involving the user).\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const step = <T extends Record<string, Tool.Any> = NoTools, S = never, E2 = never, R2 = never>(\n options: StepOptions<T>,\n then: (result: StepResult) => Stream.Stream<Step<never, S>, E2, R2>\n): Stream.Stream<Step<Event, S>, AiError.AiError | E2, LanguageModel.LanguageModel | ToolkitServices<T> | R2> =>\n Stream.unwrap(Effect.map(toolsOf(options.toolkit), (toolkit) => Loop.step({ ...options, toolkit }, then)))\n\n/**\n * Runs the agent loop as a stream.\n *\n * **Details**\n *\n * It runs {@link step} after step until the model is done and nothing new arrived while it\n * worked, or until it has made `maxSteps` model calls.\n *\n * **Example** (A turn's loop with a step limit)\n *\n * ```ts\n * import { AssistantLoop } from \"effect-assistant\"\n * import * as Layer from \"effect/Layer\"\n * import * as Stream from \"effect/Stream\"\n *\n * const instructions = \"You help a small marketing team.\"\n *\n * const MyAssistantLive = MyAssistant.toLayer((turn) =>\n * AssistantLoop.run({\n * instructions: turn.instructions(instructions),\n * toolkit: MyTools, // the assistant's own tools are added to them\n * history: turn.history(),\n * maxSteps: 12\n * }).pipe(Stream.concat(turn.replyIfOwed({ instructions })))\n * ).pipe(Layer.provide(MyToolsLive))\n * ```\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const run = <T extends Record<string, Tool.Any> = NoTools>(\n options: Options<T>\n): Stream.Stream<Event, AiError.AiError, LanguageModel.LanguageModel | ToolkitServices<T>> =>\n Stream.unwrap(Effect.map(toolsOf(options.toolkit), (toolkit) => Loop.run({ ...options, toolkit })))\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAoEA,MAAa,QAAQA;;;;;;;AAQrB,MAAa,OAAOC;;;;;;;AAQpB,MAAa,OAAOC;;;;;;;;;;AAWpB,MAAa,OAAOC;AAmDpB,MAAM,WAA+C,YACnD,OAAO,IAAIC,YAAiB,SAAS;CACnC,MAAM,MAAM,YAAY,KAAA,IAAYC,QAAiBC,YAAqB,OAAO;CAEjF,OAAO,OAAO,MAAM,MAAM;EAAE,cAAc;EAAK,SAAS,aAAaC,MAAe,UAAU,GAAG;CAAE,CAAC;AACtG,CAAC;;;;;;;;;;;;;;;;;AAkBH,MAAa,QACX,SACA,SAEA,OAAO,OAAO,OAAO,IAAI,QAAQ,QAAQ,OAAO,IAAI,YAAYC,OAAU;CAAE,GAAG;CAAS;AAAQ,GAAG,IAAI,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgC3G,MAAa,OACX,YAEA,OAAO,OAAO,OAAO,IAAI,QAAQ,QAAQ,OAAO,IAAI,YAAYC,MAAS;CAAE,GAAG;CAAS;AAAQ,CAAC,CAAC,CAAC"}
|
package/dist/Block.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Block.js","names":[],"sources":["../src/Block.ts"],"sourcesContent":["/**\n * Defines UI blocks that an assistant can put in a message.\n *\n * A block is a bit of UI for when a structured answer is easier than typing, such as options to\n * pick from,
|
|
1
|
+
{"version":3,"file":"Block.js","names":[],"sources":["../src/Block.ts"],"sourcesContent":["/**\n * Defines UI blocks that an assistant can put in a message.\n *\n * A block is a bit of UI for when a structured answer is easier than typing, such as options to\n * pick from, a yes or no, or a small input. The assistant fills in its `props`, and\n * using the block sends back a value typed by its `answer` schema.\n *\n * @since 0.1.0\n */\nimport type * as Schema from \"effect/Schema\"\n\n/**\n * Schema that a block's props or answer can use.\n *\n * It is any codec that needs no services, since the client decodes and encodes with it too.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type Codec = Schema.Codec<any, any>\n\n/**\n * Represents a kind of UI block.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface Block<Kind extends string = string, Props extends Codec = Codec, Answer extends Codec = Codec> {\n readonly kind: Kind\n /** When to use the block. The assistant sees this. */\n readonly description: string\n /** The props the assistant fills in. */\n readonly props: Props\n /** What using the block sends back, or `undefined` for a display-only card. */\n readonly answer: Answer | undefined\n}\n\n/**\n * Represents any block, for generic constraints.\n *\n * @category utility types\n * @since 0.1.0\n */\nexport type Any = Block\n\n/**\n * Creates a block.\n *\n * **Details**\n *\n * A block without an `answer` schema is a display-only card. Put the block in the assistant's\n * `BlockKit` so the assistant can use it.\n *\n * **Example** (Defining a block with options to pick from)\n *\n * ```ts\n * import { Assistant, Block, BlockKit } from \"effect-assistant\"\n * import * as Schema from \"effect/Schema\"\n *\n * const PickOne = Block.make(\"pick_one\", {\n * description: \"Options to pick from, when the user chooses between a few.\",\n * props: Schema.Struct({ options: Schema.Array(Schema.String) }),\n * answer: Schema.Struct({ picked: Schema.String })\n * })\n *\n * export const MyAssistant = Assistant.make(\"my-assistant\", { blocks: BlockKit.make([PickOne]) })\n * ```\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <const Kind extends string, Props extends Codec, Answer extends Codec = Schema.Never>(\n kind: Kind,\n options: {\n readonly description: string\n readonly props: Props\n readonly answer?: Answer | undefined\n }\n): Block<Kind, Props, Answer> => ({\n kind,\n description: options.description,\n props: options.props,\n answer: options.answer\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuEA,MAAa,QACX,MACA,aAKgC;CAChC;CACA,aAAa,QAAQ;CACrB,OAAO,QAAQ;CACf,QAAQ,QAAQ;AAClB"}
|
package/dist/BlockKit.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { AnyEntry, AssistantEvent_d_exports, BlockAnswer } from "./AssistantEvent.js";
|
|
2
2
|
import { Any, Block_d_exports } from "./Block.js";
|
|
3
|
-
import { AssistantMessage, ChatView_d_exports
|
|
3
|
+
import { AssistantMessage, ChatView_d_exports } from "./ChatView.js";
|
|
4
4
|
import { CurrentChat } from "./CurrentChat.js";
|
|
5
5
|
import * as Effect from "effect/Effect";
|
|
6
6
|
import * as Schema from "effect/Schema";
|
|
@@ -69,8 +69,7 @@ export declare const fromEntries: (entries: ReadonlyArray<AnyEntry>) => Readonly
|
|
|
69
69
|
*
|
|
70
70
|
* **Details**
|
|
71
71
|
*
|
|
72
|
-
* These are the blocks {@link closeStale} closes.
|
|
73
|
-
* on them and closing one would leave it waiting.
|
|
72
|
+
* These are the blocks {@link closeStale} closes.
|
|
74
73
|
*
|
|
75
74
|
* @category utils
|
|
76
75
|
* @since 0.1.0
|
|
@@ -102,6 +101,11 @@ export declare const closeStale: (options: {
|
|
|
102
101
|
* @since 0.1.0
|
|
103
102
|
*/
|
|
104
103
|
export interface RenderArgs<B> {
|
|
104
|
+
/**
|
|
105
|
+
* The id of the message the block is on. A block whose button calls your API can key the work
|
|
106
|
+
* on it, with the chat's id, so the work runs once per block.
|
|
107
|
+
*/
|
|
108
|
+
readonly messageId: string;
|
|
105
109
|
readonly text: string;
|
|
106
110
|
readonly props: PropsOf<B>;
|
|
107
111
|
/**
|
|
@@ -111,11 +115,6 @@ export interface RenderArgs<B> {
|
|
|
111
115
|
readonly open: boolean;
|
|
112
116
|
/** The user's answer, if they used the block. */
|
|
113
117
|
readonly answer: AnswerOf<B> | undefined;
|
|
114
|
-
/**
|
|
115
|
-
* For the decision block, the call each decision is for (its tool and params) and how it was
|
|
116
|
-
* decided. Empty for other blocks.
|
|
117
|
-
*/
|
|
118
|
-
readonly decisions: ReadonlyArray<PendingDecision>;
|
|
119
118
|
/** Sends an answer. Only call it while `open`. */
|
|
120
119
|
readonly respond: (answer: AnswerOf<B>) => void;
|
|
121
120
|
}
|
|
@@ -152,10 +151,10 @@ export interface RenderOptions {
|
|
|
152
151
|
* **Example** (Rendering blocks with React)
|
|
153
152
|
*
|
|
154
153
|
* ```tsx
|
|
155
|
-
* import { BlockKit
|
|
154
|
+
* import { BlockKit } from "effect-assistant"
|
|
156
155
|
* import type { ReactNode } from "react"
|
|
157
156
|
*
|
|
158
|
-
* const Blocks = BlockKit.make([PickOne,
|
|
157
|
+
* const Blocks = BlockKit.make([PickOne, OrderDraft])
|
|
159
158
|
*
|
|
160
159
|
* const renderBlock = BlockKit.toClient<typeof Blocks, ReactNode>(Blocks, {
|
|
161
160
|
* pick_one: ({ props, open, respond }) =>
|
|
@@ -164,11 +163,8 @@ export interface RenderOptions {
|
|
|
164
163
|
* {option}
|
|
165
164
|
* </button>
|
|
166
165
|
* )),
|
|
167
|
-
*
|
|
168
|
-
*
|
|
169
|
-
* {props.approveLabel ?? "Approve"}
|
|
170
|
-
* </button>
|
|
171
|
-
* )
|
|
166
|
+
* // No answer schema: the button calls the app's own API with the props the user sees.
|
|
167
|
+
* order_draft: ({ props }) => <button onClick={() => placeOrder(props)}>Place order</button>
|
|
172
168
|
* })
|
|
173
169
|
*
|
|
174
170
|
* // For each AssistantMessage in the chat's view:
|
package/dist/BlockKit.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BlockKit.d.ts","names":[],"sources":["../src/BlockKit.ts"],"mappings":";;;;;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"BlockKit.d.ts","names":[],"sources":["../src/BlockKit.ts"],"mappings":";;;;;;;;;;;;;;;iBA0BiB,SAAS,eAAe,MAAY;WAC1C,QAAQ,cAAc;WACtB,QAAQ,oBAAoB;;;;;;;;qBAS1B,aAAc,eAAe,cAAc,MAAU,QAAU,WAAS,SAAS;KAKzF,OAAO,KAAK;WAAqB,YAAY;IAAqB;KAElE,QAAQ,YAAY,UAAU,KAAK,QAAQ;WAAkC,MAAM;;KAEnF,QAAQ,KAAK;WAAqB,OAAO,OAAO;IAAQ;KAExD,SAAS,KAAK;WAAqB,cAAc;KAAO,UAAU,OAAO,MAAM;;;;;;;iBAQnE;WACN;;WAEA,QAAQ;;;;;;;;qBASN,QAAK,QACR,oBAAoB,QAAM;WAChB;MACjB,oBAAoB;;;;;;;qBAkCV,cAAW,SAAa,cAAc,cAA2B,oBAAoB;;;;;;;;;;;;qBAmBrF,cAAW,SACb,cAAc,WAAwB;WAC3B;MACnB;;;;;;;;;;;;;;;qBA+BU,aAAU;WAAsD;MAK3E,OAAA,oBAAA;;;;;;;iBAQe,WAAW;;;;;WAKjB;WACA;WACA,OAAO,QAAQ;;;;;WAKf;;WAEA,QAAQ,SAAS;;WAEjB,UAAU,QAAQ,SAAS;;;;;;;;YAS1B,UAAU,YAAY,UAAU,mBAChC,KAAK,OAAO,0BAA0B,MAAM,WAAW,QAAQ,KAAK,QAAQ;;;;;;;iBASvE;;WAEN,UAAU,QAAQ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;wBA0Cb,SAAS,YAAY,UAAU,KAC7C,KAAK,KACL,WAAW,UAAU,KAAK,QACxB,SAAS,kBAA2B,SAAS,kBAAkB"}
|
package/dist/BlockKit.js
CHANGED
|
@@ -2,7 +2,6 @@ import { __exportAll } from "./_virtual/_rolldown/runtime.js";
|
|
|
2
2
|
import { fromKey } from "./InputId.js";
|
|
3
3
|
import { BlockAnswer, BlocksClosed, isLibraryEvent } from "./AssistantEvent.js";
|
|
4
4
|
import { CurrentChat } from "./CurrentChat.js";
|
|
5
|
-
import "./Decision.js";
|
|
6
5
|
import * as Predicate from "effect/Predicate";
|
|
7
6
|
import * as Effect from "effect/Effect";
|
|
8
7
|
import * as Schema from "effect/Schema";
|
|
@@ -85,8 +84,7 @@ const fromEntries = (entries) => {
|
|
|
85
84
|
*
|
|
86
85
|
* **Details**
|
|
87
86
|
*
|
|
88
|
-
* These are the blocks {@link closeStale} closes.
|
|
89
|
-
* on them and closing one would leave it waiting.
|
|
87
|
+
* These are the blocks {@link closeStale} closes.
|
|
90
88
|
*
|
|
91
89
|
* @category utils
|
|
92
90
|
* @since 0.1.0
|
|
@@ -94,8 +92,7 @@ const fromEntries = (entries) => {
|
|
|
94
92
|
const staleBlocks = (entries, options) => {
|
|
95
93
|
return [...fromEntries(entries)].flatMap(([id, state]) => state.open ? [id] : []).filter((id) => {
|
|
96
94
|
const shown = entries.findIndex(({ event }) => isLibraryEvent(event) && Predicate.isTagged(event, "AssistantMessage") && event.id === id);
|
|
97
|
-
|
|
98
|
-
if (message === void 0 || isLibraryEvent(message) && Predicate.isTagged(message, "AssistantMessage") && message.block?.kind === "decision") return false;
|
|
95
|
+
if (shown === -1) return false;
|
|
99
96
|
return entries.slice(shown + 1).filter(({ event }) => Predicate.isTagged(event, "UserMessage")).length >= options.messages;
|
|
100
97
|
});
|
|
101
98
|
};
|
|
@@ -131,11 +128,11 @@ function toClient(kit, renderers) {
|
|
|
131
128
|
const answerCodec = block.answer === void 0 ? void 0 : Schema.toCodecJson(block.answer);
|
|
132
129
|
const answer = given === void 0 || answerCodec === void 0 ? Option.none() : Schema.decodeUnknownOption(answerCodec)(given);
|
|
133
130
|
return render({
|
|
131
|
+
messageId: message.id,
|
|
134
132
|
text: message.text,
|
|
135
133
|
props: props.value,
|
|
136
134
|
open: message.block.status === "open",
|
|
137
135
|
answer: Option.getOrUndefined(answer),
|
|
138
|
-
decisions: message.block.decisions ?? [],
|
|
139
136
|
respond: (value) => options.respond(BlockAnswer.make({
|
|
140
137
|
id: fromKey(`${message.id}:answer`),
|
|
141
138
|
messageId: message.id,
|
package/dist/BlockKit.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"BlockKit.js","names":["AssistantEvent.isLibraryEvent","InputId.fromKey"],"sources":["../src/BlockKit.ts"],"sourcesContent":["/**\n * Groups the blocks an assistant may put in its messages, and renders them on the client.\n *\n * A kit is created with {@link make} and passed to `Assistant.make`. {@link fromEntries} computes\n * the state of every message's block from a chat's log, {@link closeStale} closes the blocks the\n * user moved on from, and {@link toClient} creates a client-side renderer with one function per\n * block kind.\n *\n * @since 0.1.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport type * as Block from \"./Block.ts\"\nimport type * as ChatView from \"./ChatView.ts\"\nimport { CurrentChat } from \"./CurrentChat.ts\"\nimport * as Decision from \"./Decision.ts\"\nimport * as InputId from \"./InputId.ts\"\n\n/**\n * Represents a catalog of blocks, with a lookup by kind.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface BlockKit<Blocks extends Block.Any = Block.Any> {\n readonly blocks: ReadonlyArray<Blocks>\n readonly byKind: ReadonlyMap<string, Blocks>\n}\n\n/**\n * Creates a kit from blocks.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <const Blocks extends ReadonlyArray<Block.Any>>(blocks: Blocks): BlockKit<Blocks[number]> => ({\n blocks,\n byKind: new Map(blocks.map((block) => [block.kind, block]))\n})\n\ntype KindOf<B> = B extends { readonly kind: infer K extends string } ? K : never\n\ntype BlockOf<Kit extends BlockKit, K> = Extract<Kit[\"blocks\"][number], { readonly kind: K }>\n\ntype PropsOf<B> = B extends { readonly props: Schema.Top } ? B[\"props\"][\"Type\"] : never\n\ntype AnswerOf<B> = B extends { readonly answer: infer A } ? (A extends Schema.Top ? A[\"Type\"] : never) : never\n\n/**\n * Represents the state of a message's block.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface State {\n readonly open: boolean\n /** The user's answer, if they used the block. */\n readonly answer: AssistantEvent.BlockAnswer | undefined\n}\n\n/**\n * Returns the block states after one more event.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const apply = (\n states: ReadonlyMap<string, State>,\n event: { readonly _tag: string }\n): ReadonlyMap<string, State> => {\n if (!AssistantEvent.isLibraryEvent(event)) return states\n\n const close = (ids: ReadonlyArray<string>) => {\n const open = ids.filter((id) => states.get(id)?.open === true)\n\n if (open.length === 0) return states\n\n const next = new Map(states)\n\n for (const id of open) next.set(id, { open: false, answer: undefined })\n\n return next\n }\n\n if (Predicate.isTagged(event, \"BlocksClosed\")) return close(event.messageIds)\n\n if (Predicate.isTagged(event, \"AssistantMessage\")) {\n const closed = close(event.closes ?? [])\n\n return event.block === undefined ? closed : new Map(closed).set(event.id, { open: true, answer: undefined })\n }\n\n if (!Predicate.isTagged(event, \"BlockAnswer\") || states.get(event.messageId)?.open !== true) return states\n\n return new Map(states).set(event.messageId, { open: false, answer: event })\n}\n\n/**\n * Returns the state of every message's block, by message id.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const fromEntries = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlyMap<string, State> => {\n let states: ReadonlyMap<string, State> = new Map()\n\n for (const entry of entries) states = apply(states, entry.event)\n\n return states\n}\n\n/**\n * Returns the ids of the messages whose blocks are still open after the user typed the given\n * number of messages without using them.\n *\n * **Details**\n *\n * These are the blocks {@link closeStale} closes. Decision blocks never go stale, since work waits\n * on them and closing one would leave it waiting.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const staleBlocks = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n options: { readonly messages: number }\n): ReadonlyArray<string> => {\n const open = [...fromEntries(entries)].flatMap(([id, state]) => (state.open ? [id] : []))\n\n return open.filter((id) => {\n const shown = entries.findIndex(\n ({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"AssistantMessage\") && event.id === id\n )\n\n const message = entries[shown]?.event\n\n if (\n message === undefined ||\n (AssistantEvent.isLibraryEvent(message) &&\n Predicate.isTagged(message, \"AssistantMessage\") &&\n message.block?.kind === Decision.kind)\n )\n return false\n\n const typed = entries.slice(shown + 1).filter(({ event }) => Predicate.isTagged(event, \"UserMessage\")).length\n\n return typed >= options.messages\n })\n}\n\n/**\n * Closes the blocks the user moved on from, which are still open after the given number of typed\n * messages.\n *\n * **Details**\n *\n * Run it from a turn, before or after its loop. It records a `BlocksClosed` event, so every\n * client folds the blocks closed.\n *\n * @see {@link staleBlocks} for the blocks it closes\n *\n * @category utils\n * @since 0.1.0\n */\nexport const closeStale = Effect.fn(function* (options: { readonly messages: number }) {\n const chat = yield* CurrentChat\n const stale = staleBlocks(yield* chat.entries, options)\n\n if (stale.length > 0) yield* chat.append(AssistantEvent.BlocksClosed.make({ messageIds: stale }))\n})\n\n/**\n * Represents what a renderer receives for one block.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface RenderArgs<B> {\n readonly text: string\n readonly props: PropsOf<B>\n /**\n * Whether the block is open. It is `false` once the block is answered, with the block or in\n * words; show it read-only then.\n */\n readonly open: boolean\n /** The user's answer, if they used the block. */\n readonly answer: AnswerOf<B> | undefined\n /**\n * For the decision block, the call each decision is for (its tool and params) and how it was\n * decided. Empty for other blocks.\n */\n readonly decisions: ReadonlyArray<ChatView.PendingDecision>\n /** Sends an answer. Only call it while `open`. */\n readonly respond: (answer: AnswerOf<B>) => void\n}\n\n/**\n * Represents a renderer for every kind in a kit.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Renderers<Kit extends BlockKit, Out> = {\n readonly [K in KindOf<Kit[\"blocks\"][number]>]: (args: RenderArgs<BlockOf<Kit, K>>) => Out\n}\n\n/**\n * Represents the options for rendering one message's block.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface RenderOptions {\n /** Submits an answer, for example over RPC. */\n readonly respond: (answer: AssistantEvent.BlockAnswer) => void\n}\n\n/**\n * Creates a client-side renderer for the blocks on a chat view's messages\n * (`ChatView.AssistantMessage`).\n *\n * **Details**\n *\n * The renderers are type-checked, so every kind in the kit needs one, and each receives typed\n * `props` and `answer`. A renderer's `respond` builds a `BlockAnswer` input, with the answer\n * encoded by the block's answer schema, and passes it to the `respond` option to submit.\n *\n * The returned function returns `undefined` for a message without a block, or with a block it\n * can't decode or has no renderer for.\n *\n * **Example** (Rendering blocks with React)\n *\n * ```tsx\n * import { BlockKit, Decision } from \"effect-assistant\"\n * import type { ReactNode } from \"react\"\n *\n * const Blocks = BlockKit.make([PickOne, Decision.block])\n *\n * const renderBlock = BlockKit.toClient<typeof Blocks, ReactNode>(Blocks, {\n * pick_one: ({ props, open, respond }) =>\n * props.options.map((option) => (\n * <button key={option} disabled={!open} onClick={() => respond({ picked: option })}>\n * {option}\n * </button>\n * )),\n * decision: ({ props, open, respond }) => (\n * <button disabled={!open} onClick={() => respond(Decision.answerAll(props, \"approved\"))}>\n * {props.approveLabel ?? \"Approve\"}\n * </button>\n * )\n * })\n *\n * // For each AssistantMessage in the chat's view:\n * renderBlock(message, { respond: (answer) => submit(answer) })\n * ```\n *\n * @category constructors\n * @since 0.1.0\n */\nexport function toClient<Kit extends BlockKit, Out>(\n kit: Kit,\n renderers: Renderers<Kit, Out>\n): (message: ChatView.AssistantMessage, options: RenderOptions) => Out | undefined\n// The overload above checks that every kind has a renderer; here each one takes any block's\n// arguments.\nexport function toClient<Out>(\n kit: BlockKit,\n renderers: Readonly<Record<string, (args: RenderArgs<Block.Any>) => Out>>\n): (message: ChatView.AssistantMessage, options: RenderOptions) => Out | undefined {\n return (message, options) => {\n if (message.block === undefined) return undefined\n\n const { kind } = message.block\n const block = kit.byKind.get(kind)\n const render = renderers[kind]\n\n if (block === undefined || render === undefined) return undefined\n\n const props = Schema.decodeUnknownOption(block.props)(message.block.props)\n\n if (Option.isNone(props)) return undefined\n\n const given = message.block.answer\n const answerCodec = block.answer === undefined ? undefined : Schema.toCodecJson(block.answer)\n\n const answer =\n given === undefined || answerCodec === undefined ? Option.none() : Schema.decodeUnknownOption(answerCodec)(given)\n\n return render({\n text: message.text,\n props: props.value,\n open: message.block.status === \"open\",\n answer: Option.getOrUndefined(answer),\n decisions: message.block.decisions ?? [],\n respond: (value) =>\n options.respond(\n AssistantEvent.BlockAnswer.make({\n // A block takes one answer: the same id every time, so a second click is stored once.\n id: InputId.fromKey(`${message.id}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,MAAM,KAAK;EAEzE,IAAI,OAAO,OAAO,KAAK,GAAG,OAAO,KAAA;EAEjC,MAAM,QAAQ,QAAQ,MAAM;EAC5B,MAAM,cAAc,MAAM,WAAW,KAAA,IAAY,KAAA,IAAY,OAAO,YAAY,MAAM,MAAM;EAE5F,MAAM,SACJ,UAAU,KAAA,KAAa,gBAAgB,KAAA,IAAY,OAAO,KAAK,IAAI,OAAO,oBAAoB,WAAW,CAAC,CAAC,KAAK;EAElH,OAAO,OAAO;GACZ,MAAM,QAAQ;GACd,OAAO,MAAM;GACb,MAAM,QAAQ,MAAM,WAAW;GAC/B,QAAQ,OAAO,eAAe,MAAM;GACpC,WAAW,QAAQ,MAAM,aAAa,CAAC;GACvC,UAAU,UACR,QAAQ,QAAA,YACqB,KAAK;IAE9B,IAAIC,QAAgB,GAAG,QAAQ,GAAG,QAAQ;IAC1C,WAAW,QAAQ;IACnB;IACA,OAAO,gBAAgB,KAAA,IAAY,QAAQ,OAAO,kBAAkB,WAAW,CAAC,CAAC,KAAK;GACxF,CAAC,CACH;EACJ,CAAC;CACH;AACF"}
|
|
1
|
+
{"version":3,"file":"BlockKit.js","names":["AssistantEvent.isLibraryEvent","InputId.fromKey"],"sources":["../src/BlockKit.ts"],"sourcesContent":["/**\n * Groups the blocks an assistant may put in its messages, and renders them on the client.\n *\n * A kit is created with {@link make} and passed to `Assistant.make`. {@link fromEntries} computes\n * the state of every message's block from a chat's log, {@link closeStale} closes the blocks the\n * user moved on from, and {@link toClient} creates a client-side renderer with one function per\n * block kind.\n *\n * @since 0.1.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport * as AssistantEvent from \"./AssistantEvent.ts\"\nimport type * as Block from \"./Block.ts\"\nimport type * as ChatView from \"./ChatView.ts\"\nimport { CurrentChat } from \"./CurrentChat.ts\"\nimport * as InputId from \"./InputId.ts\"\n\n/**\n * Represents a catalog of blocks, with a lookup by kind.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface BlockKit<Blocks extends Block.Any = Block.Any> {\n readonly blocks: ReadonlyArray<Blocks>\n readonly byKind: ReadonlyMap<string, Blocks>\n}\n\n/**\n * Creates a kit from blocks.\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <const Blocks extends ReadonlyArray<Block.Any>>(blocks: Blocks): BlockKit<Blocks[number]> => ({\n blocks,\n byKind: new Map(blocks.map((block) => [block.kind, block]))\n})\n\ntype KindOf<B> = B extends { readonly kind: infer K extends string } ? K : never\n\ntype BlockOf<Kit extends BlockKit, K> = Extract<Kit[\"blocks\"][number], { readonly kind: K }>\n\ntype PropsOf<B> = B extends { readonly props: Schema.Top } ? B[\"props\"][\"Type\"] : never\n\ntype AnswerOf<B> = B extends { readonly answer: infer A } ? (A extends Schema.Top ? A[\"Type\"] : never) : never\n\n/**\n * Represents the state of a message's block.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface State {\n readonly open: boolean\n /** The user's answer, if they used the block. */\n readonly answer: AssistantEvent.BlockAnswer | undefined\n}\n\n/**\n * Returns the block states after one more event.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const apply = (\n states: ReadonlyMap<string, State>,\n event: { readonly _tag: string }\n): ReadonlyMap<string, State> => {\n if (!AssistantEvent.isLibraryEvent(event)) return states\n\n const close = (ids: ReadonlyArray<string>) => {\n const open = ids.filter((id) => states.get(id)?.open === true)\n\n if (open.length === 0) return states\n\n const next = new Map(states)\n\n for (const id of open) next.set(id, { open: false, answer: undefined })\n\n return next\n }\n\n if (Predicate.isTagged(event, \"BlocksClosed\")) return close(event.messageIds)\n\n if (Predicate.isTagged(event, \"AssistantMessage\")) {\n const closed = close(event.closes ?? [])\n\n return event.block === undefined ? closed : new Map(closed).set(event.id, { open: true, answer: undefined })\n }\n\n if (!Predicate.isTagged(event, \"BlockAnswer\") || states.get(event.messageId)?.open !== true) return states\n\n return new Map(states).set(event.messageId, { open: false, answer: event })\n}\n\n/**\n * Returns the state of every message's block, by message id.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const fromEntries = (entries: ReadonlyArray<AssistantEvent.AnyEntry>): ReadonlyMap<string, State> => {\n let states: ReadonlyMap<string, State> = new Map()\n\n for (const entry of entries) states = apply(states, entry.event)\n\n return states\n}\n\n/**\n * Returns the ids of the messages whose blocks are still open after the user typed the given\n * number of messages without using them.\n *\n * **Details**\n *\n * These are the blocks {@link closeStale} closes.\n *\n * @category utils\n * @since 0.1.0\n */\nexport const staleBlocks = (\n entries: ReadonlyArray<AssistantEvent.AnyEntry>,\n options: { readonly messages: number }\n): ReadonlyArray<string> => {\n const open = [...fromEntries(entries)].flatMap(([id, state]) => (state.open ? [id] : []))\n\n return open.filter((id) => {\n const shown = entries.findIndex(\n ({ event }) =>\n AssistantEvent.isLibraryEvent(event) && Predicate.isTagged(event, \"AssistantMessage\") && event.id === id\n )\n\n if (shown === -1) return false\n\n const typed = entries.slice(shown + 1).filter(({ event }) => Predicate.isTagged(event, \"UserMessage\")).length\n\n return typed >= options.messages\n })\n}\n\n/**\n * Closes the blocks the user moved on from, which are still open after the given number of typed\n * messages.\n *\n * **Details**\n *\n * Run it from a turn, before or after its loop. It records a `BlocksClosed` event, so every\n * client folds the blocks closed.\n *\n * @see {@link staleBlocks} for the blocks it closes\n *\n * @category utils\n * @since 0.1.0\n */\nexport const closeStale = Effect.fn(function* (options: { readonly messages: number }) {\n const chat = yield* CurrentChat\n const stale = staleBlocks(yield* chat.entries, options)\n\n if (stale.length > 0) yield* chat.append(AssistantEvent.BlocksClosed.make({ messageIds: stale }))\n})\n\n/**\n * Represents what a renderer receives for one block.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface RenderArgs<B> {\n /**\n * The id of the message the block is on. A block whose button calls your API can key the work\n * on it, with the chat's id, so the work runs once per block.\n */\n readonly messageId: string\n readonly text: string\n readonly props: PropsOf<B>\n /**\n * Whether the block is open. It is `false` once the block is answered, with the block or in\n * words; show it read-only then.\n */\n readonly open: boolean\n /** The user's answer, if they used the block. */\n readonly answer: AnswerOf<B> | undefined\n /** Sends an answer. Only call it while `open`. */\n readonly respond: (answer: AnswerOf<B>) => void\n}\n\n/**\n * Represents a renderer for every kind in a kit.\n *\n * @category models\n * @since 0.1.0\n */\nexport type Renderers<Kit extends BlockKit, Out> = {\n readonly [K in KindOf<Kit[\"blocks\"][number]>]: (args: RenderArgs<BlockOf<Kit, K>>) => Out\n}\n\n/**\n * Represents the options for rendering one message's block.\n *\n * @category models\n * @since 0.1.0\n */\nexport interface RenderOptions {\n /** Submits an answer, for example over RPC. */\n readonly respond: (answer: AssistantEvent.BlockAnswer) => void\n}\n\n/**\n * Creates a client-side renderer for the blocks on a chat view's messages\n * (`ChatView.AssistantMessage`).\n *\n * **Details**\n *\n * The renderers are type-checked, so every kind in the kit needs one, and each receives typed\n * `props` and `answer`. A renderer's `respond` builds a `BlockAnswer` input, with the answer\n * encoded by the block's answer schema, and passes it to the `respond` option to submit.\n *\n * The returned function returns `undefined` for a message without a block, or with a block it\n * can't decode or has no renderer for.\n *\n * **Example** (Rendering blocks with React)\n *\n * ```tsx\n * import { BlockKit } from \"effect-assistant\"\n * import type { ReactNode } from \"react\"\n *\n * const Blocks = BlockKit.make([PickOne, OrderDraft])\n *\n * const renderBlock = BlockKit.toClient<typeof Blocks, ReactNode>(Blocks, {\n * pick_one: ({ props, open, respond }) =>\n * props.options.map((option) => (\n * <button key={option} disabled={!open} onClick={() => respond({ picked: option })}>\n * {option}\n * </button>\n * )),\n * // No answer schema: the button calls the app's own API with the props the user sees.\n * order_draft: ({ props }) => <button onClick={() => placeOrder(props)}>Place order</button>\n * })\n *\n * // For each AssistantMessage in the chat's view:\n * renderBlock(message, { respond: (answer) => submit(answer) })\n * ```\n *\n * @category constructors\n * @since 0.1.0\n */\nexport function toClient<Kit extends BlockKit, Out>(\n kit: Kit,\n renderers: Renderers<Kit, Out>\n): (message: ChatView.AssistantMessage, options: RenderOptions) => Out | undefined\n// The overload above checks that every kind has a renderer; here each one takes any block's\n// arguments.\nexport function toClient<Out>(\n kit: BlockKit,\n renderers: Readonly<Record<string, (args: RenderArgs<Block.Any>) => Out>>\n): (message: ChatView.AssistantMessage, options: RenderOptions) => Out | undefined {\n return (message, options) => {\n if (message.block === undefined) return undefined\n\n const { kind } = message.block\n const block = kit.byKind.get(kind)\n const render = renderers[kind]\n\n if (block === undefined || render === undefined) return undefined\n\n const props = Schema.decodeUnknownOption(block.props)(message.block.props)\n\n if (Option.isNone(props)) return undefined\n\n const given = message.block.answer\n const answerCodec = block.answer === undefined ? undefined : Schema.toCodecJson(block.answer)\n\n const answer =\n given === undefined || answerCodec === undefined ? Option.none() : Schema.decodeUnknownOption(answerCodec)(given)\n\n return render({\n messageId: message.id,\n text: message.text,\n props: props.value,\n open: message.block.status === \"open\",\n answer: Option.getOrUndefined(answer),\n respond: (value) =>\n options.respond(\n AssistantEvent.BlockAnswer.make({\n // A block takes one answer: the same id every time, so a second click is stored once.\n id: InputId.fromKey(`${message.id}:answer`),\n messageId: message.id,\n kind,\n value: answerCodec === undefined ? value : Schema.encodeUnknownSync(answerCodec)(value)\n })\n )\n })\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,QAAuD,YAA8C;CAChH;CACA,QAAQ,IAAI,IAAI,OAAO,KAAK,UAAU,CAAC,MAAM,MAAM,KAAK,CAAC,CAAC;AAC5D;;;;;;;AA4BA,MAAa,SACX,QACA,UAC+B;CAC/B,IAAI,CAACA,eAA8B,KAAK,GAAG,OAAO;CAElD,MAAM,SAAS,QAA+B;EAC5C,MAAM,OAAO,IAAI,QAAQ,OAAO,OAAO,IAAI,EAAE,CAAC,EAAE,SAAS,IAAI;EAE7D,IAAI,KAAK,WAAW,GAAG,OAAO;EAE9B,MAAM,OAAO,IAAI,IAAI,MAAM;EAE3B,KAAK,MAAM,MAAM,MAAM,KAAK,IAAI,IAAI;GAAE,MAAM;GAAO,QAAQ,K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