@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.
- 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 -470
- 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 -186
- package/src/http-handlers.ts +0 -251
- package/src/index.ts +0 -128
- package/src/loop-guard.ts +0 -99
- package/src/mcp/client.ts +0 -129
- package/src/permission.ts +0 -114
- 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 -46
- package/src/session/compaction.ts +0 -160
- package/src/session/index.ts +0 -18
- package/src/session/memory.ts +0 -169
- package/src/session/overflow.ts +0 -50
- package/src/session/postgres.ts +0 -355
- package/src/session/processor.ts +0 -865
- package/src/session/replay.ts +0 -151
- package/src/session/schema.ts +0 -156
- package/src/session/sqlite.ts +0 -309
- 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/src/session-api.ts
DELETED
|
@@ -1,103 +0,0 @@
|
|
|
1
|
-
// SessionAPI — Promise-based session CRUD facade for consumers.
|
|
2
|
-
// Hides Effect runtime. Used by the SDK / HTTP handlers / app routes.
|
|
3
|
-
|
|
4
|
-
import { Effect } from "effect"
|
|
5
|
-
import { defaultRuntime, type AgentRuntime } from "./runtime"
|
|
6
|
-
import type {
|
|
7
|
-
ListSessionsOpts,
|
|
8
|
-
ListSessionsResult,
|
|
9
|
-
GetMessagesOpts,
|
|
10
|
-
SessionPatch,
|
|
11
|
-
SessionStore,
|
|
12
|
-
} from "./session/adapter"
|
|
13
|
-
import type { Message, MessageID, Session, SessionID } from "./session/schema"
|
|
14
|
-
|
|
15
|
-
export type CreateSessionAPIInput = {
|
|
16
|
-
readonly title?: string
|
|
17
|
-
readonly metadata?: Record<string, unknown>
|
|
18
|
-
readonly ownerId?: string
|
|
19
|
-
}
|
|
20
|
-
|
|
21
|
-
export type ListSessionsAPIOpts = {
|
|
22
|
-
readonly limit?: number
|
|
23
|
-
readonly cursor?: string
|
|
24
|
-
readonly ownerId?: string
|
|
25
|
-
}
|
|
26
|
-
|
|
27
|
-
export type MessagesAPIResult = {
|
|
28
|
-
readonly items: ReadonlyArray<Message>
|
|
29
|
-
/** Optional cursor for older messages (when `before` was used and more remain). */
|
|
30
|
-
readonly nextCursor?: string
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
export interface SessionAPI {
|
|
34
|
-
create(input?: CreateSessionAPIInput): Promise<Session.Info>
|
|
35
|
-
list(opts?: ListSessionsAPIOpts): Promise<ListSessionsResult>
|
|
36
|
-
get(id: SessionID | string): Promise<Session.Info | undefined>
|
|
37
|
-
delete(id: SessionID | string): Promise<void>
|
|
38
|
-
setTitle(id: SessionID | string, title: string): Promise<Session.Info | undefined>
|
|
39
|
-
setMetadata(id: SessionID | string, metadata: Record<string, unknown>): Promise<Session.Info | undefined>
|
|
40
|
-
patch(id: SessionID | string, patch: SessionPatch): Promise<Session.Info | undefined>
|
|
41
|
-
messages(sessionId: SessionID | string, opts?: GetMessagesOpts): Promise<MessagesAPIResult>
|
|
42
|
-
deleteMessage(sessionId: SessionID | string, messageId: MessageID | string): Promise<void>
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
export type MakeSessionAPIConfig = {
|
|
46
|
-
readonly agentName: string
|
|
47
|
-
readonly store: SessionStore
|
|
48
|
-
readonly runtime?: AgentRuntime
|
|
49
|
-
}
|
|
50
|
-
|
|
51
|
-
const withOwner = (
|
|
52
|
-
input: CreateSessionAPIInput | undefined,
|
|
53
|
-
metadata: Record<string, unknown> | undefined,
|
|
54
|
-
): Record<string, unknown> | undefined => {
|
|
55
|
-
if (!input?.ownerId) return metadata
|
|
56
|
-
return { ...(metadata ?? {}), ownerId: input.ownerId }
|
|
57
|
-
}
|
|
58
|
-
|
|
59
|
-
export const makeSessionAPI = (config: MakeSessionAPIConfig): SessionAPI => {
|
|
60
|
-
const rt = (): AgentRuntime => config.runtime ?? defaultRuntime()
|
|
61
|
-
const run = <A>(effect: Effect.Effect<A>): Promise<A> => rt().runPromise(effect)
|
|
62
|
-
|
|
63
|
-
return {
|
|
64
|
-
create: (input) =>
|
|
65
|
-
run(
|
|
66
|
-
config.store.createSession({
|
|
67
|
-
agentName: config.agentName,
|
|
68
|
-
title: input?.title,
|
|
69
|
-
metadata: withOwner(input, input?.metadata),
|
|
70
|
-
}),
|
|
71
|
-
),
|
|
72
|
-
|
|
73
|
-
list: (opts) =>
|
|
74
|
-
run(
|
|
75
|
-
config.store.listSessions({
|
|
76
|
-
limit: opts?.limit,
|
|
77
|
-
cursor: opts?.cursor,
|
|
78
|
-
agentName: config.agentName,
|
|
79
|
-
ownerId: opts?.ownerId,
|
|
80
|
-
}),
|
|
81
|
-
),
|
|
82
|
-
|
|
83
|
-
get: (id) => run(config.store.getSession(id)),
|
|
84
|
-
|
|
85
|
-
delete: (id) => run(config.store.deleteSession(id)),
|
|
86
|
-
|
|
87
|
-
setTitle: (id, title) => run(config.store.updateSession(id, { title })),
|
|
88
|
-
|
|
89
|
-
setMetadata: (id, metadata) => run(config.store.updateSession(id, { metadata })),
|
|
90
|
-
|
|
91
|
-
patch: (id, patch) => run(config.store.updateSession(id, patch)),
|
|
92
|
-
|
|
93
|
-
messages: async (sessionId, opts) => {
|
|
94
|
-
const items = await run(config.store.getMessages(sessionId, opts))
|
|
95
|
-
// If a limit was supplied and we hit it, surface the oldest id as a "before" cursor.
|
|
96
|
-
const nextCursor =
|
|
97
|
-
opts?.limit && items.length === opts.limit && items[0] ? (items[0].id as string) : undefined
|
|
98
|
-
return { items, nextCursor }
|
|
99
|
-
},
|
|
100
|
-
|
|
101
|
-
deleteMessage: (sessionId, messageId) => run(config.store.deleteMessage(sessionId, messageId)),
|
|
102
|
-
}
|
|
103
|
-
}
|
package/src/skill/index.ts
DELETED
|
@@ -1,113 +0,0 @@
|
|
|
1
|
-
// Adapted from opencode@v1.14.48 packages/opencode/src/skill/
|
|
2
|
-
|
|
3
|
-
import { readdir, readFile } from "node:fs/promises"
|
|
4
|
-
import { join, dirname } from "node:path"
|
|
5
|
-
import { homedir } from "node:os"
|
|
6
|
-
|
|
7
|
-
// ---------------------------------------------------------------------------
|
|
8
|
-
// Skill types
|
|
9
|
-
// ---------------------------------------------------------------------------
|
|
10
|
-
|
|
11
|
-
export type SkillInfo = {
|
|
12
|
-
readonly name: string
|
|
13
|
-
readonly description?: string
|
|
14
|
-
readonly location: string
|
|
15
|
-
readonly content: string
|
|
16
|
-
}
|
|
17
|
-
|
|
18
|
-
// ---------------------------------------------------------------------------
|
|
19
|
-
// Frontmatter parsing — minimal YAML-ish subset (name: / description:)
|
|
20
|
-
// ---------------------------------------------------------------------------
|
|
21
|
-
|
|
22
|
-
function parseFrontmatter(raw: string): { name?: string; description?: string; body: string } {
|
|
23
|
-
if (!raw.startsWith("---")) return { body: raw }
|
|
24
|
-
const end = raw.indexOf("\n---", 3)
|
|
25
|
-
if (end === -1) return { body: raw }
|
|
26
|
-
const fm = raw.slice(3, end).trim()
|
|
27
|
-
const body = raw.slice(end + 4).trim()
|
|
28
|
-
const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim()
|
|
29
|
-
const description = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim()
|
|
30
|
-
return { name, description, body }
|
|
31
|
-
}
|
|
32
|
-
|
|
33
|
-
// ---------------------------------------------------------------------------
|
|
34
|
-
// Scan a directory recursively for SKILL.md files
|
|
35
|
-
// ---------------------------------------------------------------------------
|
|
36
|
-
|
|
37
|
-
async function scanDir(dir: string): Promise<SkillInfo[]> {
|
|
38
|
-
const results: SkillInfo[] = []
|
|
39
|
-
let entries: { name: string; isDirectory: () => boolean }[] = []
|
|
40
|
-
try {
|
|
41
|
-
entries = await readdir(dir, { withFileTypes: true })
|
|
42
|
-
} catch {
|
|
43
|
-
return results
|
|
44
|
-
}
|
|
45
|
-
for (const entry of entries) {
|
|
46
|
-
const full = join(dir, entry.name)
|
|
47
|
-
if (entry.isDirectory()) {
|
|
48
|
-
const nested = await scanDir(full)
|
|
49
|
-
results.push(...nested)
|
|
50
|
-
} else if (entry.name === "SKILL.md") {
|
|
51
|
-
const raw = await readFile(full, "utf-8").catch(() => "")
|
|
52
|
-
if (!raw) continue
|
|
53
|
-
const { name, description, body } = parseFrontmatter(raw)
|
|
54
|
-
if (!name) continue
|
|
55
|
-
results.push({ name, description, location: full, content: body || raw })
|
|
56
|
-
}
|
|
57
|
-
}
|
|
58
|
-
return results
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
// ---------------------------------------------------------------------------
|
|
62
|
-
// Default skill directories
|
|
63
|
-
// ---------------------------------------------------------------------------
|
|
64
|
-
|
|
65
|
-
function defaultSkillDirs(): string[] {
|
|
66
|
-
return [
|
|
67
|
-
join(process.cwd(), "skills"),
|
|
68
|
-
join(homedir(), ".tinyweb-agent", "skills"),
|
|
69
|
-
]
|
|
70
|
-
}
|
|
71
|
-
|
|
72
|
-
// ---------------------------------------------------------------------------
|
|
73
|
-
// loadSkills — scan all dirs and return deduplicated skill list
|
|
74
|
-
// ---------------------------------------------------------------------------
|
|
75
|
-
|
|
76
|
-
export async function loadSkills(extraDirs: string[] = []): Promise<SkillInfo[]> {
|
|
77
|
-
const dirs = [...defaultSkillDirs(), ...extraDirs]
|
|
78
|
-
const all: SkillInfo[] = []
|
|
79
|
-
for (const dir of dirs) {
|
|
80
|
-
const found = await scanDir(dir)
|
|
81
|
-
all.push(...found)
|
|
82
|
-
}
|
|
83
|
-
// Deduplicate by name, last-wins
|
|
84
|
-
const byName = new Map<string, SkillInfo>()
|
|
85
|
-
for (const skill of all) {
|
|
86
|
-
byName.set(skill.name, skill)
|
|
87
|
-
}
|
|
88
|
-
return Array.from(byName.values())
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
// ---------------------------------------------------------------------------
|
|
92
|
-
// makeSkillTool — returns an AnyExecutableTool that retrieves skill content
|
|
93
|
-
// ---------------------------------------------------------------------------
|
|
94
|
-
|
|
95
|
-
import { Tool, ToolFailure } from "@tinyweb-agent-framework/llm"
|
|
96
|
-
import { Effect, Schema } from "effect"
|
|
97
|
-
|
|
98
|
-
export function makeSkillTool(skills: SkillInfo[]): Tool.AnyExecutableTool {
|
|
99
|
-
const byName = new Map(skills.map((s) => [s.name, s]))
|
|
100
|
-
const names = skills.map((s) => s.name).join(", ")
|
|
101
|
-
|
|
102
|
-
return Tool.make({
|
|
103
|
-
description: `Load skill instructions by name. Available skills: ${names || "(none)"}. Returns the skill's markdown content.`,
|
|
104
|
-
parameters: Schema.Struct({ name: Schema.String }),
|
|
105
|
-
success: Schema.Struct({ name: Schema.String, content: Schema.String }),
|
|
106
|
-
execute: (input) => {
|
|
107
|
-
const skill = byName.get(input.name)
|
|
108
|
-
if (!skill)
|
|
109
|
-
return Effect.fail(new ToolFailure({ message: `Skill "${input.name}" not found. Available: ${names || "(none)"}` }))
|
|
110
|
-
return Effect.succeed({ name: skill.name, content: skill.content })
|
|
111
|
-
},
|
|
112
|
-
}) as Tool.AnyExecutableTool
|
|
113
|
-
}
|
package/src/sse-handler.ts
DELETED
|
@@ -1,67 +0,0 @@
|
|
|
1
|
-
import {
|
|
2
|
-
AI_SDK_HEADERS,
|
|
3
|
-
encodeSSE,
|
|
4
|
-
toAISDKDataStream,
|
|
5
|
-
type AgentEvent as ProtocolAgentEvent,
|
|
6
|
-
} from "@tinyweb-agent-framework/protocol"
|
|
7
|
-
import type { AgentEvent } from "./events"
|
|
8
|
-
|
|
9
|
-
export type SSEFormat = "tinyweb" | "ai-sdk"
|
|
10
|
-
|
|
11
|
-
export type SSEHandlerOptions = {
|
|
12
|
-
readonly format?: SSEFormat
|
|
13
|
-
}
|
|
14
|
-
|
|
15
|
-
// Minimal duck-typed Node http req/res shapes so the handler stays node:http-free.
|
|
16
|
-
type NodeReq = {
|
|
17
|
-
readonly method?: string
|
|
18
|
-
readonly url?: string
|
|
19
|
-
// body is consumer-provided; handler reads via on('data') events.
|
|
20
|
-
on?: (event: string, listener: (...args: unknown[]) => void) => unknown
|
|
21
|
-
}
|
|
22
|
-
|
|
23
|
-
type NodeRes = {
|
|
24
|
-
setHeader: (name: string, value: string) => unknown
|
|
25
|
-
write: (chunk: string | Uint8Array) => unknown
|
|
26
|
-
end: (chunk?: string | Uint8Array) => unknown
|
|
27
|
-
flushHeaders?: () => unknown
|
|
28
|
-
on?: (event: string, listener: (...args: unknown[]) => void) => unknown
|
|
29
|
-
}
|
|
30
|
-
|
|
31
|
-
const TINYWEB_HEADERS: Readonly<Record<string, string>> = {
|
|
32
|
-
"Content-Type": "text/event-stream",
|
|
33
|
-
"Cache-Control": "no-cache, no-transform",
|
|
34
|
-
Connection: "keep-alive",
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
// Bridge a server's stream of AgentEvents to an outbound HTTP response in either
|
|
38
|
-
// the framework's native SSE format or the Vercel AI SDK Data Stream format.
|
|
39
|
-
export const writeEventsToResponse = async (
|
|
40
|
-
events: AsyncIterable<AgentEvent>,
|
|
41
|
-
res: NodeRes,
|
|
42
|
-
format: SSEFormat = "tinyweb",
|
|
43
|
-
): Promise<void> => {
|
|
44
|
-
const headers = format === "ai-sdk" ? AI_SDK_HEADERS : TINYWEB_HEADERS
|
|
45
|
-
for (const [name, value] of Object.entries(headers)) res.setHeader(name, value)
|
|
46
|
-
if (typeof res.flushHeaders === "function") res.flushHeaders()
|
|
47
|
-
for await (const event of events) {
|
|
48
|
-
const protocolEvent = event as ProtocolAgentEvent
|
|
49
|
-
const line = format === "ai-sdk" ? toAISDKDataStream(protocolEvent) : encodeSSE(protocolEvent)
|
|
50
|
-
if (line.length > 0) res.write(line)
|
|
51
|
-
}
|
|
52
|
-
res.end()
|
|
53
|
-
}
|
|
54
|
-
|
|
55
|
-
// Build a Node http-style handler for an agent. Caller is responsible for parsing
|
|
56
|
-
// the request body and supplying { prompt, sessionId? } to `getInput`.
|
|
57
|
-
export const makeSSEHandler = (
|
|
58
|
-
run: (input: { prompt: string; sessionId?: string }) => AsyncIterable<AgentEvent>,
|
|
59
|
-
options: SSEHandlerOptions = {},
|
|
60
|
-
) => {
|
|
61
|
-
const format = options.format ?? "tinyweb"
|
|
62
|
-
return async (input: { prompt: string; sessionId?: string }, res: NodeRes): Promise<void> => {
|
|
63
|
-
await writeEventsToResponse(run(input), res, format)
|
|
64
|
-
}
|
|
65
|
-
}
|
|
66
|
-
|
|
67
|
-
export type { NodeReq, NodeRes }
|
package/src/transcript.ts
DELETED
|
@@ -1,126 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Transcript helpers for consumers persisting their own chat history
|
|
3
|
-
* (e.g. a Next.js app with a `messages` table) on top of the framework's
|
|
4
|
-
* `AgentEvent` stream.
|
|
5
|
-
*
|
|
6
|
-
* Why this lives in `@tinyweb-agent-framework/agent`:
|
|
7
|
-
*
|
|
8
|
-
* The conventional "every assistant turn must call a tool" prompt regime
|
|
9
|
-
* uses [`display_response`](../../tool/src/display_response.ts:1) from
|
|
10
|
-
* `@tinyweb-agent-framework/tool` as the escape hatch for plain prose.
|
|
11
|
-
* When the model invokes `display_response` it emits NO `text-delta` —
|
|
12
|
-
* the user-facing reply lives entirely inside the tool call's
|
|
13
|
-
* `input.response`. App-level code that only watches `text-delta` ends
|
|
14
|
-
* up with an empty assistant string and skips persisting the turn, so
|
|
15
|
-
* the transcript disappears after reload (bug 0003).
|
|
16
|
-
*
|
|
17
|
-
* `collectAssistantText` centralises the fallback so every consumer gets
|
|
18
|
-
* it for free without re-implementing the convention.
|
|
19
|
-
*/
|
|
20
|
-
import type { AgentEvent } from "./events"
|
|
21
|
-
|
|
22
|
-
/**
|
|
23
|
-
* Configuration for [`collectAssistantText`](./transcript.ts:1).
|
|
24
|
-
*
|
|
25
|
-
* All fields are optional and have framework-friendly defaults. Override
|
|
26
|
-
* `displayResponseToolName` if you mounted the say tool under a different
|
|
27
|
-
* identifier via [`displayResponse({ name })`](../../tool/src/display_response.ts:58).
|
|
28
|
-
*/
|
|
29
|
-
export type CollectAssistantTextOptions = {
|
|
30
|
-
/**
|
|
31
|
-
* Tool name to treat as the "final user-facing message" fallback.
|
|
32
|
-
* Default: `"display_response"`. Pass an array to recognise multiple
|
|
33
|
-
* aliases (e.g. a legacy `"agent_say"` deployment).
|
|
34
|
-
*/
|
|
35
|
-
readonly displayResponseToolName?: string | ReadonlyArray<string>
|
|
36
|
-
}
|
|
37
|
-
|
|
38
|
-
/**
|
|
39
|
-
* Stateful accumulator: feed it one [`AgentEvent`](./events.ts:1) at a
|
|
40
|
-
* time and call `text()` at the end to read the final assistant text.
|
|
41
|
-
*
|
|
42
|
-
* Designed for streaming use inside an `await…of` loop where the caller
|
|
43
|
-
* already has to iterate events for other reasons (UI streaming, logging,
|
|
44
|
-
* etc.). Use [`collectAssistantText`](./transcript.ts:1) for the simpler
|
|
45
|
-
* "given an array, give me the text" case.
|
|
46
|
-
*/
|
|
47
|
-
export type AssistantTextAccumulator = {
|
|
48
|
-
/** Apply one event to the accumulator. Safe to call with any AgentEvent. */
|
|
49
|
-
readonly push: (event: AgentEvent) => void
|
|
50
|
-
/**
|
|
51
|
-
* The final assistant text resolved with this precedence:
|
|
52
|
-
* 1. `text-delta` content (model produced plain prose).
|
|
53
|
-
* 2. `display_response` tool-call `input.response` (the escape hatch).
|
|
54
|
-
* 3. Empty string (model produced neither).
|
|
55
|
-
*/
|
|
56
|
-
readonly text: () => string
|
|
57
|
-
/**
|
|
58
|
-
* `true` once at least one `text-delta` event has been observed. Useful
|
|
59
|
-
* for callers that want to decide "did the model speak plainly OR did
|
|
60
|
-
* it fall back to display_response" without re-deriving from the text.
|
|
61
|
-
*/
|
|
62
|
-
readonly hasPlainText: () => boolean
|
|
63
|
-
/**
|
|
64
|
-
* The captured display_response fallback, if any. Distinct from `text()`
|
|
65
|
-
* so callers persisting structured transcripts can keep the two signals
|
|
66
|
-
* separate.
|
|
67
|
-
*/
|
|
68
|
-
readonly displayResponseMessage: () => string | undefined
|
|
69
|
-
}
|
|
70
|
-
|
|
71
|
-
const toNameSet = (n: string | ReadonlyArray<string> | undefined): ReadonlySet<string> => {
|
|
72
|
-
if (n === undefined) return new Set(["display_response"])
|
|
73
|
-
if (typeof n === "string") return new Set([n])
|
|
74
|
-
return new Set(n)
|
|
75
|
-
}
|
|
76
|
-
|
|
77
|
-
/**
|
|
78
|
-
* Create a stateful accumulator. Prefer this when consuming events as a
|
|
79
|
-
* stream; prefer [`collectAssistantText`](./transcript.ts:1) for arrays.
|
|
80
|
-
*/
|
|
81
|
-
export const makeAssistantTextAccumulator = (
|
|
82
|
-
options: CollectAssistantTextOptions = {},
|
|
83
|
-
): AssistantTextAccumulator => {
|
|
84
|
-
const names = toNameSet(options.displayResponseToolName)
|
|
85
|
-
let buffer = ""
|
|
86
|
-
let sayMessage: string | undefined
|
|
87
|
-
return {
|
|
88
|
-
push(event) {
|
|
89
|
-
if (event.type === "text-delta") {
|
|
90
|
-
buffer += event.text
|
|
91
|
-
return
|
|
92
|
-
}
|
|
93
|
-
if (event.type === "tool-call" && names.has(event.name)) {
|
|
94
|
-
const input = event.input as { response?: unknown } | null | undefined
|
|
95
|
-
const msg = input && typeof input.response === "string" ? input.response : undefined
|
|
96
|
-
if (msg && msg.length > 0) sayMessage = msg
|
|
97
|
-
}
|
|
98
|
-
},
|
|
99
|
-
text() {
|
|
100
|
-
if (buffer.length > 0) return buffer
|
|
101
|
-
return sayMessage ?? ""
|
|
102
|
-
},
|
|
103
|
-
hasPlainText() {
|
|
104
|
-
return buffer.length > 0
|
|
105
|
-
},
|
|
106
|
-
displayResponseMessage() {
|
|
107
|
-
return sayMessage
|
|
108
|
-
},
|
|
109
|
-
}
|
|
110
|
-
}
|
|
111
|
-
|
|
112
|
-
/**
|
|
113
|
-
* Reduce a finite collection of events into the final assistant text.
|
|
114
|
-
*
|
|
115
|
-
* Equivalent to `events.forEach(acc.push); return acc.text()` — provided
|
|
116
|
-
* as a one-liner for the common "I already have the events array" case
|
|
117
|
-
* (tests, fully-buffered handlers, audit replay).
|
|
118
|
-
*/
|
|
119
|
-
export const collectAssistantText = (
|
|
120
|
-
events: Iterable<AgentEvent>,
|
|
121
|
-
options: CollectAssistantTextOptions = {},
|
|
122
|
-
): string => {
|
|
123
|
-
const acc = makeAssistantTextAccumulator(options)
|
|
124
|
-
for (const e of events) acc.push(e)
|
|
125
|
-
return acc.text()
|
|
126
|
-
}
|