effect-assistant 0.1.0 → 0.3.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/Assistant.d.ts +74 -28
- package/dist/Assistant.d.ts.map +1 -1
- package/dist/Assistant.js +11 -4
- package/dist/Assistant.js.map +1 -1
- package/dist/AssistantActivity.d.ts +10 -16
- package/dist/AssistantActivity.d.ts.map +1 -1
- package/dist/AssistantActivity.js +11 -4
- package/dist/AssistantActivity.js.map +1 -1
- package/dist/AssistantEngine.d.ts +39 -1
- package/dist/AssistantEngine.d.ts.map +1 -1
- package/dist/AssistantEngine.js +81 -28
- package/dist/AssistantEngine.js.map +1 -1
- package/dist/AssistantEvent.d.ts +52 -70
- package/dist/AssistantEvent.d.ts.map +1 -1
- package/dist/AssistantEvent.js +28 -57
- 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 +14 -18
- package/dist/BlockKit.d.ts.map +1 -1
- package/dist/BlockKit.js +4 -7
- package/dist/BlockKit.js.map +1 -1
- package/dist/ChatLog.js +1 -1
- package/dist/Compaction.d.ts +8 -4
- package/dist/Compaction.d.ts.map +1 -1
- package/dist/Compaction.js +12 -15
- package/dist/Compaction.js.map +1 -1
- package/dist/CurrentChat.d.ts +2 -1
- package/dist/CurrentChat.d.ts.map +1 -1
- package/dist/CurrentChat.js.map +1 -1
- package/dist/Instructions.js +1 -1
- package/dist/Skill.d.ts +33 -0
- package/dist/Skill.d.ts.map +1 -1
- package/dist/Skill.js +27 -1
- package/dist/Skill.js.map +1 -1
- package/dist/Specialist.d.ts +4 -1
- package/dist/Specialist.d.ts.map +1 -1
- package/dist/Specialist.js.map +1 -1
- package/dist/Timeline.d.ts +482 -0
- package/dist/Timeline.d.ts.map +1 -0
- package/dist/Timeline.js +572 -0
- package/dist/Timeline.js.map +1 -0
- 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 +2 -5
- package/dist/index.js +4 -7
- package/dist/internal/chat.js +11 -37
- package/dist/internal/chat.js.map +1 -1
- package/dist/internal/events.d.ts +15 -16
- package/dist/internal/events.d.ts.map +1 -1
- package/dist/internal/events.js +29 -28
- package/dist/internal/events.js.map +1 -1
- package/dist/internal/history.js +26 -58
- package/dist/internal/history.js.map +1 -1
- package/dist/internal/input.js +7 -0
- package/dist/internal/input.js.map +1 -0
- package/dist/internal/loop.d.ts +2 -2
- package/dist/internal/loop.d.ts.map +1 -1
- package/dist/internal/loop.js +21 -56
- package/dist/internal/loop.js.map +1 -1
- package/dist/internal/skills.js +6 -1
- package/dist/internal/skills.js.map +1 -1
- package/dist/internal/specialists.js +7 -7
- 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 +2 -21
- package/dist/internal/tools.js.map +1 -1
- package/dist/internal/turns.d.ts.map +1 -1
- package/dist/internal/turns.js +24 -43
- package/dist/internal/turns.js.map +1 -1
- package/package.json +3 -2
- package/src/Assistant.ts +75 -29
- package/src/AssistantActivity.ts +11 -18
- package/src/AssistantEngine.ts +110 -43
- package/src/AssistantEvent.ts +46 -74
- package/src/AssistantLoop.ts +7 -5
- package/src/Block.ts +1 -1
- package/src/BlockKit.ts +18 -31
- package/src/Compaction.ts +8 -21
- package/src/CurrentChat.ts +2 -1
- package/src/Skill.ts +34 -1
- package/src/Specialist.ts +4 -1
- package/src/Timeline.ts +861 -0
- package/src/ToolDiscovery.ts +5 -13
- package/src/ToolFailure.ts +1 -1
- package/src/index.ts +5 -20
- package/src/internal/chat.ts +8 -57
- package/src/internal/events.ts +43 -43
- package/src/internal/history.ts +36 -101
- package/src/internal/input.ts +3 -0
- package/src/internal/loop.ts +31 -101
- package/src/internal/skills.ts +11 -0
- package/src/internal/specialists.ts +6 -9
- package/src/internal/toolkit.ts +17 -60
- package/src/internal/tools.ts +2 -53
- package/src/internal/turns.ts +37 -79
- package/dist/AppEvent.d.ts +0 -111
- package/dist/AppEvent.d.ts.map +0 -1
- package/dist/AppEvent.js +0 -71
- package/dist/AppEvent.js.map +0 -1
- package/dist/ChatView.d.ts +0 -459
- package/dist/ChatView.d.ts.map +0 -1
- package/dist/ChatView.js +0 -496
- package/dist/ChatView.js.map +0 -1
- 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/AppEvent.ts +0 -134
- package/src/ChatView.ts +0 -658
- package/src/Decision.ts +0 -241
- package/src/DecisionId.ts +0 -46
- package/src/internal/decisions.ts +0 -131
package/dist/ToolDiscovery.d.ts
CHANGED
|
@@ -1,5 +1,4 @@
|
|
|
1
1
|
import { AssistantToolCall } from "./AssistantToolCall.js";
|
|
2
|
-
import { ToolServices, toolkit_d_exports } from "./internal/toolkit.js";
|
|
3
2
|
import * as Schema from "effect/Schema";
|
|
4
3
|
import * as Tool from "effect/ai/Tool";
|
|
5
4
|
import * as Toolkit from "effect/ai/Toolkit";
|
|
@@ -15,8 +14,8 @@ declare namespace ToolDiscovery_d_exports {
|
|
|
15
14
|
* the tools' handlers. A catalog tool's services are `execute_tool`'s, so the turn provides them
|
|
16
15
|
* as it does for any tool.
|
|
17
16
|
*
|
|
18
|
-
*
|
|
19
|
-
*
|
|
17
|
+
* A catalog tool with Effect's `needsApproval` set fails the layer when it is built, as it would
|
|
18
|
+
* fail a loop: the library doesn't run calls that wait for approval.
|
|
20
19
|
*
|
|
21
20
|
* **Example** (Finding rarely used tools when needed)
|
|
22
21
|
*
|
|
@@ -51,7 +50,7 @@ export declare const make: <T extends Record<string, Tool.Any>>(_catalog: Toolki
|
|
|
51
50
|
readonly success: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
52
51
|
readonly failure: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
53
52
|
readonly failureMode: "error";
|
|
54
|
-
}, AssistantToolCall |
|
|
53
|
+
}, AssistantToolCall | Exclude<Tool.HandlerServices<T[keyof T]>, AssistantToolCall>>;
|
|
55
54
|
readonly search_tools: Tool.Tool<"search_tools", {
|
|
56
55
|
readonly parameters: Schema.Struct<{
|
|
57
56
|
readonly query: Schema.String;
|
|
@@ -89,7 +88,7 @@ export declare const layer: <T extends Record<string, Tool.Any>>(catalog: Toolki
|
|
|
89
88
|
readonly success: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
90
89
|
readonly failure: Schema.Codec<Schema.Json, Schema.Json, never, never>;
|
|
91
90
|
readonly failureMode: "error";
|
|
92
|
-
}, AssistantToolCall |
|
|
91
|
+
}, AssistantToolCall | Exclude<Tool.HandlerServices<T[keyof T]>, AssistantToolCall>>;
|
|
93
92
|
readonly search_tools: Tool.Tool<"search_tools", {
|
|
94
93
|
readonly parameters: Schema.Struct<{
|
|
95
94
|
readonly query: Schema.String;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolDiscovery.d.ts","names":[],"sources":["../src/ToolDiscovery.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"ToolDiscovery.d.ts","names":[],"sources":["../src/ToolDiscovery.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBA2Ha,OAAQ,UAAU,eAAe,KAAK,MAAI,UAE3C,QAAQ,QAAQ,OAAE,QAAA;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;qBAkBjB,QAAS,UAAU,eAAe,KAAK,MAAI,SAAW,QAAQ,QAAQ,8BAAE,MAAA,KAAA;;;;;;;;;;;;;;;;;;;;;;WAmClF,QAAA,KAAA,YAAA,2BAAA"}
|
package/dist/ToolDiscovery.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { __exportAll } from "./_virtual/_rolldown/runtime.js";
|
|
2
2
|
import { toJson } from "./internal/schema.js";
|
|
3
3
|
import { AssistantToolCall } from "./AssistantToolCall.js";
|
|
4
|
-
import {
|
|
4
|
+
import { needingApproval, needsApprovalMessage, runNative } from "./internal/toolkit.js";
|
|
5
5
|
import * as Effect from "effect/Effect";
|
|
6
6
|
import * as Schema from "effect/Schema";
|
|
7
7
|
import * as Response from "effect/ai/Response";
|
|
@@ -67,8 +67,8 @@ const requiring = () => (tool) => tool;
|
|
|
67
67
|
* the tools' handlers. A catalog tool's services are `execute_tool`'s, so the turn provides them
|
|
68
68
|
* as it does for any tool.
|
|
69
69
|
*
|
|
70
|
-
*
|
|
71
|
-
*
|
|
70
|
+
* A catalog tool with Effect's `needsApproval` set fails the layer when it is built, as it would
|
|
71
|
+
* fail a loop: the library doesn't run calls that wait for approval.
|
|
72
72
|
*
|
|
73
73
|
* **Example** (Finding rarely used tools when needed)
|
|
74
74
|
*
|
|
@@ -113,6 +113,8 @@ const make = (_catalog) => Toolkit.make(SearchTools, requiring()(ExecuteTool));
|
|
|
113
113
|
const layer = (catalog) => make(catalog).toLayer(Effect.gen(function* () {
|
|
114
114
|
const resolved = yield* catalog;
|
|
115
115
|
const definitions = Object.values(resolved.tools);
|
|
116
|
+
const needingApproval$1 = needingApproval(definitions);
|
|
117
|
+
if (needingApproval$1.length > 0) return yield* Effect.die(needsApprovalMessage(needingApproval$1));
|
|
116
118
|
return {
|
|
117
119
|
search_tools: ({ query }) => Effect.sync(() => search(definitions, query, 5).map((tool) => ({
|
|
118
120
|
name: tool.name,
|
|
@@ -127,7 +129,6 @@ const layer = (catalog) => make(catalog).toLayer(Effect.gen(function* () {
|
|
|
127
129
|
params: input,
|
|
128
130
|
providerExecuted: false
|
|
129
131
|
});
|
|
130
|
-
if (yield* needsDecision(resolved, call, [])) return yield* Effect.fail(failed(`${name} needs the user's decision, so it can't run through execute_tool.`, "NeedsDecision").result);
|
|
131
132
|
const { outcome, result } = yield* runNative(resolved, call);
|
|
132
133
|
return outcome === "failure" ? yield* Effect.fail(result) : result;
|
|
133
134
|
})
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolDiscovery.js","names":["Toolkits.
|
|
1
|
+
{"version":3,"file":"ToolDiscovery.js","names":["needingApproval","Toolkits.needingApproval","Toolkits.needsApprovalMessage","Toolkits.runNative"],"sources":["../src/ToolDiscovery.ts"],"sourcesContent":["/**\n * Turns a catalog toolkit into two tools, so the prompt doesn't carry every tool definition.\n *\n * `search_tools` finds tools by what the model needs to do and returns their names, descriptions,\n * and input schemas. `execute_tool` validates an input and runs one of them. {@link make} returns\n * the two tools as a native toolkit, and {@link layer} their handlers.\n *\n * @since 0.1.0\n */\nimport * as Response from \"effect/ai/Response\"\nimport * as Tool from \"effect/ai/Tool\"\nimport * as Toolkit from \"effect/ai/Toolkit\"\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\nimport { AssistantToolCall } from \"./AssistantToolCall.ts\"\nimport { toJson } from \"./internal/schema.ts\"\nimport * as Toolkits from \"./internal/toolkit.ts\"\n\nconst words = (text: string): ReadonlySet<string> =>\n new Set(\n text\n .toLowerCase()\n .split(/[^a-z0-9]+/)\n .filter((word) => word.length >= 3)\n )\n\nconst score = (query: ReadonlySet<string>, text: string): number => {\n const target = [...words(text)]\n\n const matches = (word: string) =>\n target.some((t) => t === word || (word.length >= 4 && (t.startsWith(word) || word.startsWith(t))))\n\n return [...query].filter(matches).length\n}\n\n// Everything when nothing matches, so the model can pick or search again.\nconst search = (tools: ReadonlyArray<Tool.Any>, query: string, limit: number): ReadonlyArray<Tool.Any> => {\n const queryWords = words(query)\n\n const ranked = tools\n .flatMap((tool) => {\n const hits = score(queryWords, `${tool.name} ${Tool.getDescription(tool) ?? \"\"}`)\n\n return hits > 0 ? [{ tool, score: hits }] : []\n })\n .sort((a, b) => b.score - a.score)\n\n return (ranked.length > 0 ? ranked.map((hit) => hit.tool) : tools).slice(0, limit)\n}\n\nconst SearchTools = Tool.make(\"search_tools\", {\n description:\n \"Search for more tools by what you need to do. Returns their names, descriptions, and input schemas; call one with execute_tool.\",\n parameters: Schema.Struct({\n query: Schema.String.annotate({ description: \"What you need to do, in a few words.\" })\n }),\n success: Schema.Array(\n Schema.Struct({\n name: Schema.String,\n description: Schema.optional(Schema.String),\n inputSchema: Schema.Json\n })\n )\n})\n\nconst ExecuteTool = Tool.make(\"execute_tool\", {\n description: \"Run a tool found with search_tools. Pass its name and an input matching its input schema.\",\n parameters: Schema.Struct({\n name: Schema.String,\n input: Schema.Record(Schema.String, Schema.Json)\n }),\n success: Schema.Json,\n // The tool's failure is this call's, so the loop sees it failed (a `wait: true` message doesn't\n // end the turn).\n failure: Schema.Json,\n dependencies: [AssistantToolCall]\n})\n\n// A tool's requirements are a covariant phantom type, so one that needs nothing is one that needs\n// any.\nconst requiring =\n <R>() =>\n <N extends string, C extends (Tool.Any extends Tool.Tool<string, infer K, unknown> ? K : never), R0>(\n tool: Tool.Tool<N, C, R0>\n ): Tool.Tool<N, C, R0 | R> =>\n tool\n\n/**\n * Creates the `search_tools` and `execute_tool` tools over a catalog toolkit, as a native toolkit.\n *\n * **Details**\n *\n * Merge the toolkit into the loop's, and provide {@link layer} for the same catalog, which has\n * the tools' handlers. A catalog tool's services are `execute_tool`'s, so the turn provides them\n * as it does for any tool.\n *\n * A catalog tool with Effect's `needsApproval` set fails the layer when it is built, as it would\n * fail a loop: the library doesn't run calls that wait for approval.\n *\n * **Example** (Finding rarely used tools when needed)\n *\n * ```ts\n * import { ToolDiscovery } from \"effect-assistant\"\n * import * as Toolkit from \"effect/ai/Toolkit\"\n * import * as Layer from \"effect/Layer\"\n *\n * // OfficeTools is a big toolkit, found when needed. CommonTools stays in the prompt.\n * const OfficeDiscovery = ToolDiscovery.make(OfficeTools)\n * const OfficeDiscoveryLive = ToolDiscovery.layer(OfficeTools).pipe(Layer.provide(OfficeToolsLive))\n *\n * const MyAssistantLive = MyAssistant.toLayer((turn) =>\n * turn.loop({\n * instructions,\n * toolkit: Toolkit.merge(CommonTools, OfficeDiscovery)\n * })\n * ).pipe(Layer.provide([CommonToolsLive, OfficeDiscoveryLive]))\n * ```\n *\n * @see {@link layer} for the tools' handlers\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const make = <T extends Record<string, Tool.Any>>(\n // Only its type is used here, for `execute_tool`'s services: `layer` runs its tools.\n _catalog: Toolkit.Toolkit<T>\n) => Toolkit.make(SearchTools, requiring<Toolkits.ToolServices<T>>()(ExecuteTool))\n\n/**\n * Creates the layer with the handlers of the `search_tools` and `execute_tool` tools over a\n * catalog toolkit.\n *\n * **Details**\n *\n * The layer needs the catalog's handlers. It provides the handlers of the toolkit that\n * {@link make} returns for the same catalog: handlers are keyed by tool name, so the two calls\n * don't need to share a value. Give both the same catalog.\n *\n * @see {@link make} for the toolkit and an example\n *\n * @category layers\n * @since 0.1.0\n */\nexport const layer = <T extends Record<string, Tool.Any>>(catalog: Toolkit.Toolkit<T>) =>\n make(catalog).toLayer(\n Effect.gen(function* () {\n const resolved = yield* catalog\n const definitions = Object.values(resolved.tools)\n const needingApproval = Toolkits.needingApproval(definitions)\n\n if (needingApproval.length > 0) return yield* Effect.die(Toolkits.needsApprovalMessage(needingApproval))\n\n return {\n search_tools: ({ query }) =>\n Effect.sync(() =>\n search(definitions, query, 5).map((tool) => ({\n name: tool.name,\n description: Tool.getDescription(tool),\n inputSchema: toJson(Tool.getJsonSchema(tool))\n }))\n ),\n execute_tool: Effect.fnUntraced(function* ({ name, input }) {\n // Named after the call that runs it: the same id when a crash runs that call again.\n const outer = yield* AssistantToolCall\n\n const call = Response.makePart(\"tool-call\", {\n id: `${outer.callId}:${name}`,\n name,\n params: input,\n providerExecuted: false\n })\n\n const { outcome, result } = yield* Toolkits.runNative(resolved, call)\n\n return outcome === \"failure\" ? yield* Effect.fail(result) : result\n })\n }\n })\n )\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAkBA,MAAM,SAAS,SACb,IAAI,IACF,KACG,YAAY,CAAC,CACb,MAAM,YAAY,CAAC,CACnB,QAAQ,SAAS,KAAK,UAAU,CAAC,CACtC;AAEF,MAAM,SAAS,OAA4B,SAAyB;CAClE,MAAM,SAAS,CAAC,GAAG,MAAM,IAAI,CAAC;CAE9B,MAAM,WAAW,SACf,OAAO,MAAM,MAAM,MAAM,QAAS,KAAK,UAAU,MAAM,EAAE,WAAW,IAAI,KAAK,KAAK,WAAW,CAAC,EAAG;CAEnG,OAAO,CAAC,GAAG,KAAK,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC;AACpC;AAGA,MAAM,UAAU,OAAgC,OAAe,UAA2C;CACxG,MAAM,aAAa,MAAM,KAAK;CAE9B,MAAM,SAAS,MACZ,SAAS,SAAS;EACjB,MAAM,OAAO,MAAM,YAAY,GAAG,KAAK,KAAK,GAAG,KAAK,eAAe,IAAI,KAAK,IAAI;EAEhF,OAAO,OAAO,IAAI,CAAC;GAAE;GAAM,OAAO;EAAK,CAAC,IAAI,CAAC;CAC/C,CAAC,CAAC,CACD,MAAM,GAAG,MAAM,EAAE,QAAQ,EAAE,KAAK;CAEnC,QAAQ,OAAO,SAAS,IAAI,OAAO,KAAK,QAAQ,IAAI,IAAI,IAAI,MAAA,CAAO,MAAM,GAAG,KAAK;AACnF;AAEA,MAAM,cAAc,KAAK,KAAK,gBAAgB;CAC5C,aACE;CACF,Y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Q;IACR,kBAAkB;GACpB,CAAC;GAED,MAAM,EAAE,SAAS,WAAW,OAAOG,UAAmB,UAAU,IAAI;GAEpE,OAAO,YAAY,YAAY,OAAO,OAAO,KAAK,MAAM,IAAI;EAC9D,CAAC;CACH;AACF,CAAC,CACH"}
|
package/dist/ToolFailure.d.ts
CHANGED
|
@@ -13,7 +13,7 @@ declare const ToolFailure_base: Schema.Class<ToolFailure, Schema.Struct<{
|
|
|
13
13
|
*
|
|
14
14
|
* It holds a message that says what went wrong and, optionally, a `reason` the model can tell
|
|
15
15
|
* apart, such as `"NotFound"` or `"OverBudget"`. The library's own reasons are PascalCase, like
|
|
16
|
-
* `"
|
|
16
|
+
* `"ToolNotFoundError"`.
|
|
17
17
|
*
|
|
18
18
|
* @category errors
|
|
19
19
|
* @since 0.1.0
|
package/dist/ToolFailure.js
CHANGED
|
@@ -20,7 +20,7 @@ var ToolFailure_exports = /* @__PURE__ */ __exportAll({
|
|
|
20
20
|
*
|
|
21
21
|
* It holds a message that says what went wrong and, optionally, a `reason` the model can tell
|
|
22
22
|
* apart, such as `"NotFound"` or `"OverBudget"`. The library's own reasons are PascalCase, like
|
|
23
|
-
* `"
|
|
23
|
+
* `"ToolNotFoundError"`.
|
|
24
24
|
*
|
|
25
25
|
* @category errors
|
|
26
26
|
* @since 0.1.0
|
package/dist/ToolFailure.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"ToolFailure.js","names":[],"sources":["../src/ToolFailure.ts"],"sourcesContent":["/**\n * Defines the failure a tool returns to the model.\n *\n * A {@link ToolFailure} carries a message the model reads and adapts to, such as \"No office named\n * Paris\", instead of failing the turn. Tools declare it as their `failure` schema and fail with\n * {@link fail}.\n *\n * @since 0.1.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * Represents a tool's failure, written for the model.\n *\n * It holds a message that says what went wrong and, optionally, a `reason` the model can tell\n * apart, such as `\"NotFound\"` or `\"OverBudget\"`. The library's own reasons are PascalCase, like\n * `\"
|
|
1
|
+
{"version":3,"file":"ToolFailure.js","names":[],"sources":["../src/ToolFailure.ts"],"sourcesContent":["/**\n * Defines the failure a tool returns to the model.\n *\n * A {@link ToolFailure} carries a message the model reads and adapts to, such as \"No office named\n * Paris\", instead of failing the turn. Tools declare it as their `failure` schema and fail with\n * {@link fail}.\n *\n * @since 0.1.0\n */\nimport * as Effect from \"effect/Effect\"\nimport * as Schema from \"effect/Schema\"\n\n/**\n * Represents a tool's failure, written for the model.\n *\n * It holds a message that says what went wrong and, optionally, a `reason` the model can tell\n * apart, such as `\"NotFound\"` or `\"OverBudget\"`. The library's own reasons are PascalCase, like\n * `\"ToolNotFoundError\"`.\n *\n * @category errors\n * @since 0.1.0\n */\nexport class ToolFailure extends Schema.Error<ToolFailure>(\"effect-assistant/ToolFailure/ToolFailure\")({\n _tag: Schema.tag(\"ToolFailure\"),\n message: Schema.String,\n reason: Schema.optional(Schema.String)\n}) {}\n\n/**\n * Fails a tool's handler with a message for the model.\n *\n * **Details**\n *\n * The tool must declare `failure: ToolFailure.ToolFailure`. The model reads the failure as the\n * call's result, with its `reason` when one is given.\n *\n * **Example** (Failing a tool call the model can correct)\n *\n * ```ts\n * import { ToolFailure } from \"effect-assistant\"\n * import * as Tool from \"effect/ai/Tool\"\n * import * as Toolkit from \"effect/ai/Toolkit\"\n * import * as Effect from \"effect/Effect\"\n * import * as Schema from \"effect/Schema\"\n *\n * const budgets = new Map([[\"Oslo\", 1200]])\n *\n * const BudgetTools = Toolkit.make(\n * Tool.make(\"office_budget\", {\n * description: \"The budget left for an office.\",\n * parameters: Schema.Struct({ office: Schema.String }),\n * success: Schema.Number,\n * failure: ToolFailure.ToolFailure\n * })\n * )\n *\n * const BudgetToolsLive = BudgetTools.toLayer({\n * office_budget: ({ office }) =>\n * Effect.fromNullishOr(budgets.get(office)).pipe(\n * Effect.catch(() => ToolFailure.fail(`No office named ${office}.`, { reason: \"NotFound\" }))\n * )\n * })\n * ```\n *\n * @category constructors\n * @since 0.1.0\n */\nexport const fail = (\n message: string,\n options?: { readonly reason?: string | undefined }\n): Effect.Effect<never, ToolFailure> =>\n Effect.fail(\n options?.reason === undefined ? new ToolFailure({ message }) : new ToolFailure({ message, reason: options.reason })\n )\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;AAsBA,IAAa,cAAb,cAAiC,OAAO,MAAmB,0CAA0C,CAAC,CAAC;CACrG,MAAM,OAAO,IAAI,aAAa;CAC9B,SAAS,OAAO;CAChB,QAAQ,OAAO,SAAS,OAAO,MAAM;AACvC,CAAC,CAAC,CAAC,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCJ,MAAa,QACX,SACA,YAEA,OAAO,KACL,SAAS,WAAW,KAAA,IAAY,IAAI,YAAY,EAAE,QAAQ,CAAC,IAAI,IAAI,YAAY;CAAE;CAAS,QAAQ,QAAQ;AAAO,CAAC,CACpH"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { AppEvent_d_exports } from "./AppEvent.js";
|
|
2
1
|
import { ChatId_d_exports } from "./ChatId.js";
|
|
3
2
|
import { AssistantEvent_d_exports } from "./AssistantEvent.js";
|
|
4
3
|
import { ChatLog_d_exports } from "./ChatLog.js";
|
|
@@ -6,7 +5,7 @@ import { Instructions_d_exports } from "./Instructions.js";
|
|
|
6
5
|
import { AssistantToolCall_d_exports } from "./AssistantToolCall.js";
|
|
7
6
|
import { AssistantLoop_d_exports } from "./AssistantLoop.js";
|
|
8
7
|
import { Block_d_exports } from "./Block.js";
|
|
9
|
-
import {
|
|
8
|
+
import { Timeline_d_exports } from "./Timeline.js";
|
|
10
9
|
import { CurrentChat_d_exports } from "./CurrentChat.js";
|
|
11
10
|
import { BlockKit_d_exports } from "./BlockKit.js";
|
|
12
11
|
import { RunId_d_exports } from "./RunId.js";
|
|
@@ -18,9 +17,7 @@ import { Assistant_d_exports } from "./Assistant.js";
|
|
|
18
17
|
import { AssistantActivity_d_exports } from "./AssistantActivity.js";
|
|
19
18
|
import { Compaction_d_exports } from "./Compaction.js";
|
|
20
19
|
import { InputId_d_exports } from "./InputId.js";
|
|
21
|
-
import { Decision_d_exports } from "./Decision.js";
|
|
22
|
-
import { DecisionId_d_exports } from "./DecisionId.js";
|
|
23
20
|
import { ToolFailure_d_exports } from "./ToolFailure.js";
|
|
24
21
|
import { Memory_d_exports } from "./Memory.js";
|
|
25
22
|
import { ToolDiscovery_d_exports } from "./ToolDiscovery.js";
|
|
26
|
-
export {
|
|
23
|
+
export { Assistant_d_exports as Assistant, AssistantActivity_d_exports as AssistantActivity, AssistantEngine_d_exports as AssistantEngine, AssistantEvent_d_exports as AssistantEvent, AssistantLoop_d_exports as AssistantLoop, AssistantToolCall_d_exports as AssistantToolCall, Block_d_exports as Block, BlockKit_d_exports as BlockKit, ChatId_d_exports as ChatId, ChatLog_d_exports as ChatLog, Chats_d_exports as Chats, Compaction_d_exports as Compaction, CurrentChat_d_exports as CurrentChat, InputId_d_exports as InputId, Instructions_d_exports as Instructions, Memory_d_exports as Memory, RunId_d_exports as RunId, Skill_d_exports as Skill, Specialist_d_exports as Specialist, Timeline_d_exports as Timeline, ToolDiscovery_d_exports as ToolDiscovery, ToolFailure_d_exports as ToolFailure };
|
package/dist/index.js
CHANGED
|
@@ -1,6 +1,4 @@
|
|
|
1
|
-
import { AppEvent_exports } from "./AppEvent.js";
|
|
2
1
|
import { ChatId_exports } from "./ChatId.js";
|
|
3
|
-
import { DecisionId_exports } from "./DecisionId.js";
|
|
4
2
|
import { InputId_exports } from "./InputId.js";
|
|
5
3
|
import { RunId_exports } from "./RunId.js";
|
|
6
4
|
import { AssistantEvent_exports } from "./AssistantEvent.js";
|
|
@@ -8,9 +6,6 @@ import { ChatLog_exports } from "./ChatLog.js";
|
|
|
8
6
|
import { CurrentChat_exports } from "./CurrentChat.js";
|
|
9
7
|
import { Chats_exports } from "./Chats.js";
|
|
10
8
|
import { Specialist_exports } from "./Specialist.js";
|
|
11
|
-
import { Block_exports } from "./Block.js";
|
|
12
|
-
import { Decision_exports } from "./Decision.js";
|
|
13
|
-
import { BlockKit_exports } from "./BlockKit.js";
|
|
14
9
|
import { AssistantToolCall_exports } from "./AssistantToolCall.js";
|
|
15
10
|
import { ToolFailure_exports } from "./ToolFailure.js";
|
|
16
11
|
import { Skill_exports } from "./Skill.js";
|
|
@@ -19,8 +14,10 @@ import { AssistantEngine_exports } from "./AssistantEngine.js";
|
|
|
19
14
|
import { Assistant_exports } from "./Assistant.js";
|
|
20
15
|
import { AssistantActivity_exports } from "./AssistantActivity.js";
|
|
21
16
|
import { AssistantLoop_exports } from "./AssistantLoop.js";
|
|
22
|
-
import {
|
|
17
|
+
import { Block_exports } from "./Block.js";
|
|
18
|
+
import { BlockKit_exports } from "./BlockKit.js";
|
|
23
19
|
import { Compaction_exports } from "./Compaction.js";
|
|
24
20
|
import { Memory_exports } from "./Memory.js";
|
|
21
|
+
import { Timeline_exports } from "./Timeline.js";
|
|
25
22
|
import { ToolDiscovery_exports } from "./ToolDiscovery.js";
|
|
26
|
-
export {
|
|
23
|
+
export { Assistant_exports as Assistant, AssistantActivity_exports as AssistantActivity, AssistantEngine_exports as AssistantEngine, AssistantEvent_exports as AssistantEvent, AssistantLoop_exports as AssistantLoop, AssistantToolCall_exports as AssistantToolCall, Block_exports as Block, BlockKit_exports as BlockKit, ChatId_exports as ChatId, ChatLog_exports as ChatLog, Chats_exports as Chats, Compaction_exports as Compaction, CurrentChat_exports as CurrentChat, InputId_exports as InputId, Instructions_exports as Instructions, Memory_exports as Memory, RunId_exports as RunId, Skill_exports as Skill, Specialist_exports as Specialist, Timeline_exports as Timeline, ToolDiscovery_exports as ToolDiscovery, ToolFailure_exports as ToolFailure };
|
package/dist/internal/chat.js
CHANGED
|
@@ -1,19 +1,17 @@
|
|
|
1
|
-
import { ChatDeleted,
|
|
1
|
+
import { ChatDeleted, isInput, isLibraryEvent } from "../AssistantEvent.js";
|
|
2
2
|
import { ChatLog } from "../ChatLog.js";
|
|
3
3
|
import { CurrentChat } from "../CurrentChat.js";
|
|
4
4
|
import { Chats } from "../Chats.js";
|
|
5
5
|
import { Runner } from "../Specialist.js";
|
|
6
|
-
import {
|
|
7
|
-
import { decodeEntries, encode, isRegistered } from "./events.js";
|
|
6
|
+
import { decodeEntries, encode, isRegistered, markInput } from "./events.js";
|
|
8
7
|
import { needsTurn } from "./history.js";
|
|
9
8
|
import { makeRunner } from "./specialists.js";
|
|
10
9
|
import { run } from "./turns.js";
|
|
11
|
-
import * as Predicate from "effect/Predicate";
|
|
12
10
|
import * as Context from "effect/Context";
|
|
13
11
|
import * as Effect from "effect/Effect";
|
|
12
|
+
import * as Predicate from "effect/Predicate";
|
|
14
13
|
import * as Stream from "effect/Stream";
|
|
15
14
|
import * as Exit from "effect/Exit";
|
|
16
|
-
import * as Option from "effect/Option";
|
|
17
15
|
import * as Scope from "effect/Scope";
|
|
18
16
|
import * as Ref from "effect/Ref";
|
|
19
17
|
import * as Cause from "effect/Cause";
|
|
@@ -53,14 +51,12 @@ const refused = (input, why) => Effect.logDebug(`assistant chat ${why}: ${input.
|
|
|
53
51
|
const make = Effect.fnUntraced(function* (options) {
|
|
54
52
|
const { registration, chatId } = options;
|
|
55
53
|
const { app } = registration.definition;
|
|
56
|
-
const { wakes } = app;
|
|
57
54
|
const storage = yield* ChatLog;
|
|
58
55
|
const chats = yield* Chats;
|
|
59
56
|
const initial = yield* storage.read(chatId);
|
|
60
57
|
if (initial.some(isChatDeleted)) return deletedChat(initial);
|
|
61
58
|
const channel = yield* makeChannelPubSub;
|
|
62
59
|
const writes = yield* Semaphore.make(1);
|
|
63
|
-
const storing = yield* Semaphore.make(1);
|
|
64
60
|
const turnsLock = yield* Semaphore.make(1);
|
|
65
61
|
const holding = yield* makeHolding(options.keepAlive);
|
|
66
62
|
const deleted = yield* Deferred.make();
|
|
@@ -93,36 +89,17 @@ const make = Effect.fnUntraced(function* (options) {
|
|
|
93
89
|
entries: Effect.map(chat.entries, (all) => decodeEntries(app, all)),
|
|
94
90
|
append: (...events) => Effect.asVoid(Effect.flatMap(Effect.forEach(events, toStored), chat.append))
|
|
95
91
|
};
|
|
96
|
-
const resolve = Effect.fnUntraced(function* (decided, answer) {
|
|
97
|
-
yield* chat.append(decided.map(({ request, outcome }) => DecisionResolved.make({
|
|
98
|
-
id: request.id,
|
|
99
|
-
outcome,
|
|
100
|
-
answer
|
|
101
|
-
})));
|
|
102
|
-
});
|
|
103
92
|
const checkAvailable = chats.get(chatId).pipe(Effect.as(true), Effect.catchTag("GetChatError", (unavailable) => unavailable.reason === "Deleted" ? Effect.as(Effect.suspend(() => remove), false) : Effect.succeed(false)));
|
|
104
93
|
const store = Effect.fnUntraced(function* (input) {
|
|
105
94
|
if (yield* isDeleted) return yield* refused(input, "is deleted");
|
|
106
95
|
if (!(yield* checkAvailable)) return yield* refused(input, "is unavailable");
|
|
107
|
-
|
|
108
|
-
if (yield* isDeleted)
|
|
109
|
-
yield* refused(input, "is deleted");
|
|
110
|
-
return Option.none();
|
|
111
|
-
}
|
|
112
|
-
const stored = yield* Ref.get(entries);
|
|
96
|
+
yield* Semaphore.withPermit(writes)(Effect.gen(function* () {
|
|
97
|
+
if (yield* isDeleted) return yield* refused(input, "is deleted");
|
|
113
98
|
const id = idOf(input);
|
|
114
|
-
if (id !== void 0 &&
|
|
115
|
-
|
|
116
|
-
if (Predicate.isTagged(verdict$1, "Refuse")) {
|
|
117
|
-
yield* Effect.logWarning(`assistant chat refused ${input._tag}: ${verdict$1.reason}`);
|
|
118
|
-
return Option.none();
|
|
119
|
-
}
|
|
120
|
-
yield* write([input]);
|
|
121
|
-
return Option.some(verdict$1);
|
|
99
|
+
if (id !== void 0 && (yield* Ref.get(entries)).some(({ event }) => idOf(event) === id)) return;
|
|
100
|
+
yield* write([isLibraryEvent(input) ? input : markInput(input)]);
|
|
122
101
|
}));
|
|
123
|
-
|
|
124
|
-
}, Semaphore.withPermit(storing));
|
|
125
|
-
yield* Effect.forEach(unresolved(yield* Ref.get(entries)), (decided) => resolve([decided], decided.answer), { discard: true });
|
|
102
|
+
});
|
|
126
103
|
const handler = yield* inWorking(Effect.provideService(registration.open(handle), CurrentChat, handle));
|
|
127
104
|
const specialists = yield* Effect.forEach(registration.specialists, Effect.fnUntraced(function* ({ specialist, built }) {
|
|
128
105
|
return {
|
|
@@ -137,7 +114,7 @@ const make = Effect.fnUntraced(function* (options) {
|
|
|
137
114
|
if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) return yield* Effect.failCause(exit.cause);
|
|
138
115
|
}, Effect.orDie);
|
|
139
116
|
const drain = Semaphore.withPermit(turnsLock)(Effect.gen(function* () {
|
|
140
|
-
while (!(yield* isDeleted) && needsTurn(yield* chat.entries
|
|
117
|
+
while (!(yield* isDeleted) && needsTurn(yield* chat.entries)) yield* run({
|
|
141
118
|
registration,
|
|
142
119
|
handler,
|
|
143
120
|
chat,
|
|
@@ -156,10 +133,7 @@ const make = Effect.fnUntraced(function* (options) {
|
|
|
156
133
|
yield* inBackground(drain);
|
|
157
134
|
})
|
|
158
135
|
}));
|
|
159
|
-
const services = Context.make(CurrentChat, handle).pipe(Context.add(Runner, runner), Context.
|
|
160
|
-
const all = yield* chat.entries;
|
|
161
|
-
return approvedCalls(all);
|
|
162
|
-
}) })), Context.merge(registration.model));
|
|
136
|
+
const services = Context.make(CurrentChat, handle).pipe(Context.add(Runner, runner), Context.merge(registration.model));
|
|
163
137
|
const remove = Effect.gen(function* () {
|
|
164
138
|
if (!(yield* Semaphore.withPermit(writes)(Effect.gen(function* () {
|
|
165
139
|
if (yield* isDeleted) return false;
|
|
@@ -183,7 +157,7 @@ const make = Effect.fnUntraced(function* (options) {
|
|
|
183
157
|
yield* inBackground(drain);
|
|
184
158
|
}),
|
|
185
159
|
resume: Effect.gen(function* () {
|
|
186
|
-
if (needsTurn(yield* chat.entries
|
|
160
|
+
if (needsTurn(yield* chat.entries)) yield* inBackground(drain);
|
|
187
161
|
}),
|
|
188
162
|
stream: (after) => Stream.unwrap(Effect.gen(function* () {
|
|
189
163
|
const subscription = yield* PubSub.subscribe(channel);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"chat.js","names":["AssistantEvent.isLibraryEvent","AssistantEvent.isInput","Chats.Chats","AppEvents.isRegistered","AppEvents.encode","AppEvents.decodeEntries","verdict","Decisions.verdict","Decisions.unresolved","History.needsTurn","Turns.run","Specialists.makeRunner","SpecialistService.Runner","Decisions.TurnDecisions","Decisions.approvedCalls"],"sources":["../../src/internal/chat.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberSet from \"effect/FiberSet\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as PubSub from \"effect/PubSub\"\nimport * as Ref from \"effect/Ref\"\nimport * as Scope from \"effect/Scope\"\nimport * as Semaphore from \"effect/Semaphore\"\nimport * as Stream from \"effect/Stream\"\nimport * as SynchronizedRef from \"effect/SynchronizedRef\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type { ChatId } from \"../ChatId.ts\"\nimport { ChatLog } from \"../ChatLog.ts\"\nimport { CurrentChat } from \"../CurrentChat.ts\"\nimport type { InputId } from \"../InputId.ts\"\nimport * as Chats from \"../Chats.ts\"\nimport * as SpecialistService from \"../Specialist.ts\"\nimport * as Decisions from \"./decisions.ts\"\nimport * as AppEvents from \"./events.ts\"\nimport * as History from \"./history.ts\"\nimport * as Specialists from \"./specialists.ts\"\nimport * as Turns from \"./turns.ts\"\nimport type { Writer } from \"./writer.ts\"\n\nconst idOf = (event: { readonly _tag: string }): string | undefined =>\n AssistantEvent.isLibraryEvent(event)\n ? AssistantEvent.isInput(event)\n ? event.id\n : undefined\n : Predicate.hasProperty(event, \"id\") && Predicate.isString(event.id)\n ? event.id\n : undefined\n\nconst makeChannelPubSub = Effect.acquireRelease(PubSub.unbounded<AssistantEvent.Entry>(), PubSub.shutdown)\n\nconst makeHolding = Effect.fnUntraced(function* (keepAlive: (enabled: boolean) => Effect.Effect<void>) {\n const holds = yield* SynchronizedRef.make(0)\n\n const acquire = SynchronizedRef.updateEffect(\n holds,\n Effect.fnUntraced(function* (n: number) {\n if (n !== 0) return n + 1\n\n yield* keepAlive(true)\n\n return 1\n })\n )\n\n const release = SynchronizedRef.updateEffect(\n holds,\n Effect.fnUntraced(function* (n: number) {\n if (n !== 1) return n - 1\n\n yield* keepAlive(false)\n\n return 0\n })\n )\n\n return (effect: Effect.Effect<void>) =>\n Effect.acquireUseRelease(\n acquire,\n () => effect,\n // An interrupted effect (a shutdown) keeps its hold, so the chat starts again and picks up where it was cut off.\n (_, exit) => (Exit.hasInterrupts(exit) ? Effect.void : release)\n )\n})\n\n/** @internal */\nexport interface Chat {\n readonly submit: (input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) => Effect.Effect<void>\n readonly submitInBackground: (input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) => Effect.Effect<void>\n // For inputs no turn has read, like a report stored during a shutdown.\n readonly resume: Effect.Effect<void>\n readonly stream: (after: number) => Stream.Stream<AssistantEvent.Entry>\n // Stops what works in the chat and ends its subscribers' streams; its log stays.\n readonly delete: Effect.Effect<void>\n}\n\nconst isChatDeleted = (entry: AssistantEvent.Entry) => Predicate.isTagged(entry.event, \"ChatDeleted\")\n\nconst deletedChat = (entries: ReadonlyArray<AssistantEvent.Entry>): Chat => ({\n submit: () => Effect.void,\n submitInBackground: () => Effect.void,\n resume: Effect.void,\n stream: (after) => Stream.fromIterable(entries.filter((entry) => entry.seq > after)),\n delete: Effect.void\n})\n\nconst refused = (input: { readonly _tag: string }, why: string) =>\n Effect.logDebug(`assistant chat ${why}: ${input._tag} not stored`)\n\n/** @internal */\nexport const make = Effect.fnUntraced(function* (options: {\n readonly registration: Turns.Registration\n readonly chatId: ChatId\n readonly keepAlive: (enabled: boolean) => Effect.Effect<void>\n}) {\n const { registration, chatId } = options\n const { app } = registration.definition\n const { wakes } = app\n const storage = yield* ChatLog\n const chats = yield* Chats.Chats\n const initial = yield* storage.read(chatId)\n\n if (initial.some(isChatDeleted)) return deletedChat(initial)\n\n const channel = yield* makeChannelPubSub\n const writes = yield* Semaphore.make(1)\n // Inputs are stored one at a time with the decisions they make: an answer checks the decisions the last one made.\n const storing = yield* Semaphore.make(1)\n const turnsLock = yield* Semaphore.make(1)\n const holding = yield* makeHolding(options.keepAlive)\n const deleted = yield* Deferred.make<undefined>()\n // So deleting the chat stops all its work: its turns, runs, and the builds' resources.\n const working = yield* Scope.fork(yield* Effect.scope)\n const inWorking = Effect.provideService(Scope.Scope, working)\n const background = yield* inWorking(FiberSet.make())\n const requests = yield* inWorking(FiberSet.make())\n\n const isDeleted = Deferred.isDone(deleted)\n\n // The chat is its log's only writer, so it reads the log once and turns read memory.\n const entries = yield* Ref.make(initial)\n\n // Every writer goes through here, one at a time, so each append is numbered after the last. After a delete it\n // stores nothing.\n const write = Effect.fnUntraced(function* (\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) {\n const unknown = events.find((event) => !AssistantEvent.isLibraryEvent(event) && !AppEvents.isRegistered(app, event))\n\n if (unknown !== undefined) {\n return yield* Effect.die(`${unknown._tag} isn't one of the ${registration.definition.name} assistant's events.`)\n }\n\n if (yield* isDeleted) return []\n\n return yield* stored(events)\n })\n\n // Uninterruptible: a stored append must reach memory and the subscribers too, or a turn misses it and replies twice.\n const stored = Effect.fnUntraced(function* (\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) {\n const stored = yield* storage.append(chatId, events)\n\n yield* Ref.update(entries, (all) => [...all, ...stored])\n yield* PubSub.publishAll(channel, stored)\n\n return stored\n }, Effect.uninterruptible)\n\n const chat: Writer = {\n chatId,\n entries: Ref.get(entries),\n append: (events) => Semaphore.withPermit(writes)(write(events))\n }\n\n const toStored = (event: {\n readonly _tag: string\n }): Effect.Effect<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent> =>\n AssistantEvent.isLibraryEvent(event)\n ? Effect.succeed(event)\n : AppEvents.isRegistered(app, event)\n ? AppEvents.encode(app, event)\n : Effect.die(`${event._tag} isn't one of the ${registration.definition.name} assistant's events.`)\n\n // What handlers, tools, and runs see: the assistant's own events decoded, and encoded when appended.\n const handle: Turns.TypedChat = {\n chatId,\n entries: Effect.map(chat.entries, (all) => AppEvents.decodeEntries(app, all)),\n append: (...events) => Effect.asVoid(Effect.flatMap(Effect.forEach(events, toStored), chat.append))\n }\n\n // An approved call runs at the turn's next step.\n const resolve = Effect.fnUntraced(function* (decided: ReadonlyArray<Decisions.Decided>, answer: InputId) {\n yield* chat.append(\n decided.map(({ request, outcome }) => AssistantEvent.DecisionResolved.make({ id: request.id, outcome, answer }))\n )\n })\n\n // A chat the app deleted is deleted here too, which stops what works in it: a turn that checks stops there.\n const checkAvailable: Effect.Effect<boolean> = chats.get(chatId).pipe(\n Effect.as(true),\n Effect.catchTag(\"GetChatError\", (unavailable) =>\n unavailable.reason === \"Deleted\"\n ? Effect.as(\n Effect.suspend(() => remove),\n false\n )\n : Effect.succeed(false)\n )\n )\n\n // Under `storing`: an answer's decisions are resolved before the next input is stored.\n const store = Effect.fnUntraced(function* (input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) {\n if (yield* isDeleted) return yield* refused(input, \"is deleted\")\n\n if (!(yield* checkAvailable)) return yield* refused(input, \"is unavailable\")\n\n // Checked under the write lock: a retry that arrives while the first submit is storing is stored once.\n const verdict = yield* Semaphore.withPermit(writes)(\n Effect.gen(function* () {\n if (yield* isDeleted) {\n yield* refused(input, \"is deleted\")\n\n return Option.none()\n }\n\n const stored = yield* Ref.get(entries)\n const id = idOf(input)\n\n if (id !== undefined && stored.some(({ event }) => idOf(event) === id)) return Option.none()\n\n const verdict = Decisions.verdict(stored, input)\n\n if (Predicate.isTagged(verdict, \"Refuse\")) {\n yield* Effect.logWarning(`assistant chat refused ${input._tag}: ${verdict.reason}`)\n\n return Option.none()\n }\n\n yield* write([input])\n\n return Option.some(verdict)\n })\n )\n\n if (Option.isSome(verdict) && Predicate.isTagged(verdict.value, \"Decide\")) {\n yield* resolve(verdict.value.decided, verdict.value.answer)\n }\n }, Semaphore.withPermit(storing))\n\n // A restart between storing an answer and resolving it: resolve it now, before anything reads the chat.\n yield* Effect.forEach(\n Decisions.unresolved(yield* Ref.get(entries)),\n (decided) => resolve([decided], decided.answer),\n { discard: true }\n )\n\n // The handlers' builds run in the chat's working scope: what they set up lives until the chat closes or is deleted.\n const handler = yield* inWorking(Effect.provideService(registration.open(handle), CurrentChat, handle))\n\n const specialists = yield* Effect.forEach(\n registration.specialists,\n Effect.fnUntraced(function* ({ specialist, built }) {\n const handler = yield* inWorking(Effect.provideService(built.open, CurrentChat, handle))\n\n return { specialist, handler }\n })\n )\n\n const inBackground = (effect: Effect.Effect<void>) => FiberSet.run(background, holding(effect)).pipe(Effect.asVoid)\n\n // A request's turns run in the working scope too, so a delete stops them; the request ends quietly then.\n const inRequest = Effect.fnUntraced(function* (effect: Effect.Effect<void>) {\n const fiber = yield* FiberSet.run(requests, effect)\n const exit = yield* Fiber.await(fiber).pipe(Effect.onInterrupt(() => Fiber.interrupt(fiber)))\n\n if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {\n return yield* Effect.failCause(exit.cause)\n }\n }, Effect.orDie)\n\n const drain: Effect.Effect<void> = Semaphore.withPermit(turnsLock)(\n Effect.gen(function* () {\n while (!(yield* isDeleted) && History.needsTurn(yield* chat.entries, wakes)) {\n yield* Turns.run({ registration, handler, chat, services, checkOpen: Effect.asVoid(checkAvailable) })\n }\n })\n )\n\n const runner = yield* inWorking(\n Specialists.makeRunner({\n chat,\n handle,\n specialists,\n model: registration.model,\n holding,\n report: Effect.fnUntraced(function* (finished) {\n yield* store(finished)\n yield* inBackground(drain)\n })\n })\n )\n\n const services = Context.make(CurrentChat, handle).pipe(\n Context.add(SpecialistService.Runner, runner),\n Context.add(\n Decisions.TurnDecisions,\n Option.some({\n approved: Effect.gen(function* () {\n const all = yield* chat.entries\n\n return Decisions.approvedCalls(all)\n })\n })\n ),\n Context.merge(registration.model)\n )\n\n const remove = Effect.gen(function* () {\n // Under the write lock: an append in flight is stored before the `ChatDeleted`; none comes after.\n const first = yield* Semaphore.withPermit(writes)(\n Effect.gen(function* () {\n if (yield* isDeleted) return false\n\n yield* stored([AssistantEvent.ChatDeleted.make({})])\n\n return yield* Deferred.succeed(deleted, undefined)\n })\n ).pipe(Effect.uninterruptible)\n\n if (!first) return\n\n // Its own fiber: a tool that deletes its own chat is in the working scope, and closing it interrupts that tool.\n // Interrupted work keeps its hold (see `makeHolding`), so the chat lets go of it here.\n const closing = yield* Effect.forkDetach(\n Effect.gen(function* () {\n yield* Scope.close(working, Exit.void)\n yield* options.keepAlive(false)\n })\n )\n\n yield* Fiber.await(closing)\n })\n\n // A chat the app deleted while it was closed is deleted now, so its subscribers hear it.\n yield* checkAvailable\n\n const chatApi: Chat = {\n submit: Effect.fnUntraced(function* (input) {\n yield* store(input)\n yield* inRequest(drain)\n }),\n submitInBackground: Effect.fnUntraced(function* (input) {\n yield* store(input)\n yield* inBackground(drain)\n }),\n resume: Effect.gen(function* () {\n if (History.needsTurn(yield* chat.entries, wakes)) yield* inBackground(drain)\n }),\n stream: (after) =>\n Stream.unwrap(\n Effect.gen(function* () {\n // Subscribes before it reads, so nothing appended in between is missed.\n const subscription = yield* PubSub.subscribe(channel)\n const all = yield* chat.entries\n const stored = all.filter((entry) => entry.seq > after)\n const last = stored.at(-1)?.seq ?? after\n\n // Deleted: what the reader hasn't seen, then the end. Otherwise the stream ends with the `ChatDeleted`.\n if (all.some(isChatDeleted)) return Stream.fromIterable(stored)\n\n return Stream.concat(\n Stream.fromIterable(stored),\n Stream.fromSubscription(subscription).pipe(Stream.filter((entry) => entry.seq > last))\n ).pipe(Stream.takeUntil(isChatDeleted))\n })\n ),\n delete: remove\n }\n\n return chatApi\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA6BA,MAAM,QAAQ,UACZA,eAA8B,KAAK,IAC/BC,QAAuB,KAAK,IAC1B,MAAM,KACN,KAAA,IACF,UAAU,YAAY,OAAO,IAAI,KAAK,UAAU,SAAS,MAAM,EAAE,IAC/D,MAAM,KACN,KAAA;AAER,MAAM,oBAAoB,OAAO,eAAe,OAAO,UAAgC,GAAG,OAAO,QAAQ;AAEzG,MAAM,cAAc,OAAO,WAAW,WAAW,WAAsD;CACrG,MAAM,QAAQ,OAAO,gBAAgB,KAAK,CAAC;CAE3C,MAAM,UAAU,gBAAgB,aAC9B,OACA,OAAO,WAAW,WAAW,GAAW;EACtC,IAAI,MAAM,GAAG,OAAO,IAAI;EAExB,OAAO,UAAU,IAAI;EAErB,OAAO;CACT,CAAC,CACH;CAEA,MAAM,UAAU,gBAAgB,aAC9B,OACA,OAAO,WAAW,WAAW,GAAW;EACtC,IAAI,MAAM,GAAG,OAAO,IAAI;EAExB,OAAO,UAAU,KAAK;EAEtB,OAAO;CACT,CAAC,CACH;CAEA,QAAQ,WACN,OAAO,kBACL,eACM,SAEL,GAAG,SAAU,KAAK,cAAc,IAAI,IAAI,OAAO,OAAO,OACzD;AACJ,CAAC;AAaD,MAAM,iBAAiB,UAAgC,UAAU,SAAS,MAAM,OAAO,aAAa;AAEpG,MAAM,eAAe,aAAwD;CAC3E,cAAc,OAAO;CACrB,0BAA0B,OAAO;CACjC,QAAQ,OAAO;CACf,SAAS,UAAU,OAAO,aAAa,QAAQ,QAAQ,UAAU,MAAM,MAAM,KAAK,CAAC;CACnF,QAAQ,OAAO;AACjB;AAEA,MAAM,WAAW,OAAkC,QACjD,OAAO,SAAS,kBAAkB,IAAI,IAAI,MAAM,KAAK,YAAY;;AAGnE,MAAa,OAA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Event.isInput","Chats.Chats","AppEvents.isRegistered","AppEvents.encode","AppEvents.decodeEntries","AppEvents.markInput","History.needsTurn","Turns.run","Specialists.makeRunner","SpecialistService.Runner"],"sources":["../../src/internal/chat.ts"],"sourcesContent":["import * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Deferred from \"effect/Deferred\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport * as Fiber from \"effect/Fiber\"\nimport * as FiberSet from \"effect/FiberSet\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as PubSub from \"effect/PubSub\"\nimport * as Ref from \"effect/Ref\"\nimport * as Scope from \"effect/Scope\"\nimport * as Semaphore from \"effect/Semaphore\"\nimport * as Stream from \"effect/Stream\"\nimport * as SynchronizedRef from \"effect/SynchronizedRef\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type { ChatId } from \"../ChatId.ts\"\nimport { ChatLog } from \"../ChatLog.ts\"\nimport { CurrentChat } from \"../CurrentChat.ts\"\nimport * as Chats from \"../Chats.ts\"\nimport * as SpecialistService from \"../Specialist.ts\"\nimport * as AppEvents from \"./events.ts\"\nimport * as History from \"./history.ts\"\nimport * as Specialists from \"./specialists.ts\"\nimport * as Turns from \"./turns.ts\"\nimport type { Writer } from \"./writer.ts\"\n\nconst idOf = (event: { readonly _tag: string }): string | undefined =>\n AssistantEvent.isLibraryEvent(event)\n ? AssistantEvent.isInput(event)\n ? event.id\n : undefined\n : Predicate.hasProperty(event, \"id\") && Predicate.isString(event.id)\n ? event.id\n : undefined\n\nconst makeChannelPubSub = Effect.acquireRelease(PubSub.unbounded<AssistantEvent.Entry>(), PubSub.shutdown)\n\nconst makeHolding = Effect.fnUntraced(function* (keepAlive: (enabled: boolean) => Effect.Effect<void>) {\n const holds = yield* SynchronizedRef.make(0)\n\n const acquire = SynchronizedRef.updateEffect(\n holds,\n Effect.fnUntraced(function* (n: number) {\n if (n !== 0) return n + 1\n\n yield* keepAlive(true)\n\n return 1\n })\n )\n\n const release = SynchronizedRef.updateEffect(\n holds,\n Effect.fnUntraced(function* (n: number) {\n if (n !== 1) return n - 1\n\n yield* keepAlive(false)\n\n return 0\n })\n )\n\n return (effect: Effect.Effect<void>) =>\n Effect.acquireUseRelease(\n acquire,\n () => effect,\n // An interrupted effect (a shutdown) keeps its hold, so the chat starts again and picks up where it was cut off.\n (_, exit) => (Exit.hasInterrupts(exit) ? Effect.void : release)\n )\n})\n\n/** @internal */\nexport interface Chat {\n readonly submit: (input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) => Effect.Effect<void>\n readonly submitInBackground: (input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) => Effect.Effect<void>\n // For inputs no turn has read, like a report stored during a shutdown.\n readonly resume: Effect.Effect<void>\n readonly stream: (after: number) => Stream.Stream<AssistantEvent.Entry>\n // Stops what works in the chat and ends its subscribers' streams; its log stays.\n readonly delete: Effect.Effect<void>\n}\n\nconst isChatDeleted = (entry: AssistantEvent.Entry) => Predicate.isTagged(entry.event, \"ChatDeleted\")\n\nconst deletedChat = (entries: ReadonlyArray<AssistantEvent.Entry>): Chat => ({\n submit: () => Effect.void,\n submitInBackground: () => Effect.void,\n resume: Effect.void,\n stream: (after) => Stream.fromIterable(entries.filter((entry) => entry.seq > after)),\n delete: Effect.void\n})\n\nconst refused = (input: { readonly _tag: string }, why: string) =>\n Effect.logDebug(`assistant chat ${why}: ${input._tag} not stored`)\n\n/** @internal */\nexport const make = Effect.fnUntraced(function* (options: {\n readonly registration: Turns.Registration\n readonly chatId: ChatId\n readonly keepAlive: (enabled: boolean) => Effect.Effect<void>\n}) {\n const { registration, chatId } = options\n const { app } = registration.definition\n const storage = yield* ChatLog\n const chats = yield* Chats.Chats\n const initial = yield* storage.read(chatId)\n\n if (initial.some(isChatDeleted)) return deletedChat(initial)\n\n const channel = yield* makeChannelPubSub\n const writes = yield* Semaphore.make(1)\n const turnsLock = yield* Semaphore.make(1)\n const holding = yield* makeHolding(options.keepAlive)\n const deleted = yield* Deferred.make<undefined>()\n // So deleting the chat stops all its work: its turns, runs, and the builds' resources.\n const working = yield* Scope.fork(yield* Effect.scope)\n const inWorking = Effect.provideService(Scope.Scope, working)\n const background = yield* inWorking(FiberSet.make())\n const requests = yield* inWorking(FiberSet.make())\n\n const isDeleted = Deferred.isDone(deleted)\n\n // The chat is its log's only writer, so it reads the log once and turns read memory.\n const entries = yield* Ref.make(initial)\n\n // Every writer goes through here, one at a time, so each append is numbered after the last. After a delete it\n // stores nothing.\n const write = Effect.fnUntraced(function* (\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) {\n const unknown = events.find((event) => !AssistantEvent.isLibraryEvent(event) && !AppEvents.isRegistered(app, event))\n\n if (unknown !== undefined) {\n return yield* Effect.die(`${unknown._tag} isn't one of the ${registration.definition.name} assistant's events.`)\n }\n\n if (yield* isDeleted) return []\n\n return yield* stored(events)\n })\n\n // Uninterruptible: a stored append must reach memory and the subscribers too, or a turn misses it and replies twice.\n const stored = Effect.fnUntraced(function* (\n events: ReadonlyArray<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent>\n ) {\n const stored = yield* storage.append(chatId, events)\n\n yield* Ref.update(entries, (all) => [...all, ...stored])\n yield* PubSub.publishAll(channel, stored)\n\n return stored\n }, Effect.uninterruptible)\n\n const chat: Writer = {\n chatId,\n entries: Ref.get(entries),\n append: (events) => Semaphore.withPermit(writes)(write(events))\n }\n\n const toStored = (event: {\n readonly _tag: string\n }): Effect.Effect<AssistantEvent.AssistantEvent | AssistantEvent.StoredAppEvent> =>\n AssistantEvent.isLibraryEvent(event)\n ? Effect.succeed(event)\n : AppEvents.isRegistered(app, event)\n ? AppEvents.encode(app, event)\n : Effect.die(`${event._tag} isn't one of the ${registration.definition.name} assistant's events.`)\n\n // What handlers, tools, and runs see: the assistant's own events decoded, and encoded when appended.\n const handle: Turns.TypedChat = {\n chatId,\n entries: Effect.map(chat.entries, (all) => AppEvents.decodeEntries(app, all)),\n append: (...events) => Effect.asVoid(Effect.flatMap(Effect.forEach(events, toStored), chat.append))\n }\n\n // A chat the app deleted is deleted here too, which stops what works in it: a turn that checks stops there.\n const checkAvailable: Effect.Effect<boolean> = chats.get(chatId).pipe(\n Effect.as(true),\n Effect.catchTag(\"GetChatError\", (unavailable) =>\n unavailable.reason === \"Deleted\"\n ? Effect.as(\n Effect.suspend(() => remove),\n false\n )\n : Effect.succeed(false)\n )\n )\n\n const store = Effect.fnUntraced(function* (input: AssistantEvent.Input | AssistantEvent.StoredAppEvent) {\n if (yield* isDeleted) return yield* refused(input, \"is deleted\")\n\n if (!(yield* checkAvailable)) return yield* refused(input, \"is unavailable\")\n\n // Checked under the write lock: a retry that arrives while the first submit is storing is stored once.\n yield* Semaphore.withPermit(writes)(\n Effect.gen(function* () {\n if (yield* isDeleted) return yield* refused(input, \"is deleted\")\n\n const id = idOf(input)\n\n if (id !== undefined && (yield* Ref.get(entries)).some(({ event }) => idOf(event) === id)) return\n\n // Stored as an input: it came in from outside a turn, so it wakes one, also after a restart.\n yield* write([AssistantEvent.isLibraryEvent(input) ? input : AppEvents.markInput(input)])\n })\n )\n })\n\n // The handlers' builds run in the chat's working scope: what they set up lives until the chat closes or is deleted.\n const handler = yield* inWorking(Effect.provideService(registration.open(handle), CurrentChat, handle))\n\n const specialists = yield* Effect.forEach(\n registration.specialists,\n Effect.fnUntraced(function* ({ specialist, built }) {\n const handler = yield* inWorking(Effect.provideService(built.open, CurrentChat, handle))\n\n return { specialist, handler }\n })\n )\n\n const inBackground = (effect: Effect.Effect<void>) => FiberSet.run(background, holding(effect)).pipe(Effect.asVoid)\n\n // A request's turns run in the working scope too, so a delete stops them; the request ends quietly then.\n const inRequest = Effect.fnUntraced(function* (effect: Effect.Effect<void>) {\n const fiber = yield* FiberSet.run(requests, effect)\n const exit = yield* Fiber.await(fiber).pipe(Effect.onInterrupt(() => Fiber.interrupt(fiber)))\n\n if (Exit.isFailure(exit) && !Cause.hasInterruptsOnly(exit.cause)) {\n return yield* Effect.failCause(exit.cause)\n }\n }, Effect.orDie)\n\n const drain: Effect.Effect<void> = Semaphore.withPermit(turnsLock)(\n Effect.gen(function* () {\n while (!(yield* isDeleted) && History.needsTurn(yield* chat.entries)) {\n yield* Turns.run({ registration, handler, chat, services, checkOpen: Effect.asVoid(checkAvailable) })\n }\n })\n )\n\n const runner = yield* inWorking(\n Specialists.makeRunner({\n chat,\n handle,\n specialists,\n model: registration.model,\n holding,\n report: Effect.fnUntraced(function* (finished) {\n yield* store(finished)\n yield* inBackground(drain)\n })\n })\n )\n\n const services = Context.make(CurrentChat, handle).pipe(\n Context.add(SpecialistService.Runner, runner),\n Context.merge(registration.model)\n )\n\n const remove = Effect.gen(function* () {\n // Under the write lock: an append in flight is stored before the `ChatDeleted`; none comes after.\n const first = yield* Semaphore.withPermit(writes)(\n Effect.gen(function* () {\n if (yield* isDeleted) return false\n\n yield* stored([AssistantEvent.ChatDeleted.make({})])\n\n return yield* Deferred.succeed(deleted, undefined)\n })\n ).pipe(Effect.uninterruptible)\n\n if (!first) return\n\n // Its own fiber: a tool that deletes its own chat is in the working scope, and closing it interrupts that tool.\n // Interrupted work keeps its hold (see `makeHolding`), so the chat lets go of it here.\n const closing = yield* Effect.forkDetach(\n Effect.gen(function* () {\n yield* Scope.close(working, Exit.void)\n yield* options.keepAlive(false)\n })\n )\n\n yield* Fiber.await(closing)\n })\n\n // A chat the app deleted while it was closed is deleted now, so its subscribers hear it.\n yield* checkAvailable\n\n const chatApi: Chat = {\n submit: Effect.fnUntraced(function* (input) {\n yield* store(input)\n yield* inRequest(drain)\n }),\n submitInBackground: Effect.fnUntraced(function* (input) {\n yield* store(input)\n yield* inBackground(drain)\n }),\n resume: Effect.gen(function* () {\n if (History.needsTurn(yield* chat.entries)) yield* inBackground(drain)\n }),\n stream: (after) =>\n Stream.unwrap(\n Effect.gen(function* () {\n // Subscribes before it reads, so nothing appended in between is missed.\n const subscription = yield* PubSub.subscribe(channel)\n const all = yield* chat.entries\n const stored = all.filter((entry) => entry.seq > after)\n const last = stored.at(-1)?.seq ?? after\n\n // Deleted: what the reader hasn't seen, then the end. Otherwise the stream ends with the `ChatDeleted`.\n if (all.some(isChatDeleted)) return Stream.fromIterable(stored)\n\n return Stream.concat(\n Stream.fromIterable(stored),\n Stream.fromSubscription(subscription).pipe(Stream.filter((entry) => entry.seq > last))\n ).pipe(Stream.takeUntil(isChatDeleted))\n })\n ),\n delete: remove\n }\n\n return chatApi\n})\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AA0BA,MAAM,QAAQ,UACZA,eAA8B,KAAK,IAC/BC,QAAuB,KAAK,IAC1B,MAAM,KACN,KAAA,IACF,UAAU,YAAY,OAAO,IAAI,KAAK,UAAU,SAAS,MAAM,EAAE,IAC/D,MAAM,KACN,KAAA;AAER,MAAM,oBAAoB,OAAO,eAAe,OAAO,UAAgC,GAAG,OAAO,QAAQ;AAEzG,MAAM,cAAc,OAAO,WAAW,WAAW,WAAsD;CACrG,MAAM,QAAQ,OAAO,gBAAgB,KAAK,CAAC;CAE3C,MAAM,UAAU,gBAAgB,aAC9B,OACA,OAAO,WAAW,WAAW,GAAW;EACtC,IAAI,MAAM,GAAG,OAAO,IAAI;EAExB,OAAO,UAAU,IAAI;EAErB,OAAO;CACT,CAAC,CACH;CAEA,MAAM,UAAU,gBAAgB,aAC9B,OACA,OAAO,WAAW,WAAW,GAAW;EACtC,IAAI,MAAM,GAAG,OAAO,IAAI;EAExB,OAAO,UAAU,KAAK;EAEtB,OAAO;CACT,CAAC,CACH;CAEA,QAAQ,WACN,OAAO,kBACL,eACM,SAEL,GAAG,SAAU,KAAK,cAAc,IAAI,IAAI,OAAO,OAAO,OACzD;AACJ,CAAC;AAaD,MAAM,iBAAiB,UAAgC,UAAU,SAAS,MAAM,OAAO,aAAa;AAEpG,MAAM,eAAe,aAAwD;CAC3E,cAAc,OAAO;CACrB,0BAA0B,OAAO;CACjC,QAAQ,OAAO;CACf,S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KAAK;GACxB,MAAM,SAAS,IAAI,QAAQ,UAAU,MAAM,MAAM,KAAK;GACtD,MAAM,OAAO,OAAO,GAAG,EAAE,CAAC,EAAE,OAAO;GAGnC,IAAI,IAAI,KAAK,aAAa,GAAG,OAAO,OAAO,aAAa,MAAM;GAE9D,OAAO,OAAO,OACZ,OAAO,aAAa,MAAM,GAC1B,OAAO,iBAAiB,YAAY,CAAC,CAAC,KAAK,OAAO,QAAQ,UAAU,MAAM,MAAM,IAAI,CAAC,CACvF,CAAC,CAAC,KAAK,OAAO,UAAU,aAAa,CAAC;EACxC,CAAC,CACH;EACF,QAAQ;CAGG;AACf,CAAC"}
|
|
@@ -1,46 +1,45 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import { AnyEntry, AssistantEvent_d_exports } from "../AssistantEvent.js";
|
|
1
|
+
import { AnyEntry, AppEventSchema, AssistantEvent_d_exports, StoredAppEvent } from "../AssistantEvent.js";
|
|
3
2
|
import { Assistant_d_exports, Entry } from "../Assistant.js";
|
|
4
3
|
import * as Effect from "effect/Effect";
|
|
5
4
|
import * as Schema from "effect/Schema";
|
|
6
5
|
import * as Option from "effect/Option";
|
|
7
6
|
declare namespace events_d_exports {
|
|
8
|
-
export { AppEvents, DecodedEntries, decodeEntries, decodeEntry, encode, isRegistered, make,
|
|
7
|
+
export { AppEvents, DecodedEntries, decodeEntries, decodeEntry, decodeWith, encode, isRegistered, make, markInput, tagOf };
|
|
9
8
|
}
|
|
10
9
|
/** @internal */
|
|
11
10
|
export interface AppEvents {
|
|
12
|
-
readonly byTag: ReadonlyMap<string,
|
|
13
|
-
readonly wakes: ReadonlySet<string>;
|
|
14
|
-
}
|
|
15
|
-
interface Registered {
|
|
16
|
-
readonly schema: EventSchema;
|
|
17
|
-
readonly render: Render<{
|
|
18
|
-
readonly _tag: string;
|
|
19
|
-
}> | undefined;
|
|
11
|
+
readonly byTag: ReadonlyMap<string, AppEventSchema>;
|
|
20
12
|
}
|
|
21
13
|
/** @internal */
|
|
22
|
-
export declare const
|
|
14
|
+
export declare const tagOf: (schema: AppEventSchema) => string;
|
|
15
|
+
/** @internal */
|
|
16
|
+
export declare const make: (events: ReadonlyArray<AppEventSchema>) => AppEvents;
|
|
23
17
|
/** @internal */
|
|
24
18
|
export declare const encode: (app: AppEvents, event: {
|
|
25
19
|
readonly _tag: string;
|
|
26
20
|
}) => Effect.Effect<{
|
|
27
21
|
readonly [x: string]: Schema.Json;
|
|
28
22
|
readonly _tag: string & import("effect/Brand").Brand<"~effect-assistant/AppTag">;
|
|
23
|
+
readonly "~effect-assistant/input"?: true | undefined;
|
|
29
24
|
}, never, never>;
|
|
30
25
|
/** @internal */
|
|
31
26
|
export declare const isRegistered: (app: AppEvents, event: {
|
|
32
27
|
readonly _tag: string;
|
|
33
28
|
}) => boolean;
|
|
34
29
|
/** @internal */
|
|
30
|
+
export declare const decodeWith: (schema: AppEventSchema, event: {
|
|
31
|
+
readonly _tag: string;
|
|
32
|
+
}) => Option.Option<{
|
|
33
|
+
readonly _tag: string;
|
|
34
|
+
}>;
|
|
35
|
+
/** @internal */
|
|
36
|
+
export declare const markInput: (event: StoredAppEvent) => StoredAppEvent;
|
|
37
|
+
/** @internal */
|
|
35
38
|
export declare const decodeEntry: (app: AppEvents, entry: AnyEntry) => Option.Option<Entry<any>>;
|
|
36
39
|
/** @internal */
|
|
37
40
|
export declare const decodeEntries: (app: AppEvents, entries: ReadonlyArray<AnyEntry>) => ReadonlyArray<Entry<any>>;
|
|
38
41
|
/** @internal */
|
|
39
42
|
export type DecodedEntries = ReturnType<typeof decodeEntries>;
|
|
40
|
-
/** @internal */
|
|
41
|
-
export declare const read: (app: AppEvents, event: {
|
|
42
|
-
readonly _tag: string;
|
|
43
|
-
}) => string | undefined;
|
|
44
43
|
//#endregion
|
|
45
44
|
export { events_d_exports };
|
|
46
45
|
//# sourceMappingURL=events.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"events.d.ts","names":[],"sources":["../../src/internal/events.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"events.d.ts","names":[],"sources":["../../src/internal/events.ts"],"mappings":";;;;;;;;;iBAWiB;WACN,OAAO,oBAAoB;;;qBAIzB,QAAK,QAAY;;qBASjB,OAAI,QAAY,cAAc,oBAAiC;;qBAa/D,SAAM,KAAA,WAAA;WAAwE;;;;;;;qBAY9E,eAAY,KAAS,WAAS;WAAoB;;;qBAQlD,aAAU,QACb,gBAA6B;WACnB;MACjB,OAAO;WAAkB;;;qBAUf,YAAS,OAAW,mBAAgC;;qBAOpD,cAAW,KAAS,WAAS,OAAS,aAA0B,OAAO,OAAO;;qBAS9E,gBAAa,KACnB,WAAS,SACL,cAAc,cACtB,cAAc;;YAGL,iBAAiB,kBAAkB"}
|
package/dist/internal/events.js
CHANGED
|
@@ -1,31 +1,46 @@
|
|
|
1
|
+
import { inputKey } from "./input.js";
|
|
1
2
|
import { StoredAppEvent, isLibraryEvent } from "../AssistantEvent.js";
|
|
2
|
-
import { toJsonText } from "./schema.js";
|
|
3
3
|
import * as Effect from "effect/Effect";
|
|
4
|
+
import * as Predicate from "effect/Predicate";
|
|
4
5
|
import * as Schema from "effect/Schema";
|
|
5
6
|
import * as Option from "effect/Option";
|
|
7
|
+
import * as Record from "effect/Record";
|
|
8
|
+
import * as SchemaAST from "effect/SchemaAST";
|
|
6
9
|
//#region src/internal/events.ts
|
|
7
10
|
/** @internal */
|
|
11
|
+
const tagOf = (schema) => {
|
|
12
|
+
const ast = schema.fields._tag.ast;
|
|
13
|
+
if (SchemaAST.isLiteral(ast) && Predicate.isString(ast.literal)) return ast.literal;
|
|
14
|
+
throw new Error("An app event is a tagged struct or class.");
|
|
15
|
+
};
|
|
16
|
+
/** @internal */
|
|
8
17
|
const make = (events) => {
|
|
9
|
-
const byTag = new Map(events.map((
|
|
10
|
-
schema: event.schema,
|
|
11
|
-
render: event.render
|
|
12
|
-
}]));
|
|
18
|
+
const byTag = new Map(events.map((schema) => [tagOf(schema), schema]));
|
|
13
19
|
for (const tag of byTag.keys()) if (isLibraryEvent({ _tag: tag })) throw new Error(`${tag} is one of the library's events.`);
|
|
14
20
|
if (byTag.size !== events.length) throw new Error("An assistant's events have different tags.");
|
|
15
|
-
return {
|
|
16
|
-
byTag,
|
|
17
|
-
wakes: new Set(events.flatMap((event) => event.wakes ? [event.tag] : []))
|
|
18
|
-
};
|
|
21
|
+
return { byTag };
|
|
19
22
|
};
|
|
20
23
|
/** @internal */
|
|
21
24
|
const encode = Effect.fnUntraced(function* (app, event) {
|
|
22
|
-
const
|
|
23
|
-
if (
|
|
24
|
-
const json = yield* Schema.encodeUnknownEffect(Schema.toCodecJson(
|
|
25
|
+
const schema = app.byTag.get(event._tag);
|
|
26
|
+
if (schema === void 0) return yield* Effect.die(`${event._tag} isn't one of this assistant's events.`);
|
|
27
|
+
const json = yield* Schema.encodeUnknownEffect(Schema.toCodecJson(schema))(event);
|
|
25
28
|
return yield* Schema.decodeUnknownEffect(StoredAppEvent)(json);
|
|
26
29
|
}, Effect.orDie);
|
|
27
30
|
/** @internal */
|
|
28
31
|
const isRegistered = (app, event) => app.byTag.has(event._tag);
|
|
32
|
+
const unmarked = (event) => Predicate.hasProperty(event, "~effect-assistant/input") ? Record.remove(event, inputKey) : event;
|
|
33
|
+
/** @internal */
|
|
34
|
+
const decodeWith = (schema, event) => Schema.decodeUnknownOption(Schema.toCodecJson(schema))(unmarked(event));
|
|
35
|
+
const decodeEvent = (app, event) => {
|
|
36
|
+
const schema = app.byTag.get(event._tag);
|
|
37
|
+
return schema === void 0 ? Option.none() : decodeWith(schema, event);
|
|
38
|
+
};
|
|
39
|
+
/** @internal */
|
|
40
|
+
const markInput = (event) => ({
|
|
41
|
+
...event,
|
|
42
|
+
[inputKey]: true
|
|
43
|
+
});
|
|
29
44
|
/** @internal */
|
|
30
45
|
const decodeEntry = (app, entry) => {
|
|
31
46
|
const { event } = entry;
|
|
@@ -33,33 +48,19 @@ const decodeEntry = (app, entry) => {
|
|
|
33
48
|
...toEntry(entry),
|
|
34
49
|
event
|
|
35
50
|
});
|
|
36
|
-
|
|
37
|
-
if (registered === void 0) return Option.none();
|
|
38
|
-
return Option.map(Schema.decodeUnknownOption(Schema.toCodecJson(registered.schema))(event), (decoded) => ({
|
|
51
|
+
return Option.map(decodeEvent(app, event), (decoded) => ({
|
|
39
52
|
...toEntry(entry),
|
|
40
53
|
event: decoded
|
|
41
54
|
}));
|
|
42
55
|
};
|
|
43
56
|
/** @internal */
|
|
44
57
|
const decodeEntries = (app, entries) => entries.flatMap((entry) => Option.toArray(decodeEntry(app, entry)));
|
|
45
|
-
const decodeStored = Schema.decodeUnknownOption(StoredAppEvent);
|
|
46
58
|
const toEntry = (entry) => ({
|
|
47
59
|
chatId: entry.chatId,
|
|
48
60
|
seq: entry.seq,
|
|
49
61
|
at: entry.at
|
|
50
62
|
});
|
|
51
|
-
/** @internal */
|
|
52
|
-
const read = (app, event) => {
|
|
53
|
-
const registered = app.byTag.get(event._tag);
|
|
54
|
-
if (registered?.render === void 0) return void 0;
|
|
55
|
-
if (registered.render !== "json") return registered.render(event);
|
|
56
|
-
const stored = Schema.encodeUnknownOption(Schema.toCodecJson(registered.schema))(event).pipe(Option.flatMap(decodeStored));
|
|
57
|
-
return Option.match(stored, {
|
|
58
|
-
onNone: () => void 0,
|
|
59
|
-
onSome: ({ _tag, ...fields }) => `<${_tag}>\n${toJsonText(fields)}\n</${_tag}>`
|
|
60
|
-
});
|
|
61
|
-
};
|
|
62
63
|
//#endregion
|
|
63
|
-
export { decodeEntries, decodeEntry, encode, isRegistered, make,
|
|
64
|
+
export { decodeEntries, decodeEntry, decodeWith, encode, isRegistered, make, markInput, tagOf };
|
|
64
65
|
|
|
65
66
|
//# sourceMappingURL=events.js.map
|