@tinyweb_dev/agent-framework-agent 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/dist/agent.d.ts +116 -0
- package/dist/agent.d.ts.map +1 -0
- package/dist/attachments.d.ts +41 -0
- package/dist/attachments.d.ts.map +1 -0
- package/dist/bus/bus.d.ts +46 -0
- package/dist/bus/bus.d.ts.map +1 -0
- package/dist/bus/index.d.ts +2 -0
- package/dist/bus/index.d.ts.map +1 -0
- package/dist/define-tool.d.ts +13 -0
- package/dist/define-tool.d.ts.map +1 -0
- package/dist/events.d.ts +136 -0
- package/dist/events.d.ts.map +1 -0
- package/dist/http-handlers.cjs +253 -0
- package/dist/http-handlers.cjs.map +1 -0
- package/dist/http-handlers.d.ts +49 -0
- package/dist/http-handlers.d.ts.map +1 -0
- package/dist/http-handlers.js +251 -0
- package/dist/http-handlers.js.map +1 -0
- package/dist/index.cjs +2073 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.ts +19 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +2015 -0
- package/dist/index.js.map +1 -0
- package/dist/loop-guard.d.ts +42 -0
- package/dist/loop-guard.d.ts.map +1 -0
- package/dist/mcp/client.d.ts +25 -0
- package/dist/mcp/client.d.ts.map +1 -0
- package/dist/mcp/index.cjs +66 -0
- package/dist/mcp/index.cjs.map +1 -0
- package/{src/mcp/index.ts → dist/mcp/index.d.ts} +2 -1
- package/dist/mcp/index.d.ts.map +1 -0
- package/dist/mcp/index.js +63 -0
- package/dist/mcp/index.js.map +1 -0
- package/dist/permission.d.ts +26 -0
- package/dist/permission.d.ts.map +1 -0
- package/dist/plugin/apply.d.ts +12 -0
- package/dist/plugin/apply.d.ts.map +1 -0
- package/dist/plugin/index.cjs +63 -0
- package/dist/plugin/index.cjs.map +1 -0
- package/dist/plugin/index.d.ts +4 -0
- package/dist/plugin/index.d.ts.map +1 -0
- package/dist/plugin/index.js +52 -0
- package/dist/plugin/index.js.map +1 -0
- package/dist/plugin/loader.d.ts +3 -0
- package/dist/plugin/loader.d.ts.map +1 -0
- package/dist/plugin/types.d.ts +98 -0
- package/dist/plugin/types.d.ts.map +1 -0
- package/dist/prompt/index.d.ts +51 -0
- package/dist/prompt/index.d.ts.map +1 -0
- package/dist/prompt/objective.d.ts +29 -0
- package/dist/prompt/objective.d.ts.map +1 -0
- package/dist/prompt/response-style.d.ts +19 -0
- package/dist/prompt/response-style.d.ts.map +1 -0
- package/dist/prompt/tool-use-guidelines.d.ts +22 -0
- package/dist/prompt/tool-use-guidelines.d.ts.map +1 -0
- package/dist/prompt/tool-use.d.ts +12 -0
- package/dist/prompt/tool-use.d.ts.map +1 -0
- package/dist/runtime.d.ts +7 -0
- package/dist/runtime.d.ts.map +1 -0
- package/dist/session/adapter.d.ts +40 -0
- package/dist/session/adapter.d.ts.map +1 -0
- package/dist/session/compaction.d.ts +37 -0
- package/dist/session/compaction.d.ts.map +1 -0
- package/dist/session/index.d.ts +7 -0
- package/dist/session/index.d.ts.map +1 -0
- package/dist/session/memory.cjs +130 -0
- package/dist/session/memory.cjs.map +1 -0
- package/dist/session/memory.d.ts +3 -0
- package/dist/session/memory.d.ts.map +1 -0
- package/dist/session/memory.js +128 -0
- package/dist/session/memory.js.map +1 -0
- package/dist/session/overflow.d.ts +19 -0
- package/dist/session/overflow.d.ts.map +1 -0
- package/dist/session/postgres.cjs +245 -0
- package/dist/session/postgres.cjs.map +1 -0
- package/dist/session/postgres.d.ts +10 -0
- package/dist/session/postgres.d.ts.map +1 -0
- package/dist/session/postgres.js +243 -0
- package/dist/session/postgres.js.map +1 -0
- package/dist/session/processor.d.ts +52 -0
- package/dist/session/processor.d.ts.map +1 -0
- package/dist/session/replay.d.ts +4 -0
- package/dist/session/replay.d.ts.map +1 -0
- package/dist/session/schema.d.ts +104 -0
- package/dist/session/schema.d.ts.map +1 -0
- package/dist/session/sqlite.cjs +236 -0
- package/dist/session/sqlite.cjs.map +1 -0
- package/dist/session/sqlite.d.ts +3 -0
- package/dist/session/sqlite.d.ts.map +1 -0
- package/dist/session/sqlite.js +234 -0
- package/dist/session/sqlite.js.map +1 -0
- package/dist/session-api.cjs +56 -0
- package/dist/session-api.cjs.map +1 -0
- package/dist/session-api.d.ts +36 -0
- package/dist/session-api.d.ts.map +1 -0
- package/dist/session-api.js +54 -0
- package/dist/session-api.js.map +1 -0
- package/dist/skill/index.cjs +81 -0
- package/dist/skill/index.cjs.map +1 -0
- package/dist/skill/index.d.ts +10 -0
- package/dist/skill/index.d.ts.map +1 -0
- package/dist/skill/index.js +78 -0
- package/dist/skill/index.js.map +1 -0
- package/dist/sse-handler.d.ts +27 -0
- package/dist/sse-handler.d.ts.map +1 -0
- package/dist/transcript.d.ts +81 -0
- package/dist/transcript.d.ts.map +1 -0
- package/package.json +54 -19
- package/src/agent.ts +0 -317
- package/src/attachments.ts +0 -155
- package/src/bus/bus.ts +0 -89
- package/src/bus/index.ts +0 -1
- package/src/define-tool.ts +0 -41
- package/src/events.ts +0 -162
- package/src/http-handlers.ts +0 -251
- package/src/index.ts +0 -120
- package/src/loop-guard.ts +0 -99
- package/src/mcp/client.ts +0 -110
- package/src/permission.ts +0 -72
- package/src/plugin/apply.ts +0 -89
- package/src/plugin/index.ts +0 -3
- package/src/plugin/loader.ts +0 -42
- package/src/plugin/types.ts +0 -134
- package/src/prompt/index.ts +0 -90
- package/src/prompt/objective.ts +0 -104
- package/src/prompt/response-style.ts +0 -59
- package/src/prompt/tool-use-guidelines.ts +0 -57
- package/src/prompt/tool-use.ts +0 -27
- package/src/runtime.ts +0 -22
- package/src/session/adapter.ts +0 -37
- package/src/session/compaction.ts +0 -160
- package/src/session/index.ts +0 -11
- package/src/session/memory.ts +0 -154
- package/src/session/overflow.ts +0 -50
- package/src/session/postgres.ts +0 -330
- package/src/session/processor.ts +0 -500
- package/src/session/replay.ts +0 -140
- package/src/session/schema.ts +0 -140
- package/src/session/sqlite.ts +0 -281
- package/src/session-api.ts +0 -103
- package/src/skill/index.ts +0 -113
- package/src/sse-handler.ts +0 -67
- package/src/transcript.ts +0 -126
package/dist/index.cjs
ADDED
|
@@ -0,0 +1,2073 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
var llm = require('@tinyweb_dev/agent-framework-llm');
|
|
4
|
+
var effect = require('effect');
|
|
5
|
+
var core = require('@tinyweb_dev/agent-framework-core');
|
|
6
|
+
var protocol = require('@tinyweb_dev/agent-framework-protocol');
|
|
7
|
+
var index_js = require('@modelcontextprotocol/sdk/client/index.js');
|
|
8
|
+
var stdio_js = require('@modelcontextprotocol/sdk/client/stdio.js');
|
|
9
|
+
var streamableHttp_js = require('@modelcontextprotocol/sdk/client/streamableHttp.js');
|
|
10
|
+
var promises = require('fs/promises');
|
|
11
|
+
var path = require('path');
|
|
12
|
+
var os = require('os');
|
|
13
|
+
|
|
14
|
+
// src/agent.ts
|
|
15
|
+
|
|
16
|
+
// src/session/overflow.ts
|
|
17
|
+
var DEFAULT_OUTPUT_RESERVE = 2e4;
|
|
18
|
+
var textFromPart = (part) => {
|
|
19
|
+
if (part.type === "text") return part.text;
|
|
20
|
+
if (part.type === "reasoning") return part.text;
|
|
21
|
+
return "";
|
|
22
|
+
};
|
|
23
|
+
var estimateTokens = (msgs) => {
|
|
24
|
+
const totalChars = msgs.reduce(
|
|
25
|
+
(acc, msg) => acc + msg.parts.reduce((sum, part) => sum + textFromPart(part).length, 0),
|
|
26
|
+
0
|
|
27
|
+
);
|
|
28
|
+
return Math.ceil(totalChars / 4);
|
|
29
|
+
};
|
|
30
|
+
var usable = (input) => {
|
|
31
|
+
const context = input.limits?.context;
|
|
32
|
+
if (context === void 0 || context <= 0) return Number.POSITIVE_INFINITY;
|
|
33
|
+
const output = input.limits?.output ?? DEFAULT_OUTPUT_RESERVE;
|
|
34
|
+
const reserved = input.reservedTokens ?? Math.min(DEFAULT_OUTPUT_RESERVE, output);
|
|
35
|
+
const budget = context - reserved;
|
|
36
|
+
return budget > 0 ? budget : Math.floor(context * 0.9);
|
|
37
|
+
};
|
|
38
|
+
var isOverflowEstimate = (tokens, budget) => tokens >= budget;
|
|
39
|
+
var isOverflow = (msgs, budget) => isOverflowEstimate(estimateTokens(msgs), budget);
|
|
40
|
+
var newSessionID = () => core.Id.prefixed("ses");
|
|
41
|
+
var newMessageID = () => core.Id.prefixed("msg");
|
|
42
|
+
var newPartID = () => core.Id.prefixed("prt");
|
|
43
|
+
var makeUserMessage = (input) => {
|
|
44
|
+
const text = typeof input === "string" ? input : input.text;
|
|
45
|
+
const images = typeof input === "string" ? [] : input.images ?? [];
|
|
46
|
+
const parts = [];
|
|
47
|
+
if (text.length > 0) parts.push({ type: "text", text });
|
|
48
|
+
for (const img of images) parts.push(img);
|
|
49
|
+
return { id: newMessageID(), role: "user", parts };
|
|
50
|
+
};
|
|
51
|
+
var makeAssistantMessage = (parts) => ({
|
|
52
|
+
id: newMessageID(),
|
|
53
|
+
role: "assistant",
|
|
54
|
+
parts
|
|
55
|
+
});
|
|
56
|
+
var makeCompactionMessage = (input) => ({
|
|
57
|
+
id: newMessageID(),
|
|
58
|
+
role: "user",
|
|
59
|
+
parts: [
|
|
60
|
+
{
|
|
61
|
+
type: "compaction",
|
|
62
|
+
summary: input.summary,
|
|
63
|
+
tailStartId: input.tailStartId,
|
|
64
|
+
auto: input.auto ?? true,
|
|
65
|
+
overflow: input.overflow ?? false
|
|
66
|
+
}
|
|
67
|
+
]
|
|
68
|
+
});
|
|
69
|
+
var findCompactionPart = (msg) => {
|
|
70
|
+
if (msg.role !== "user") return void 0;
|
|
71
|
+
return msg.parts.find((p) => p.type === "compaction");
|
|
72
|
+
};
|
|
73
|
+
|
|
74
|
+
// src/session/compaction.ts
|
|
75
|
+
var SUMMARY_PROMPT = `You are a conversation summarizer. Summarize the entire conversation below into a concise factual summary (1-3 paragraphs) that preserves: user intent, key facts established, decisions made, and outstanding tasks. Do not add commentary.`;
|
|
76
|
+
var SUMMARY_FALLBACK_MAX_CHARS = 2e5;
|
|
77
|
+
var partText = (part) => {
|
|
78
|
+
const tagged = part;
|
|
79
|
+
if (tagged.type === "text") return tagged.text ?? "";
|
|
80
|
+
if (tagged.type === "reasoning") return tagged.text ?? "";
|
|
81
|
+
if (tagged.type === "compaction") return `[previous summary] ${tagged.summary ?? ""}`;
|
|
82
|
+
return "";
|
|
83
|
+
};
|
|
84
|
+
var messageToWireText = (msg) => {
|
|
85
|
+
const role = msg.role.toUpperCase();
|
|
86
|
+
const text = msg.parts.map((p) => partText(p)).filter((s) => s.length > 0).join("\n");
|
|
87
|
+
return `[${role}] ${text}`;
|
|
88
|
+
};
|
|
89
|
+
var truncateForSummary = (transcript, max) => {
|
|
90
|
+
if (transcript.length <= max) return transcript;
|
|
91
|
+
const half = Math.floor(max / 2) - 64;
|
|
92
|
+
return `${transcript.slice(0, half)}
|
|
93
|
+
|
|
94
|
+
[... ${transcript.length - max} chars elided ...]
|
|
95
|
+
|
|
96
|
+
${transcript.slice(-half)}`;
|
|
97
|
+
};
|
|
98
|
+
var compact = (input) => effect.Effect.gen(function* () {
|
|
99
|
+
const keepRecent = input.keepRecent ?? 4;
|
|
100
|
+
const all = yield* input.store.getMessages(input.sessionId);
|
|
101
|
+
if (all.length <= keepRecent + 1) return { compacted: false };
|
|
102
|
+
const lastMarkerIdx = (() => {
|
|
103
|
+
for (let i = all.length - 1; i >= 0; i--) {
|
|
104
|
+
if (findCompactionPart(all[i])) return i;
|
|
105
|
+
}
|
|
106
|
+
return -1;
|
|
107
|
+
})();
|
|
108
|
+
const head = all.slice(lastMarkerIdx + 1, Math.max(lastMarkerIdx + 1, all.length - keepRecent));
|
|
109
|
+
if (head.length === 0) return { compacted: false };
|
|
110
|
+
const tail = all.slice(all.length - keepRecent);
|
|
111
|
+
const tailStartId = tail[0]?.id;
|
|
112
|
+
const transcript = truncateForSummary(
|
|
113
|
+
head.map(messageToWireText).join("\n\n"),
|
|
114
|
+
SUMMARY_FALLBACK_MAX_CHARS
|
|
115
|
+
);
|
|
116
|
+
const request = llm.LLM.request({
|
|
117
|
+
model: input.model,
|
|
118
|
+
system: SUMMARY_PROMPT,
|
|
119
|
+
messages: [llm.LLM.user(`Conversation transcript to summarize:
|
|
120
|
+
|
|
121
|
+
${transcript}`)]
|
|
122
|
+
});
|
|
123
|
+
const response = yield* llm.LLMClient.generate(request);
|
|
124
|
+
const summary = response.text.trim().length > 0 ? response.text : extractFallbackSummary(head);
|
|
125
|
+
const marker = makeCompactionMessage({
|
|
126
|
+
summary,
|
|
127
|
+
tailStartId,
|
|
128
|
+
auto: true,
|
|
129
|
+
overflow: input.overflow ?? false
|
|
130
|
+
});
|
|
131
|
+
yield* input.store.appendMessage(input.sessionId, marker);
|
|
132
|
+
const prevTokens = estimateTokens(head);
|
|
133
|
+
const newTokens = estimateTokens([marker, ...tail]);
|
|
134
|
+
const usage = response.usage;
|
|
135
|
+
const cost = typeof usage?.cost === "number" ? usage.cost : void 0;
|
|
136
|
+
return {
|
|
137
|
+
compacted: true,
|
|
138
|
+
summary,
|
|
139
|
+
markerId: marker.id,
|
|
140
|
+
tailStartId,
|
|
141
|
+
prevTokens,
|
|
142
|
+
newTokens,
|
|
143
|
+
cost,
|
|
144
|
+
modelId: input.model.id
|
|
145
|
+
};
|
|
146
|
+
});
|
|
147
|
+
var extractFallbackSummary = (msgs) => {
|
|
148
|
+
const lines = msgs.flatMap(
|
|
149
|
+
(m) => m.parts.map((p) => p.type === "text" ? p.text : "").filter((s) => s.length > 0)
|
|
150
|
+
);
|
|
151
|
+
const head = lines.slice(0, 4).join(" ");
|
|
152
|
+
return `Compacted ${msgs.length} prior message(s). ${head.slice(0, 400)}`;
|
|
153
|
+
};
|
|
154
|
+
|
|
155
|
+
// src/events.ts
|
|
156
|
+
var FINISH_REASON_APPROVAL_REQUIRED = "approval-required";
|
|
157
|
+
var fromLLMEvent = (event) => {
|
|
158
|
+
if (event.type === "text-delta") return { type: "text-delta", id: event.id, text: event.text };
|
|
159
|
+
if (event.type === "text-end") return { type: "text-end", id: event.id };
|
|
160
|
+
if (event.type === "reasoning-delta") return { type: "reasoning-delta", id: event.id, text: event.text };
|
|
161
|
+
if (event.type === "tool-call") return { type: "tool-call", id: event.id, name: event.name, input: event.input };
|
|
162
|
+
if (event.type === "tool-result")
|
|
163
|
+
return { type: "tool-result", id: event.id, name: event.name, result: event.result.value };
|
|
164
|
+
if (event.type === "tool-error")
|
|
165
|
+
return {
|
|
166
|
+
type: "tool-error",
|
|
167
|
+
id: event.id,
|
|
168
|
+
name: event.name,
|
|
169
|
+
message: event.message,
|
|
170
|
+
metadata: event.metadata
|
|
171
|
+
};
|
|
172
|
+
if (event.type === "step-finish")
|
|
173
|
+
return { type: "step-finish", index: event.index, reason: event.reason, usage: event.usage };
|
|
174
|
+
if (event.type === "request-finish") return { type: "finish", reason: event.reason, usage: event.usage };
|
|
175
|
+
if (event.type === "provider-error")
|
|
176
|
+
return { type: "error", message: event.message, retryable: event.retryable };
|
|
177
|
+
return void 0;
|
|
178
|
+
};
|
|
179
|
+
var TOOL_INTERRUPT_KIND = "tool-interrupt";
|
|
180
|
+
var isToolInterruptMetadata = (metadata) => metadata?.kind === TOOL_INTERRUPT_KIND;
|
|
181
|
+
var toolInterruptFailure = (toolName, input) => new llm.ToolFailure({
|
|
182
|
+
message: `Tool "${toolName}" requires user approval`,
|
|
183
|
+
metadata: {
|
|
184
|
+
kind: TOOL_INTERRUPT_KIND,
|
|
185
|
+
toolName,
|
|
186
|
+
input
|
|
187
|
+
}
|
|
188
|
+
});
|
|
189
|
+
var resolveRule = (config, toolName) => {
|
|
190
|
+
if (config === void 0) return "allow";
|
|
191
|
+
if (typeof config === "string") return config;
|
|
192
|
+
return config[toolName] ?? "allow";
|
|
193
|
+
};
|
|
194
|
+
var deniedFailure = (toolName) => new llm.ToolFailure({ message: `Tool "${toolName}" denied by permission policy` });
|
|
195
|
+
var askDeniedFailure = (toolName) => new llm.ToolFailure({ message: `Tool "${toolName}" denied by permission ask handler` });
|
|
196
|
+
var wrapTool = (name, base, rule, askHandler, askMode) => {
|
|
197
|
+
if (rule === "allow") return base;
|
|
198
|
+
if (rule === "deny") {
|
|
199
|
+
return llm.Tool.make({
|
|
200
|
+
description: base.description,
|
|
201
|
+
parameters: base.parameters,
|
|
202
|
+
success: base.success,
|
|
203
|
+
execute: () => effect.Effect.fail(deniedFailure(name))
|
|
204
|
+
});
|
|
205
|
+
}
|
|
206
|
+
if (askMode === "interrupt") {
|
|
207
|
+
return llm.Tool.make({
|
|
208
|
+
description: base.description,
|
|
209
|
+
parameters: base.parameters,
|
|
210
|
+
success: base.success,
|
|
211
|
+
execute: (input) => effect.Effect.fail(toolInterruptFailure(name, input))
|
|
212
|
+
});
|
|
213
|
+
}
|
|
214
|
+
return llm.Tool.make({
|
|
215
|
+
description: base.description,
|
|
216
|
+
parameters: base.parameters,
|
|
217
|
+
success: base.success,
|
|
218
|
+
execute: (input) => effect.Effect.gen(function* () {
|
|
219
|
+
const allowed = yield* effect.Effect.tryPromise({
|
|
220
|
+
try: () => askHandler ? askHandler({ toolName: name, input }) : Promise.resolve(false),
|
|
221
|
+
catch: (cause) => new llm.ToolFailure({ message: `Permission ask handler threw: ${String(cause)}` })
|
|
222
|
+
});
|
|
223
|
+
if (!allowed) return yield* effect.Effect.fail(askDeniedFailure(name));
|
|
224
|
+
return yield* base.execute(input);
|
|
225
|
+
})
|
|
226
|
+
});
|
|
227
|
+
};
|
|
228
|
+
var applyPermission = (tools, config, askHandler, askMode = "handler") => {
|
|
229
|
+
if (config === void 0) return tools;
|
|
230
|
+
const out = {};
|
|
231
|
+
const names = Object.keys(tools);
|
|
232
|
+
for (const name of names) {
|
|
233
|
+
const tool = tools[name];
|
|
234
|
+
if (!tool) continue;
|
|
235
|
+
out[name] = wrapTool(name, tool, resolveRule(config, name), askHandler, askMode);
|
|
236
|
+
}
|
|
237
|
+
return out;
|
|
238
|
+
};
|
|
239
|
+
var mainLayer = llm.LLMClient.layer.pipe(effect.Layer.provide(llm.RequestExecutor.defaultLayer));
|
|
240
|
+
var cached;
|
|
241
|
+
var createRuntime = () => effect.ManagedRuntime.make(mainLayer);
|
|
242
|
+
var defaultRuntime = () => {
|
|
243
|
+
if (cached) return cached;
|
|
244
|
+
cached = createRuntime();
|
|
245
|
+
return cached;
|
|
246
|
+
};
|
|
247
|
+
var disposeDefaultRuntime = async () => {
|
|
248
|
+
if (!cached) return;
|
|
249
|
+
await cached.dispose();
|
|
250
|
+
cached = void 0;
|
|
251
|
+
};
|
|
252
|
+
var COMPACTION_PREFIX = "[Compacted conversation summary]";
|
|
253
|
+
var MAX_TOOL_OUTPUT_CHARS = 6e4;
|
|
254
|
+
var TRUNCATION_NOTE = (elided) => `
|
|
255
|
+
|
|
256
|
+
[... ${elided} chars elided by tinyweb-agent \u2014 output exceeded ${MAX_TOOL_OUTPUT_CHARS} chars ...]
|
|
257
|
+
|
|
258
|
+
`;
|
|
259
|
+
var truncateToolOutput = (output) => {
|
|
260
|
+
if (output === void 0 || output === null) return output;
|
|
261
|
+
if (typeof output === "string") {
|
|
262
|
+
if (output.length <= MAX_TOOL_OUTPUT_CHARS) return output;
|
|
263
|
+
const half2 = Math.floor(MAX_TOOL_OUTPUT_CHARS / 2) - 64;
|
|
264
|
+
return `${output.slice(0, half2)}${TRUNCATION_NOTE(output.length - MAX_TOOL_OUTPUT_CHARS)}${output.slice(-half2)}`;
|
|
265
|
+
}
|
|
266
|
+
const serialised = (() => {
|
|
267
|
+
try {
|
|
268
|
+
return JSON.stringify(output);
|
|
269
|
+
} catch {
|
|
270
|
+
return String(output);
|
|
271
|
+
}
|
|
272
|
+
})();
|
|
273
|
+
if (serialised.length <= MAX_TOOL_OUTPUT_CHARS) return output;
|
|
274
|
+
const half = Math.floor(MAX_TOOL_OUTPUT_CHARS / 2) - 64;
|
|
275
|
+
return `${serialised.slice(0, half)}${TRUNCATION_NOTE(serialised.length - MAX_TOOL_OUTPUT_CHARS)}${serialised.slice(-half)}`;
|
|
276
|
+
};
|
|
277
|
+
var textOf = (msg) => msg.parts.map((p) => p.type === "text" ? p.text : "").filter((s) => s.length > 0).join("\n");
|
|
278
|
+
var imagePartToMedia = (part) => {
|
|
279
|
+
const data = part.url ?? part.data;
|
|
280
|
+
if (!data) return void 0;
|
|
281
|
+
return { type: "media", mediaType: part.mediaType ?? "image/png", data };
|
|
282
|
+
};
|
|
283
|
+
var expandMessage = (msg) => {
|
|
284
|
+
if (msg.role === "user") {
|
|
285
|
+
const content = [];
|
|
286
|
+
const text2 = textOf(msg);
|
|
287
|
+
if (text2.length > 0) content.push({ type: "text", text: text2 });
|
|
288
|
+
for (const p of msg.parts) {
|
|
289
|
+
if (p.type !== "image") continue;
|
|
290
|
+
const media = imagePartToMedia(p);
|
|
291
|
+
if (media) content.push(media);
|
|
292
|
+
}
|
|
293
|
+
return content.length > 0 ? [llm.LLM.user(content)] : [];
|
|
294
|
+
}
|
|
295
|
+
const text = textOf(msg);
|
|
296
|
+
const toolParts = msg.parts.filter((p) => p.type === "tool");
|
|
297
|
+
const completed = toolParts.filter(
|
|
298
|
+
(t) => t.state === "complete" || t.state === "error" || t.state === "rejected"
|
|
299
|
+
);
|
|
300
|
+
if (text.length === 0 && completed.length === 0) return [];
|
|
301
|
+
const assistantContent = [];
|
|
302
|
+
if (text.length > 0) assistantContent.push(llm.LLM.text(text));
|
|
303
|
+
for (const t of completed) {
|
|
304
|
+
assistantContent.push(llm.LLM.toolCall({ id: t.callID, name: t.name, input: t.input }));
|
|
305
|
+
}
|
|
306
|
+
const out = [];
|
|
307
|
+
if (assistantContent.length > 0) out.push(llm.LLM.assistant(assistantContent));
|
|
308
|
+
for (const t of completed) {
|
|
309
|
+
const isError = t.state === "error" || t.state === "rejected";
|
|
310
|
+
const result = t.output !== void 0 ? t.output : isError ? { message: t.state === "rejected" ? "User denied tool execution" : "Tool failed" } : void 0;
|
|
311
|
+
out.push(
|
|
312
|
+
llm.LLM.toolMessage({
|
|
313
|
+
id: t.callID,
|
|
314
|
+
name: t.name,
|
|
315
|
+
result: truncateToolOutput(result),
|
|
316
|
+
resultType: isError ? "error" : "json"
|
|
317
|
+
})
|
|
318
|
+
);
|
|
319
|
+
}
|
|
320
|
+
return out;
|
|
321
|
+
};
|
|
322
|
+
var historyToLLMMessages = (messages) => {
|
|
323
|
+
let markerIdx = -1;
|
|
324
|
+
for (let i = messages.length - 1; i >= 0; i--) {
|
|
325
|
+
if (findCompactionPart(messages[i])) {
|
|
326
|
+
markerIdx = i;
|
|
327
|
+
break;
|
|
328
|
+
}
|
|
329
|
+
}
|
|
330
|
+
if (markerIdx === -1) {
|
|
331
|
+
return messages.flatMap(expandMessage);
|
|
332
|
+
}
|
|
333
|
+
const marker = findCompactionPart(messages[markerIdx]);
|
|
334
|
+
const seed = llm.LLM.user(`${COMPACTION_PREFIX}
|
|
335
|
+
${marker.summary}`);
|
|
336
|
+
const tail = messages.slice(markerIdx + 1);
|
|
337
|
+
return [seed, ...tail.flatMap(expandMessage)];
|
|
338
|
+
};
|
|
339
|
+
|
|
340
|
+
// src/session/processor.ts
|
|
341
|
+
var attachmentToImagePart = (a) => ({
|
|
342
|
+
type: "image",
|
|
343
|
+
url: a.url,
|
|
344
|
+
data: a.data,
|
|
345
|
+
mediaType: a.mediaType
|
|
346
|
+
});
|
|
347
|
+
var attachmentToContentPart = (a) => ({
|
|
348
|
+
type: "media",
|
|
349
|
+
mediaType: a.mediaType,
|
|
350
|
+
data: a.url ?? a.data ?? "",
|
|
351
|
+
filename: a.filename
|
|
352
|
+
});
|
|
353
|
+
var DEFAULT_COMPACTION = { auto: true };
|
|
354
|
+
var errorFromCause = (cause) => {
|
|
355
|
+
const failure = effect.Cause.findErrorOption(cause);
|
|
356
|
+
if (effect.Option.isSome(failure)) {
|
|
357
|
+
const e = failure.value;
|
|
358
|
+
return { type: "error", message: e.message ?? String(failure.value), retryable: e.retryable };
|
|
359
|
+
}
|
|
360
|
+
return { type: "error", message: effect.Cause.pretty(cause) };
|
|
361
|
+
};
|
|
362
|
+
var isContextOverflowError = (failure) => {
|
|
363
|
+
if (!(failure instanceof llm.LLMError)) return false;
|
|
364
|
+
return failure.reason._tag === "ContextOverflow";
|
|
365
|
+
};
|
|
366
|
+
var emptyAcc = () => ({ textBuffer: "", parts: [], toolByCall: /* @__PURE__ */ new Map() });
|
|
367
|
+
var flushText = (acc) => {
|
|
368
|
+
if (acc.textBuffer.length === 0) return;
|
|
369
|
+
acc.parts.push({ type: "text", text: acc.textBuffer });
|
|
370
|
+
acc.textBuffer = "";
|
|
371
|
+
};
|
|
372
|
+
var handleLLMEvent = (acc, event) => {
|
|
373
|
+
if (event.type === "text-delta") {
|
|
374
|
+
acc.textBuffer += event.text;
|
|
375
|
+
return;
|
|
376
|
+
}
|
|
377
|
+
if (event.type === "text-end") {
|
|
378
|
+
flushText(acc);
|
|
379
|
+
return;
|
|
380
|
+
}
|
|
381
|
+
if (event.type === "tool-call") {
|
|
382
|
+
flushText(acc);
|
|
383
|
+
const part = {
|
|
384
|
+
id: newPartID(),
|
|
385
|
+
type: "tool",
|
|
386
|
+
callID: event.id,
|
|
387
|
+
name: event.name,
|
|
388
|
+
state: "running",
|
|
389
|
+
input: event.input
|
|
390
|
+
};
|
|
391
|
+
acc.parts.push(part);
|
|
392
|
+
acc.toolByCall.set(event.id, part);
|
|
393
|
+
return;
|
|
394
|
+
}
|
|
395
|
+
if (event.type === "tool-result") {
|
|
396
|
+
const part = acc.toolByCall.get(event.id);
|
|
397
|
+
if (!part) return;
|
|
398
|
+
const idx = acc.parts.indexOf(part);
|
|
399
|
+
if (idx === -1) return;
|
|
400
|
+
acc.parts[idx] = { ...part, state: "complete", output: event.result.value };
|
|
401
|
+
acc.toolByCall.set(event.id, acc.parts[idx]);
|
|
402
|
+
return;
|
|
403
|
+
}
|
|
404
|
+
if (event.type === "tool-error") {
|
|
405
|
+
const part = acc.toolByCall.get(event.id);
|
|
406
|
+
if (!part) return;
|
|
407
|
+
const idx = acc.parts.indexOf(part);
|
|
408
|
+
if (idx === -1) return;
|
|
409
|
+
if (isToolInterruptMetadata(event.metadata)) {
|
|
410
|
+
acc.parts[idx] = {
|
|
411
|
+
...part,
|
|
412
|
+
state: "pending-approval",
|
|
413
|
+
metadata: { ...part.metadata ?? {}, ...event.metadata }
|
|
414
|
+
};
|
|
415
|
+
acc.toolByCall.set(event.id, acc.parts[idx]);
|
|
416
|
+
return;
|
|
417
|
+
}
|
|
418
|
+
acc.parts[idx] = { ...part, state: "error", output: { message: event.message } };
|
|
419
|
+
acc.toolByCall.set(event.id, acc.parts[idx]);
|
|
420
|
+
return;
|
|
421
|
+
}
|
|
422
|
+
};
|
|
423
|
+
var mapAgentEvent = (acc, event) => {
|
|
424
|
+
if (event.type === "tool-error" && isToolInterruptMetadata(event.metadata)) {
|
|
425
|
+
const part = acc.toolByCall.get(event.id);
|
|
426
|
+
return {
|
|
427
|
+
type: "tool-approval-request",
|
|
428
|
+
id: event.id,
|
|
429
|
+
name: event.name,
|
|
430
|
+
input: part?.input ?? event.metadata?.input
|
|
431
|
+
};
|
|
432
|
+
}
|
|
433
|
+
return fromLLMEvent(event);
|
|
434
|
+
};
|
|
435
|
+
var hasPendingApproval = (acc) => acc.parts.some((p) => p.type === "tool" && p.state === "pending-approval");
|
|
436
|
+
var persistMessageUpdate = (store, sessionId, message) => {
|
|
437
|
+
if (store.updateMessage) {
|
|
438
|
+
return store.updateMessage(sessionId, message.id, message);
|
|
439
|
+
}
|
|
440
|
+
return effect.Effect.gen(function* () {
|
|
441
|
+
yield* store.deleteMessage(sessionId, message.id);
|
|
442
|
+
yield* store.appendMessage(sessionId, message);
|
|
443
|
+
});
|
|
444
|
+
};
|
|
445
|
+
var DENIED_OUTPUT = { message: "User denied tool execution" };
|
|
446
|
+
var findApprovalMessage = (history) => {
|
|
447
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
448
|
+
const msg = history[i];
|
|
449
|
+
if (!msg || msg.role !== "assistant") continue;
|
|
450
|
+
const has = msg.parts.some(
|
|
451
|
+
(p) => p.type === "tool" && (p.state === "pending-approval" || p.state === "approved" || p.state === "rejected")
|
|
452
|
+
);
|
|
453
|
+
if (has) return { message: msg, index: i };
|
|
454
|
+
}
|
|
455
|
+
return void 0;
|
|
456
|
+
};
|
|
457
|
+
var buildAssistantMessage = (acc) => {
|
|
458
|
+
flushText(acc);
|
|
459
|
+
return makeAssistantMessage(acc.parts);
|
|
460
|
+
};
|
|
461
|
+
var makeProcessor = (config) => {
|
|
462
|
+
const stopWhen = config.stopWhen ?? llm.LLM.stepCountIs(100);
|
|
463
|
+
const compaction = config.compaction ?? DEFAULT_COMPACTION;
|
|
464
|
+
const buildRequest = (history, prompt, attachments) => {
|
|
465
|
+
const userContent = [];
|
|
466
|
+
if (prompt.length > 0) userContent.push({ type: "text", text: prompt });
|
|
467
|
+
for (const a of attachments ?? []) userContent.push(attachmentToContentPart(a));
|
|
468
|
+
const userMsg = userContent.length === 0 ? llm.LLM.user(prompt) : llm.LLM.user(userContent);
|
|
469
|
+
return llm.LLM.request({
|
|
470
|
+
model: config.model,
|
|
471
|
+
system: config.systemPrompt,
|
|
472
|
+
messages: [...historyToLLMMessages([...history]), userMsg],
|
|
473
|
+
generation: config.generation
|
|
474
|
+
});
|
|
475
|
+
};
|
|
476
|
+
const estimateUpcoming = (history, prompt) => {
|
|
477
|
+
const promptTokens = Math.ceil(prompt.length / 4);
|
|
478
|
+
const systemTokens = Math.ceil((config.systemPrompt?.length ?? 0) / 4);
|
|
479
|
+
return estimateTokens(history) + promptTokens + systemTokens;
|
|
480
|
+
};
|
|
481
|
+
const budget = () => usable({
|
|
482
|
+
limits: config.model.limits,
|
|
483
|
+
reservedTokens: compaction.reservedTokens
|
|
484
|
+
});
|
|
485
|
+
const runCompaction = (sessionId, overflow, keepRecentOverride) => compact({
|
|
486
|
+
sessionId,
|
|
487
|
+
store: config.store,
|
|
488
|
+
model: config.model,
|
|
489
|
+
keepRecent: keepRecentOverride ?? compaction.preserveRecentTurns ?? 4,
|
|
490
|
+
overflow
|
|
491
|
+
});
|
|
492
|
+
const condenseStart = (trigger, estimatedTokens, budgetTokens) => ({
|
|
493
|
+
type: "context-condense-start",
|
|
494
|
+
trigger,
|
|
495
|
+
estimatedTokens,
|
|
496
|
+
budgetTokens
|
|
497
|
+
});
|
|
498
|
+
const condenseSuccess = (trigger, result) => {
|
|
499
|
+
if (!result.markerId || typeof result.summary !== "string") return void 0;
|
|
500
|
+
return {
|
|
501
|
+
type: "context-condense",
|
|
502
|
+
trigger,
|
|
503
|
+
summary: result.summary,
|
|
504
|
+
markerId: String(result.markerId),
|
|
505
|
+
prevTokens: result.prevTokens,
|
|
506
|
+
newTokens: result.newTokens,
|
|
507
|
+
cost: result.cost,
|
|
508
|
+
modelId: result.modelId
|
|
509
|
+
};
|
|
510
|
+
};
|
|
511
|
+
const condenseError = (trigger, message, retryExhausted = false) => ({
|
|
512
|
+
type: "context-condense-error",
|
|
513
|
+
trigger,
|
|
514
|
+
message,
|
|
515
|
+
retryExhausted
|
|
516
|
+
});
|
|
517
|
+
const runTurn = (input) => {
|
|
518
|
+
const acc = emptyAcc();
|
|
519
|
+
return {
|
|
520
|
+
[Symbol.asyncIterator]() {
|
|
521
|
+
let inner;
|
|
522
|
+
let sessionId = input.sessionId;
|
|
523
|
+
let didRetryAfterOverflow = false;
|
|
524
|
+
let overflowPending = false;
|
|
525
|
+
let userMessageAppended = false;
|
|
526
|
+
let finalized = false;
|
|
527
|
+
const userMsg = makeUserMessage({
|
|
528
|
+
text: input.prompt,
|
|
529
|
+
images: (input.attachments ?? []).map(attachmentToImagePart)
|
|
530
|
+
});
|
|
531
|
+
const pendingEvents = [];
|
|
532
|
+
const buildIterable = () => config.runtime.runPromise(
|
|
533
|
+
effect.Effect.gen(function* () {
|
|
534
|
+
const session = yield* config.store.upsertSession({
|
|
535
|
+
id: sessionId,
|
|
536
|
+
agentName: config.agentName
|
|
537
|
+
});
|
|
538
|
+
sessionId = session.id;
|
|
539
|
+
if (compaction.auto && !userMessageAppended) {
|
|
540
|
+
const history2 = yield* config.store.getMessages(session.id);
|
|
541
|
+
const estimate = estimateUpcoming(history2, input.prompt);
|
|
542
|
+
const budgetTokens = budget();
|
|
543
|
+
if (estimate >= budgetTokens) {
|
|
544
|
+
pendingEvents.push(
|
|
545
|
+
condenseStart(
|
|
546
|
+
"preflight",
|
|
547
|
+
estimate,
|
|
548
|
+
Number.isFinite(budgetTokens) ? budgetTokens : void 0
|
|
549
|
+
)
|
|
550
|
+
);
|
|
551
|
+
const preflight = yield* runCompaction(session.id, false).pipe(
|
|
552
|
+
effect.Effect.catchCause(
|
|
553
|
+
(cause) => effect.Effect.sync(() => {
|
|
554
|
+
pendingEvents.push(condenseError("preflight", effect.Cause.pretty(cause)));
|
|
555
|
+
return { compacted: false };
|
|
556
|
+
})
|
|
557
|
+
)
|
|
558
|
+
);
|
|
559
|
+
const successEvent = condenseSuccess("preflight", preflight);
|
|
560
|
+
if (successEvent) pendingEvents.push(successEvent);
|
|
561
|
+
}
|
|
562
|
+
}
|
|
563
|
+
const history = yield* config.store.getMessages(session.id);
|
|
564
|
+
if (!userMessageAppended) {
|
|
565
|
+
yield* config.store.appendMessage(session.id, userMsg);
|
|
566
|
+
userMessageAppended = true;
|
|
567
|
+
}
|
|
568
|
+
const request = buildRequest(history, input.prompt, input.attachments);
|
|
569
|
+
const tools = config.tools ?? {};
|
|
570
|
+
const llmStream = llm.LLMClient.stream({ request, tools, stopWhen });
|
|
571
|
+
const mapped = llmStream.pipe(
|
|
572
|
+
effect.Stream.tap((event) => effect.Effect.sync(() => handleLLMEvent(acc, event))),
|
|
573
|
+
effect.Stream.map((event) => mapAgentEvent(acc, event)),
|
|
574
|
+
effect.Stream.filter((event) => event !== void 0),
|
|
575
|
+
effect.Stream.catchCause((cause) => {
|
|
576
|
+
const failure = effect.Cause.findErrorOption(cause);
|
|
577
|
+
if (effect.Option.isSome(failure) && isContextOverflowError(failure.value)) {
|
|
578
|
+
overflowPending = true;
|
|
579
|
+
return effect.Stream.empty;
|
|
580
|
+
}
|
|
581
|
+
return effect.Stream.succeed(errorFromCause(cause));
|
|
582
|
+
})
|
|
583
|
+
);
|
|
584
|
+
const iterable = yield* effect.Stream.toAsyncIterableEffect(mapped);
|
|
585
|
+
return iterable[Symbol.asyncIterator]();
|
|
586
|
+
})
|
|
587
|
+
);
|
|
588
|
+
const ensure = async () => {
|
|
589
|
+
if (inner) return inner;
|
|
590
|
+
inner = await buildIterable();
|
|
591
|
+
return inner;
|
|
592
|
+
};
|
|
593
|
+
const finalize = async () => {
|
|
594
|
+
if (!sessionId || finalized) return;
|
|
595
|
+
finalized = true;
|
|
596
|
+
const message = buildAssistantMessage(acc);
|
|
597
|
+
if (message.parts.length === 0) return;
|
|
598
|
+
await config.runtime.runPromise(config.store.appendMessage(sessionId, message));
|
|
599
|
+
};
|
|
600
|
+
let terminalErrorEmitted = false;
|
|
601
|
+
const handleOverflowAndRetry = async () => {
|
|
602
|
+
if (didRetryAfterOverflow || !compaction.auto || !sessionId) {
|
|
603
|
+
overflowPending = false;
|
|
604
|
+
if (!done) {
|
|
605
|
+
done = true;
|
|
606
|
+
await finalize();
|
|
607
|
+
}
|
|
608
|
+
if (inner && typeof inner.return === "function") {
|
|
609
|
+
await inner.return(void 0).catch(() => {
|
|
610
|
+
});
|
|
611
|
+
}
|
|
612
|
+
inner = void 0;
|
|
613
|
+
if (terminalErrorEmitted) {
|
|
614
|
+
return { done: true, value: void 0 };
|
|
615
|
+
}
|
|
616
|
+
terminalErrorEmitted = true;
|
|
617
|
+
pendingEvents.push({
|
|
618
|
+
type: "error",
|
|
619
|
+
message: "Context overflow: compaction retry exhausted",
|
|
620
|
+
retryable: false
|
|
621
|
+
});
|
|
622
|
+
return {
|
|
623
|
+
done: false,
|
|
624
|
+
value: condenseError(
|
|
625
|
+
"overflow-retry",
|
|
626
|
+
"Context overflow: compaction retry exhausted \u2014 the model context could not be reduced further.",
|
|
627
|
+
true
|
|
628
|
+
)
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
didRetryAfterOverflow = true;
|
|
632
|
+
overflowPending = false;
|
|
633
|
+
acc.textBuffer = "";
|
|
634
|
+
acc.parts = [];
|
|
635
|
+
acc.toolByCall = /* @__PURE__ */ new Map();
|
|
636
|
+
pendingEvents.push(condenseStart("overflow-retry", void 0, void 0));
|
|
637
|
+
const retryResult = await config.runtime.runPromise(runCompaction(sessionId, true, 1)).catch((err) => {
|
|
638
|
+
pendingEvents.push(
|
|
639
|
+
condenseError("overflow-retry", err instanceof Error ? err.message : String(err))
|
|
640
|
+
);
|
|
641
|
+
return { compacted: false };
|
|
642
|
+
});
|
|
643
|
+
const successEvent = condenseSuccess("overflow-retry", retryResult);
|
|
644
|
+
if (successEvent) pendingEvents.push(successEvent);
|
|
645
|
+
inner = await buildIterable();
|
|
646
|
+
return inner.next();
|
|
647
|
+
};
|
|
648
|
+
let done = false;
|
|
649
|
+
return {
|
|
650
|
+
async next() {
|
|
651
|
+
if (pendingEvents.length > 0) {
|
|
652
|
+
const value = pendingEvents.shift();
|
|
653
|
+
return { done: false, value };
|
|
654
|
+
}
|
|
655
|
+
if (terminalErrorEmitted) {
|
|
656
|
+
return { done: true, value: void 0 };
|
|
657
|
+
}
|
|
658
|
+
const it = await ensure();
|
|
659
|
+
if (pendingEvents.length > 0) {
|
|
660
|
+
const value = pendingEvents.shift();
|
|
661
|
+
return { done: false, value };
|
|
662
|
+
}
|
|
663
|
+
const result = await it.next();
|
|
664
|
+
if (pendingEvents.length > 0) {
|
|
665
|
+
const value = pendingEvents.shift();
|
|
666
|
+
if (!result.done) {
|
|
667
|
+
pendingEvents.push(result.value);
|
|
668
|
+
}
|
|
669
|
+
return { done: false, value };
|
|
670
|
+
}
|
|
671
|
+
if (result.done && overflowPending) {
|
|
672
|
+
return handleOverflowAndRetry();
|
|
673
|
+
}
|
|
674
|
+
if (result.done && !done) {
|
|
675
|
+
done = true;
|
|
676
|
+
await finalize();
|
|
677
|
+
if (hasPendingApproval(acc)) {
|
|
678
|
+
return {
|
|
679
|
+
done: false,
|
|
680
|
+
value: { type: "finish", reason: FINISH_REASON_APPROVAL_REQUIRED }
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
return result;
|
|
685
|
+
},
|
|
686
|
+
async return(value) {
|
|
687
|
+
if (!done) {
|
|
688
|
+
done = true;
|
|
689
|
+
await finalize();
|
|
690
|
+
}
|
|
691
|
+
if (inner && typeof inner.return === "function") {
|
|
692
|
+
await inner.return(value).catch(() => {
|
|
693
|
+
});
|
|
694
|
+
}
|
|
695
|
+
inner = void 0;
|
|
696
|
+
return { value, done: true };
|
|
697
|
+
}
|
|
698
|
+
};
|
|
699
|
+
}
|
|
700
|
+
};
|
|
701
|
+
};
|
|
702
|
+
const resumeTurn = (input) => {
|
|
703
|
+
const acc = emptyAcc();
|
|
704
|
+
return {
|
|
705
|
+
[Symbol.asyncIterator]() {
|
|
706
|
+
let inner;
|
|
707
|
+
let sessionId = input.sessionId;
|
|
708
|
+
let finalized = false;
|
|
709
|
+
let done = false;
|
|
710
|
+
let preEvents = [];
|
|
711
|
+
let preDrained = false;
|
|
712
|
+
const pendingEvents = [];
|
|
713
|
+
const stopWhen2 = config.stopWhen ?? llm.LLM.stepCountIs(100);
|
|
714
|
+
const executeApprovedTools = async () => {
|
|
715
|
+
const history = await config.runtime.runPromise(config.store.getMessages(input.sessionId));
|
|
716
|
+
const found = findApprovalMessage(history);
|
|
717
|
+
if (!found) {
|
|
718
|
+
preEvents.push({
|
|
719
|
+
type: "error",
|
|
720
|
+
message: "No pending tool approvals to resume",
|
|
721
|
+
retryable: false
|
|
722
|
+
});
|
|
723
|
+
return;
|
|
724
|
+
}
|
|
725
|
+
const tools = config.resumeTools ?? config.tools ?? {};
|
|
726
|
+
const original = found.message;
|
|
727
|
+
const nextParts = original.parts.map((p) => ({ ...p }));
|
|
728
|
+
let mutated = false;
|
|
729
|
+
for (let i = 0; i < nextParts.length; i++) {
|
|
730
|
+
const part = nextParts[i];
|
|
731
|
+
if (!part || part.type !== "tool") continue;
|
|
732
|
+
const toolPart = part;
|
|
733
|
+
if (toolPart.state === "rejected") {
|
|
734
|
+
const updated = {
|
|
735
|
+
...toolPart,
|
|
736
|
+
state: "error",
|
|
737
|
+
output: DENIED_OUTPUT
|
|
738
|
+
};
|
|
739
|
+
nextParts[i] = updated;
|
|
740
|
+
mutated = true;
|
|
741
|
+
preEvents.push({
|
|
742
|
+
type: "tool-error",
|
|
743
|
+
id: toolPart.callID,
|
|
744
|
+
name: toolPart.name,
|
|
745
|
+
message: DENIED_OUTPUT.message
|
|
746
|
+
});
|
|
747
|
+
continue;
|
|
748
|
+
}
|
|
749
|
+
if (toolPart.state !== "approved") continue;
|
|
750
|
+
preEvents.push({
|
|
751
|
+
type: "tool-call",
|
|
752
|
+
id: toolPart.callID,
|
|
753
|
+
name: toolPart.name,
|
|
754
|
+
input: toolPart.input
|
|
755
|
+
});
|
|
756
|
+
const tool = tools[toolPart.name];
|
|
757
|
+
if (!tool || !tool.execute) {
|
|
758
|
+
const msg = tool ? `Tool has no execute handler: ${toolPart.name}` : `Unknown tool: ${toolPart.name}`;
|
|
759
|
+
nextParts[i] = { ...toolPart, state: "error", output: { message: msg } };
|
|
760
|
+
mutated = true;
|
|
761
|
+
preEvents.push({
|
|
762
|
+
type: "tool-error",
|
|
763
|
+
id: toolPart.callID,
|
|
764
|
+
name: toolPart.name,
|
|
765
|
+
message: msg
|
|
766
|
+
});
|
|
767
|
+
continue;
|
|
768
|
+
}
|
|
769
|
+
try {
|
|
770
|
+
const value = await config.runtime.runPromise(tool.execute(toolPart.input));
|
|
771
|
+
nextParts[i] = { ...toolPart, state: "complete", output: value };
|
|
772
|
+
mutated = true;
|
|
773
|
+
preEvents.push({
|
|
774
|
+
type: "tool-result",
|
|
775
|
+
id: toolPart.callID,
|
|
776
|
+
name: toolPart.name,
|
|
777
|
+
result: value
|
|
778
|
+
});
|
|
779
|
+
} catch (err) {
|
|
780
|
+
const message = err && typeof err === "object" && "message" in err ? String(err.message) : err instanceof Error ? err.message : String(err);
|
|
781
|
+
nextParts[i] = { ...toolPart, state: "error", output: { message } };
|
|
782
|
+
mutated = true;
|
|
783
|
+
preEvents.push({
|
|
784
|
+
type: "tool-error",
|
|
785
|
+
id: toolPart.callID,
|
|
786
|
+
name: toolPart.name,
|
|
787
|
+
message
|
|
788
|
+
});
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
const stillPending = nextParts.some(
|
|
792
|
+
(p) => p.type === "tool" && p.state === "pending-approval"
|
|
793
|
+
);
|
|
794
|
+
if (mutated) {
|
|
795
|
+
const updatedMsg = { ...original, parts: nextParts };
|
|
796
|
+
await config.runtime.runPromise(persistMessageUpdate(config.store, input.sessionId, updatedMsg));
|
|
797
|
+
}
|
|
798
|
+
if (stillPending) {
|
|
799
|
+
preEvents.push({ type: "finish", reason: FINISH_REASON_APPROVAL_REQUIRED });
|
|
800
|
+
}
|
|
801
|
+
};
|
|
802
|
+
const buildFollowUp = () => config.runtime.runPromise(
|
|
803
|
+
effect.Effect.gen(function* () {
|
|
804
|
+
const session = yield* config.store.upsertSession({
|
|
805
|
+
id: sessionId,
|
|
806
|
+
agentName: config.agentName
|
|
807
|
+
});
|
|
808
|
+
sessionId = session.id;
|
|
809
|
+
const history = yield* config.store.getMessages(session.id);
|
|
810
|
+
const request = buildRequest(history, "");
|
|
811
|
+
const tools = config.tools ?? {};
|
|
812
|
+
const llmStream = llm.LLMClient.stream({ request, tools, stopWhen: stopWhen2 });
|
|
813
|
+
const mapped = llmStream.pipe(
|
|
814
|
+
effect.Stream.tap((event) => effect.Effect.sync(() => handleLLMEvent(acc, event))),
|
|
815
|
+
effect.Stream.map((event) => mapAgentEvent(acc, event)),
|
|
816
|
+
effect.Stream.filter((event) => event !== void 0),
|
|
817
|
+
effect.Stream.catchCause((cause) => {
|
|
818
|
+
const failure = effect.Cause.findErrorOption(cause);
|
|
819
|
+
if (effect.Option.isSome(failure) && isContextOverflowError(failure.value)) {
|
|
820
|
+
return effect.Stream.succeed({
|
|
821
|
+
type: "error",
|
|
822
|
+
message: "Context overflow during approval resume",
|
|
823
|
+
retryable: false
|
|
824
|
+
});
|
|
825
|
+
}
|
|
826
|
+
return effect.Stream.succeed(errorFromCause(cause));
|
|
827
|
+
})
|
|
828
|
+
);
|
|
829
|
+
const iterable = yield* effect.Stream.toAsyncIterableEffect(mapped);
|
|
830
|
+
return iterable[Symbol.asyncIterator]();
|
|
831
|
+
})
|
|
832
|
+
);
|
|
833
|
+
const finalize = async () => {
|
|
834
|
+
if (!sessionId || finalized) return;
|
|
835
|
+
finalized = true;
|
|
836
|
+
const message = buildAssistantMessage(acc);
|
|
837
|
+
if (message.parts.length === 0) return;
|
|
838
|
+
await config.runtime.runPromise(config.store.appendMessage(sessionId, message));
|
|
839
|
+
};
|
|
840
|
+
return {
|
|
841
|
+
async next() {
|
|
842
|
+
if (!preDrained) {
|
|
843
|
+
preDrained = true;
|
|
844
|
+
await executeApprovedTools();
|
|
845
|
+
const endedEarly = preEvents.some(
|
|
846
|
+
(e) => e.type === "finish" && e.reason === FINISH_REASON_APPROVAL_REQUIRED
|
|
847
|
+
);
|
|
848
|
+
if (endedEarly) {
|
|
849
|
+
done = true;
|
|
850
|
+
} else if (preEvents.some((e) => e.type === "error" && !e.retryable)) {
|
|
851
|
+
const onlyError = preEvents.length === 1 && preEvents[0]?.type === "error";
|
|
852
|
+
if (onlyError) {
|
|
853
|
+
done = true;
|
|
854
|
+
}
|
|
855
|
+
} else {
|
|
856
|
+
try {
|
|
857
|
+
inner = await buildFollowUp();
|
|
858
|
+
} catch (err) {
|
|
859
|
+
preEvents.push({
|
|
860
|
+
type: "error",
|
|
861
|
+
message: err instanceof Error ? err.message : String(err),
|
|
862
|
+
retryable: false
|
|
863
|
+
});
|
|
864
|
+
done = true;
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
if (preEvents.length > 0) {
|
|
869
|
+
const value = preEvents.shift();
|
|
870
|
+
return { done: false, value };
|
|
871
|
+
}
|
|
872
|
+
if (pendingEvents.length > 0) {
|
|
873
|
+
const value = pendingEvents.shift();
|
|
874
|
+
return { done: false, value };
|
|
875
|
+
}
|
|
876
|
+
if (done || !inner) {
|
|
877
|
+
return { done: true, value: void 0 };
|
|
878
|
+
}
|
|
879
|
+
const result = await inner.next();
|
|
880
|
+
if (result.done && !done) {
|
|
881
|
+
done = true;
|
|
882
|
+
await finalize();
|
|
883
|
+
if (hasPendingApproval(acc)) {
|
|
884
|
+
return {
|
|
885
|
+
done: false,
|
|
886
|
+
value: { type: "finish", reason: FINISH_REASON_APPROVAL_REQUIRED }
|
|
887
|
+
};
|
|
888
|
+
}
|
|
889
|
+
}
|
|
890
|
+
return result;
|
|
891
|
+
},
|
|
892
|
+
async return(value) {
|
|
893
|
+
if (!done) {
|
|
894
|
+
done = true;
|
|
895
|
+
await finalize();
|
|
896
|
+
}
|
|
897
|
+
if (inner && typeof inner.return === "function") {
|
|
898
|
+
await inner.return(value).catch(() => {
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
inner = void 0;
|
|
902
|
+
return { value, done: true };
|
|
903
|
+
}
|
|
904
|
+
};
|
|
905
|
+
}
|
|
906
|
+
};
|
|
907
|
+
};
|
|
908
|
+
return { runTurn, resumeTurn };
|
|
909
|
+
};
|
|
910
|
+
var encodeCursor = (cursor) => Buffer.from(JSON.stringify(cursor), "utf8").toString("base64url");
|
|
911
|
+
var decodeCursor = (raw) => {
|
|
912
|
+
const json = Buffer.from(raw, "base64url").toString("utf8");
|
|
913
|
+
const parsed = JSON.parse(json);
|
|
914
|
+
if (typeof parsed.updatedAt !== "number" || typeof parsed.id !== "string") return void 0;
|
|
915
|
+
return { updatedAt: parsed.updatedAt, id: parsed.id };
|
|
916
|
+
};
|
|
917
|
+
var makeMemoryStore = () => {
|
|
918
|
+
const store = /* @__PURE__ */ new Map();
|
|
919
|
+
const createSession = (input) => {
|
|
920
|
+
const now = Date.now();
|
|
921
|
+
const info = {
|
|
922
|
+
id: newSessionID(),
|
|
923
|
+
agentName: input.agentName,
|
|
924
|
+
title: input.title,
|
|
925
|
+
metadata: input.metadata,
|
|
926
|
+
createdAt: now,
|
|
927
|
+
updatedAt: now
|
|
928
|
+
};
|
|
929
|
+
store.set(info.id, { info, messages: [] });
|
|
930
|
+
return effect.Effect.succeed(info);
|
|
931
|
+
};
|
|
932
|
+
const getSession = (id) => effect.Effect.succeed(store.get(id)?.info);
|
|
933
|
+
const upsertSession = (input) => {
|
|
934
|
+
const existing = input.id ? store.get(input.id) : void 0;
|
|
935
|
+
if (existing) return effect.Effect.succeed(existing.info);
|
|
936
|
+
if (!input.id) return createSession(input);
|
|
937
|
+
const now = Date.now();
|
|
938
|
+
const info = {
|
|
939
|
+
id: input.id,
|
|
940
|
+
agentName: input.agentName,
|
|
941
|
+
title: input.title,
|
|
942
|
+
metadata: input.metadata,
|
|
943
|
+
createdAt: now,
|
|
944
|
+
updatedAt: now
|
|
945
|
+
};
|
|
946
|
+
store.set(info.id, { info, messages: [] });
|
|
947
|
+
return effect.Effect.succeed(info);
|
|
948
|
+
};
|
|
949
|
+
const listSessions = (opts) => {
|
|
950
|
+
const limit = opts?.limit ?? 50;
|
|
951
|
+
const filtered = Array.from(store.values()).map((e) => e.info).filter((info) => opts?.agentName ? info.agentName === opts.agentName : true).filter(
|
|
952
|
+
(info) => opts?.ownerId ? info.metadata?.ownerId === opts.ownerId : true
|
|
953
|
+
).sort((a, b) => {
|
|
954
|
+
if (b.updatedAt !== a.updatedAt) return b.updatedAt - a.updatedAt;
|
|
955
|
+
return b.id.localeCompare(a.id);
|
|
956
|
+
});
|
|
957
|
+
const cursor = opts?.cursor ? decodeCursor(opts.cursor) : void 0;
|
|
958
|
+
const startIdx = cursor ? filtered.findIndex(
|
|
959
|
+
(info) => info.updatedAt < cursor.updatedAt || info.updatedAt === cursor.updatedAt && info.id.localeCompare(cursor.id) < 0
|
|
960
|
+
) : 0;
|
|
961
|
+
if (startIdx === -1) return effect.Effect.succeed({ items: [] });
|
|
962
|
+
const page = filtered.slice(startIdx, startIdx + limit);
|
|
963
|
+
const tail = page[page.length - 1];
|
|
964
|
+
const hasMore = startIdx + limit < filtered.length;
|
|
965
|
+
const nextCursor = hasMore && tail ? encodeCursor({ updatedAt: tail.updatedAt, id: tail.id }) : void 0;
|
|
966
|
+
return effect.Effect.succeed({ items: page, nextCursor });
|
|
967
|
+
};
|
|
968
|
+
const updateSession = (id, patch) => {
|
|
969
|
+
const entry = store.get(id);
|
|
970
|
+
if (!entry) return effect.Effect.succeed(void 0);
|
|
971
|
+
entry.info = {
|
|
972
|
+
...entry.info,
|
|
973
|
+
...patch.title !== void 0 ? { title: patch.title } : {},
|
|
974
|
+
...patch.metadata !== void 0 ? { metadata: patch.metadata } : {},
|
|
975
|
+
updatedAt: Date.now()
|
|
976
|
+
};
|
|
977
|
+
return effect.Effect.succeed(entry.info);
|
|
978
|
+
};
|
|
979
|
+
const appendMessage = (sessionId, msg) => {
|
|
980
|
+
const entry = store.get(sessionId);
|
|
981
|
+
if (!entry) return effect.Effect.void;
|
|
982
|
+
entry.messages.push(msg);
|
|
983
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
984
|
+
return effect.Effect.void;
|
|
985
|
+
};
|
|
986
|
+
const getMessages = (sessionId, opts) => {
|
|
987
|
+
const msgs = store.get(sessionId)?.messages ?? [];
|
|
988
|
+
const sliced = opts?.before ? msgs.slice(0, msgs.findIndex((m) => m.id === opts.before)) : msgs;
|
|
989
|
+
const limited = opts?.limit ? sliced.slice(-opts.limit) : sliced;
|
|
990
|
+
return effect.Effect.succeed([...limited]);
|
|
991
|
+
};
|
|
992
|
+
const deleteMessage = (sessionId, messageId) => {
|
|
993
|
+
const entry = store.get(sessionId);
|
|
994
|
+
if (!entry) return effect.Effect.void;
|
|
995
|
+
const idx = entry.messages.findIndex((m) => m.id === messageId);
|
|
996
|
+
if (idx === -1) return effect.Effect.void;
|
|
997
|
+
entry.messages.splice(idx, 1);
|
|
998
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
999
|
+
return effect.Effect.void;
|
|
1000
|
+
};
|
|
1001
|
+
const updateMessage = (sessionId, messageId, msg) => {
|
|
1002
|
+
const entry = store.get(sessionId);
|
|
1003
|
+
if (!entry) return effect.Effect.void;
|
|
1004
|
+
const idx = entry.messages.findIndex((m) => m.id === messageId);
|
|
1005
|
+
if (idx === -1) return effect.Effect.void;
|
|
1006
|
+
entry.messages[idx] = msg;
|
|
1007
|
+
entry.info = { ...entry.info, updatedAt: Date.now() };
|
|
1008
|
+
return effect.Effect.void;
|
|
1009
|
+
};
|
|
1010
|
+
const deleteSession = (id) => {
|
|
1011
|
+
store.delete(id);
|
|
1012
|
+
return effect.Effect.void;
|
|
1013
|
+
};
|
|
1014
|
+
return {
|
|
1015
|
+
createSession,
|
|
1016
|
+
getSession,
|
|
1017
|
+
upsertSession,
|
|
1018
|
+
listSessions,
|
|
1019
|
+
updateSession,
|
|
1020
|
+
appendMessage,
|
|
1021
|
+
getMessages,
|
|
1022
|
+
deleteMessage,
|
|
1023
|
+
updateMessage,
|
|
1024
|
+
deleteSession
|
|
1025
|
+
};
|
|
1026
|
+
};
|
|
1027
|
+
var TINYWEB_HEADERS = {
|
|
1028
|
+
"Content-Type": "text/event-stream",
|
|
1029
|
+
"Cache-Control": "no-cache, no-transform",
|
|
1030
|
+
Connection: "keep-alive"
|
|
1031
|
+
};
|
|
1032
|
+
var writeEventsToResponse = async (events, res, format = "tinyweb") => {
|
|
1033
|
+
const headers = format === "ai-sdk" ? protocol.AI_SDK_HEADERS : TINYWEB_HEADERS;
|
|
1034
|
+
for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
|
|
1035
|
+
if (typeof res.flushHeaders === "function") res.flushHeaders();
|
|
1036
|
+
for await (const event of events) {
|
|
1037
|
+
const protocolEvent = event;
|
|
1038
|
+
const line = format === "ai-sdk" ? protocol.toAISDKDataStream(protocolEvent) : protocol.encodeSSE(protocolEvent);
|
|
1039
|
+
if (line.length > 0) res.write(line);
|
|
1040
|
+
}
|
|
1041
|
+
res.end();
|
|
1042
|
+
};
|
|
1043
|
+
var makeSSEHandler = (run, options = {}) => {
|
|
1044
|
+
const format = options.format ?? "tinyweb";
|
|
1045
|
+
return async (input, res) => {
|
|
1046
|
+
await writeEventsToResponse(run(input), res, format);
|
|
1047
|
+
};
|
|
1048
|
+
};
|
|
1049
|
+
|
|
1050
|
+
// src/plugin/loader.ts
|
|
1051
|
+
var isPlugin = (value) => typeof value === "function";
|
|
1052
|
+
var idFromPath = (path) => path.replace(/[^a-z0-9]+/gi, "-").replace(/^-+|-+$/g, "") || "plugin";
|
|
1053
|
+
var importPlugin = async (path) => {
|
|
1054
|
+
const mod = await import(path);
|
|
1055
|
+
const plugin = mod.server ?? mod.default;
|
|
1056
|
+
if (!isPlugin(plugin))
|
|
1057
|
+
throw new Error(`Plugin at ${path} must export a 'server' or default function returning Hooks`);
|
|
1058
|
+
return { id: mod.id ?? idFromPath(path), plugin };
|
|
1059
|
+
};
|
|
1060
|
+
var normalizeEntry = async (entry, index) => {
|
|
1061
|
+
if (isPlugin(entry)) return { id: `inline-${index}`, plugin: entry };
|
|
1062
|
+
if (typeof entry === "string") {
|
|
1063
|
+
const loaded2 = await importPlugin(entry);
|
|
1064
|
+
return { id: loaded2.id, plugin: loaded2.plugin };
|
|
1065
|
+
}
|
|
1066
|
+
const loaded = await importPlugin(entry[0]);
|
|
1067
|
+
return { id: loaded.id, plugin: loaded.plugin, options: entry[1] };
|
|
1068
|
+
};
|
|
1069
|
+
var loadPlugins = async (entries, input) => {
|
|
1070
|
+
const resolved = await Promise.all(entries.map((entry, i) => normalizeEntry(entry, i)));
|
|
1071
|
+
const loaded = await Promise.all(
|
|
1072
|
+
resolved.map(async (item) => ({ id: item.id, hooks: await item.plugin(input, item.options) }))
|
|
1073
|
+
);
|
|
1074
|
+
return loaded;
|
|
1075
|
+
};
|
|
1076
|
+
|
|
1077
|
+
// src/plugin/apply.ts
|
|
1078
|
+
var runHooks = async (plugins, key, input, output) => {
|
|
1079
|
+
for (const p of plugins) {
|
|
1080
|
+
const hook = p.hooks[key];
|
|
1081
|
+
if (hook) await hook(input, output);
|
|
1082
|
+
}
|
|
1083
|
+
return output;
|
|
1084
|
+
};
|
|
1085
|
+
var applyEvent = async (plugins, input) => {
|
|
1086
|
+
for (const p of plugins) {
|
|
1087
|
+
if (p.hooks.event) await p.hooks.event(input);
|
|
1088
|
+
}
|
|
1089
|
+
};
|
|
1090
|
+
var applyChatMessage = (plugins, input, output) => runHooks(plugins, "chat.message", input, output);
|
|
1091
|
+
var applyChatParams = (plugins, input, output) => runHooks(plugins, "chat.params", input, output);
|
|
1092
|
+
var applyChatHeaders = (plugins, input, output) => runHooks(plugins, "chat.headers", input, output);
|
|
1093
|
+
var applyToolBefore = (plugins, input, output) => runHooks(plugins, "tool.execute.before", input, output);
|
|
1094
|
+
var applyToolAfter = (plugins, input, output) => runHooks(plugins, "tool.execute.after", input, output);
|
|
1095
|
+
var applyToolDefinition = (plugins, input, output) => runHooks(plugins, "tool.definition", input, output);
|
|
1096
|
+
var applyPermissionHook = (plugins, input, output) => runHooks(plugins, "permission.ask", input, output);
|
|
1097
|
+
var applySystemTransform = (plugins, input, output) => runHooks(plugins, "experimental.chat.system.transform", input, output);
|
|
1098
|
+
function asJsonSchema(inputSchema) {
|
|
1099
|
+
if (inputSchema && typeof inputSchema === "object" && !Array.isArray(inputSchema)) {
|
|
1100
|
+
return inputSchema;
|
|
1101
|
+
}
|
|
1102
|
+
return { type: "object", properties: {} };
|
|
1103
|
+
}
|
|
1104
|
+
function buildTool(serverName, mcpTool, client) {
|
|
1105
|
+
const toolName = `${serverName}__${mcpTool.name}`;
|
|
1106
|
+
const jsonSchema = asJsonSchema(mcpTool.inputSchema);
|
|
1107
|
+
return llm.Tool.make({
|
|
1108
|
+
description: mcpTool.description ?? toolName,
|
|
1109
|
+
// Dynamic mode — preserves MCP inputSchema on the wire for the LLM.
|
|
1110
|
+
jsonSchema,
|
|
1111
|
+
execute: (input) => effect.Effect.tryPromise({
|
|
1112
|
+
try: async () => {
|
|
1113
|
+
const args = input && typeof input === "object" && !Array.isArray(input) ? input : {};
|
|
1114
|
+
const result = await client.callTool({ name: mcpTool.name, arguments: args });
|
|
1115
|
+
const parts = result.content ?? [];
|
|
1116
|
+
const text = parts.map((c) => c.text ?? "").join("\n");
|
|
1117
|
+
if (result.isError) {
|
|
1118
|
+
throw new Error(text || "MCP tool returned error");
|
|
1119
|
+
}
|
|
1120
|
+
return text;
|
|
1121
|
+
},
|
|
1122
|
+
catch: (err) => new llm.ToolFailure({ message: String(err) })
|
|
1123
|
+
})
|
|
1124
|
+
});
|
|
1125
|
+
}
|
|
1126
|
+
async function connectMcp(name, config) {
|
|
1127
|
+
const client = new index_js.Client({ name: "tinyweb-agent", version: "0.0.1" });
|
|
1128
|
+
const transport = config.type === "stdio" ? new stdio_js.StdioClientTransport({ command: config.command, args: config.args, env: config.env }) : new streamableHttp_js.StreamableHTTPClientTransport(new URL(config.url), { requestInit: { headers: config.headers ?? {} } });
|
|
1129
|
+
await client.connect(transport);
|
|
1130
|
+
const listResult = await client.listTools();
|
|
1131
|
+
const tools = {};
|
|
1132
|
+
for (const mcpTool of listResult.tools) {
|
|
1133
|
+
const namespaced = `${name}__${mcpTool.name}`;
|
|
1134
|
+
tools[namespaced] = buildTool(name, mcpTool, client);
|
|
1135
|
+
}
|
|
1136
|
+
return {
|
|
1137
|
+
name,
|
|
1138
|
+
tools,
|
|
1139
|
+
disconnect: () => client.close()
|
|
1140
|
+
};
|
|
1141
|
+
}
|
|
1142
|
+
async function connectAllMcp(configs) {
|
|
1143
|
+
const clients = await Promise.all(Object.entries(configs).map(([name, config]) => connectMcp(name, config)));
|
|
1144
|
+
const tools = {};
|
|
1145
|
+
for (const mcp of clients) {
|
|
1146
|
+
Object.assign(tools, mcp.tools);
|
|
1147
|
+
}
|
|
1148
|
+
return { clients, tools };
|
|
1149
|
+
}
|
|
1150
|
+
function parseFrontmatter(raw) {
|
|
1151
|
+
if (!raw.startsWith("---")) return { body: raw };
|
|
1152
|
+
const end = raw.indexOf("\n---", 3);
|
|
1153
|
+
if (end === -1) return { body: raw };
|
|
1154
|
+
const fm = raw.slice(3, end).trim();
|
|
1155
|
+
const body = raw.slice(end + 4).trim();
|
|
1156
|
+
const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim();
|
|
1157
|
+
const description = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim();
|
|
1158
|
+
return { name, description, body };
|
|
1159
|
+
}
|
|
1160
|
+
async function scanDir(dir) {
|
|
1161
|
+
const results = [];
|
|
1162
|
+
let entries = [];
|
|
1163
|
+
try {
|
|
1164
|
+
entries = await promises.readdir(dir, { withFileTypes: true });
|
|
1165
|
+
} catch {
|
|
1166
|
+
return results;
|
|
1167
|
+
}
|
|
1168
|
+
for (const entry of entries) {
|
|
1169
|
+
const full = path.join(dir, entry.name);
|
|
1170
|
+
if (entry.isDirectory()) {
|
|
1171
|
+
const nested = await scanDir(full);
|
|
1172
|
+
results.push(...nested);
|
|
1173
|
+
} else if (entry.name === "SKILL.md") {
|
|
1174
|
+
const raw = await promises.readFile(full, "utf-8").catch(() => "");
|
|
1175
|
+
if (!raw) continue;
|
|
1176
|
+
const { name, description, body } = parseFrontmatter(raw);
|
|
1177
|
+
if (!name) continue;
|
|
1178
|
+
results.push({ name, description, location: full, content: body || raw });
|
|
1179
|
+
}
|
|
1180
|
+
}
|
|
1181
|
+
return results;
|
|
1182
|
+
}
|
|
1183
|
+
function defaultSkillDirs() {
|
|
1184
|
+
return [
|
|
1185
|
+
path.join(process.cwd(), "skills"),
|
|
1186
|
+
path.join(os.homedir(), ".tinyweb-agent", "skills")
|
|
1187
|
+
];
|
|
1188
|
+
}
|
|
1189
|
+
async function loadSkills(extraDirs = []) {
|
|
1190
|
+
const dirs = [...defaultSkillDirs(), ...extraDirs];
|
|
1191
|
+
const all = [];
|
|
1192
|
+
for (const dir of dirs) {
|
|
1193
|
+
const found = await scanDir(dir);
|
|
1194
|
+
all.push(...found);
|
|
1195
|
+
}
|
|
1196
|
+
const byName = /* @__PURE__ */ new Map();
|
|
1197
|
+
for (const skill of all) {
|
|
1198
|
+
byName.set(skill.name, skill);
|
|
1199
|
+
}
|
|
1200
|
+
return Array.from(byName.values());
|
|
1201
|
+
}
|
|
1202
|
+
function makeSkillTool(skills) {
|
|
1203
|
+
const byName = new Map(skills.map((s) => [s.name, s]));
|
|
1204
|
+
const names = skills.map((s) => s.name).join(", ");
|
|
1205
|
+
return llm.Tool.make({
|
|
1206
|
+
description: `Load skill instructions by name. Available skills: ${names || "(none)"}. Returns the skill's markdown content.`,
|
|
1207
|
+
parameters: effect.Schema.Struct({ name: effect.Schema.String }),
|
|
1208
|
+
success: effect.Schema.Struct({ name: effect.Schema.String, content: effect.Schema.String }),
|
|
1209
|
+
execute: (input) => {
|
|
1210
|
+
const skill = byName.get(input.name);
|
|
1211
|
+
if (!skill)
|
|
1212
|
+
return effect.Effect.fail(new llm.ToolFailure({ message: `Skill "${input.name}" not found. Available: ${names || "(none)"}` }));
|
|
1213
|
+
return effect.Effect.succeed({ name: skill.name, content: skill.content });
|
|
1214
|
+
}
|
|
1215
|
+
});
|
|
1216
|
+
}
|
|
1217
|
+
var withOwner = (input, metadata) => {
|
|
1218
|
+
if (!input?.ownerId) return metadata;
|
|
1219
|
+
return { ...metadata ?? {}, ownerId: input.ownerId };
|
|
1220
|
+
};
|
|
1221
|
+
var makeSessionAPI = (config) => {
|
|
1222
|
+
const rt = () => config.runtime ?? defaultRuntime();
|
|
1223
|
+
const run = (effect) => rt().runPromise(effect);
|
|
1224
|
+
return {
|
|
1225
|
+
create: (input) => run(
|
|
1226
|
+
config.store.createSession({
|
|
1227
|
+
agentName: config.agentName,
|
|
1228
|
+
title: input?.title,
|
|
1229
|
+
metadata: withOwner(input, input?.metadata)
|
|
1230
|
+
})
|
|
1231
|
+
),
|
|
1232
|
+
list: (opts) => run(
|
|
1233
|
+
config.store.listSessions({
|
|
1234
|
+
limit: opts?.limit,
|
|
1235
|
+
cursor: opts?.cursor,
|
|
1236
|
+
agentName: config.agentName,
|
|
1237
|
+
ownerId: opts?.ownerId
|
|
1238
|
+
})
|
|
1239
|
+
),
|
|
1240
|
+
get: (id) => run(config.store.getSession(id)),
|
|
1241
|
+
delete: (id) => run(config.store.deleteSession(id)),
|
|
1242
|
+
setTitle: (id, title) => run(config.store.updateSession(id, { title })),
|
|
1243
|
+
setMetadata: (id, metadata) => run(config.store.updateSession(id, { metadata })),
|
|
1244
|
+
patch: (id, patch) => run(config.store.updateSession(id, patch)),
|
|
1245
|
+
messages: async (sessionId, opts) => {
|
|
1246
|
+
const items = await run(config.store.getMessages(sessionId, opts));
|
|
1247
|
+
const nextCursor = opts?.limit && items.length === opts.limit && items[0] ? items[0].id : void 0;
|
|
1248
|
+
return { items, nextCursor };
|
|
1249
|
+
},
|
|
1250
|
+
deleteMessage: (sessionId, messageId) => run(config.store.deleteMessage(sessionId, messageId))
|
|
1251
|
+
};
|
|
1252
|
+
};
|
|
1253
|
+
|
|
1254
|
+
// src/attachments.ts
|
|
1255
|
+
var DEFAULT_IMAGE_MIMES = /* @__PURE__ */ new Set(["image/png", "image/jpeg", "image/webp", "image/gif"]);
|
|
1256
|
+
var DEFAULT_MAX_BYTES_PER_FILE = 8 * 1024 * 1024;
|
|
1257
|
+
var DEFAULT_MAX_BYTES_TOTAL = 16 * 1024 * 1024;
|
|
1258
|
+
var DEFAULT_MAX_COUNT = 4;
|
|
1259
|
+
var base64ByteLength = (b64) => {
|
|
1260
|
+
const idx = b64.indexOf("base64,");
|
|
1261
|
+
const body = idx >= 0 ? b64.slice(idx + "base64,".length) : b64;
|
|
1262
|
+
const padding = body.endsWith("==") ? 2 : body.endsWith("=") ? 1 : 0;
|
|
1263
|
+
return Math.max(0, Math.floor(body.length * 3 / 4) - padding);
|
|
1264
|
+
};
|
|
1265
|
+
var isHttpOrFile = (s) => s.startsWith("http://") || s.startsWith("https://") || s.startsWith("file://") || s.startsWith("data:");
|
|
1266
|
+
var validateAttachments = (raw, config) => {
|
|
1267
|
+
if (raw === void 0 || raw === null) return { ok: true, value: [] };
|
|
1268
|
+
if (!Array.isArray(raw))
|
|
1269
|
+
return { ok: false, code: "attachment_invalid", message: "attachments must be an array" };
|
|
1270
|
+
const imageMimes = config?.imageMimes ?? DEFAULT_IMAGE_MIMES;
|
|
1271
|
+
const maxBytesPerFile = config?.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE;
|
|
1272
|
+
const maxBytesTotal = config?.maxBytesTotal ?? DEFAULT_MAX_BYTES_TOTAL;
|
|
1273
|
+
const maxCount = config?.maxCount ?? DEFAULT_MAX_COUNT;
|
|
1274
|
+
if (raw.length > maxCount)
|
|
1275
|
+
return {
|
|
1276
|
+
ok: false,
|
|
1277
|
+
code: "attachment_too_many",
|
|
1278
|
+
message: `Too many attachments (max ${maxCount}, received ${raw.length})`
|
|
1279
|
+
};
|
|
1280
|
+
const out = [];
|
|
1281
|
+
let totalBytes = 0;
|
|
1282
|
+
for (let i = 0; i < raw.length; i++) {
|
|
1283
|
+
const item = raw[i];
|
|
1284
|
+
if (!item || typeof item !== "object")
|
|
1285
|
+
return { ok: false, code: "attachment_invalid", message: `attachments[${i}] must be an object` };
|
|
1286
|
+
const obj = item;
|
|
1287
|
+
if (obj.type !== "image")
|
|
1288
|
+
return {
|
|
1289
|
+
ok: false,
|
|
1290
|
+
code: "attachment_unsupported_type",
|
|
1291
|
+
message: `attachments[${i}].type must be "image" (received ${String(obj.type)})`
|
|
1292
|
+
};
|
|
1293
|
+
const mediaType = obj.mediaType;
|
|
1294
|
+
if (typeof mediaType !== "string" || mediaType.length === 0)
|
|
1295
|
+
return { ok: false, code: "attachment_invalid", message: `attachments[${i}].mediaType is required` };
|
|
1296
|
+
if (!imageMimes.has(mediaType))
|
|
1297
|
+
return {
|
|
1298
|
+
ok: false,
|
|
1299
|
+
code: "attachment_unsupported_type",
|
|
1300
|
+
message: `Unsupported attachment type: ${mediaType}`
|
|
1301
|
+
};
|
|
1302
|
+
const data = typeof obj.data === "string" ? obj.data : void 0;
|
|
1303
|
+
const url = typeof obj.url === "string" ? obj.url : void 0;
|
|
1304
|
+
if (!data && !url)
|
|
1305
|
+
return {
|
|
1306
|
+
ok: false,
|
|
1307
|
+
code: "attachment_invalid",
|
|
1308
|
+
message: `attachments[${i}] requires either "data" (base64) or "url"`
|
|
1309
|
+
};
|
|
1310
|
+
if (data && url)
|
|
1311
|
+
return {
|
|
1312
|
+
ok: false,
|
|
1313
|
+
code: "attachment_invalid",
|
|
1314
|
+
message: `attachments[${i}] must not set both "data" and "url"`
|
|
1315
|
+
};
|
|
1316
|
+
if (url && !isHttpOrFile(url))
|
|
1317
|
+
return {
|
|
1318
|
+
ok: false,
|
|
1319
|
+
code: "attachment_invalid",
|
|
1320
|
+
message: `attachments[${i}].url must be http(s)/file/data scheme`
|
|
1321
|
+
};
|
|
1322
|
+
if (data) {
|
|
1323
|
+
const bytes = base64ByteLength(data);
|
|
1324
|
+
if (bytes === 0)
|
|
1325
|
+
return { ok: false, code: "attachment_invalid", message: `attachments[${i}].data is empty or malformed` };
|
|
1326
|
+
if (bytes > maxBytesPerFile)
|
|
1327
|
+
return {
|
|
1328
|
+
ok: false,
|
|
1329
|
+
code: "attachment_too_large",
|
|
1330
|
+
message: `Attachment ${obj.filename ?? `#${i}`} exceeds ${maxBytesPerFile} bytes (got ${bytes})`
|
|
1331
|
+
};
|
|
1332
|
+
totalBytes += bytes;
|
|
1333
|
+
if (totalBytes > maxBytesTotal)
|
|
1334
|
+
return {
|
|
1335
|
+
ok: false,
|
|
1336
|
+
code: "attachment_too_large",
|
|
1337
|
+
message: `Total attachment bytes exceed ${maxBytesTotal} (got ${totalBytes})`
|
|
1338
|
+
};
|
|
1339
|
+
}
|
|
1340
|
+
out.push({
|
|
1341
|
+
type: "image",
|
|
1342
|
+
mediaType,
|
|
1343
|
+
data,
|
|
1344
|
+
url,
|
|
1345
|
+
filename: typeof obj.filename === "string" ? obj.filename : void 0
|
|
1346
|
+
});
|
|
1347
|
+
}
|
|
1348
|
+
return { ok: true, value: out };
|
|
1349
|
+
};
|
|
1350
|
+
|
|
1351
|
+
// src/http-handlers.ts
|
|
1352
|
+
var isReadableLike = (body) => typeof body === "object" && body !== null && typeof body.on === "function";
|
|
1353
|
+
var readBody = async (req) => {
|
|
1354
|
+
if (req.body !== void 0 && req.body !== null && typeof req.body === "object" && !isReadableLike(req.body)) {
|
|
1355
|
+
return req.body;
|
|
1356
|
+
}
|
|
1357
|
+
if (typeof req.on !== "function") return void 0;
|
|
1358
|
+
const chunks = [];
|
|
1359
|
+
await new Promise((resolve, reject) => {
|
|
1360
|
+
const onData = (...args) => chunks.push(Buffer.from(args[0]));
|
|
1361
|
+
const onEnd = () => resolve();
|
|
1362
|
+
const onErr = (...args) => reject(args[0]);
|
|
1363
|
+
req.on("data", onData);
|
|
1364
|
+
req.on("end", onEnd);
|
|
1365
|
+
req.on("error", onErr);
|
|
1366
|
+
});
|
|
1367
|
+
const raw = Buffer.concat(chunks).toString("utf8");
|
|
1368
|
+
if (raw.length === 0) return void 0;
|
|
1369
|
+
return JSON.parse(raw);
|
|
1370
|
+
};
|
|
1371
|
+
var parseUrl = (req) => {
|
|
1372
|
+
const host = req.headers?.["host"] ?? "localhost";
|
|
1373
|
+
return new URL(req.url ?? "/", `http://${host}`);
|
|
1374
|
+
};
|
|
1375
|
+
var param = (req, key, url, index) => {
|
|
1376
|
+
if (req.params && typeof req.params[key] === "string") return req.params[key];
|
|
1377
|
+
const segs = url.pathname.split("/").filter(Boolean);
|
|
1378
|
+
return segs[index];
|
|
1379
|
+
};
|
|
1380
|
+
var sendJSON = (res, status, body) => {
|
|
1381
|
+
res.statusCode = status;
|
|
1382
|
+
res.setHeader("Content-Type", "application/json; charset=utf-8");
|
|
1383
|
+
res.end(JSON.stringify(body));
|
|
1384
|
+
};
|
|
1385
|
+
var sendError = (res, status, message) => sendJSON(res, status, { error: message });
|
|
1386
|
+
var TINYWEB_HEADERS2 = {
|
|
1387
|
+
"Content-Type": "text/event-stream",
|
|
1388
|
+
"Cache-Control": "no-cache, no-transform",
|
|
1389
|
+
Connection: "keep-alive"
|
|
1390
|
+
};
|
|
1391
|
+
var makeHTTPHandlers = (config) => {
|
|
1392
|
+
const defaultFormat = config.defaultFormat ?? "tinyweb";
|
|
1393
|
+
const ownerOf = async (req) => {
|
|
1394
|
+
if (!config.authorize) return void 0;
|
|
1395
|
+
const result = await config.authorize(req);
|
|
1396
|
+
return result?.ownerId;
|
|
1397
|
+
};
|
|
1398
|
+
const listSessions = async (req, res) => {
|
|
1399
|
+
const url = parseUrl(req);
|
|
1400
|
+
const limit = url.searchParams.get("limit");
|
|
1401
|
+
const cursor = url.searchParams.get("cursor") ?? void 0;
|
|
1402
|
+
const ownerOverride = url.searchParams.get("ownerId") ?? void 0;
|
|
1403
|
+
const owner = await ownerOf(req) ?? ownerOverride;
|
|
1404
|
+
const result = await config.api.list({
|
|
1405
|
+
limit: limit ? Number(limit) : void 0,
|
|
1406
|
+
cursor,
|
|
1407
|
+
ownerId: owner
|
|
1408
|
+
});
|
|
1409
|
+
sendJSON(res, 200, result);
|
|
1410
|
+
};
|
|
1411
|
+
const createSession = async (req, res) => {
|
|
1412
|
+
const body = await readBody(req) ?? {};
|
|
1413
|
+
const ownerHook = await ownerOf(req);
|
|
1414
|
+
const session = await config.api.create({
|
|
1415
|
+
title: body.title,
|
|
1416
|
+
metadata: body.metadata,
|
|
1417
|
+
ownerId: ownerHook ?? body.ownerId
|
|
1418
|
+
});
|
|
1419
|
+
sendJSON(res, 201, session);
|
|
1420
|
+
};
|
|
1421
|
+
const getSession = async (req, res) => {
|
|
1422
|
+
const url = parseUrl(req);
|
|
1423
|
+
const id = param(req, "id", url, 1);
|
|
1424
|
+
if (!id) return sendError(res, 400, "missing session id");
|
|
1425
|
+
const session = await config.api.get(id);
|
|
1426
|
+
if (!session) return sendError(res, 404, "session not found");
|
|
1427
|
+
sendJSON(res, 200, session);
|
|
1428
|
+
};
|
|
1429
|
+
const updateSession = async (req, res) => {
|
|
1430
|
+
const url = parseUrl(req);
|
|
1431
|
+
const id = param(req, "id", url, 1);
|
|
1432
|
+
if (!id) return sendError(res, 400, "missing session id");
|
|
1433
|
+
const body = await readBody(req) ?? {};
|
|
1434
|
+
const updated = await config.api.patch(id, { title: body.title, metadata: body.metadata });
|
|
1435
|
+
if (!updated) return sendError(res, 404, "session not found");
|
|
1436
|
+
sendJSON(res, 200, updated);
|
|
1437
|
+
};
|
|
1438
|
+
const deleteSession = async (req, res) => {
|
|
1439
|
+
const url = parseUrl(req);
|
|
1440
|
+
const id = param(req, "id", url, 1);
|
|
1441
|
+
if (!id) return sendError(res, 400, "missing session id");
|
|
1442
|
+
await config.api.delete(id);
|
|
1443
|
+
sendJSON(res, 200, { ok: true });
|
|
1444
|
+
};
|
|
1445
|
+
const listMessages = async (req, res) => {
|
|
1446
|
+
const url = parseUrl(req);
|
|
1447
|
+
const id = param(req, "id", url, 1);
|
|
1448
|
+
if (!id) return sendError(res, 400, "missing session id");
|
|
1449
|
+
const limit = url.searchParams.get("limit");
|
|
1450
|
+
const before = url.searchParams.get("before") ?? void 0;
|
|
1451
|
+
const result = await config.api.messages(id, {
|
|
1452
|
+
limit: limit ? Number(limit) : void 0,
|
|
1453
|
+
before
|
|
1454
|
+
});
|
|
1455
|
+
sendJSON(res, 200, result);
|
|
1456
|
+
};
|
|
1457
|
+
const deleteMessage = async (req, res) => {
|
|
1458
|
+
const url = parseUrl(req);
|
|
1459
|
+
const id = param(req, "id", url, 1);
|
|
1460
|
+
const mid = param(req, "mid", url, 3);
|
|
1461
|
+
if (!id || !mid) return sendError(res, 400, "missing ids");
|
|
1462
|
+
await config.api.deleteMessage(id, mid);
|
|
1463
|
+
sendJSON(res, 200, { ok: true });
|
|
1464
|
+
};
|
|
1465
|
+
const chat = async (req, res) => {
|
|
1466
|
+
const url = parseUrl(req);
|
|
1467
|
+
const id = param(req, "id", url, 1);
|
|
1468
|
+
if (!id) return sendError(res, 400, "missing session id");
|
|
1469
|
+
const body = await readBody(req) ?? {};
|
|
1470
|
+
const prompt = body.prompt?.trim() ?? "";
|
|
1471
|
+
const validation = validateAttachments(body.attachments, config.attachments);
|
|
1472
|
+
if (!validation.ok) return sendJSON(res, 400, { error: validation.message, code: validation.code });
|
|
1473
|
+
const attachments = validation.value;
|
|
1474
|
+
if (!prompt && attachments.length === 0) return sendError(res, 400, "missing prompt");
|
|
1475
|
+
const format = body.format ?? defaultFormat;
|
|
1476
|
+
const headers = format === "ai-sdk" ? protocol.AI_SDK_HEADERS : TINYWEB_HEADERS2;
|
|
1477
|
+
for (const [name, value] of Object.entries(headers)) res.setHeader(name, value);
|
|
1478
|
+
if (typeof res.flushHeaders === "function") res.flushHeaders();
|
|
1479
|
+
for await (const event of config.run({ prompt, sessionId: id, attachments })) {
|
|
1480
|
+
const proto = event;
|
|
1481
|
+
const line = format === "ai-sdk" ? protocol.toAISDKDataStream(proto) : protocol.encodeSSE(proto);
|
|
1482
|
+
if (line.length > 0) res.write(line);
|
|
1483
|
+
}
|
|
1484
|
+
res.end();
|
|
1485
|
+
};
|
|
1486
|
+
return {
|
|
1487
|
+
listSessions,
|
|
1488
|
+
createSession,
|
|
1489
|
+
getSession,
|
|
1490
|
+
updateSession,
|
|
1491
|
+
deleteSession,
|
|
1492
|
+
listMessages,
|
|
1493
|
+
deleteMessage,
|
|
1494
|
+
chat
|
|
1495
|
+
};
|
|
1496
|
+
};
|
|
1497
|
+
|
|
1498
|
+
// src/prompt/tool-use.ts
|
|
1499
|
+
var toolUseSection = () => [
|
|
1500
|
+
"====",
|
|
1501
|
+
"",
|
|
1502
|
+
"TOOL USE",
|
|
1503
|
+
"",
|
|
1504
|
+
"You have access to a set of tools provided by the host application. Tools are",
|
|
1505
|
+
"invoked through the provider-native function-calling mechanism \u2014 you do NOT",
|
|
1506
|
+
"write tool calls as text, JSON, or XML inside your assistant content.",
|
|
1507
|
+
"",
|
|
1508
|
+
"- Each tool call must specify a registered tool name and arguments matching",
|
|
1509
|
+
" that tool's parameter schema.",
|
|
1510
|
+
"- Tool results are returned as a separate `tool` message in the conversation",
|
|
1511
|
+
" history. Read the result before deciding the next action.",
|
|
1512
|
+
"- You may call multiple tools across a single turn when it genuinely helps,",
|
|
1513
|
+
" but every call must be justified by the user's intent."
|
|
1514
|
+
].join("\n");
|
|
1515
|
+
|
|
1516
|
+
// src/prompt/tool-use-guidelines.ts
|
|
1517
|
+
var DEFAULT_MAX_CALLS_PER_TURN = 3;
|
|
1518
|
+
var toolUseGuidelinesSection = (config = {}) => {
|
|
1519
|
+
const maxCalls = config.maxCallsPerTurn ?? DEFAULT_MAX_CALLS_PER_TURN;
|
|
1520
|
+
return [
|
|
1521
|
+
"====",
|
|
1522
|
+
"",
|
|
1523
|
+
"TOOL USE GUIDELINES",
|
|
1524
|
+
"",
|
|
1525
|
+
"1. READ the user's intent before picking a tool. Do NOT pick a tool just",
|
|
1526
|
+
" because a keyword in the message matches the tool name. Example: if the",
|
|
1527
|
+
" user asks for travel recommendations about a city, that does NOT mean",
|
|
1528
|
+
" you should call a weather tool \u2014 pick the search/recommendation tool.",
|
|
1529
|
+
"",
|
|
1530
|
+
"2. Prefer answering directly when the question is conversational, opinion-",
|
|
1531
|
+
" based, or covered by your general knowledge. Tools exist for fresh,",
|
|
1532
|
+
" external, or computed data \u2014 not for restating things you already know.",
|
|
1533
|
+
"",
|
|
1534
|
+
"3. If multiple tools could plausibly fit, pick the most specific one. If",
|
|
1535
|
+
" you are not confident, answer directly instead of guessing a tool.",
|
|
1536
|
+
"",
|
|
1537
|
+
"4. ANTI-LOOP RULES (strict):",
|
|
1538
|
+
" - Do NOT call the same tool twice with identical arguments in one turn.",
|
|
1539
|
+
" - If a tool returns an error, do NOT retry it. Briefly tell the user",
|
|
1540
|
+
" what failed and stop.",
|
|
1541
|
+
` - Hard cap: at most ${maxCalls} tool call(s) per turn. After reaching the`,
|
|
1542
|
+
" cap you MUST stop calling tools and answer with whatever data you",
|
|
1543
|
+
" already collected.",
|
|
1544
|
+
" - Once a tool has returned enough data to answer the user, STOP. Do not",
|
|
1545
|
+
' call additional tools "to be safe" or to corroborate.',
|
|
1546
|
+
"",
|
|
1547
|
+
"5. Each tool call must be informed by the previous result. Do not plan a",
|
|
1548
|
+
" chain of calls up front and execute it blindly \u2014 read each result and",
|
|
1549
|
+
" decide whether the next call is still needed."
|
|
1550
|
+
].join("\n");
|
|
1551
|
+
};
|
|
1552
|
+
|
|
1553
|
+
// src/prompt/objective.ts
|
|
1554
|
+
var chatObjective = () => [
|
|
1555
|
+
"====",
|
|
1556
|
+
"",
|
|
1557
|
+
"OBJECTIVE",
|
|
1558
|
+
"",
|
|
1559
|
+
"Your job is to be GENUINELY HELPFUL to the user. Treat every question as",
|
|
1560
|
+
"something you want to answer well \u2014 not something to deflect.",
|
|
1561
|
+
"",
|
|
1562
|
+
"1. UNDERSTAND the user's actual intent before responding. Re-read the last",
|
|
1563
|
+
' few turns of conversation; questions like "gi\xE1m \u0111\u1ED1c l\xE0 ai?" or "th\xEC sao?"',
|
|
1564
|
+
" only make sense in context of the prior topic. Resolve pronouns and",
|
|
1565
|
+
" topic references from history before deciding how to answer.",
|
|
1566
|
+
"",
|
|
1567
|
+
"2. DECIDE: can you answer well from your own knowledge?",
|
|
1568
|
+
" - YES \u2192 answer directly, concisely, in the user's language.",
|
|
1569
|
+
" - NO, or the answer needs FRESH data (people, prices, current events,",
|
|
1570
|
+
" specific companies, recent news) \u2192 use the most relevant tool to find",
|
|
1571
|
+
` out. Do NOT bail with "I don't have updated info" when a search tool`,
|
|
1572
|
+
" is available. Search first, then answer with what you found.",
|
|
1573
|
+
"",
|
|
1574
|
+
"3. BE PROACTIVE, NOT LAZY:",
|
|
1575
|
+
" - If the user asks about a specific entity (a company, person, product)",
|
|
1576
|
+
" and you are not confident your knowledge is current, search.",
|
|
1577
|
+
" - If a search returns partial info, share what you found and explicitly",
|
|
1578
|
+
" state what is still unknown \u2014 don't pretend nothing was found.",
|
|
1579
|
+
' - Follow-up questions inherit the topic of the previous turn. "gi\xE1m \u0111\u1ED1c',
|
|
1580
|
+
` l\xE0 ai?" right after a question about company X means "who is X's CEO?"`,
|
|
1581
|
+
` \u2014 search for that, don't reply "I don't know which company".`,
|
|
1582
|
+
"",
|
|
1583
|
+
"4. ASK ONLY WHEN TRULY AMBIGUOUS. A clarifying question is appropriate when",
|
|
1584
|
+
" the request is missing information you cannot infer (e.g. user says",
|
|
1585
|
+
' "book a flight" with no destination). It is NOT appropriate as an escape',
|
|
1586
|
+
" hatch when you simply didn't try to find the answer.",
|
|
1587
|
+
"",
|
|
1588
|
+
"5. RESPECT THE TOOL CAPS in TOOL USE GUIDELINES \u2014 but use the budget you",
|
|
1589
|
+
" have. If you have 3 tool calls allowed and you've used 0, and the user's",
|
|
1590
|
+
" question clearly needs a search, USE one. The cap is a ceiling, not a",
|
|
1591
|
+
" target to avoid.",
|
|
1592
|
+
"",
|
|
1593
|
+
"6. END EACH TURN with a complete, useful answer. Don't stop mid-thought,",
|
|
1594
|
+
` don't promise to "check later", don't return only a tool result without`,
|
|
1595
|
+
" summarizing it in plain language for the user."
|
|
1596
|
+
].join("\n");
|
|
1597
|
+
var taskObjective = () => [
|
|
1598
|
+
"====",
|
|
1599
|
+
"",
|
|
1600
|
+
"OBJECTIVE",
|
|
1601
|
+
"",
|
|
1602
|
+
"You accomplish a given task iteratively, breaking it down into clear steps",
|
|
1603
|
+
"and working through them methodically.",
|
|
1604
|
+
"",
|
|
1605
|
+
"1. Analyze the user's task and set clear, achievable goals. Prioritize them",
|
|
1606
|
+
" in a logical order.",
|
|
1607
|
+
"2. Work through goals sequentially, using tools one at a time. Each tool",
|
|
1608
|
+
" call should be informed by the previous result.",
|
|
1609
|
+
"3. Before calling a tool, analyze the context. Determine which tool is most",
|
|
1610
|
+
" relevant and whether all required parameters are present or inferable.",
|
|
1611
|
+
" If a required parameter is missing and cannot be inferred, ask the user",
|
|
1612
|
+
" instead of guessing.",
|
|
1613
|
+
"4. When the task is complete, present the final result clearly. Do not",
|
|
1614
|
+
' continue with extra tool calls "to be safe".',
|
|
1615
|
+
"5. If the user provides feedback, use it to improve and try again \u2014 but do",
|
|
1616
|
+
" not engage in pointless back-and-forth. Don't end responses with open",
|
|
1617
|
+
" offers for further assistance."
|
|
1618
|
+
].join("\n");
|
|
1619
|
+
var objectiveSection = (config = {}) => {
|
|
1620
|
+
const kind = config.kind ?? "chat";
|
|
1621
|
+
if (kind === "task") return taskObjective();
|
|
1622
|
+
return chatObjective();
|
|
1623
|
+
};
|
|
1624
|
+
|
|
1625
|
+
// src/prompt/response-style.ts
|
|
1626
|
+
var chatStyle = () => [
|
|
1627
|
+
"====",
|
|
1628
|
+
"",
|
|
1629
|
+
"RESPONSE STYLE",
|
|
1630
|
+
"",
|
|
1631
|
+
"Your replies are rendered next to a tool-result card that already shows",
|
|
1632
|
+
"structured data to the user. Therefore:",
|
|
1633
|
+
"",
|
|
1634
|
+
"- Do NOT repeat numbers, names, dates, units, codes, or any field value",
|
|
1635
|
+
" that is already visible on the tool-result card.",
|
|
1636
|
+
"- After a tool call, write AT MOST one short sentence of commentary,",
|
|
1637
|
+
" insight, warning, or follow-up suggestion \u2014 something the card does not",
|
|
1638
|
+
" already say.",
|
|
1639
|
+
"- If you have nothing useful to add, reply with a single short ack such",
|
|
1640
|
+
` as "Here you go." / "Done." / "That's the latest." \u2014 but never restate`,
|
|
1641
|
+
" the card contents.",
|
|
1642
|
+
"- If the user asked multiple things in one message and you called several",
|
|
1643
|
+
" tools, write ONE combined sentence with brief observations \u2014 do not list",
|
|
1644
|
+
" the numbers again.",
|
|
1645
|
+
"- Match the user's language. Keep replies short and direct."
|
|
1646
|
+
].join("\n");
|
|
1647
|
+
var verboseStyle = () => [
|
|
1648
|
+
"====",
|
|
1649
|
+
"",
|
|
1650
|
+
"RESPONSE STYLE",
|
|
1651
|
+
"",
|
|
1652
|
+
"Narrate your reasoning and actions so the user can follow along. Summarise",
|
|
1653
|
+
"tool results in your own words. Keep paragraphs short. Match the user's",
|
|
1654
|
+
"language. Do not pad with filler."
|
|
1655
|
+
].join("\n");
|
|
1656
|
+
var responseStyleSection = (config = {}) => {
|
|
1657
|
+
const kind = config.kind ?? "chat";
|
|
1658
|
+
if (kind === "off") return "";
|
|
1659
|
+
if (kind === "verbose") return verboseStyle();
|
|
1660
|
+
return chatStyle();
|
|
1661
|
+
};
|
|
1662
|
+
|
|
1663
|
+
// src/prompt/index.ts
|
|
1664
|
+
var resolveToggle = (toggle, defaults) => {
|
|
1665
|
+
if (toggle === false) return void 0;
|
|
1666
|
+
if (toggle === void 0 || toggle === true) return defaults;
|
|
1667
|
+
return toggle;
|
|
1668
|
+
};
|
|
1669
|
+
var composeSystemPrompt = (input) => {
|
|
1670
|
+
const parts = [];
|
|
1671
|
+
const role = input.role?.trim();
|
|
1672
|
+
if (role && role.length > 0) parts.push(role);
|
|
1673
|
+
const sections = input.sections ?? {};
|
|
1674
|
+
if (sections.toolUse !== false) {
|
|
1675
|
+
parts.push(toolUseSection());
|
|
1676
|
+
}
|
|
1677
|
+
const guidelinesCfg = resolveToggle(sections.toolUseGuidelines, {});
|
|
1678
|
+
if (guidelinesCfg) {
|
|
1679
|
+
parts.push(toolUseGuidelinesSection(guidelinesCfg));
|
|
1680
|
+
}
|
|
1681
|
+
const objectiveCfg = resolveToggle(sections.objective, {});
|
|
1682
|
+
if (objectiveCfg) {
|
|
1683
|
+
parts.push(objectiveSection(objectiveCfg));
|
|
1684
|
+
}
|
|
1685
|
+
const styleCfg = resolveToggle(sections.responseStyle, {});
|
|
1686
|
+
if (styleCfg) {
|
|
1687
|
+
const rendered = responseStyleSection(styleCfg);
|
|
1688
|
+
if (rendered.length > 0) parts.push(rendered);
|
|
1689
|
+
}
|
|
1690
|
+
return parts.join("\n\n");
|
|
1691
|
+
};
|
|
1692
|
+
|
|
1693
|
+
// src/agent.ts
|
|
1694
|
+
var defaultStore;
|
|
1695
|
+
var getDefaultStore = () => {
|
|
1696
|
+
if (defaultStore) return defaultStore;
|
|
1697
|
+
defaultStore = makeMemoryStore();
|
|
1698
|
+
return defaultStore;
|
|
1699
|
+
};
|
|
1700
|
+
async function buildMergedTools(config, loadedHooks) {
|
|
1701
|
+
const baseTools = config.tools ?? {};
|
|
1702
|
+
let mcpTools = {};
|
|
1703
|
+
if (config.mcp && Object.keys(config.mcp).length > 0) {
|
|
1704
|
+
const { tools } = await connectAllMcp(config.mcp);
|
|
1705
|
+
mcpTools = tools;
|
|
1706
|
+
}
|
|
1707
|
+
let skillToolRecord = {};
|
|
1708
|
+
if (config.skillDirs !== void 0 || Object.keys(baseTools).length > 0) {
|
|
1709
|
+
const skills = await loadSkills(config.skillDirs);
|
|
1710
|
+
if (skills.length > 0) skillToolRecord = { skill: makeSkillTool(skills) };
|
|
1711
|
+
}
|
|
1712
|
+
const merged = { ...skillToolRecord, ...mcpTools, ...baseTools };
|
|
1713
|
+
for (const hooks of loadedHooks) {
|
|
1714
|
+
if (!hooks["tool.definition"]) continue;
|
|
1715
|
+
for (const [toolId, tool] of Object.entries(merged)) {
|
|
1716
|
+
const output = { description: tool.description, parameters: tool._definition.inputSchema };
|
|
1717
|
+
await hooks["tool.definition"]({ toolId }, output);
|
|
1718
|
+
if (output.description !== tool.description) {
|
|
1719
|
+
tool.description = output.description;
|
|
1720
|
+
}
|
|
1721
|
+
}
|
|
1722
|
+
}
|
|
1723
|
+
return merged;
|
|
1724
|
+
}
|
|
1725
|
+
async function buildTools(config, loadedHooks) {
|
|
1726
|
+
const merged = await buildMergedTools(config, loadedHooks);
|
|
1727
|
+
const askMode = config.askMode ?? "handler";
|
|
1728
|
+
return {
|
|
1729
|
+
tools: applyPermission(merged, config.permission, config.askHandler, askMode),
|
|
1730
|
+
resumeTools: merged
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
var defineAgent = (config) => {
|
|
1734
|
+
const rt = () => config.runtime ?? defaultRuntime();
|
|
1735
|
+
const store = config.store ?? getDefaultStore();
|
|
1736
|
+
const stopWhen = config.stopWhen ?? llm.LLM.stepCountIs(100);
|
|
1737
|
+
const resolvedSystemPrompt = composeSystemPrompt({
|
|
1738
|
+
role: config.systemPrompt,
|
|
1739
|
+
sections: config.promptSections
|
|
1740
|
+
});
|
|
1741
|
+
const compactionCfg = {
|
|
1742
|
+
auto: config.compaction?.auto !== false,
|
|
1743
|
+
reservedTokens: config.compaction?.reservedTokens,
|
|
1744
|
+
preserveRecentTurns: config.compaction?.preserveRecentTurns
|
|
1745
|
+
};
|
|
1746
|
+
let toolsPromise;
|
|
1747
|
+
const getTools = () => {
|
|
1748
|
+
if (!toolsPromise) {
|
|
1749
|
+
const pluginInput = { agentName: config.name, directory: process.cwd() };
|
|
1750
|
+
toolsPromise = loadPlugins(config.plugins ?? [], pluginInput).then((loaded) => {
|
|
1751
|
+
const hooks = loaded.map((l) => l.hooks);
|
|
1752
|
+
return buildTools(config, hooks);
|
|
1753
|
+
});
|
|
1754
|
+
}
|
|
1755
|
+
return toolsPromise;
|
|
1756
|
+
};
|
|
1757
|
+
const makeAgentProcessor = async () => {
|
|
1758
|
+
const built = await getTools();
|
|
1759
|
+
return makeProcessor({
|
|
1760
|
+
agentName: config.name,
|
|
1761
|
+
model: config.model,
|
|
1762
|
+
store,
|
|
1763
|
+
runtime: rt(),
|
|
1764
|
+
systemPrompt: resolvedSystemPrompt,
|
|
1765
|
+
tools: built.tools,
|
|
1766
|
+
resumeTools: built.resumeTools,
|
|
1767
|
+
stopWhen,
|
|
1768
|
+
generation: config.generation,
|
|
1769
|
+
compaction: compactionCfg
|
|
1770
|
+
});
|
|
1771
|
+
};
|
|
1772
|
+
const run = (input) => {
|
|
1773
|
+
let innerIter;
|
|
1774
|
+
return {
|
|
1775
|
+
[Symbol.asyncIterator]() {
|
|
1776
|
+
return {
|
|
1777
|
+
async next() {
|
|
1778
|
+
if (!innerIter) {
|
|
1779
|
+
const processor = await makeAgentProcessor();
|
|
1780
|
+
innerIter = processor.runTurn(input)[Symbol.asyncIterator]();
|
|
1781
|
+
}
|
|
1782
|
+
return innerIter.next();
|
|
1783
|
+
},
|
|
1784
|
+
async return(value) {
|
|
1785
|
+
return innerIter ? innerIter.return ? innerIter.return(value) : { done: true, value } : { done: true, value };
|
|
1786
|
+
}
|
|
1787
|
+
};
|
|
1788
|
+
}
|
|
1789
|
+
};
|
|
1790
|
+
};
|
|
1791
|
+
const resume = (input) => {
|
|
1792
|
+
let innerIter;
|
|
1793
|
+
return {
|
|
1794
|
+
[Symbol.asyncIterator]() {
|
|
1795
|
+
return {
|
|
1796
|
+
async next() {
|
|
1797
|
+
if (!innerIter) {
|
|
1798
|
+
const processor = await makeAgentProcessor();
|
|
1799
|
+
innerIter = processor.resumeTurn({ sessionId: input.sessionId })[Symbol.asyncIterator]();
|
|
1800
|
+
}
|
|
1801
|
+
return innerIter.next();
|
|
1802
|
+
},
|
|
1803
|
+
async return(value) {
|
|
1804
|
+
return innerIter ? innerIter.return ? innerIter.return(value) : { done: true, value } : { done: true, value };
|
|
1805
|
+
}
|
|
1806
|
+
};
|
|
1807
|
+
}
|
|
1808
|
+
};
|
|
1809
|
+
};
|
|
1810
|
+
const resolveApproval = async (input) => {
|
|
1811
|
+
const history = await rt().runPromise(store.getMessages(input.sessionId));
|
|
1812
|
+
let targetMsg;
|
|
1813
|
+
let targetPart;
|
|
1814
|
+
let partIndex = -1;
|
|
1815
|
+
for (let i = history.length - 1; i >= 0; i--) {
|
|
1816
|
+
const msg = history[i];
|
|
1817
|
+
if (!msg || msg.role !== "assistant") continue;
|
|
1818
|
+
const idx = msg.parts.findIndex(
|
|
1819
|
+
(p) => p.type === "tool" && p.callID === input.callID && p.state === "pending-approval"
|
|
1820
|
+
);
|
|
1821
|
+
if (idx !== -1) {
|
|
1822
|
+
targetMsg = msg;
|
|
1823
|
+
targetPart = msg.parts[idx];
|
|
1824
|
+
partIndex = idx;
|
|
1825
|
+
break;
|
|
1826
|
+
}
|
|
1827
|
+
}
|
|
1828
|
+
if (!targetMsg || !targetPart || partIndex < 0) {
|
|
1829
|
+
throw new Error(`No pending approval found for callID="${input.callID}"`);
|
|
1830
|
+
}
|
|
1831
|
+
const nextState = input.approved ? "approved" : "rejected";
|
|
1832
|
+
const nextParts = targetMsg.parts.map(
|
|
1833
|
+
(p, idx) => idx === partIndex ? { ...targetPart, state: nextState } : p
|
|
1834
|
+
);
|
|
1835
|
+
const updated = { ...targetMsg, parts: nextParts };
|
|
1836
|
+
await rt().runPromise(persistMessageUpdate(store, input.sessionId, updated));
|
|
1837
|
+
return {
|
|
1838
|
+
callID: input.callID,
|
|
1839
|
+
state: nextState,
|
|
1840
|
+
toolName: targetPart.name,
|
|
1841
|
+
input: targetPart.input
|
|
1842
|
+
};
|
|
1843
|
+
};
|
|
1844
|
+
const runOnce = async (input) => {
|
|
1845
|
+
const { tools } = await getTools();
|
|
1846
|
+
const budget = usable({
|
|
1847
|
+
limits: config.model.limits,
|
|
1848
|
+
reservedTokens: compactionCfg.reservedTokens
|
|
1849
|
+
});
|
|
1850
|
+
const keepRecent = compactionCfg.preserveRecentTurns ?? 4;
|
|
1851
|
+
const result = await rt().runPromise(
|
|
1852
|
+
effect.Effect.gen(function* () {
|
|
1853
|
+
const session = yield* store.upsertSession({ id: input.sessionId, agentName: config.name });
|
|
1854
|
+
if (compactionCfg.auto) {
|
|
1855
|
+
const history = yield* store.getMessages(session.id);
|
|
1856
|
+
const promptTokens = Math.ceil(input.prompt.length / 4);
|
|
1857
|
+
const systemTokens = Math.ceil(resolvedSystemPrompt.length / 4);
|
|
1858
|
+
if (estimateTokens(history) + promptTokens + systemTokens >= budget) {
|
|
1859
|
+
yield* compact({
|
|
1860
|
+
sessionId: session.id,
|
|
1861
|
+
store,
|
|
1862
|
+
model: config.model,
|
|
1863
|
+
keepRecent,
|
|
1864
|
+
overflow: false
|
|
1865
|
+
});
|
|
1866
|
+
}
|
|
1867
|
+
}
|
|
1868
|
+
const attempt = () => effect.Effect.gen(function* () {
|
|
1869
|
+
const history = yield* store.getMessages(session.id);
|
|
1870
|
+
const userContent = [];
|
|
1871
|
+
if (input.prompt.length > 0) userContent.push({ type: "text", text: input.prompt });
|
|
1872
|
+
for (const a of input.attachments ?? [])
|
|
1873
|
+
userContent.push({
|
|
1874
|
+
type: "media",
|
|
1875
|
+
mediaType: a.mediaType,
|
|
1876
|
+
data: a.url ?? a.data ?? "",
|
|
1877
|
+
filename: a.filename
|
|
1878
|
+
});
|
|
1879
|
+
const userMsg = userContent.length === 0 ? llm.LLM.user(input.prompt) : llm.LLM.user(userContent);
|
|
1880
|
+
const request = llm.LLM.request({
|
|
1881
|
+
model: config.model,
|
|
1882
|
+
system: resolvedSystemPrompt,
|
|
1883
|
+
messages: [...historyToLLMMessages([...history]), userMsg],
|
|
1884
|
+
generation: config.generation
|
|
1885
|
+
});
|
|
1886
|
+
return yield* llm.LLMClient.generate({ request, tools, stopWhen });
|
|
1887
|
+
});
|
|
1888
|
+
let didRetry = false;
|
|
1889
|
+
const response = yield* attempt().pipe(
|
|
1890
|
+
effect.Effect.catchTag("LLM.Error", (err) => {
|
|
1891
|
+
if (err.reason._tag === "ContextOverflow" && compactionCfg.auto && !didRetry) {
|
|
1892
|
+
didRetry = true;
|
|
1893
|
+
return effect.Effect.gen(function* () {
|
|
1894
|
+
yield* compact({
|
|
1895
|
+
sessionId: session.id,
|
|
1896
|
+
store,
|
|
1897
|
+
model: config.model,
|
|
1898
|
+
keepRecent,
|
|
1899
|
+
overflow: true
|
|
1900
|
+
});
|
|
1901
|
+
return yield* attempt();
|
|
1902
|
+
});
|
|
1903
|
+
}
|
|
1904
|
+
return effect.Effect.fail(err);
|
|
1905
|
+
})
|
|
1906
|
+
);
|
|
1907
|
+
return response;
|
|
1908
|
+
})
|
|
1909
|
+
);
|
|
1910
|
+
return { text: result.text, usage: result.usage, events: result.events };
|
|
1911
|
+
};
|
|
1912
|
+
const toSSEHandler = (options) => makeSSEHandler(run, options);
|
|
1913
|
+
const sessions = makeSessionAPI({
|
|
1914
|
+
agentName: config.name,
|
|
1915
|
+
store,
|
|
1916
|
+
runtime: config.runtime
|
|
1917
|
+
});
|
|
1918
|
+
const toHTTPHandlers = (options) => makeHTTPHandlers({
|
|
1919
|
+
api: sessions,
|
|
1920
|
+
run: (input) => run({ prompt: input.prompt, sessionId: input.sessionId, attachments: input.attachments }),
|
|
1921
|
+
authorize: options?.authorize,
|
|
1922
|
+
defaultFormat: options?.defaultFormat
|
|
1923
|
+
});
|
|
1924
|
+
return {
|
|
1925
|
+
name: config.name,
|
|
1926
|
+
run,
|
|
1927
|
+
runOnce,
|
|
1928
|
+
resolveApproval,
|
|
1929
|
+
resume,
|
|
1930
|
+
toSSEHandler,
|
|
1931
|
+
sessions,
|
|
1932
|
+
toHTTPHandlers
|
|
1933
|
+
};
|
|
1934
|
+
};
|
|
1935
|
+
var wrapExecute = (execute) => (input) => {
|
|
1936
|
+
const result = execute(input);
|
|
1937
|
+
if (effect.Effect.isEffect(result)) return result;
|
|
1938
|
+
return effect.Effect.tryPromise({
|
|
1939
|
+
try: () => result,
|
|
1940
|
+
catch: (cause) => new llm.ToolFailure({ message: cause instanceof Error ? cause.message : String(cause) })
|
|
1941
|
+
});
|
|
1942
|
+
};
|
|
1943
|
+
function defineTool(config) {
|
|
1944
|
+
const success = config.success ?? effect.Schema.Unknown;
|
|
1945
|
+
return llm.Tool.make({
|
|
1946
|
+
description: config.description,
|
|
1947
|
+
parameters: config.parameters,
|
|
1948
|
+
success,
|
|
1949
|
+
execute: wrapExecute(config.execute)
|
|
1950
|
+
});
|
|
1951
|
+
}
|
|
1952
|
+
|
|
1953
|
+
// src/transcript.ts
|
|
1954
|
+
var toNameSet = (n) => {
|
|
1955
|
+
if (n === void 0) return /* @__PURE__ */ new Set(["display_response"]);
|
|
1956
|
+
if (typeof n === "string") return /* @__PURE__ */ new Set([n]);
|
|
1957
|
+
return new Set(n);
|
|
1958
|
+
};
|
|
1959
|
+
var makeAssistantTextAccumulator = (options = {}) => {
|
|
1960
|
+
const names = toNameSet(options.displayResponseToolName);
|
|
1961
|
+
let buffer = "";
|
|
1962
|
+
let sayMessage;
|
|
1963
|
+
return {
|
|
1964
|
+
push(event) {
|
|
1965
|
+
if (event.type === "text-delta") {
|
|
1966
|
+
buffer += event.text;
|
|
1967
|
+
return;
|
|
1968
|
+
}
|
|
1969
|
+
if (event.type === "tool-call" && names.has(event.name)) {
|
|
1970
|
+
const input = event.input;
|
|
1971
|
+
const msg = input && typeof input.response === "string" ? input.response : void 0;
|
|
1972
|
+
if (msg && msg.length > 0) sayMessage = msg;
|
|
1973
|
+
}
|
|
1974
|
+
},
|
|
1975
|
+
text() {
|
|
1976
|
+
if (buffer.length > 0) return buffer;
|
|
1977
|
+
return sayMessage ?? "";
|
|
1978
|
+
},
|
|
1979
|
+
hasPlainText() {
|
|
1980
|
+
return buffer.length > 0;
|
|
1981
|
+
},
|
|
1982
|
+
displayResponseMessage() {
|
|
1983
|
+
return sayMessage;
|
|
1984
|
+
}
|
|
1985
|
+
};
|
|
1986
|
+
};
|
|
1987
|
+
var collectAssistantText = (events, options = {}) => {
|
|
1988
|
+
const acc = makeAssistantTextAccumulator(options);
|
|
1989
|
+
for (const e of events) acc.push(e);
|
|
1990
|
+
return acc.text();
|
|
1991
|
+
};
|
|
1992
|
+
var makeBus = () => {
|
|
1993
|
+
const pubsubEffect = effect.PubSub.unbounded();
|
|
1994
|
+
let cached2;
|
|
1995
|
+
const get = () => {
|
|
1996
|
+
if (cached2) return effect.Effect.succeed(cached2);
|
|
1997
|
+
return pubsubEffect.pipe(
|
|
1998
|
+
effect.Effect.tap((p) => {
|
|
1999
|
+
cached2 = p;
|
|
2000
|
+
return effect.Effect.void;
|
|
2001
|
+
})
|
|
2002
|
+
);
|
|
2003
|
+
};
|
|
2004
|
+
const publish = (event) => effect.Effect.flatMap(get(), (pubsub) => effect.Effect.asVoid(effect.PubSub.publish(pubsub, event)));
|
|
2005
|
+
const subscribeAll = () => effect.Stream.unwrap(effect.Effect.map(get(), (pubsub) => effect.Stream.fromPubSub(pubsub)));
|
|
2006
|
+
const subscribe = (type) => subscribeAll().pipe(
|
|
2007
|
+
effect.Stream.filter((e) => e.type === type)
|
|
2008
|
+
);
|
|
2009
|
+
return { publish, subscribe, subscribeAll };
|
|
2010
|
+
};
|
|
2011
|
+
|
|
2012
|
+
// src/index.ts
|
|
2013
|
+
var VERSION = "0.0.1";
|
|
2014
|
+
|
|
2015
|
+
exports.DEFAULT_IMAGE_MIMES = DEFAULT_IMAGE_MIMES;
|
|
2016
|
+
exports.DEFAULT_MAX_BYTES_PER_FILE = DEFAULT_MAX_BYTES_PER_FILE;
|
|
2017
|
+
exports.DEFAULT_MAX_BYTES_TOTAL = DEFAULT_MAX_BYTES_TOTAL;
|
|
2018
|
+
exports.DEFAULT_MAX_COUNT = DEFAULT_MAX_COUNT;
|
|
2019
|
+
exports.FINISH_REASON_APPROVAL_REQUIRED = FINISH_REASON_APPROVAL_REQUIRED;
|
|
2020
|
+
exports.TOOL_INTERRUPT_KIND = TOOL_INTERRUPT_KIND;
|
|
2021
|
+
exports.VERSION = VERSION;
|
|
2022
|
+
exports.applyChatHeaders = applyChatHeaders;
|
|
2023
|
+
exports.applyChatMessage = applyChatMessage;
|
|
2024
|
+
exports.applyChatParams = applyChatParams;
|
|
2025
|
+
exports.applyEvent = applyEvent;
|
|
2026
|
+
exports.applyPermission = applyPermission;
|
|
2027
|
+
exports.applyPermissionHook = applyPermissionHook;
|
|
2028
|
+
exports.applySystemTransform = applySystemTransform;
|
|
2029
|
+
exports.applyToolAfter = applyToolAfter;
|
|
2030
|
+
exports.applyToolBefore = applyToolBefore;
|
|
2031
|
+
exports.applyToolDefinition = applyToolDefinition;
|
|
2032
|
+
exports.collectAssistantText = collectAssistantText;
|
|
2033
|
+
exports.compact = compact;
|
|
2034
|
+
exports.composeSystemPrompt = composeSystemPrompt;
|
|
2035
|
+
exports.connectAllMcp = connectAllMcp;
|
|
2036
|
+
exports.connectMcp = connectMcp;
|
|
2037
|
+
exports.createRuntime = createRuntime;
|
|
2038
|
+
exports.defaultRuntime = defaultRuntime;
|
|
2039
|
+
exports.defineAgent = defineAgent;
|
|
2040
|
+
exports.defineTool = defineTool;
|
|
2041
|
+
exports.disposeDefaultRuntime = disposeDefaultRuntime;
|
|
2042
|
+
exports.estimateTokens = estimateTokens;
|
|
2043
|
+
exports.findCompactionPart = findCompactionPart;
|
|
2044
|
+
exports.fromLLMEvent = fromLLMEvent;
|
|
2045
|
+
exports.isOverflow = isOverflow;
|
|
2046
|
+
exports.isToolInterruptMetadata = isToolInterruptMetadata;
|
|
2047
|
+
exports.loadPlugins = loadPlugins;
|
|
2048
|
+
exports.loadSkills = loadSkills;
|
|
2049
|
+
exports.makeAssistantMessage = makeAssistantMessage;
|
|
2050
|
+
exports.makeAssistantTextAccumulator = makeAssistantTextAccumulator;
|
|
2051
|
+
exports.makeBus = makeBus;
|
|
2052
|
+
exports.makeCompactionMessage = makeCompactionMessage;
|
|
2053
|
+
exports.makeHTTPHandlers = makeHTTPHandlers;
|
|
2054
|
+
exports.makeMemoryStore = makeMemoryStore;
|
|
2055
|
+
exports.makeProcessor = makeProcessor;
|
|
2056
|
+
exports.makeSSEHandler = makeSSEHandler;
|
|
2057
|
+
exports.makeSessionAPI = makeSessionAPI;
|
|
2058
|
+
exports.makeSkillTool = makeSkillTool;
|
|
2059
|
+
exports.makeUserMessage = makeUserMessage;
|
|
2060
|
+
exports.newMessageID = newMessageID;
|
|
2061
|
+
exports.newPartID = newPartID;
|
|
2062
|
+
exports.newSessionID = newSessionID;
|
|
2063
|
+
exports.objectiveSection = objectiveSection;
|
|
2064
|
+
exports.persistMessageUpdate = persistMessageUpdate;
|
|
2065
|
+
exports.resolveRule = resolveRule;
|
|
2066
|
+
exports.responseStyleSection = responseStyleSection;
|
|
2067
|
+
exports.toolInterruptFailure = toolInterruptFailure;
|
|
2068
|
+
exports.toolUseGuidelinesSection = toolUseGuidelinesSection;
|
|
2069
|
+
exports.toolUseSection = toolUseSection;
|
|
2070
|
+
exports.validateAttachments = validateAttachments;
|
|
2071
|
+
exports.writeEventsToResponse = writeEventsToResponse;
|
|
2072
|
+
//# sourceMappingURL=index.cjs.map
|
|
2073
|
+
//# sourceMappingURL=index.cjs.map
|