effect-assistant 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +22 -2
- package/dist/AppEvent.d.ts +111 -0
- package/dist/AppEvent.d.ts.map +1 -0
- package/dist/AppEvent.js +71 -0
- package/dist/AppEvent.js.map +1 -0
- package/dist/Assistant.d.ts +403 -0
- package/dist/Assistant.d.ts.map +1 -0
- package/dist/Assistant.js +126 -0
- package/dist/Assistant.js.map +1 -0
- package/dist/AssistantActivity.d.ts +85 -0
- package/dist/AssistantActivity.d.ts.map +1 -0
- package/dist/AssistantActivity.js +105 -0
- package/dist/AssistantActivity.js.map +1 -0
- package/dist/AssistantEngine.d.ts +116 -0
- package/dist/AssistantEngine.d.ts.map +1 -0
- package/dist/AssistantEngine.js +255 -0
- package/dist/AssistantEngine.js.map +1 -0
- package/dist/AssistantEvent.d.ts +614 -0
- package/dist/AssistantEvent.d.ts.map +1 -0
- package/dist/AssistantEvent.js +523 -0
- package/dist/AssistantEvent.js.map +1 -0
- package/dist/AssistantLoop.d.ts +171 -0
- package/dist/AssistantLoop.d.ts.map +1 -0
- package/dist/AssistantLoop.js +108 -0
- package/dist/AssistantLoop.js.map +1 -0
- package/dist/AssistantToolCall.d.ts +32 -0
- package/dist/AssistantToolCall.d.ts.map +1 -0
- package/dist/AssistantToolCall.js +37 -0
- package/dist/AssistantToolCall.js.map +1 -0
- package/dist/Block.d.ts +69 -0
- package/dist/Block.d.ts.map +1 -0
- package/dist/Block.js +39 -0
- package/dist/Block.js.map +1 -0
- package/dist/BlockKit.d.ts +184 -0
- package/dist/BlockKit.d.ts.map +1 -0
- package/dist/BlockKit.js +151 -0
- package/dist/BlockKit.js.map +1 -0
- package/dist/ChatId.d.ts +31 -0
- package/dist/ChatId.d.ts.map +1 -0
- package/dist/ChatId.js +36 -0
- package/dist/ChatId.js.map +1 -0
- package/dist/ChatLog.d.ts +109 -0
- package/dist/ChatLog.d.ts.map +1 -0
- package/dist/ChatLog.js +177 -0
- package/dist/ChatLog.js.map +1 -0
- package/dist/ChatView.d.ts +459 -0
- package/dist/ChatView.d.ts.map +1 -0
- package/dist/ChatView.js +496 -0
- package/dist/ChatView.js.map +1 -0
- package/dist/Chats.d.ts +110 -0
- package/dist/Chats.d.ts.map +1 -0
- package/dist/Chats.js +98 -0
- package/dist/Chats.js.map +1 -0
- package/dist/Compaction.d.ts +105 -0
- package/dist/Compaction.d.ts.map +1 -0
- package/dist/Compaction.js +133 -0
- package/dist/Compaction.js.map +1 -0
- package/dist/CurrentChat.d.ts +40 -0
- package/dist/CurrentChat.d.ts.map +1 -0
- package/dist/CurrentChat.js +33 -0
- package/dist/CurrentChat.js.map +1 -0
- package/dist/Decision.d.ts +145 -0
- package/dist/Decision.d.ts.map +1 -0
- package/dist/Decision.js +178 -0
- package/dist/Decision.js.map +1 -0
- package/dist/DecisionId.d.ts +37 -0
- package/dist/DecisionId.d.ts.map +1 -0
- package/dist/DecisionId.js +44 -0
- package/dist/DecisionId.js.map +1 -0
- package/dist/InputId.d.ts +38 -0
- package/dist/InputId.d.ts.map +1 -0
- package/dist/InputId.js +43 -0
- package/dist/InputId.js.map +1 -0
- package/dist/Instructions.d.ts +56 -0
- package/dist/Instructions.d.ts.map +1 -0
- package/dist/Instructions.js +50 -0
- package/dist/Instructions.js.map +1 -0
- package/dist/Memory.d.ts +190 -0
- package/dist/Memory.d.ts.map +1 -0
- package/dist/Memory.js +216 -0
- package/dist/Memory.js.map +1 -0
- package/dist/RunId.d.ts +41 -0
- package/dist/RunId.d.ts.map +1 -0
- package/dist/RunId.js +46 -0
- package/dist/RunId.js.map +1 -0
- package/dist/Skill.d.ts +72 -0
- package/dist/Skill.d.ts.map +1 -0
- package/dist/Skill.js +58 -0
- package/dist/Skill.js.map +1 -0
- package/dist/Specialist.d.ts +267 -0
- package/dist/Specialist.d.ts.map +1 -0
- package/dist/Specialist.js +119 -0
- package/dist/Specialist.js.map +1 -0
- package/dist/ToolDiscovery.d.ts +108 -0
- package/dist/ToolDiscovery.d.ts.map +1 -0
- package/dist/ToolDiscovery.js +139 -0
- package/dist/ToolDiscovery.js.map +1 -0
- package/dist/ToolFailure.d.ts +66 -0
- package/dist/ToolFailure.d.ts.map +1 -0
- package/dist/ToolFailure.js +79 -0
- package/dist/ToolFailure.js.map +1 -0
- package/dist/_virtual/_rolldown/runtime.js +13 -0
- package/dist/index.d.ts +26 -0
- package/dist/index.js +26 -0
- package/dist/internal/chat.js +202 -0
- package/dist/internal/chat.js.map +1 -0
- package/dist/internal/decisions.js +66 -0
- package/dist/internal/decisions.js.map +1 -0
- package/dist/internal/events.d.ts +46 -0
- package/dist/internal/events.d.ts.map +1 -0
- package/dist/internal/events.js +65 -0
- package/dist/internal/events.js.map +1 -0
- package/dist/internal/history.js +185 -0
- package/dist/internal/history.js.map +1 -0
- package/dist/internal/instructions.js +11 -0
- package/dist/internal/instructions.js.map +1 -0
- package/dist/internal/loop.d.ts +73 -0
- package/dist/internal/loop.d.ts.map +1 -0
- package/dist/internal/loop.js +166 -0
- package/dist/internal/loop.js.map +1 -0
- package/dist/internal/schema.js +14 -0
- package/dist/internal/schema.js.map +1 -0
- package/dist/internal/skills.js +28 -0
- package/dist/internal/skills.js.map +1 -0
- package/dist/internal/specialists.js +273 -0
- package/dist/internal/specialists.js.map +1 -0
- package/dist/internal/telemetry.js +85 -0
- package/dist/internal/telemetry.js.map +1 -0
- package/dist/internal/toolkit.d.ts +76 -0
- package/dist/internal/toolkit.d.ts.map +1 -0
- package/dist/internal/toolkit.js +129 -0
- package/dist/internal/toolkit.js.map +1 -0
- package/dist/internal/tools.js +132 -0
- package/dist/internal/tools.js.map +1 -0
- package/dist/internal/turns.d.ts +64 -0
- package/dist/internal/turns.d.ts.map +1 -0
- package/dist/internal/turns.js +221 -0
- package/dist/internal/turns.js.map +1 -0
- package/dist/internal/uuid.js +45 -0
- package/dist/internal/uuid.js.map +1 -0
- package/dist/internal/writer.d.ts +12 -0
- package/dist/internal/writer.d.ts.map +1 -0
- package/package.json +51 -3
- package/src/AppEvent.ts +134 -0
- package/src/Assistant.ts +589 -0
- package/src/AssistantActivity.ts +150 -0
- package/src/AssistantEngine.ts +343 -0
- package/src/AssistantEvent.ts +635 -0
- package/src/AssistantLoop.ts +207 -0
- package/src/AssistantToolCall.ts +40 -0
- package/src/Block.ts +84 -0
- package/src/BlockKit.ts +311 -0
- package/src/ChatId.ts +36 -0
- package/src/ChatLog.ts +247 -0
- package/src/ChatView.ts +658 -0
- package/src/Chats.ts +122 -0
- package/src/Compaction.ts +224 -0
- package/src/CurrentChat.ts +47 -0
- package/src/Decision.ts +241 -0
- package/src/DecisionId.ts +46 -0
- package/src/InputId.ts +43 -0
- package/src/Instructions.ts +72 -0
- package/src/Memory.ts +276 -0
- package/src/RunId.ts +46 -0
- package/src/Skill.ts +91 -0
- package/src/Specialist.ts +355 -0
- package/src/ToolDiscovery.ts +187 -0
- package/src/ToolFailure.ts +74 -0
- package/src/index.ts +130 -0
- package/src/internal/chat.ts +372 -0
- package/src/internal/decisions.ts +131 -0
- package/src/internal/events.ts +100 -0
- package/src/internal/history.ts +366 -0
- package/src/internal/instructions.ts +9 -0
- package/src/internal/loop.ts +344 -0
- package/src/internal/schema.ts +25 -0
- package/src/internal/skills.ts +37 -0
- package/src/internal/specialists.ts +414 -0
- package/src/internal/telemetry.ts +125 -0
- package/src/internal/toolkit.ts +231 -0
- package/src/internal/tools.ts +210 -0
- package/src/internal/turns.ts +429 -0
- package/src/internal/uuid.ts +50 -0
- package/src/internal/writer.ts +12 -0
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
import { ToolResult, TurnCompleted, TurnFailed, TurnStarted, isLibraryEvent } from "../AssistantEvent.js";
|
|
2
|
+
import { block, kind } from "../Decision.js";
|
|
3
|
+
import { approvedCalls } from "./decisions.js";
|
|
4
|
+
import { toJsonText } from "./schema.js";
|
|
5
|
+
import { decodeEntries, read } from "./events.js";
|
|
6
|
+
import { fromEntries, mayHaveRunOutput, notRunOutput, owesDelivery, owesReply, unansweredCalls, unhandledInputs, unreadAfter, userText } from "./history.js";
|
|
7
|
+
import { agentInput, agentOutput, agentSpan, currentTraceId } from "./telemetry.js";
|
|
8
|
+
import { duplicateNames, fromToolkitOrEmpty, merge, provide, runOnly } from "./toolkit.js";
|
|
9
|
+
import { makeMessaging, sendUserMessageName, waitToolName } from "./tools.js";
|
|
10
|
+
import { TurnTools, run as run$1 } from "./loop.js";
|
|
11
|
+
import { withCatalog } from "../Skill.js";
|
|
12
|
+
import { protocol } from "../Instructions.js";
|
|
13
|
+
import { toTools } from "./skills.js";
|
|
14
|
+
import { mapText } from "./instructions.js";
|
|
15
|
+
import { toolkit } from "./specialists.js";
|
|
16
|
+
import * as Predicate from "effect/Predicate";
|
|
17
|
+
import "effect/Context";
|
|
18
|
+
import * as Effect from "effect/Effect";
|
|
19
|
+
import * as Schema from "effect/Schema";
|
|
20
|
+
import * as Stream from "effect/Stream";
|
|
21
|
+
import * as Exit from "effect/Exit";
|
|
22
|
+
import * as Option from "effect/Option";
|
|
23
|
+
import * as Cause from "effect/Cause";
|
|
24
|
+
import { identity } from "effect/Function";
|
|
25
|
+
//#region src/internal/turns.ts
|
|
26
|
+
/** @internal */
|
|
27
|
+
const silentTurnMessage = "I finished without sending a reply.";
|
|
28
|
+
/** @internal */
|
|
29
|
+
const defaultReplyNudge = "You haven't replied to the user's latest message yet. Reply now with send_user_message.";
|
|
30
|
+
/** @internal */
|
|
31
|
+
const deliveryNudge = "You told the user you're on it, but stopped without giving them the result. Send it now with send_user_message; if part of it is still running, say what and that you'll report back. If they already have everything, call wait.";
|
|
32
|
+
/** @internal */
|
|
33
|
+
const register = Effect.fnUntraced(function* (definition, options) {
|
|
34
|
+
const model = yield* Effect.context();
|
|
35
|
+
const decisionBlock = definition.blocks?.byKind.get(kind);
|
|
36
|
+
if (decisionBlock !== void 0 && decisionBlock !== block) return yield* Effect.die(`The ${kind} block kind is the library's: use Decision.block.`);
|
|
37
|
+
const specialists = yield* Effect.forEach(definition.specialists, Effect.fnUntraced(function* (specialist) {
|
|
38
|
+
const built = yield* Effect.serviceOption(specialist.Handler);
|
|
39
|
+
if (Option.isNone(built)) return yield* Effect.die(`No handler for the ${specialist.name} specialist: provide ${specialist.name}.toLayer.`);
|
|
40
|
+
return {
|
|
41
|
+
specialist,
|
|
42
|
+
built: built.value
|
|
43
|
+
};
|
|
44
|
+
}));
|
|
45
|
+
const builtins = merge(yield* makeMessaging(definition.blocks), yield* toolkit(definition.specialists));
|
|
46
|
+
return {
|
|
47
|
+
definition,
|
|
48
|
+
model,
|
|
49
|
+
open: options.open,
|
|
50
|
+
specialists,
|
|
51
|
+
builtins
|
|
52
|
+
};
|
|
53
|
+
});
|
|
54
|
+
const ProviderError = Schema.Struct({
|
|
55
|
+
_tag: Schema.optional(Schema.String),
|
|
56
|
+
raw: Schema.Unknown
|
|
57
|
+
});
|
|
58
|
+
const failureMessage = (cause) => Option.match(Schema.decodeUnknownOption(ProviderError)(Cause.squash(cause)), {
|
|
59
|
+
onNone: () => Cause.pretty(cause),
|
|
60
|
+
onSome: ({ _tag, raw }) => `${_tag ?? "Error"}: ${Predicate.isString(raw) ? raw : toJsonText(raw)}`
|
|
61
|
+
});
|
|
62
|
+
const lastSeq = (entries, otherwise) => entries.at(-1)?.seq ?? otherwise;
|
|
63
|
+
const toHistory = (viewed, app) => {
|
|
64
|
+
const out = [];
|
|
65
|
+
let run = [];
|
|
66
|
+
const flush = () => {
|
|
67
|
+
out.push(...fromEntries(run, (event) => read(app, event)));
|
|
68
|
+
run = [];
|
|
69
|
+
};
|
|
70
|
+
for (const item of viewed) if (isEntry(item)) run.push(item);
|
|
71
|
+
else {
|
|
72
|
+
flush();
|
|
73
|
+
out.push(item);
|
|
74
|
+
}
|
|
75
|
+
flush();
|
|
76
|
+
return out;
|
|
77
|
+
};
|
|
78
|
+
const isEntry = (item) => Predicate.hasProperty(item, "seq");
|
|
79
|
+
const closeOpenCalls = Effect.fnUntraced(function* (chat, startSeq) {
|
|
80
|
+
const entries = (yield* chat.entries).filter(({ seq }) => seq > startSeq);
|
|
81
|
+
const started = new Set(entries.flatMap(({ event }) => Predicate.isTagged(event, "ToolStarted") ? [event.callId] : []));
|
|
82
|
+
const all = yield* chat.entries;
|
|
83
|
+
const approved = approvedCalls(all).filter((call) => started.has(call.id));
|
|
84
|
+
const open = [...unansweredCalls(fromEntries(entries, () => void 0)), ...approved];
|
|
85
|
+
if (open.length === 0) return;
|
|
86
|
+
yield* chat.append(open.map((call) => ToolResult.make({
|
|
87
|
+
callId: call.id,
|
|
88
|
+
tool: call.name,
|
|
89
|
+
outcome: "failure",
|
|
90
|
+
...started.has(call.id) ? {
|
|
91
|
+
result: mayHaveRunOutput,
|
|
92
|
+
reason: "MayHaveRun"
|
|
93
|
+
} : {
|
|
94
|
+
result: notRunOutput,
|
|
95
|
+
reason: "NotRun"
|
|
96
|
+
}
|
|
97
|
+
})));
|
|
98
|
+
});
|
|
99
|
+
const handledThrough = (entries, startSeq) => entries.reduce((through, { seq, event }) => seq > startSeq && isLibraryEvent(event) && Predicate.isTagged(event, "ModelOutput") && event.seenThroughSeq !== void 0 ? Math.max(through, event.seenThroughSeq) : through, startSeq);
|
|
100
|
+
const finishTurn = Effect.fnUntraced(function* (chat, read, wakes) {
|
|
101
|
+
const entries = yield* chat.entries;
|
|
102
|
+
const end = owesReply(entries, read) && !unreadAfter(entries, read, wakes) ? TurnFailed.make({
|
|
103
|
+
throughSeq: read,
|
|
104
|
+
message: silentTurnMessage
|
|
105
|
+
}) : TurnCompleted.make({ throughSeq: read });
|
|
106
|
+
yield* chat.append([end]);
|
|
107
|
+
});
|
|
108
|
+
const failTurn = Effect.fnUntraced(function* (chat, cause) {
|
|
109
|
+
yield* Effect.logError("assistant turn failed", cause);
|
|
110
|
+
const last = lastSeq(yield* chat.entries, 0);
|
|
111
|
+
yield* chat.append([TurnFailed.make({
|
|
112
|
+
throughSeq: last,
|
|
113
|
+
message: failureMessage(cause)
|
|
114
|
+
})]);
|
|
115
|
+
});
|
|
116
|
+
const makeTurnApi = (registration, chat, startSeq, checkOpen) => {
|
|
117
|
+
const { definition, builtins } = registration;
|
|
118
|
+
const { app } = definition;
|
|
119
|
+
const history = Effect.fnUntraced(function* (view = identity) {
|
|
120
|
+
yield* checkOpen;
|
|
121
|
+
const all = yield* chat.entries;
|
|
122
|
+
return {
|
|
123
|
+
messages: toHistory(view(decodeEntries(app, all)), app),
|
|
124
|
+
throughSeq: lastSeq(all, startSeq)
|
|
125
|
+
};
|
|
126
|
+
});
|
|
127
|
+
const instructions = (given) => mapText(given, (text) => `${protocol}\n\n${text}`);
|
|
128
|
+
const replyPass = (options) => Stream.unwrap(Effect.gen(function* () {
|
|
129
|
+
const all = yield* chat.entries;
|
|
130
|
+
const through = handledThrough(all, startSeq);
|
|
131
|
+
if (unreadAfter(all, through, app.wakes)) return Stream.empty;
|
|
132
|
+
const owed = owesReply(all, through);
|
|
133
|
+
const undelivered = !owed && owesDelivery(all, through);
|
|
134
|
+
if (!owed && !undelivered) return Stream.empty;
|
|
135
|
+
const nudge = undelivered ? deliveryNudge : options.nudge ?? "You haven't replied to the user's latest message yet. Reply now with send_user_message.";
|
|
136
|
+
return run$1({
|
|
137
|
+
instructions: options.instructions,
|
|
138
|
+
toolkit: runOnly(options.toolkit, owed ? [sendUserMessageName] : [sendUserMessageName, waitToolName], "Not now: reply to the user with send_user_message."),
|
|
139
|
+
history: Effect.gen(function* () {
|
|
140
|
+
yield* checkOpen;
|
|
141
|
+
const entries = yield* chat.entries;
|
|
142
|
+
return {
|
|
143
|
+
messages: [...toHistory(options.view(decodeEntries(app, entries)), app), userText(nudge)],
|
|
144
|
+
throughSeq: lastSeq(entries, startSeq)
|
|
145
|
+
};
|
|
146
|
+
}),
|
|
147
|
+
maxSteps: 2
|
|
148
|
+
});
|
|
149
|
+
}));
|
|
150
|
+
const replyIfOwed = (options) => replyPass({
|
|
151
|
+
instructions: instructions(options.instructions),
|
|
152
|
+
toolkit: builtins,
|
|
153
|
+
view: identity,
|
|
154
|
+
nudge: options.nudge
|
|
155
|
+
});
|
|
156
|
+
const prepare = (options) => {
|
|
157
|
+
const skills = options.skills ?? [];
|
|
158
|
+
return {
|
|
159
|
+
system: mapText(instructions(options.instructions), (text) => withCatalog(text, skills)),
|
|
160
|
+
toolkit: merge(merge(builtins, toTools(skills)), fromToolkitOrEmpty(options.toolkit)),
|
|
161
|
+
view: options.history ?? identity
|
|
162
|
+
};
|
|
163
|
+
};
|
|
164
|
+
return {
|
|
165
|
+
chatId: chat.chatId,
|
|
166
|
+
history,
|
|
167
|
+
instructions,
|
|
168
|
+
replyIfOwed,
|
|
169
|
+
loop: (options) => {
|
|
170
|
+
const { system, toolkit, view } = prepare(options);
|
|
171
|
+
const twice = duplicateNames(toolkit);
|
|
172
|
+
const deciding = toolkit.definitions.filter((tool) => tool.needsApproval !== void 0 && tool.needsApproval !== false);
|
|
173
|
+
const loop = twice.length > 0 ? Stream.die(`Tool names used twice, like one named after a built-in: ${twice.join(", ")}`) : deciding.length > 0 && definition.blocks?.byKind.get("decision") === void 0 ? Stream.die(`${deciding.map((tool) => tool.name).join(", ")} can wait for the user's decision: add Decision.block to the assistant's blocks.`) : run$1({
|
|
174
|
+
instructions: system,
|
|
175
|
+
toolkit,
|
|
176
|
+
history: history(view),
|
|
177
|
+
maxSteps: options.maxSteps ?? 16
|
|
178
|
+
});
|
|
179
|
+
return Stream.concat(loop, replyPass({
|
|
180
|
+
instructions: system,
|
|
181
|
+
toolkit,
|
|
182
|
+
view,
|
|
183
|
+
nudge: options.replyNudge
|
|
184
|
+
}));
|
|
185
|
+
}
|
|
186
|
+
};
|
|
187
|
+
};
|
|
188
|
+
/** @internal */
|
|
189
|
+
const run = Effect.fnUntraced(function* (options) {
|
|
190
|
+
const { chat } = options;
|
|
191
|
+
const before = yield* chat.entries;
|
|
192
|
+
yield* agentInput(unhandledInputs(before, options.registration.definition.app.wakes));
|
|
193
|
+
const assistant = options.registration.definition.name;
|
|
194
|
+
const traceId = yield* currentTraceId;
|
|
195
|
+
const started = yield* chat.append([TurnStarted.make(Option.match(traceId, {
|
|
196
|
+
onNone: () => ({ assistant }),
|
|
197
|
+
onSome: (id) => ({
|
|
198
|
+
assistant,
|
|
199
|
+
traceId: id
|
|
200
|
+
})
|
|
201
|
+
}))]);
|
|
202
|
+
const startSeq = lastSeq(started, 0);
|
|
203
|
+
const turn = makeTurnApi(options.registration, chat, startSeq, options.checkOpen);
|
|
204
|
+
const record = (event) => chat.append([event]);
|
|
205
|
+
yield* options.handler(turn).pipe(Stream.runForEach(record), Effect.onExit((exit) => Exit.hasInterrupts(exit) ? Effect.void : closeOpenCalls(chat, startSeq)), Effect.provideService(TurnTools, Option.some(provide(options.registration.builtins, options.services))), Effect.provideContext(options.services), Effect.matchCauseEffect({
|
|
206
|
+
onSuccess: Effect.fnUntraced(function* () {
|
|
207
|
+
const all = yield* chat.entries;
|
|
208
|
+
yield* finishTurn(chat, handledThrough(all, startSeq), options.registration.definition.app.wakes);
|
|
209
|
+
}),
|
|
210
|
+
onFailure: (cause) => failTurn(chat, cause)
|
|
211
|
+
}));
|
|
212
|
+
const shown = (yield* chat.entries).flatMap(({ event, seq }) => seq > startSeq && (Predicate.isTagged(event, "AssistantMessage") || Predicate.isTagged(event, "TurnFailed")) ? [event] : []);
|
|
213
|
+
yield* agentOutput(shown);
|
|
214
|
+
}, (effect, options) => effect.pipe(agentSpan(options.registration.definition.name, {
|
|
215
|
+
chatId: options.chat.chatId,
|
|
216
|
+
root: true
|
|
217
|
+
})));
|
|
218
|
+
//#endregion
|
|
219
|
+
export { defaultReplyNudge, deliveryNudge, register, run, silentTurnMessage };
|
|
220
|
+
|
|
221
|
+
//# sourceMappingURL=turns.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"turns.js","names":["Decision.kind","Decision.block","Toolkits.merge","Tools.makeMessaging","Specialists.toolkit","History.fromEntries","AppEvents.read","Decisions.approvedCalls","History.unansweredCalls","History.mayHaveRunOutput","History.notRunOutput","AssistantEvent.isLibraryEvent","History.owesReply","History.unreadAfter","AppEvents.decodeEntries","Instructions.protocol","History.owesDelivery","Loop.run","Toolkits.runOnly","Tools.sendUserMessageName","Tools.waitToolName","History.userText","Skill.withCatalog","Skills.toTools","Toolkits.fromToolkitOrEmpty","Toolkits.duplicateNames","Telemetry.agentInput","History.unhandledInputs","Telemetry.currentTraceId","Loop.TurnTools","Toolkits.provide","Telemetry.agentOutput","Telemetry.agentSpan"],"sources":["../../src/internal/turns.ts"],"sourcesContent":["import type * as LanguageModel from \"effect/ai/LanguageModel\"\nimport type * as Tool from \"effect/ai/Tool\"\nimport type * as Prompt from \"effect/ai/Prompt\"\nimport * as Cause from \"effect/Cause\"\nimport * as Context from \"effect/Context\"\nimport * as Effect from \"effect/Effect\"\nimport * as Exit from \"effect/Exit\"\nimport { identity } from \"effect/Function\"\nimport * as Option from \"effect/Option\"\nimport * as Predicate from \"effect/Predicate\"\nimport * as Schema from \"effect/Schema\"\nimport type * as Scope from \"effect/Scope\"\nimport * as Stream from \"effect/Stream\"\nimport type * as Assistant from \"../Assistant.ts\"\nimport type { ChatId } from \"../ChatId.ts\"\nimport * as AssistantEvent from \"../AssistantEvent.ts\"\nimport type * as AssistantLoop from \"../AssistantLoop.ts\"\nimport * as Loop from \"./loop.ts\"\nimport type * as BlockKit from \"../BlockKit.ts\"\nimport type { CurrentChat } from \"../CurrentChat.ts\"\nimport * as Decision from \"../Decision.ts\"\nimport * as Instructions from \"../Instructions.ts\"\nimport * as Skill from \"../Skill.ts\"\nimport * as Skills from \"./skills.ts\"\nimport type * as Specialist from \"../Specialist.ts\"\nimport * as Decisions from \"./decisions.ts\"\nimport * as AppEvents from \"./events.ts\"\nimport * as History from \"./history.ts\"\nimport { mapText } from \"./instructions.ts\"\nimport { toJsonText } from \"./schema.ts\"\nimport * as Specialists from \"./specialists.ts\"\nimport * as Telemetry from \"./telemetry.ts\"\nimport * as Toolkits from \"./toolkit.ts\"\nimport type { Writer } from \"./writer.ts\"\nimport * as Tools from \"./tools.ts\"\n\n/** @internal */\nexport const silentTurnMessage = \"I finished without sending a reply.\"\n\n/** @internal */\nexport const defaultReplyNudge =\n \"You haven't replied to the user's latest message yet. Reply now with send_user_message.\"\n\n/** @internal */\nexport const deliveryNudge =\n \"You told the user you're on it, but stopped without giving them the result. Send it now with send_user_message; if part of it is still running, say what and that you'll report back. If they already have everything, call wait.\"\n\n/** @internal */\nexport interface Definition {\n readonly name: string\n readonly blocks: BlockKit.BlockKit | undefined\n readonly specialists: ReadonlyArray<Specialist.Any>\n readonly app: AppEvents.AppEvents\n}\n\n// Once its build ran the layer's services are provided, so its streams need only what a turn provides.\n/** @internal */\nexport type TurnHandler = (\n turn: Assistant.Turn<any>\n) => Stream.Stream<AssistantLoop.Event, unknown, Assistant.TurnServices | LanguageModel.LanguageModel>\n\n// The chat `CurrentChat` gives, with its entries typed as the assistant's decode returns them: the assistant's typed\n// chat is this one, so it needs no check of its own.\n/** @internal */\nexport interface TypedChat {\n readonly chatId: ChatId\n readonly entries: Effect.Effect<AppEvents.DecodedEntries>\n readonly append: CurrentChat[\"Service\"][\"append\"]\n}\n\n/** @internal */\nexport interface Registration {\n readonly definition: Definition\n readonly model: Context.Context<LanguageModel.LanguageModel>\n readonly open: (chat: TypedChat) => Effect.Effect<TurnHandler, never, Scope.Scope | CurrentChat>\n readonly specialists: ReadonlyArray<{\n readonly specialist: Specialist.Any\n readonly built: Specialist.Built\n }>\n readonly builtins: Toolkits.Tools<Assistant.TurnServices>\n}\n\n/** @internal */\nexport const register = Effect.fnUntraced(function* (\n definition: Definition,\n options: { readonly open: Registration[\"open\"] }\n) {\n const model = yield* Effect.context<LanguageModel.LanguageModel>()\n\n const decisionBlock = definition.blocks?.byKind.get(Decision.kind)\n\n if (decisionBlock !== undefined && decisionBlock !== Decision.block) {\n return yield* Effect.die(`The ${Decision.kind} block kind is the library's: use Decision.block.`)\n }\n\n const specialists = yield* Effect.forEach(\n definition.specialists,\n Effect.fnUntraced(function* (specialist) {\n const built = yield* Effect.serviceOption(specialist.Handler)\n\n if (Option.isNone(built)) {\n return yield* Effect.die(\n `No handler for the ${specialist.name} specialist: provide ${specialist.name}.toLayer.`\n )\n }\n\n return { specialist, built: built.value }\n })\n )\n\n const builtins = Toolkits.merge(\n yield* Tools.makeMessaging(definition.blocks),\n yield* Specialists.toolkit(definition.specialists)\n )\n\n const registration: Registration = {\n definition,\n model,\n open: options.open,\n specialists,\n builtins\n }\n\n return registration\n})\n\nconst ProviderError = Schema.Struct({ _tag: Schema.optional(Schema.String), raw: Schema.Unknown })\n\n// Provider errors keep their response body.\nconst failureMessage = (cause: Cause.Cause<unknown>): string =>\n Option.match(Schema.decodeUnknownOption(ProviderError)(Cause.squash(cause)), {\n onNone: () => Cause.pretty(cause),\n onSome: ({ _tag, raw }) => `${_tag ?? \"Error\"}: ${Predicate.isString(raw) ? raw : toJsonText(raw)}`\n })\n\nconst lastSeq = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, otherwise: number) => entries.at(-1)?.seq ?? otherwise\n\nconst toHistory = (\n viewed: ReadonlyArray<Assistant.Entry<any> | Prompt.Message>,\n app: AppEvents.AppEvents\n): ReadonlyArray<Prompt.Message> => {\n const out: Array<Prompt.Message> = []\n let run: Array<AssistantEvent.AnyEntry> = []\n\n const flush = () => {\n out.push(...History.fromEntries(run, (event) => AppEvents.read(app, event)))\n run = []\n }\n\n for (const item of viewed) {\n if (isEntry(item)) run.push(item)\n else {\n flush()\n out.push(item)\n }\n }\n\n flush()\n\n return out\n}\n\nconst isEntry = (item: Assistant.Entry<any> | Prompt.Message): item is Assistant.Entry<any> =>\n Predicate.hasProperty(item, \"seq\")\n\n// The handler's stream can end between a step's output and its tools, or while they run. An interrupted turn (a\n// shutdown) leaves its calls open instead: the next turn runs them again.\nconst closeOpenCalls = Effect.fnUntraced(function* (chat: Writer, startSeq: number) {\n const entries = (yield* chat.entries).filter(({ seq }) => seq > startSeq)\n\n const started = new Set(\n entries.flatMap(({ event }) => (Predicate.isTagged(event, \"ToolStarted\") ? [event.callId] : []))\n )\n\n // Approved calls this turn started that have no result are cut off like any other; one not started yet waits.\n const all = yield* chat.entries\n const approved = Decisions.approvedCalls(all).filter((call) => started.has(call.id))\n const open = [...History.unansweredCalls(History.fromEntries(entries, () => undefined)), ...approved]\n\n if (open.length === 0) return\n\n yield* chat.append(\n open.map((call) =>\n AssistantEvent.ToolResult.make({\n callId: call.id,\n tool: call.name,\n outcome: \"failure\",\n ...(started.has(call.id)\n ? { result: History.mayHaveRunOutput, reason: \"MayHaveRun\" }\n : { result: History.notRunOutput, reason: \"NotRun\" })\n })\n )\n )\n})\n\n// The inputs before the turn's `TurnStarted` (at `startSeq`) woke it; past that, what its model outputs record\n// reading.\nconst handledThrough = (entries: ReadonlyArray<AssistantEvent.AnyEntry>, startSeq: number) =>\n entries.reduce(\n (through, { seq, event }) =>\n seq > startSeq &&\n AssistantEvent.isLibraryEvent(event) &&\n Predicate.isTagged(event, \"ModelOutput\") &&\n event.seenThroughSeq !== undefined\n ? Math.max(through, event.seenThroughSeq)\n : through,\n startSeq\n )\n\n// Fails visibly when the user's latest input got no reply; an input that arrived after what its model read gets the\n// next turn, which replies.\nconst finishTurn = Effect.fnUntraced(function* (chat: Writer, read: number, wakes: ReadonlySet<string>) {\n const entries = yield* chat.entries\n\n const end =\n History.owesReply(entries, read) && !History.unreadAfter(entries, read, wakes)\n ? AssistantEvent.TurnFailed.make({ throughSeq: read, message: silentTurnMessage })\n : AssistantEvent.TurnCompleted.make({ throughSeq: read })\n\n yield* chat.append([end])\n})\n\n// Everything stored so far counts as read, so a failing input isn't retried forever.\nconst failTurn = Effect.fnUntraced(function* (chat: Writer, cause: Cause.Cause<unknown>) {\n yield* Effect.logError(\"assistant turn failed\", cause)\n\n const last = lastSeq(yield* chat.entries, 0)\n\n yield* chat.append([AssistantEvent.TurnFailed.make({ throughSeq: last, message: failureMessage(cause) })])\n})\n\nconst makeTurnApi = (\n registration: Registration,\n chat: Writer,\n startSeq: number,\n checkOpen: Effect.Effect<void>\n): Assistant.Turn<any> => {\n const { definition, builtins } = registration\n const { app } = definition\n\n // With how far into the chat it goes: the step records it on the model's output.\n // Read before every model call: a chat the app deleted meanwhile stops here.\n const history = Effect.fnUntraced(function* (view: Assistant.HistoryView<any> = identity) {\n yield* checkOpen\n\n const all = yield* chat.entries\n\n const read: AssistantLoop.ChatHistory = {\n messages: toHistory(view(AppEvents.decodeEntries(app, all)), app),\n throughSeq: lastSeq(all, startSeq)\n }\n\n return read\n })\n\n const instructions = (given: string | Instructions.Resolved) =>\n mapText(given, (text) => `${Instructions.protocol}\\n\\n${text}`)\n\n // The loop's own prompt and tools, so the prompt stays cached, with the nudge at the end.\n const replyPass = <R>(options: {\n readonly instructions: Instructions.Resolved\n readonly toolkit: Toolkits.Tools<R>\n readonly view: Assistant.HistoryView<any>\n readonly nudge: string | undefined\n }) =>\n Stream.unwrap(\n Effect.gen(function* () {\n const all = yield* chat.entries\n const through = handledThrough(all, startSeq)\n\n // Something arrived after what the loop's model read: the next turn reads it with the full loop, and replies.\n if (History.unreadAfter(all, through, app.wakes)) return Stream.empty\n\n const owed = History.owesReply(all, through)\n const undelivered = !owed && History.owesDelivery(all, through)\n\n if (!owed && !undelivered) return Stream.empty\n\n const nudge = undelivered ? deliveryNudge : (options.nudge ?? defaultReplyNudge)\n\n return Loop.run({\n instructions: options.instructions,\n // A reply that's owed can only be sent; a result it may have given may also be for nobody.\n toolkit: Toolkits.runOnly(\n options.toolkit,\n owed ? [Tools.sendUserMessageName] : [Tools.sendUserMessageName, Tools.waitToolName],\n \"Not now: reply to the user with send_user_message.\"\n ),\n history: Effect.gen(function* () {\n yield* checkOpen\n\n const entries = yield* chat.entries\n\n return {\n messages: [\n ...toHistory(options.view(AppEvents.decodeEntries(app, entries)), app),\n History.userText(nudge)\n ],\n throughSeq: lastSeq(entries, startSeq)\n }\n }),\n // A second step, for a reply after a call it was refused.\n maxSteps: 2\n })\n })\n )\n\n const replyIfOwed = (options: Assistant.ReplyOptions) =>\n replyPass({\n instructions: instructions(options.instructions),\n toolkit: builtins,\n view: identity,\n nudge: options.nudge\n })\n\n const prepare = <T extends Record<string, Tool.Any>, RS>(options: Assistant.LoopOptions<T, RS, any>) => {\n const skills = options.skills ?? []\n\n return {\n system: mapText(instructions(options.instructions), (text) => Skill.withCatalog(text, skills)),\n toolkit: Toolkits.merge(\n Toolkits.merge(builtins, Skills.toTools(skills)),\n Toolkits.fromToolkitOrEmpty(options.toolkit)\n ),\n view: options.history ?? identity\n }\n }\n\n return {\n chatId: chat.chatId,\n history,\n instructions,\n replyIfOwed,\n loop: (options) => {\n const { system, toolkit, view } = prepare(options)\n const twice = Toolkits.duplicateNames(toolkit)\n\n const deciding = toolkit.definitions.filter(\n (tool) => tool.needsApproval !== undefined && tool.needsApproval !== false\n )\n\n const loop =\n twice.length > 0\n ? Stream.die(`Tool names used twice, like one named after a built-in: ${twice.join(\", \")}`)\n : deciding.length > 0 && definition.blocks?.byKind.get(Decision.kind) === undefined\n ? Stream.die(\n `${deciding.map((tool) => tool.name).join(\", \")} can wait for the user's decision: add Decision.block to the assistant's blocks.`\n )\n : Loop.run({\n instructions: system,\n toolkit,\n history: history(view),\n maxSteps: options.maxSteps ?? 16\n })\n\n return Stream.concat(loop, replyPass({ instructions: system, toolkit, view, nudge: options.replyNudge }))\n }\n }\n}\n\n// Every event the handler's loop emits is recorded before the loop is pulled again.\n/** @internal */\nexport const run = Effect.fnUntraced(\n function* (options: {\n readonly registration: Registration\n readonly handler: TurnHandler\n readonly chat: Writer\n readonly services: Context.Context<Assistant.TurnServices | LanguageModel.LanguageModel>\n // A chat the app deleted is deleted here, and the turn stops.\n readonly checkOpen: Effect.Effect<void>\n }) {\n const { chat } = options\n const before = yield* chat.entries\n\n yield* Telemetry.agentInput(History.unhandledInputs(before, options.registration.definition.app.wakes))\n\n const assistant = options.registration.definition.name\n const traceId = yield* Telemetry.currentTraceId\n\n const started = yield* chat.append([\n AssistantEvent.TurnStarted.make(\n Option.match(traceId, {\n onNone: () => ({ assistant }),\n onSome: (id) => ({ assistant, traceId: id })\n })\n )\n ])\n\n const startSeq = lastSeq(started, 0)\n const turn = makeTurnApi(options.registration, chat, startSeq, options.checkOpen)\n\n const record = (event: AssistantLoop.Event) => chat.append([event])\n\n yield* options.handler(turn).pipe(\n Stream.runForEach(record),\n Effect.onExit((exit) => (Exit.hasInterrupts(exit) ? Effect.void : closeOpenCalls(chat, startSeq))),\n // A loop the app writes gets the assistant's own tools too, with this turn's services.\n Effect.provideService(\n Loop.TurnTools,\n Option.some(Toolkits.provide(options.registration.builtins, options.services))\n ),\n Effect.provideContext(options.services),\n Effect.matchCauseEffect({\n onSuccess: Effect.fnUntraced(function* () {\n const all = yield* chat.entries\n\n yield* finishTurn(chat, handledThrough(all, startSeq), options.registration.definition.app.wakes)\n }),\n onFailure: (cause) => failTurn(chat, cause)\n })\n )\n\n // The trace's output is what the user saw this turn, and a failure if any.\n const shown = (yield* chat.entries).flatMap(({ event, seq }) =>\n seq > startSeq && (Predicate.isTagged(event, \"AssistantMessage\") || Predicate.isTagged(event, \"TurnFailed\"))\n ? [event]\n : []\n )\n\n yield* Telemetry.agentOutput(shown)\n },\n (effect, options) =>\n effect.pipe(\n Telemetry.agentSpan(options.registration.definition.name, {\n chatId: options.chat.chatId,\n root: true\n })\n )\n)\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAqCA,MAAa,oBAAoB;;AAGjC,MAAa,oBACX;;AAGF,MAAa,gBACX;;AAsCF,MAAa,WAAW,OAAO,WAAW,WACxC,YACA,SACA;CACA,MAAM,QAAQ,OAAO,OAAO,QAAqC;CAEjE,MAAM,gBAAgB,WAAW,QAAQ,OAAO,IAAIA,IAAa;CAEjE,IAAI,kBAAkB,KAAA,KAAa,kBAAkBC,OACnD,OAAO,OAAO,OAAO,IAAI,OAAOD,KAAc,kDAAkD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,UAAU,SAAS,OAAO,kBAAkB,KAAK,UAAU,SAAS,OAAO,YAAY,KACtG,CAAC,KAAK,IACN,CAAC,CACP;CAEA,OAAOC,YAAsB,KAAK;AACpC,IACC,QAAQ,YACP,OAAO,KACLC,UAAoB,QAAQ,aAAa,WAAW,MAAM;CACxD,QAAQ,QAAQ,KAAK;CACrB,MAAM;AACR,CAAC,CACH,CACJ"}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import * as Effect from "effect/Effect";
|
|
2
|
+
import * as Schema from "effect/Schema";
|
|
3
|
+
import * as Random from "effect/Random";
|
|
4
|
+
//#region src/internal/uuid.ts
|
|
5
|
+
/** @internal */
|
|
6
|
+
const Uuid = Schema.String.check(Schema.isUUID());
|
|
7
|
+
const hex = (bytes) => {
|
|
8
|
+
const digits = bytes.map((byte) => byte.toString(16).padStart(2, "0")).join("");
|
|
9
|
+
return `${digits.slice(0, 8)}-${digits.slice(8, 12)}-${digits.slice(12, 16)}-${digits.slice(16, 20)}-${digits.slice(20)}`;
|
|
10
|
+
};
|
|
11
|
+
const format = (bytes, version) => {
|
|
12
|
+
const out = [...bytes];
|
|
13
|
+
out[6] = (out[6] ?? 0) & 15 | version << 4;
|
|
14
|
+
out[8] = (out[8] ?? 0) & 63 | 128;
|
|
15
|
+
return hex(out);
|
|
16
|
+
};
|
|
17
|
+
/** @internal */
|
|
18
|
+
const make = Effect.gen(function* () {
|
|
19
|
+
const bytes = yield* Effect.forEach(Array.from({ length: 16 }), () => Random.nextIntBetween(0, 255));
|
|
20
|
+
return format(bytes, 4);
|
|
21
|
+
});
|
|
22
|
+
const fnv1a = (key, round) => {
|
|
23
|
+
let hash = 2166136261 ^ round;
|
|
24
|
+
for (let i = 0; i < key.length; i++) hash = Math.imul(hash ^ key.charCodeAt(i), 16777619);
|
|
25
|
+
return hash >>> 0;
|
|
26
|
+
};
|
|
27
|
+
/** @internal */
|
|
28
|
+
const fromKey = (key) => format([
|
|
29
|
+
0,
|
|
30
|
+
1,
|
|
31
|
+
2,
|
|
32
|
+
3
|
|
33
|
+
].flatMap((round) => {
|
|
34
|
+
const hash = fnv1a(key, round);
|
|
35
|
+
return [
|
|
36
|
+
hash >>> 24,
|
|
37
|
+
hash >>> 16 & 255,
|
|
38
|
+
hash >>> 8 & 255,
|
|
39
|
+
hash & 255
|
|
40
|
+
];
|
|
41
|
+
}), 8);
|
|
42
|
+
//#endregion
|
|
43
|
+
export { Uuid, fromKey, make };
|
|
44
|
+
|
|
45
|
+
//# sourceMappingURL=uuid.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"uuid.js","names":[],"sources":["../../src/internal/uuid.ts"],"sourcesContent":["import * as Effect from \"effect/Effect\"\nimport * as Random from \"effect/Random\"\nimport * as Schema from \"effect/Schema\"\n\n/** @internal */\nexport const Uuid = Schema.String.check(Schema.isUUID())\n\nconst hex = (bytes: ReadonlyArray<number>): string => {\n const digits = bytes.map((byte) => byte.toString(16).padStart(2, \"0\")).join(\"\")\n\n return `${digits.slice(0, 8)}-${digits.slice(8, 12)}-${digits.slice(12, 16)}-${digits.slice(16, 20)}-${digits.slice(20)}`\n}\n\n// RFC 9562 version nibble and variant bits.\nconst format = (bytes: ReadonlyArray<number>, version: number): string => {\n const out = [...bytes]\n\n out[6] = ((out[6] ?? 0) & 0x0f) | (version << 4)\n out[8] = ((out[8] ?? 0) & 0x3f) | 0x80\n\n return hex(out)\n}\n\n// From the `Random` service, so a seeded test gets the same ids every run.\n/** @internal */\nexport const make: Effect.Effect<string> = Effect.gen(function* () {\n const bytes = yield* Effect.forEach(Array.from({ length: 16 }), () => Random.nextIntBetween(0, 255))\n\n return format(bytes, 4)\n})\n\nconst fnv1a = (key: string, round: number): number => {\n let hash = 0x811c9dc5 ^ round\n\n for (let i = 0; i < key.length; i++) hash = Math.imul(hash ^ key.charCodeAt(i), 0x01000193)\n\n return hash >>> 0\n}\n\n// Version 8: the same key gives the same UUID. Not a secret, only unlikely to collide: four 32-bit FNV-1a hashes.\n/** @internal */\nexport const fromKey = (key: string): string =>\n format(\n [0, 1, 2, 3].flatMap((round) => {\n const hash = fnv1a(key, round)\n\n return [hash >>> 24, (hash >>> 16) & 0xff, (hash >>> 8) & 0xff, hash & 0xff]\n }),\n 8\n )\n"],"mappings":";;;;;AAKA,MAAa,OAAO,OAAO,OAAO,MAAM,OAAO,OAAO,CAAC;AAEvD,MAAM,OAAO,UAAyC;CACpD,MAAM,SAAS,MAAM,KAAK,SAAS,KAAK,SAAS,EAAE,CAAC,CAAC,SAAS,GAAG,GAAG,CAAC,CAAC,CAAC,KAAK,EAAE;CAE9E,OAAO,GAAG,OAAO,MAAM,GAAG,CAAC,EAAE,GAAG,OAAO,MAAM,GAAG,EAAE,EAAE,GAAG,OAAO,MAAM,IAAI,EAAE,EAAE,GAAG,OAAO,MAAM,IAAI,EAAE,EAAE,GAAG,OAAO,MAAM,EAAE;AACxH;AAGA,MAAM,UAAU,OAA8B,YAA4B;CACxE,MAAM,MAAM,CAAC,GAAG,KAAK;CAErB,IAAI,MAAO,IAAI,MAAM,KAAK,KAAS,WAAW;CAC9C,IAAI,MAAO,IAAI,MAAM,KAAK,KAAQ;CAElC,OAAO,IAAI,GAAG;AAChB;;AAIA,MAAa,OAA8B,OAAO,IAAI,aAAa;CACjE,MAAM,QAAQ,OAAO,OAAO,QAAQ,MAAM,KAAK,EAAE,QAAQ,GAAG,CAAC,SAAS,OAAO,eAAe,GAAG,GAAG,CAAC;CAEnG,OAAO,OAAO,OAAO,CAAC;AACxB,CAAC;AAED,MAAM,SAAS,KAAa,UAA0B;CACpD,IAAI,OAAO,aAAa;CAExB,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK,OAAO,KAAK,KAAK,OAAO,IAAI,WAAW,CAAC,GAAG,QAAU;CAE1F,OAAO,SAAS;AAClB;;AAIA,MAAa,WAAW,QACtB,OACE;CAAC;CAAG;CAAG;CAAG;AAAC,CAAC,CAAC,SAAS,UAAU;CAC9B,MAAM,OAAO,MAAM,KAAK,KAAK;CAE7B,OAAO;EAAC,SAAS;EAAK,SAAS,KAAM;EAAO,SAAS,IAAK;EAAM,OAAO;CAAI;AAC7E,CAAC,GACD,CACF"}
|
|
@@ -0,0 +1,12 @@
|
|
|
1
|
+
import { ChatId } from "../ChatId.js";
|
|
2
|
+
import { AssistantEvent, AssistantEvent_d_exports, Entry, StoredAppEvent } from "../AssistantEvent.js";
|
|
3
|
+
import * as Effect from "effect/Effect";
|
|
4
|
+
//#region src/internal/writer.d.ts
|
|
5
|
+
/** @internal */
|
|
6
|
+
export interface Writer {
|
|
7
|
+
readonly chatId: ChatId;
|
|
8
|
+
readonly entries: Effect.Effect<ReadonlyArray<Entry>>;
|
|
9
|
+
readonly append: (events: ReadonlyArray<AssistantEvent | StoredAppEvent>) => Effect.Effect<ReadonlyArray<Entry>>;
|
|
10
|
+
}
|
|
11
|
+
//#endregion
|
|
12
|
+
//# sourceMappingURL=writer.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"writer.d.ts","names":[],"sources":["../../src/internal/writer.ts"],"mappings":";;;;;iBAKiB;WACN,QAAQ;WACR,SAAS,OAAO,OAAO,cAAc;WACrC,SACP,QAAQ,cAAc,iBAAgC,oBACnD,OAAO,OAAO,cAAc"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,54 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "effect-assistant",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.0",
|
|
4
|
+
"description": "A colleague assistant on Effect: an append-only event log per chat, an interruptible agent loop, specialists, skills, and UI blocks",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/dbrxnds/effect-assistant.git",
|
|
9
|
+
"directory": "packages/effect-assistant"
|
|
10
|
+
},
|
|
11
|
+
"files": [
|
|
12
|
+
"src/**/*.ts",
|
|
13
|
+
"dist/**/*.js",
|
|
14
|
+
"dist/**/*.js.map",
|
|
15
|
+
"dist/**/*.d.ts",
|
|
16
|
+
"dist/**/*.d.ts.map"
|
|
17
|
+
],
|
|
18
|
+
"type": "module",
|
|
19
|
+
"sideEffects": [],
|
|
20
|
+
"exports": {
|
|
21
|
+
"./package.json": "./package.json",
|
|
22
|
+
".": {
|
|
23
|
+
"types": "./dist/index.d.ts",
|
|
24
|
+
"default": "./dist/index.js"
|
|
25
|
+
},
|
|
26
|
+
"./*": {
|
|
27
|
+
"types": "./dist/*.d.ts",
|
|
28
|
+
"default": "./dist/*.js"
|
|
29
|
+
},
|
|
30
|
+
"./internal/*": null
|
|
31
|
+
},
|
|
32
|
+
"publishConfig": {
|
|
33
|
+
"access": "public",
|
|
34
|
+
"provenance": true
|
|
35
|
+
},
|
|
36
|
+
"devDependencies": {
|
|
37
|
+
"@effect/ai-anthropic": "4.0.0",
|
|
38
|
+
"@effect/sql-sqlite-node": "4.0.0",
|
|
39
|
+
"@effect/vitest": "4.0.0",
|
|
40
|
+
"@types/node": "^22.15.3",
|
|
41
|
+
"effect": "4.0.0",
|
|
42
|
+
"typescript": "7.0.2",
|
|
43
|
+
"vite-plus": "1.0.0-rc.0",
|
|
44
|
+
"vitest": "5.0.1"
|
|
45
|
+
},
|
|
46
|
+
"peerDependencies": {
|
|
47
|
+
"effect": "^4.0.0"
|
|
48
|
+
},
|
|
49
|
+
"scripts": {
|
|
50
|
+
"build": "vp pack",
|
|
51
|
+
"test": "vp test run --exclude test/contract.test.ts",
|
|
52
|
+
"test:contract": "vp test run test/contract.test.ts"
|
|
53
|
+
}
|
|
6
54
|
}
|
package/src/AppEvent.ts
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Registers an application's own events with an assistant.
|
|
3
|
+
*
|
|
4
|
+
* An app event is a tagged schema for something the application reports into a chat, such as a
|
|
5
|
+
* workflow's progress, a webhook, a summary for compaction, or the draft the user opened.
|
|
6
|
+
* {@link make} registers one with two choices: whether storing it wakes a turn (`wakes`), and
|
|
7
|
+
* how the model reads it (`render`).
|
|
8
|
+
*
|
|
9
|
+
* @since 0.1.0
|
|
10
|
+
*/
|
|
11
|
+
import * as Predicate from "effect/Predicate"
|
|
12
|
+
import type * as Schema from "effect/Schema"
|
|
13
|
+
import * as SchemaAST from "effect/SchemaAST"
|
|
14
|
+
|
|
15
|
+
/**
|
|
16
|
+
* Schema for one of the application's own events.
|
|
17
|
+
*
|
|
18
|
+
* It is a tagged struct or class (`Schema.TaggedStruct`, `Schema.TaggedClass`) that needs no
|
|
19
|
+
* services.
|
|
20
|
+
*
|
|
21
|
+
* @category models
|
|
22
|
+
* @since 0.1.0
|
|
23
|
+
*/
|
|
24
|
+
export type EventSchema = Schema.Codec<{ readonly _tag: string }, { readonly _tag: string }> & {
|
|
25
|
+
readonly fields: { readonly _tag: { readonly ast: SchemaAST.AST } }
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* Describes how the model reads an event.
|
|
30
|
+
*
|
|
31
|
+
* `"json"` shows the event's tag and fields as JSON. A function shows the text it returns for the
|
|
32
|
+
* event.
|
|
33
|
+
*
|
|
34
|
+
* @category models
|
|
35
|
+
* @since 0.1.0
|
|
36
|
+
*/
|
|
37
|
+
export type Render<A> = "json" | ((event: A) => string)
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Represents one of the application's events, registered with an assistant.
|
|
41
|
+
*
|
|
42
|
+
* It holds the event's schema and tag, whether storing it wakes a turn, and how the model reads
|
|
43
|
+
* it. A `render` of `undefined` means the model doesn't read it.
|
|
44
|
+
*
|
|
45
|
+
* @category models
|
|
46
|
+
* @since 0.1.0
|
|
47
|
+
*/
|
|
48
|
+
export interface AppEvent<S extends EventSchema = EventSchema> {
|
|
49
|
+
readonly schema: S
|
|
50
|
+
readonly tag: string
|
|
51
|
+
readonly wakes: boolean
|
|
52
|
+
readonly render: Render<S["Type"]> | undefined
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* Represents any registered event, for generic constraints.
|
|
57
|
+
*
|
|
58
|
+
* @category utility types
|
|
59
|
+
* @since 0.1.0
|
|
60
|
+
*/
|
|
61
|
+
export type Any = AppEvent<any>
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Extracts the type of a registered event's values.
|
|
65
|
+
*
|
|
66
|
+
* @category utility types
|
|
67
|
+
* @since 0.1.0
|
|
68
|
+
*/
|
|
69
|
+
export type Type<E extends Any> = E["schema"]["Type"]
|
|
70
|
+
|
|
71
|
+
const tagOf = (schema: EventSchema): string => {
|
|
72
|
+
const ast = schema.fields._tag.ast
|
|
73
|
+
|
|
74
|
+
if (SchemaAST.isLiteral(ast) && Predicate.isString(ast.literal)) return ast.literal
|
|
75
|
+
|
|
76
|
+
throw new Error("An app event is a tagged struct or class.")
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/**
|
|
80
|
+
* Registers one of the application's events with an assistant.
|
|
81
|
+
*
|
|
82
|
+
* **Details**
|
|
83
|
+
*
|
|
84
|
+
* Storing the event wakes a turn only when `wakes` is `true`; it defaults to `false`. `render`
|
|
85
|
+
* defaults to `"json"` for an event that wakes a turn. An event that doesn't wake a turn and has
|
|
86
|
+
* no `render` isn't read by the model.
|
|
87
|
+
*
|
|
88
|
+
* The schema must be a tagged struct or class whose `_tag` is a string literal; `make` throws
|
|
89
|
+
* otherwise.
|
|
90
|
+
*
|
|
91
|
+
* **Example** (Registering an event that wakes a turn)
|
|
92
|
+
*
|
|
93
|
+
* ```ts
|
|
94
|
+
* import { AppEvent, Assistant, InputId } from "effect-assistant"
|
|
95
|
+
* import * as Schema from "effect/Schema"
|
|
96
|
+
*
|
|
97
|
+
* class OrderShipped extends Schema.TaggedClass<OrderShipped>()("OrderShipped", {
|
|
98
|
+
* id: InputId.InputId,
|
|
99
|
+
* orderId: Schema.String,
|
|
100
|
+
* carrier: Schema.String
|
|
101
|
+
* }) {}
|
|
102
|
+
*
|
|
103
|
+
* export const MyAssistant = Assistant.make("my-assistant", {
|
|
104
|
+
* events: [
|
|
105
|
+
* AppEvent.make(OrderShipped, {
|
|
106
|
+
* wakes: true,
|
|
107
|
+
* render: (shipped) =>
|
|
108
|
+
* `Order ${shipped.orderId} shipped with ${shipped.carrier}. Tell the user if it matters.`
|
|
109
|
+
* })
|
|
110
|
+
* ]
|
|
111
|
+
* })
|
|
112
|
+
* ```
|
|
113
|
+
*
|
|
114
|
+
* @category constructors
|
|
115
|
+
* @since 0.1.0
|
|
116
|
+
*/
|
|
117
|
+
export const make = <S extends EventSchema>(
|
|
118
|
+
schema: S,
|
|
119
|
+
options?: {
|
|
120
|
+
/** Whether storing it starts a turn, like a user's message. Default false. */
|
|
121
|
+
readonly wakes?: boolean | undefined
|
|
122
|
+
/** How the model reads it in its history. */
|
|
123
|
+
readonly render?: Render<S["Type"]> | undefined
|
|
124
|
+
}
|
|
125
|
+
): AppEvent<S> => {
|
|
126
|
+
const wakes = options?.wakes ?? false
|
|
127
|
+
|
|
128
|
+
return {
|
|
129
|
+
schema,
|
|
130
|
+
tag: tagOf(schema),
|
|
131
|
+
wakes,
|
|
132
|
+
render: options?.render ?? (wakes ? "json" : undefined)
|
|
133
|
+
}
|
|
134
|
+
}
|