@tinyweb_dev/agent-framework-agent 0.2.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (144) hide show
  1. package/dist/agent.d.ts +116 -0
  2. package/dist/agent.d.ts.map +1 -0
  3. package/dist/attachments.d.ts +41 -0
  4. package/dist/attachments.d.ts.map +1 -0
  5. package/dist/bus/bus.d.ts +46 -0
  6. package/dist/bus/bus.d.ts.map +1 -0
  7. package/dist/bus/index.d.ts +2 -0
  8. package/dist/bus/index.d.ts.map +1 -0
  9. package/dist/define-tool.d.ts +13 -0
  10. package/dist/define-tool.d.ts.map +1 -0
  11. package/dist/events.d.ts +136 -0
  12. package/dist/events.d.ts.map +1 -0
  13. package/dist/http-handlers.cjs +253 -0
  14. package/dist/http-handlers.cjs.map +1 -0
  15. package/dist/http-handlers.d.ts +49 -0
  16. package/dist/http-handlers.d.ts.map +1 -0
  17. package/dist/http-handlers.js +251 -0
  18. package/dist/http-handlers.js.map +1 -0
  19. package/dist/index.cjs +2073 -0
  20. package/dist/index.cjs.map +1 -0
  21. package/dist/index.d.ts +19 -0
  22. package/dist/index.d.ts.map +1 -0
  23. package/dist/index.js +2015 -0
  24. package/dist/index.js.map +1 -0
  25. package/dist/loop-guard.d.ts +42 -0
  26. package/dist/loop-guard.d.ts.map +1 -0
  27. package/dist/mcp/client.d.ts +25 -0
  28. package/dist/mcp/client.d.ts.map +1 -0
  29. package/dist/mcp/index.cjs +66 -0
  30. package/dist/mcp/index.cjs.map +1 -0
  31. package/{src/mcp/index.ts → dist/mcp/index.d.ts} +2 -1
  32. package/dist/mcp/index.d.ts.map +1 -0
  33. package/dist/mcp/index.js +63 -0
  34. package/dist/mcp/index.js.map +1 -0
  35. package/dist/permission.d.ts +26 -0
  36. package/dist/permission.d.ts.map +1 -0
  37. package/dist/plugin/apply.d.ts +12 -0
  38. package/dist/plugin/apply.d.ts.map +1 -0
  39. package/dist/plugin/index.cjs +63 -0
  40. package/dist/plugin/index.cjs.map +1 -0
  41. package/dist/plugin/index.d.ts +4 -0
  42. package/dist/plugin/index.d.ts.map +1 -0
  43. package/dist/plugin/index.js +52 -0
  44. package/dist/plugin/index.js.map +1 -0
  45. package/dist/plugin/loader.d.ts +3 -0
  46. package/dist/plugin/loader.d.ts.map +1 -0
  47. package/dist/plugin/types.d.ts +98 -0
  48. package/dist/plugin/types.d.ts.map +1 -0
  49. package/dist/prompt/index.d.ts +51 -0
  50. package/dist/prompt/index.d.ts.map +1 -0
  51. package/dist/prompt/objective.d.ts +29 -0
  52. package/dist/prompt/objective.d.ts.map +1 -0
  53. package/dist/prompt/response-style.d.ts +19 -0
  54. package/dist/prompt/response-style.d.ts.map +1 -0
  55. package/dist/prompt/tool-use-guidelines.d.ts +22 -0
  56. package/dist/prompt/tool-use-guidelines.d.ts.map +1 -0
  57. package/dist/prompt/tool-use.d.ts +12 -0
  58. package/dist/prompt/tool-use.d.ts.map +1 -0
  59. package/dist/runtime.d.ts +7 -0
  60. package/dist/runtime.d.ts.map +1 -0
  61. package/dist/session/adapter.d.ts +40 -0
  62. package/dist/session/adapter.d.ts.map +1 -0
  63. package/dist/session/compaction.d.ts +37 -0
  64. package/dist/session/compaction.d.ts.map +1 -0
  65. package/dist/session/index.d.ts +7 -0
  66. package/dist/session/index.d.ts.map +1 -0
  67. package/dist/session/memory.cjs +130 -0
  68. package/dist/session/memory.cjs.map +1 -0
  69. package/dist/session/memory.d.ts +3 -0
  70. package/dist/session/memory.d.ts.map +1 -0
  71. package/dist/session/memory.js +128 -0
  72. package/dist/session/memory.js.map +1 -0
  73. package/dist/session/overflow.d.ts +19 -0
  74. package/dist/session/overflow.d.ts.map +1 -0
  75. package/dist/session/postgres.cjs +245 -0
  76. package/dist/session/postgres.cjs.map +1 -0
  77. package/dist/session/postgres.d.ts +10 -0
  78. package/dist/session/postgres.d.ts.map +1 -0
  79. package/dist/session/postgres.js +243 -0
  80. package/dist/session/postgres.js.map +1 -0
  81. package/dist/session/processor.d.ts +52 -0
  82. package/dist/session/processor.d.ts.map +1 -0
  83. package/dist/session/replay.d.ts +4 -0
  84. package/dist/session/replay.d.ts.map +1 -0
  85. package/dist/session/schema.d.ts +104 -0
  86. package/dist/session/schema.d.ts.map +1 -0
  87. package/dist/session/sqlite.cjs +236 -0
  88. package/dist/session/sqlite.cjs.map +1 -0
  89. package/dist/session/sqlite.d.ts +3 -0
  90. package/dist/session/sqlite.d.ts.map +1 -0
  91. package/dist/session/sqlite.js +234 -0
  92. package/dist/session/sqlite.js.map +1 -0
  93. package/dist/session-api.cjs +56 -0
  94. package/dist/session-api.cjs.map +1 -0
  95. package/dist/session-api.d.ts +36 -0
  96. package/dist/session-api.d.ts.map +1 -0
  97. package/dist/session-api.js +54 -0
  98. package/dist/session-api.js.map +1 -0
  99. package/dist/skill/index.cjs +81 -0
  100. package/dist/skill/index.cjs.map +1 -0
  101. package/dist/skill/index.d.ts +10 -0
  102. package/dist/skill/index.d.ts.map +1 -0
  103. package/dist/skill/index.js +78 -0
  104. package/dist/skill/index.js.map +1 -0
  105. package/dist/sse-handler.d.ts +27 -0
  106. package/dist/sse-handler.d.ts.map +1 -0
  107. package/dist/transcript.d.ts +81 -0
  108. package/dist/transcript.d.ts.map +1 -0
  109. package/package.json +54 -19
  110. package/src/agent.ts +0 -470
  111. package/src/attachments.ts +0 -155
  112. package/src/bus/bus.ts +0 -89
  113. package/src/bus/index.ts +0 -1
  114. package/src/define-tool.ts +0 -41
  115. package/src/events.ts +0 -186
  116. package/src/http-handlers.ts +0 -251
  117. package/src/index.ts +0 -128
  118. package/src/loop-guard.ts +0 -99
  119. package/src/mcp/client.ts +0 -129
  120. package/src/permission.ts +0 -114
  121. package/src/plugin/apply.ts +0 -89
  122. package/src/plugin/index.ts +0 -3
  123. package/src/plugin/loader.ts +0 -42
  124. package/src/plugin/types.ts +0 -134
  125. package/src/prompt/index.ts +0 -90
  126. package/src/prompt/objective.ts +0 -104
  127. package/src/prompt/response-style.ts +0 -59
  128. package/src/prompt/tool-use-guidelines.ts +0 -57
  129. package/src/prompt/tool-use.ts +0 -27
  130. package/src/runtime.ts +0 -22
  131. package/src/session/adapter.ts +0 -46
  132. package/src/session/compaction.ts +0 -160
  133. package/src/session/index.ts +0 -18
  134. package/src/session/memory.ts +0 -169
  135. package/src/session/overflow.ts +0 -50
  136. package/src/session/postgres.ts +0 -355
  137. package/src/session/processor.ts +0 -865
  138. package/src/session/replay.ts +0 -151
  139. package/src/session/schema.ts +0 -156
  140. package/src/session/sqlite.ts +0 -309
  141. package/src/session-api.ts +0 -103
  142. package/src/skill/index.ts +0 -113
  143. package/src/sse-handler.ts +0 -67
  144. package/src/transcript.ts +0 -126
package/src/agent.ts DELETED
@@ -1,470 +0,0 @@
1
- import {
2
- LLM,
3
- LLMClient,
4
- type ExecutableTools,
5
- type GenerationOptions,
6
- type LLMResponse,
7
- type ModelRef,
8
- type StopCondition,
9
- type Tools,
10
- } from "@tinyweb-agent-framework/llm"
11
- import { Effect } from "effect"
12
- import type { AttachmentInput } from "./attachments"
13
- import { compact } from "./session/compaction"
14
- import { estimateTokens, usable } from "./session/overflow"
15
- import { type AgentEvent } from "./events"
16
- import {
17
- applyPermission,
18
- type PermissionAskHandler,
19
- type PermissionAskMode,
20
- type PermissionConfig,
21
- } from "./permission"
22
- import { defaultRuntime, type AgentRuntime } from "./runtime"
23
- import { makeProcessor, persistMessageUpdate } from "./session/processor"
24
- import { makeMemoryStore } from "./session/memory"
25
- import type { SessionStore } from "./session/adapter"
26
- import { historyToLLMMessages } from "./session/replay"
27
- import type { AssistantMessage, Message, ToolPart } from "./session/schema"
28
- import { makeSSEHandler, type SSEHandlerOptions } from "./sse-handler"
29
- import { loadPlugins, type Hooks, type PluginEntry } from "./plugin"
30
- import { connectAllMcp, type McpConfig } from "./mcp"
31
- import { loadSkills, makeSkillTool } from "./skill"
32
- import { makeSessionAPI, type SessionAPI } from "./session-api"
33
- import { makeHTTPHandlers, type AuthorizeFn, type ChatFormat, type HTTPHandlers } from "./http-handlers"
34
- import { composeSystemPrompt, type PromptSectionsConfig } from "./prompt"
35
-
36
- /**
37
- * Auto-compaction policy. The agent estimates input tokens on every turn and,
38
- * when the estimate crosses the model's usable budget, summarises the leading
39
- * slice of the conversation into a marker user message before calling the LLM.
40
- * On a `ContextOverflowReason` from the provider the agent retries once with
41
- * a freshly compacted history.
42
- */
43
- export type CompactionConfig = {
44
- /** Default: true. Set to false to opt out entirely. */
45
- readonly auto?: boolean
46
- /** Reserved output buffer. Default `min(20_000, model.limits.output)`. */
47
- readonly reservedTokens?: number
48
- /** Number of trailing turns kept verbatim. Default 4. */
49
- readonly preserveRecentTurns?: number
50
- }
51
-
52
- export type DefineAgentConfig<T extends Tools> = {
53
- readonly name: string
54
- readonly model: ModelRef
55
- /**
56
- * The agent's ROLE / persona block. Verbatim — no transformation.
57
- *
58
- * Framework-owned blocks (TOOL USE, TOOL USE GUIDELINES, RESPONSE STYLE) are
59
- * automatically appended after this. Disable or tune them via
60
- * `promptSections`. To skip the framework blocks entirely set
61
- * `promptSections: { toolUse: false, toolUseGuidelines: false, responseStyle: false }`.
62
- */
63
- readonly systemPrompt?: string
64
- /**
65
- * Per-section toggles for the framework-owned prompt blocks. Defaults: all
66
- * enabled with chat-style response rules. See [`prompt/index.ts`](./prompt/index.ts:1).
67
- */
68
- readonly promptSections?: PromptSectionsConfig
69
- readonly tools?: T
70
- readonly stopWhen?: StopCondition
71
- readonly generation?: GenerationOptions.Input
72
- readonly runtime?: AgentRuntime
73
- readonly store?: SessionStore
74
- readonly permission?: PermissionConfig
75
- readonly askHandler?: PermissionAskHandler
76
- /**
77
- * How `"ask"` permission rules are enforced.
78
- * - `"handler"` (default) — block on `askHandler` Promise (CLI / in-process UI).
79
- * - `"interrupt"` — persist `pending-approval` ToolPart and stop the turn;
80
- * host later calls `resolveApproval` + `resume`. Preferred for durable UIs.
81
- */
82
- readonly askMode?: PermissionAskMode
83
- /** Plugins to load — inline Plugin fn, path string, or [path, options] tuple */
84
- readonly plugins?: PluginEntry[]
85
- /** MCP servers to connect — Record<serverName, McpServerConfig> */
86
- readonly mcp?: McpConfig
87
- /** Extra directories to scan for SKILL.md files */
88
- readonly skillDirs?: string[]
89
- /** Auto-compaction tuning. Defaults are sane; pass `{ auto: false }` to disable. */
90
- readonly compaction?: CompactionConfig
91
- }
92
-
93
- export type RunInput = {
94
- readonly prompt: string
95
- readonly sessionId?: string
96
- readonly attachments?: ReadonlyArray<AttachmentInput>
97
- }
98
-
99
- export type ResumeInput = {
100
- readonly sessionId: string
101
- }
102
-
103
- export type ResolveApprovalInput = {
104
- readonly sessionId: string
105
- /** Tool call id (`ToolPart.callID` / SSE `tool-approval-request.id`). */
106
- readonly callID: string
107
- readonly approved: boolean
108
- }
109
-
110
- export type ResolveApprovalResult = {
111
- readonly callID: string
112
- readonly state: "approved" | "rejected"
113
- readonly toolName: string
114
- readonly input: unknown
115
- }
116
-
117
- export type RunOnceResult = {
118
- readonly text: string
119
- readonly usage: LLMResponse["usage"]
120
- readonly events: LLMResponse["events"]
121
- }
122
-
123
- export type ToHTTPHandlersOptions = {
124
- readonly authorize?: AuthorizeFn
125
- readonly defaultFormat?: ChatFormat
126
- }
127
-
128
- export type Agent = {
129
- readonly name: string
130
- readonly run: (input: RunInput) => AsyncIterable<AgentEvent>
131
- readonly runOnce: (input: RunInput) => Promise<RunOnceResult>
132
- /**
133
- * Mark a `pending-approval` tool call as approved or rejected (persisted in
134
- * the SessionStore). Does NOT execute the tool — call `resume` afterwards.
135
- */
136
- readonly resolveApproval: (input: ResolveApprovalInput) => Promise<ResolveApprovalResult>
137
- /**
138
- * Continue a session after approvals were resolved. Executes approved tools,
139
- * records denials, then streams a follow-up LLM turn.
140
- */
141
- readonly resume: (input: ResumeInput) => AsyncIterable<AgentEvent>
142
- readonly toSSEHandler: (options?: SSEHandlerOptions) => ReturnType<typeof makeSSEHandler>
143
- readonly sessions: SessionAPI
144
- readonly toHTTPHandlers: (options?: ToHTTPHandlersOptions) => HTTPHandlers
145
- }
146
-
147
- let defaultStore: SessionStore | undefined
148
- const getDefaultStore = (): SessionStore => {
149
- if (defaultStore) return defaultStore
150
- // Default to MemoryStore — SQLite must be opted into explicitly via
151
- // `store: makeSqliteStore()` to keep this package usable in environments
152
- // without bun:sqlite (e.g. Next.js/webpack server runtime).
153
- defaultStore = makeMemoryStore()
154
- return defaultStore
155
- }
156
-
157
- // ---------------------------------------------------------------------------
158
- // buildTools — merge user tools + MCP tools + optional skill tool
159
- // ---------------------------------------------------------------------------
160
-
161
- type BuiltTools = {
162
- /** Permission-wrapped tools for the normal agentic loop. */
163
- readonly tools: ExecutableTools
164
- /** Unwrapped tools for resume (execute host-approved calls). */
165
- readonly resumeTools: ExecutableTools
166
- }
167
-
168
- async function buildMergedTools(
169
- config: DefineAgentConfig<Tools>,
170
- loadedHooks: Hooks[],
171
- ): Promise<ExecutableTools> {
172
- const baseTools: ExecutableTools = (config.tools ?? {}) as ExecutableTools
173
-
174
- // MCP tools
175
- let mcpTools: ExecutableTools = {}
176
- if (config.mcp && Object.keys(config.mcp).length > 0) {
177
- const { tools } = await connectAllMcp(config.mcp)
178
- mcpTools = tools
179
- }
180
-
181
- // Skill tool
182
- let skillToolRecord: ExecutableTools = {}
183
- if (config.skillDirs !== undefined || Object.keys(baseTools).length > 0) {
184
- const skills = await loadSkills(config.skillDirs)
185
- if (skills.length > 0) skillToolRecord = { skill: makeSkillTool(skills) }
186
- }
187
-
188
- const merged: ExecutableTools = { ...skillToolRecord, ...mcpTools, ...baseTools }
189
-
190
- // Apply plugin tool.definition hooks — mutate description/parameters per tool
191
- for (const hooks of loadedHooks) {
192
- if (!hooks["tool.definition"]) continue
193
- for (const [toolId, tool] of Object.entries(merged)) {
194
- const output = { description: tool.description, parameters: tool._definition.inputSchema }
195
- await hooks["tool.definition"]!({ toolId }, output)
196
- // We only propagate description mutation for now (parameters schema is read-only at runtime)
197
- if (output.description !== tool.description) {
198
- ;(tool as { description: string }).description = output.description
199
- }
200
- }
201
- }
202
-
203
- return merged
204
- }
205
-
206
- async function buildTools(
207
- config: DefineAgentConfig<Tools>,
208
- loadedHooks: Hooks[],
209
- ): Promise<BuiltTools> {
210
- const merged = await buildMergedTools(config, loadedHooks)
211
- const askMode = config.askMode ?? "handler"
212
- return {
213
- tools: applyPermission(merged, config.permission, config.askHandler, askMode),
214
- resumeTools: merged,
215
- }
216
- }
217
-
218
- // ---------------------------------------------------------------------------
219
- // defineAgent
220
- // ---------------------------------------------------------------------------
221
-
222
- export const defineAgent = <T extends Tools = Tools>(config: DefineAgentConfig<T>): Agent => {
223
- const rt = (): AgentRuntime => config.runtime ?? defaultRuntime()
224
- const store = config.store ?? getDefaultStore()
225
- // Default cap is intentionally generous — agentic loops (browser automation,
226
- // MCP tool chains) commonly exceed 10 rounds. The tool runtime already
227
- // terminates naturally when the model's `finish_reason !== "tool-calls"`,
228
- // so this is purely a safety ceiling against runaway loops. Override per
229
- // agent via `stopWhen: LLM.stepCountIs(N)` if you need a different policy.
230
- const stopWhen = config.stopWhen ?? LLM.stepCountIs(100)
231
- // Compose final system prompt once: user-authored ROLE + framework-owned
232
- // TOOL USE / GUIDELINES / RESPONSE STYLE blocks. See `./prompt/index.ts`.
233
- const resolvedSystemPrompt = composeSystemPrompt({
234
- role: config.systemPrompt,
235
- sections: config.promptSections,
236
- })
237
- const compactionCfg = {
238
- auto: config.compaction?.auto !== false,
239
- reservedTokens: config.compaction?.reservedTokens,
240
- preserveRecentTurns: config.compaction?.preserveRecentTurns,
241
- }
242
-
243
- // Build tools lazily on first use (async — MCP / skills may need network/fs)
244
- let toolsPromise: Promise<BuiltTools> | undefined
245
-
246
- const getTools = (): Promise<BuiltTools> => {
247
- if (!toolsPromise) {
248
- const pluginInput = { agentName: config.name, directory: process.cwd() }
249
- toolsPromise = loadPlugins(config.plugins ?? [], pluginInput).then((loaded) => {
250
- const hooks = loaded.map((l) => l.hooks)
251
- return buildTools(config, hooks)
252
- })
253
- }
254
- return toolsPromise
255
- }
256
-
257
- const makeAgentProcessor = async () => {
258
- const built = await getTools()
259
- return makeProcessor({
260
- agentName: config.name,
261
- model: config.model,
262
- store,
263
- runtime: rt(),
264
- systemPrompt: resolvedSystemPrompt,
265
- tools: built.tools,
266
- resumeTools: built.resumeTools,
267
- stopWhen,
268
- generation: config.generation,
269
- compaction: compactionCfg,
270
- })
271
- }
272
-
273
- const run = (input: RunInput): AsyncIterable<AgentEvent> => {
274
- let innerIter: AsyncIterator<AgentEvent> | undefined
275
- return {
276
- [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
277
- return {
278
- async next() {
279
- if (!innerIter) {
280
- const processor = await makeAgentProcessor()
281
- innerIter = processor.runTurn(input)[Symbol.asyncIterator]()
282
- }
283
- return innerIter.next()
284
- },
285
- async return(value) {
286
- return innerIter
287
- ? innerIter.return
288
- ? innerIter.return(value)
289
- : { done: true, value }
290
- : { done: true, value }
291
- },
292
- }
293
- },
294
- }
295
- }
296
-
297
- const resume = (input: ResumeInput): AsyncIterable<AgentEvent> => {
298
- let innerIter: AsyncIterator<AgentEvent> | undefined
299
- return {
300
- [Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
301
- return {
302
- async next() {
303
- if (!innerIter) {
304
- const processor = await makeAgentProcessor()
305
- innerIter = processor.resumeTurn({ sessionId: input.sessionId })[Symbol.asyncIterator]()
306
- }
307
- return innerIter.next()
308
- },
309
- async return(value) {
310
- return innerIter
311
- ? innerIter.return
312
- ? innerIter.return(value)
313
- : { done: true, value }
314
- : { done: true, value }
315
- },
316
- }
317
- },
318
- }
319
- }
320
-
321
- const resolveApproval = async (input: ResolveApprovalInput): Promise<ResolveApprovalResult> => {
322
- const history = await rt().runPromise(store.getMessages(input.sessionId))
323
- let targetMsg: AssistantMessage | undefined
324
- let targetPart: ToolPart | undefined
325
- let partIndex = -1
326
-
327
- for (let i = history.length - 1; i >= 0; i--) {
328
- const msg = history[i]
329
- if (!msg || msg.role !== "assistant") continue
330
- const idx = msg.parts.findIndex(
331
- (p) =>
332
- (p as ToolPart).type === "tool" &&
333
- (p as ToolPart).callID === input.callID &&
334
- (p as ToolPart).state === "pending-approval",
335
- )
336
- if (idx !== -1) {
337
- targetMsg = msg as AssistantMessage
338
- targetPart = msg.parts[idx] as ToolPart
339
- partIndex = idx
340
- break
341
- }
342
- }
343
-
344
- if (!targetMsg || !targetPart || partIndex < 0) {
345
- throw new Error(`No pending approval found for callID="${input.callID}"`)
346
- }
347
-
348
- const nextState = input.approved ? ("approved" as const) : ("rejected" as const)
349
- const nextParts = targetMsg.parts.map((p, idx) =>
350
- idx === partIndex ? ({ ...targetPart!, state: nextState } satisfies ToolPart) : p,
351
- )
352
- const updated: AssistantMessage = { ...targetMsg, parts: nextParts }
353
- await rt().runPromise(persistMessageUpdate(store, input.sessionId, updated as Message))
354
-
355
- return {
356
- callID: input.callID,
357
- state: nextState,
358
- toolName: targetPart.name,
359
- input: targetPart.input,
360
- }
361
- }
362
-
363
- const runOnce = async (input: RunInput): Promise<RunOnceResult> => {
364
- const { tools } = await getTools()
365
- const budget = usable({
366
- limits: config.model.limits,
367
- reservedTokens: compactionCfg.reservedTokens,
368
- })
369
- const keepRecent = compactionCfg.preserveRecentTurns ?? 4
370
-
371
- const result = await rt().runPromise(
372
- Effect.gen(function* () {
373
- const session = yield* store.upsertSession({ id: input.sessionId, agentName: config.name })
374
-
375
- // Pre-flight: compact if estimate would overflow the usable budget.
376
- if (compactionCfg.auto) {
377
- const history = yield* store.getMessages(session.id)
378
- const promptTokens = Math.ceil(input.prompt.length / 4)
379
- const systemTokens = Math.ceil(resolvedSystemPrompt.length / 4)
380
- if (estimateTokens(history) + promptTokens + systemTokens >= budget) {
381
- yield* compact({
382
- sessionId: session.id,
383
- store,
384
- model: config.model,
385
- keepRecent,
386
- overflow: false,
387
- })
388
- }
389
- }
390
-
391
- const attempt = () =>
392
- Effect.gen(function* () {
393
- const history = yield* store.getMessages(session.id)
394
- const userContent: Array<
395
- | { type: "text"; text: string }
396
- | { type: "media"; mediaType: string; data: string; filename?: string }
397
- > = []
398
- if (input.prompt.length > 0) userContent.push({ type: "text", text: input.prompt })
399
- for (const a of input.attachments ?? [])
400
- userContent.push({
401
- type: "media",
402
- mediaType: a.mediaType,
403
- data: a.url ?? a.data ?? "",
404
- filename: a.filename,
405
- })
406
- const userMsg =
407
- userContent.length === 0 ? LLM.user(input.prompt) : LLM.user(userContent)
408
- const request = LLM.request({
409
- model: config.model,
410
- system: resolvedSystemPrompt,
411
- messages: [...historyToLLMMessages([...history]), userMsg],
412
- generation: config.generation,
413
- })
414
- return yield* LLMClient.generate({ request, tools, stopWhen })
415
- })
416
-
417
- // Post-flight: catch ContextOverflow once, compact with overflow=true, retry once.
418
- let didRetry = false
419
- const response = yield* attempt().pipe(
420
- Effect.catchTag("LLM.Error", (err) => {
421
- if (err.reason._tag === "ContextOverflow" && compactionCfg.auto && !didRetry) {
422
- didRetry = true
423
- return Effect.gen(function* () {
424
- yield* compact({
425
- sessionId: session.id,
426
- store,
427
- model: config.model,
428
- keepRecent,
429
- overflow: true,
430
- })
431
- return yield* attempt()
432
- })
433
- }
434
- return Effect.fail(err)
435
- }),
436
- )
437
- return response
438
- }),
439
- )
440
- return { text: result.text, usage: result.usage, events: result.events }
441
- }
442
-
443
- const toSSEHandler = (options?: SSEHandlerOptions) => makeSSEHandler(run, options)
444
-
445
- const sessions = makeSessionAPI({
446
- agentName: config.name,
447
- store,
448
- runtime: config.runtime,
449
- })
450
-
451
- const toHTTPHandlers = (options?: ToHTTPHandlersOptions): HTTPHandlers =>
452
- makeHTTPHandlers({
453
- api: sessions,
454
- run: (input) =>
455
- run({ prompt: input.prompt, sessionId: input.sessionId, attachments: input.attachments }),
456
- authorize: options?.authorize,
457
- defaultFormat: options?.defaultFormat,
458
- })
459
-
460
- return {
461
- name: config.name,
462
- run,
463
- runOnce,
464
- resolveApproval,
465
- resume,
466
- toSSEHandler,
467
- sessions,
468
- toHTTPHandlers,
469
- }
470
- }
@@ -1,155 +0,0 @@
1
- /**
2
- * Public attachment shape forwarded from HTTP/UI → agent.run.
3
- * MVP: image-only, base64 inline OR pre-uploaded URL.
4
- * Validation enforced both client-side (chat-ui) and server-side (http-handlers).
5
- */
6
- export type AttachmentInput = {
7
- readonly type: "image"
8
- readonly mediaType: string
9
- /** Either `data` (raw base64, no `data:` prefix) OR `url` (http/https/file/data:). Exactly one. */
10
- readonly data?: string
11
- readonly url?: string
12
- readonly filename?: string
13
- }
14
-
15
- export type AttachmentErrorCode =
16
- | "attachment_too_large"
17
- | "attachment_unsupported_type"
18
- | "attachment_invalid"
19
- | "attachment_too_many"
20
-
21
- export type ValidateAttachmentsConfig = {
22
- readonly imageMimes?: ReadonlySet<string>
23
- readonly maxBytesPerFile?: number
24
- readonly maxBytesTotal?: number
25
- readonly maxCount?: number
26
- }
27
-
28
- export type ValidateOk = { readonly ok: true; readonly value: ReadonlyArray<AttachmentInput> }
29
- export type ValidateErr = {
30
- readonly ok: false
31
- readonly code: AttachmentErrorCode
32
- readonly message: string
33
- }
34
- export type ValidateResult = ValidateOk | ValidateErr
35
-
36
- export const DEFAULT_IMAGE_MIMES: ReadonlySet<string> = new Set(["image/png", "image/jpeg", "image/webp", "image/gif"])
37
- export const DEFAULT_MAX_BYTES_PER_FILE = 8 * 1024 * 1024
38
- export const DEFAULT_MAX_BYTES_TOTAL = 16 * 1024 * 1024
39
- export const DEFAULT_MAX_COUNT = 4
40
-
41
- const base64ByteLength = (b64: string): number => {
42
- // Strip optional data URL prefix `data:<mime>;base64,`.
43
- const idx = b64.indexOf("base64,")
44
- const body = idx >= 0 ? b64.slice(idx + "base64,".length) : b64
45
- const padding = body.endsWith("==") ? 2 : body.endsWith("=") ? 1 : 0
46
- return Math.max(0, Math.floor((body.length * 3) / 4) - padding)
47
- }
48
-
49
- const isHttpOrFile = (s: string) =>
50
- s.startsWith("http://") || s.startsWith("https://") || s.startsWith("file://") || s.startsWith("data:")
51
-
52
- /**
53
- * Validate raw attachments. Pure function — no I/O. First failure short-circuits.
54
- *
55
- * Order: count → per-item (mime, exactly-one-of, size) → total size.
56
- */
57
- export const validateAttachments = (
58
- raw: unknown,
59
- config?: ValidateAttachmentsConfig,
60
- ): ValidateResult => {
61
- if (raw === undefined || raw === null) return { ok: true, value: [] }
62
- if (!Array.isArray(raw))
63
- return { ok: false, code: "attachment_invalid", message: "attachments must be an array" }
64
-
65
- const imageMimes = config?.imageMimes ?? DEFAULT_IMAGE_MIMES
66
- const maxBytesPerFile = config?.maxBytesPerFile ?? DEFAULT_MAX_BYTES_PER_FILE
67
- const maxBytesTotal = config?.maxBytesTotal ?? DEFAULT_MAX_BYTES_TOTAL
68
- const maxCount = config?.maxCount ?? DEFAULT_MAX_COUNT
69
-
70
- if (raw.length > maxCount)
71
- return {
72
- ok: false,
73
- code: "attachment_too_many",
74
- message: `Too many attachments (max ${maxCount}, received ${raw.length})`,
75
- }
76
-
77
- const out: AttachmentInput[] = []
78
- let totalBytes = 0
79
-
80
- for (let i = 0; i < raw.length; i++) {
81
- const item = raw[i]
82
- if (!item || typeof item !== "object")
83
- return { ok: false, code: "attachment_invalid", message: `attachments[${i}] must be an object` }
84
-
85
- const obj = item as Record<string, unknown>
86
- if (obj.type !== "image")
87
- return {
88
- ok: false,
89
- code: "attachment_unsupported_type",
90
- message: `attachments[${i}].type must be "image" (received ${String(obj.type)})`,
91
- }
92
-
93
- const mediaType = obj.mediaType
94
- if (typeof mediaType !== "string" || mediaType.length === 0)
95
- return { ok: false, code: "attachment_invalid", message: `attachments[${i}].mediaType is required` }
96
- if (!imageMimes.has(mediaType))
97
- return {
98
- ok: false,
99
- code: "attachment_unsupported_type",
100
- message: `Unsupported attachment type: ${mediaType}`,
101
- }
102
-
103
- const data = typeof obj.data === "string" ? obj.data : undefined
104
- const url = typeof obj.url === "string" ? obj.url : undefined
105
-
106
- if (!data && !url)
107
- return {
108
- ok: false,
109
- code: "attachment_invalid",
110
- message: `attachments[${i}] requires either "data" (base64) or "url"`,
111
- }
112
- if (data && url)
113
- return {
114
- ok: false,
115
- code: "attachment_invalid",
116
- message: `attachments[${i}] must not set both "data" and "url"`,
117
- }
118
-
119
- if (url && !isHttpOrFile(url))
120
- return {
121
- ok: false,
122
- code: "attachment_invalid",
123
- message: `attachments[${i}].url must be http(s)/file/data scheme`,
124
- }
125
-
126
- if (data) {
127
- const bytes = base64ByteLength(data)
128
- if (bytes === 0)
129
- return { ok: false, code: "attachment_invalid", message: `attachments[${i}].data is empty or malformed` }
130
- if (bytes > maxBytesPerFile)
131
- return {
132
- ok: false,
133
- code: "attachment_too_large",
134
- message: `Attachment ${obj.filename ?? `#${i}`} exceeds ${maxBytesPerFile} bytes (got ${bytes})`,
135
- }
136
- totalBytes += bytes
137
- if (totalBytes > maxBytesTotal)
138
- return {
139
- ok: false,
140
- code: "attachment_too_large",
141
- message: `Total attachment bytes exceed ${maxBytesTotal} (got ${totalBytes})`,
142
- }
143
- }
144
-
145
- out.push({
146
- type: "image",
147
- mediaType,
148
- data,
149
- url,
150
- filename: typeof obj.filename === "string" ? obj.filename : undefined,
151
- })
152
- }
153
-
154
- return { ok: true, value: out }
155
- }