@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
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
import { readdir, readFile } from 'fs/promises';
|
|
2
|
+
import { join } from 'path';
|
|
3
|
+
import { homedir } from 'os';
|
|
4
|
+
import { Tool, ToolFailure } from '@tinyweb_dev/agent-framework-llm';
|
|
5
|
+
import { Effect, Schema } from 'effect';
|
|
6
|
+
|
|
7
|
+
// src/skill/index.ts
|
|
8
|
+
function parseFrontmatter(raw) {
|
|
9
|
+
if (!raw.startsWith("---")) return { body: raw };
|
|
10
|
+
const end = raw.indexOf("\n---", 3);
|
|
11
|
+
if (end === -1) return { body: raw };
|
|
12
|
+
const fm = raw.slice(3, end).trim();
|
|
13
|
+
const body = raw.slice(end + 4).trim();
|
|
14
|
+
const name = fm.match(/^name:\s*(.+)$/m)?.[1]?.trim();
|
|
15
|
+
const description = fm.match(/^description:\s*(.+)$/m)?.[1]?.trim();
|
|
16
|
+
return { name, description, body };
|
|
17
|
+
}
|
|
18
|
+
async function scanDir(dir) {
|
|
19
|
+
const results = [];
|
|
20
|
+
let entries = [];
|
|
21
|
+
try {
|
|
22
|
+
entries = await readdir(dir, { withFileTypes: true });
|
|
23
|
+
} catch {
|
|
24
|
+
return results;
|
|
25
|
+
}
|
|
26
|
+
for (const entry of entries) {
|
|
27
|
+
const full = join(dir, entry.name);
|
|
28
|
+
if (entry.isDirectory()) {
|
|
29
|
+
const nested = await scanDir(full);
|
|
30
|
+
results.push(...nested);
|
|
31
|
+
} else if (entry.name === "SKILL.md") {
|
|
32
|
+
const raw = await readFile(full, "utf-8").catch(() => "");
|
|
33
|
+
if (!raw) continue;
|
|
34
|
+
const { name, description, body } = parseFrontmatter(raw);
|
|
35
|
+
if (!name) continue;
|
|
36
|
+
results.push({ name, description, location: full, content: body || raw });
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
return results;
|
|
40
|
+
}
|
|
41
|
+
function defaultSkillDirs() {
|
|
42
|
+
return [
|
|
43
|
+
join(process.cwd(), "skills"),
|
|
44
|
+
join(homedir(), ".tinyweb-agent", "skills")
|
|
45
|
+
];
|
|
46
|
+
}
|
|
47
|
+
async function loadSkills(extraDirs = []) {
|
|
48
|
+
const dirs = [...defaultSkillDirs(), ...extraDirs];
|
|
49
|
+
const all = [];
|
|
50
|
+
for (const dir of dirs) {
|
|
51
|
+
const found = await scanDir(dir);
|
|
52
|
+
all.push(...found);
|
|
53
|
+
}
|
|
54
|
+
const byName = /* @__PURE__ */ new Map();
|
|
55
|
+
for (const skill of all) {
|
|
56
|
+
byName.set(skill.name, skill);
|
|
57
|
+
}
|
|
58
|
+
return Array.from(byName.values());
|
|
59
|
+
}
|
|
60
|
+
function makeSkillTool(skills) {
|
|
61
|
+
const byName = new Map(skills.map((s) => [s.name, s]));
|
|
62
|
+
const names = skills.map((s) => s.name).join(", ");
|
|
63
|
+
return Tool.make({
|
|
64
|
+
description: `Load skill instructions by name. Available skills: ${names || "(none)"}. Returns the skill's markdown content.`,
|
|
65
|
+
parameters: Schema.Struct({ name: Schema.String }),
|
|
66
|
+
success: Schema.Struct({ name: Schema.String, content: Schema.String }),
|
|
67
|
+
execute: (input) => {
|
|
68
|
+
const skill = byName.get(input.name);
|
|
69
|
+
if (!skill)
|
|
70
|
+
return Effect.fail(new ToolFailure({ message: `Skill "${input.name}" not found. Available: ${names || "(none)"}` }));
|
|
71
|
+
return Effect.succeed({ name: skill.name, content: skill.content });
|
|
72
|
+
}
|
|
73
|
+
});
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
export { loadSkills, makeSkillTool };
|
|
77
|
+
//# sourceMappingURL=index.js.map
|
|
78
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../../src/skill/index.ts"],"names":[],"mappings":"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","file":"index.js","sourcesContent":["// Adapted from opencode@v1.14.48 packages/opencode/src/skill/\n\nimport { readdir, readFile } from \"node:fs/promises\"\nimport { join, dirname } from \"node:path\"\nimport { homedir } from \"node:os\"\n\n// ---------------------------------------------------------------------------\n// Skill types\n// ---------------------------------------------------------------------------\n\nexport type SkillInfo = {\n readonly name: string\n readonly description?: string\n readonly location: string\n readonly content: string\n}\n\n// ---------------------------------------------------------------------------\n// Frontmatter parsing — minimal YAML-ish subset (name: / description:)\n// ---------------------------------------------------------------------------\n\nfunction parseFrontmatter(raw: string): { name?: string; description?: string; body: string } {\n if (!raw.startsWith(\"---\")) return { body: raw }\n const end = raw.indexOf(\"\\n---\", 3)\n if (end === -1) return { body: raw }\n const fm = raw.slice(3, end).trim()\n const body = raw.slice(end + 4).trim()\n const name = fm.match(/^name:\\s*(.+)$/m)?.[1]?.trim()\n const description = fm.match(/^description:\\s*(.+)$/m)?.[1]?.trim()\n return { name, description, body }\n}\n\n// ---------------------------------------------------------------------------\n// Scan a directory recursively for SKILL.md files\n// ---------------------------------------------------------------------------\n\nasync function scanDir(dir: string): Promise<SkillInfo[]> {\n const results: SkillInfo[] = []\n let entries: { name: string; isDirectory: () => boolean }[] = []\n try {\n entries = await readdir(dir, { withFileTypes: true })\n } catch {\n return results\n }\n for (const entry of entries) {\n const full = join(dir, entry.name)\n if (entry.isDirectory()) {\n const nested = await scanDir(full)\n results.push(...nested)\n } else if (entry.name === \"SKILL.md\") {\n const raw = await readFile(full, \"utf-8\").catch(() => \"\")\n if (!raw) continue\n const { name, description, body } = parseFrontmatter(raw)\n if (!name) continue\n results.push({ name, description, location: full, content: body || raw })\n }\n }\n return results\n}\n\n// ---------------------------------------------------------------------------\n// Default skill directories\n// ---------------------------------------------------------------------------\n\nfunction defaultSkillDirs(): string[] {\n return [\n join(process.cwd(), \"skills\"),\n join(homedir(), \".tinyweb-agent\", \"skills\"),\n ]\n}\n\n// ---------------------------------------------------------------------------\n// loadSkills — scan all dirs and return deduplicated skill list\n// ---------------------------------------------------------------------------\n\nexport async function loadSkills(extraDirs: string[] = []): Promise<SkillInfo[]> {\n const dirs = [...defaultSkillDirs(), ...extraDirs]\n const all: SkillInfo[] = []\n for (const dir of dirs) {\n const found = await scanDir(dir)\n all.push(...found)\n }\n // Deduplicate by name, last-wins\n const byName = new Map<string, SkillInfo>()\n for (const skill of all) {\n byName.set(skill.name, skill)\n }\n return Array.from(byName.values())\n}\n\n// ---------------------------------------------------------------------------\n// makeSkillTool — returns an AnyExecutableTool that retrieves skill content\n// ---------------------------------------------------------------------------\n\nimport { Tool, ToolFailure } from \"@tinyweb_dev/agent-framework-llm\"\nimport { Effect, Schema } from \"effect\"\n\nexport function makeSkillTool(skills: SkillInfo[]): Tool.AnyExecutableTool {\n const byName = new Map(skills.map((s) => [s.name, s]))\n const names = skills.map((s) => s.name).join(\", \")\n\n return Tool.make({\n description: `Load skill instructions by name. Available skills: ${names || \"(none)\"}. Returns the skill's markdown content.`,\n parameters: Schema.Struct({ name: Schema.String }),\n success: Schema.Struct({ name: Schema.String, content: Schema.String }),\n execute: (input) => {\n const skill = byName.get(input.name)\n if (!skill)\n return Effect.fail(new ToolFailure({ message: `Skill \"${input.name}\" not found. Available: ${names || \"(none)\"}` }))\n return Effect.succeed({ name: skill.name, content: skill.content })\n },\n }) as Tool.AnyExecutableTool\n}\n"]}
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import type { AgentEvent } from "./events";
|
|
2
|
+
export type SSEFormat = "tinyweb" | "ai-sdk";
|
|
3
|
+
export type SSEHandlerOptions = {
|
|
4
|
+
readonly format?: SSEFormat;
|
|
5
|
+
};
|
|
6
|
+
type NodeReq = {
|
|
7
|
+
readonly method?: string;
|
|
8
|
+
readonly url?: string;
|
|
9
|
+
on?: (event: string, listener: (...args: unknown[]) => void) => unknown;
|
|
10
|
+
};
|
|
11
|
+
type NodeRes = {
|
|
12
|
+
setHeader: (name: string, value: string) => unknown;
|
|
13
|
+
write: (chunk: string | Uint8Array) => unknown;
|
|
14
|
+
end: (chunk?: string | Uint8Array) => unknown;
|
|
15
|
+
flushHeaders?: () => unknown;
|
|
16
|
+
on?: (event: string, listener: (...args: unknown[]) => void) => unknown;
|
|
17
|
+
};
|
|
18
|
+
export declare const writeEventsToResponse: (events: AsyncIterable<AgentEvent>, res: NodeRes, format?: SSEFormat) => Promise<void>;
|
|
19
|
+
export declare const makeSSEHandler: (run: (input: {
|
|
20
|
+
prompt: string;
|
|
21
|
+
sessionId?: string;
|
|
22
|
+
}) => AsyncIterable<AgentEvent>, options?: SSEHandlerOptions) => (input: {
|
|
23
|
+
prompt: string;
|
|
24
|
+
sessionId?: string;
|
|
25
|
+
}, res: NodeRes) => Promise<void>;
|
|
26
|
+
export type { NodeReq, NodeRes };
|
|
27
|
+
//# sourceMappingURL=sse-handler.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse-handler.d.ts","sourceRoot":"","sources":["../src/sse-handler.ts"],"names":[],"mappings":"AAMA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAE1C,MAAM,MAAM,SAAS,GAAG,SAAS,GAAG,QAAQ,CAAA;AAE5C,MAAM,MAAM,iBAAiB,GAAG;IAC9B,QAAQ,CAAC,MAAM,CAAC,EAAE,SAAS,CAAA;CAC5B,CAAA;AAGD,KAAK,OAAO,GAAG;IACb,QAAQ,CAAC,MAAM,CAAC,EAAE,MAAM,CAAA;IACxB,QAAQ,CAAC,GAAG,CAAC,EAAE,MAAM,CAAA;IAErB,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,KAAK,OAAO,CAAA;CACxE,CAAA;AAED,KAAK,OAAO,GAAG;IACb,SAAS,EAAE,CAAC,IAAI,EAAE,MAAM,EAAE,KAAK,EAAE,MAAM,KAAK,OAAO,CAAA;IACnD,KAAK,EAAE,CAAC,KAAK,EAAE,MAAM,GAAG,UAAU,KAAK,OAAO,CAAA;IAC9C,GAAG,EAAE,CAAC,KAAK,CAAC,EAAE,MAAM,GAAG,UAAU,KAAK,OAAO,CAAA;IAC7C,YAAY,CAAC,EAAE,MAAM,OAAO,CAAA;IAC5B,EAAE,CAAC,EAAE,CAAC,KAAK,EAAE,MAAM,EAAE,QAAQ,EAAE,CAAC,GAAG,IAAI,EAAE,OAAO,EAAE,KAAK,IAAI,KAAK,OAAO,CAAA;CACxE,CAAA;AAUD,eAAO,MAAM,qBAAqB,GAChC,QAAQ,aAAa,CAAC,UAAU,CAAC,EACjC,KAAK,OAAO,EACZ,SAAQ,SAAqB,KAC5B,OAAO,CAAC,IAAI,CAUd,CAAA;AAID,eAAO,MAAM,cAAc,GACzB,KAAK,CAAC,KAAK,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,KAAK,aAAa,CAAC,UAAU,CAAC,EACjF,UAAS,iBAAsB,MAGjB,OAAO;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,SAAS,CAAC,EAAE,MAAM,CAAA;CAAE,EAAE,KAAK,OAAO,KAAG,OAAO,CAAC,IAAI,CAGzF,CAAA;AAED,YAAY,EAAE,OAAO,EAAE,OAAO,EAAE,CAAA"}
|
|
@@ -0,0 +1,81 @@
|
|
|
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_dev/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_dev/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
|
+
* Configuration for [`collectAssistantText`](./transcript.ts:1).
|
|
23
|
+
*
|
|
24
|
+
* All fields are optional and have framework-friendly defaults. Override
|
|
25
|
+
* `displayResponseToolName` if you mounted the say tool under a different
|
|
26
|
+
* identifier via [`displayResponse({ name })`](../../tool/src/display_response.ts:58).
|
|
27
|
+
*/
|
|
28
|
+
export type CollectAssistantTextOptions = {
|
|
29
|
+
/**
|
|
30
|
+
* Tool name to treat as the "final user-facing message" fallback.
|
|
31
|
+
* Default: `"display_response"`. Pass an array to recognise multiple
|
|
32
|
+
* aliases (e.g. a legacy `"agent_say"` deployment).
|
|
33
|
+
*/
|
|
34
|
+
readonly displayResponseToolName?: string | ReadonlyArray<string>;
|
|
35
|
+
};
|
|
36
|
+
/**
|
|
37
|
+
* Stateful accumulator: feed it one [`AgentEvent`](./events.ts:1) at a
|
|
38
|
+
* time and call `text()` at the end to read the final assistant text.
|
|
39
|
+
*
|
|
40
|
+
* Designed for streaming use inside an `await…of` loop where the caller
|
|
41
|
+
* already has to iterate events for other reasons (UI streaming, logging,
|
|
42
|
+
* etc.). Use [`collectAssistantText`](./transcript.ts:1) for the simpler
|
|
43
|
+
* "given an array, give me the text" case.
|
|
44
|
+
*/
|
|
45
|
+
export type AssistantTextAccumulator = {
|
|
46
|
+
/** Apply one event to the accumulator. Safe to call with any AgentEvent. */
|
|
47
|
+
readonly push: (event: AgentEvent) => void;
|
|
48
|
+
/**
|
|
49
|
+
* The final assistant text resolved with this precedence:
|
|
50
|
+
* 1. `text-delta` content (model produced plain prose).
|
|
51
|
+
* 2. `display_response` tool-call `input.response` (the escape hatch).
|
|
52
|
+
* 3. Empty string (model produced neither).
|
|
53
|
+
*/
|
|
54
|
+
readonly text: () => string;
|
|
55
|
+
/**
|
|
56
|
+
* `true` once at least one `text-delta` event has been observed. Useful
|
|
57
|
+
* for callers that want to decide "did the model speak plainly OR did
|
|
58
|
+
* it fall back to display_response" without re-deriving from the text.
|
|
59
|
+
*/
|
|
60
|
+
readonly hasPlainText: () => boolean;
|
|
61
|
+
/**
|
|
62
|
+
* The captured display_response fallback, if any. Distinct from `text()`
|
|
63
|
+
* so callers persisting structured transcripts can keep the two signals
|
|
64
|
+
* separate.
|
|
65
|
+
*/
|
|
66
|
+
readonly displayResponseMessage: () => string | undefined;
|
|
67
|
+
};
|
|
68
|
+
/**
|
|
69
|
+
* Create a stateful accumulator. Prefer this when consuming events as a
|
|
70
|
+
* stream; prefer [`collectAssistantText`](./transcript.ts:1) for arrays.
|
|
71
|
+
*/
|
|
72
|
+
export declare const makeAssistantTextAccumulator: (options?: CollectAssistantTextOptions) => AssistantTextAccumulator;
|
|
73
|
+
/**
|
|
74
|
+
* Reduce a finite collection of events into the final assistant text.
|
|
75
|
+
*
|
|
76
|
+
* Equivalent to `events.forEach(acc.push); return acc.text()` — provided
|
|
77
|
+
* as a one-liner for the common "I already have the events array" case
|
|
78
|
+
* (tests, fully-buffered handlers, audit replay).
|
|
79
|
+
*/
|
|
80
|
+
export declare const collectAssistantText: (events: Iterable<AgentEvent>, options?: CollectAssistantTextOptions) => string;
|
|
81
|
+
//# sourceMappingURL=transcript.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"transcript.d.ts","sourceRoot":"","sources":["../src/transcript.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,UAAU,CAAA;AAE1C;;;;;;GAMG;AACH,MAAM,MAAM,2BAA2B,GAAG;IACxC;;;;OAIG;IACH,QAAQ,CAAC,uBAAuB,CAAC,EAAE,MAAM,GAAG,aAAa,CAAC,MAAM,CAAC,CAAA;CAClE,CAAA;AAED;;;;;;;;GAQG;AACH,MAAM,MAAM,wBAAwB,GAAG;IACrC,4EAA4E;IAC5E,QAAQ,CAAC,IAAI,EAAE,CAAC,KAAK,EAAE,UAAU,KAAK,IAAI,CAAA;IAC1C;;;;;OAKG;IACH,QAAQ,CAAC,IAAI,EAAE,MAAM,MAAM,CAAA;IAC3B;;;;OAIG;IACH,QAAQ,CAAC,YAAY,EAAE,MAAM,OAAO,CAAA;IACpC;;;;OAIG;IACH,QAAQ,CAAC,sBAAsB,EAAE,MAAM,MAAM,GAAG,SAAS,CAAA;CAC1D,CAAA;AAQD;;;GAGG;AACH,eAAO,MAAM,4BAA4B,GACvC,UAAS,2BAAgC,KACxC,wBA2BF,CAAA;AAED;;;;;;GAMG;AACH,eAAO,MAAM,oBAAoB,GAC/B,QAAQ,QAAQ,CAAC,UAAU,CAAC,EAC5B,UAAS,2BAAgC,KACxC,MAIF,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,28 +1,60 @@
|
|
|
1
1
|
{
|
|
2
2
|
"$schema": "https://json.schemastore.org/package.json",
|
|
3
3
|
"name": "@tinyweb_dev/agent-framework-agent",
|
|
4
|
-
"version": "0.
|
|
4
|
+
"version": "0.3.0",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MIT",
|
|
7
|
-
"scripts": {
|
|
8
|
-
"typecheck": "tsc --noEmit",
|
|
9
|
-
"test": "bun test --timeout 30000"
|
|
10
|
-
},
|
|
11
7
|
"files": [
|
|
12
|
-
"
|
|
8
|
+
"dist",
|
|
13
9
|
"README.md",
|
|
14
10
|
"LICENSE"
|
|
15
11
|
],
|
|
16
12
|
"exports": {
|
|
17
|
-
".":
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
"./
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
13
|
+
".": {
|
|
14
|
+
"types": "./dist/index.d.ts",
|
|
15
|
+
"import": "./dist/index.js",
|
|
16
|
+
"require": "./dist/index.cjs"
|
|
17
|
+
},
|
|
18
|
+
"./plugin": {
|
|
19
|
+
"types": "./dist/plugin/index.d.ts",
|
|
20
|
+
"import": "./dist/plugin/index.js",
|
|
21
|
+
"require": "./dist/plugin/index.cjs"
|
|
22
|
+
},
|
|
23
|
+
"./mcp": {
|
|
24
|
+
"types": "./dist/mcp/index.d.ts",
|
|
25
|
+
"import": "./dist/mcp/index.js",
|
|
26
|
+
"require": "./dist/mcp/index.cjs"
|
|
27
|
+
},
|
|
28
|
+
"./skill": {
|
|
29
|
+
"types": "./dist/skill/index.d.ts",
|
|
30
|
+
"import": "./dist/skill/index.js",
|
|
31
|
+
"require": "./dist/skill/index.cjs"
|
|
32
|
+
},
|
|
33
|
+
"./session/sqlite": {
|
|
34
|
+
"types": "./dist/session/sqlite.d.ts",
|
|
35
|
+
"import": "./dist/session/sqlite.js",
|
|
36
|
+
"require": "./dist/session/sqlite.cjs"
|
|
37
|
+
},
|
|
38
|
+
"./session/postgres": {
|
|
39
|
+
"types": "./dist/session/postgres.d.ts",
|
|
40
|
+
"import": "./dist/session/postgres.js",
|
|
41
|
+
"require": "./dist/session/postgres.cjs"
|
|
42
|
+
},
|
|
43
|
+
"./session/memory": {
|
|
44
|
+
"types": "./dist/session/memory.d.ts",
|
|
45
|
+
"import": "./dist/session/memory.js",
|
|
46
|
+
"require": "./dist/session/memory.cjs"
|
|
47
|
+
},
|
|
48
|
+
"./session-api": {
|
|
49
|
+
"types": "./dist/session-api.d.ts",
|
|
50
|
+
"import": "./dist/session-api.js",
|
|
51
|
+
"require": "./dist/session-api.cjs"
|
|
52
|
+
},
|
|
53
|
+
"./http-handlers": {
|
|
54
|
+
"types": "./dist/http-handlers.d.ts",
|
|
55
|
+
"import": "./dist/http-handlers.js",
|
|
56
|
+
"require": "./dist/http-handlers.cjs"
|
|
57
|
+
}
|
|
26
58
|
},
|
|
27
59
|
"devDependencies": {
|
|
28
60
|
"@tsconfig/bun": "1.0.9",
|
|
@@ -34,8 +66,11 @@
|
|
|
34
66
|
"drizzle-orm": "1.0.0-beta.19-d95b7a4",
|
|
35
67
|
"effect": "4.0.0-beta.59",
|
|
36
68
|
"ulid": "3.0.1",
|
|
37
|
-
"@tinyweb_dev/agent-framework-core": "0.
|
|
38
|
-
"@tinyweb_dev/agent-framework-llm": "0.
|
|
39
|
-
"@tinyweb_dev/agent-framework-protocol": "0.
|
|
40
|
-
}
|
|
69
|
+
"@tinyweb_dev/agent-framework-core": "0.3.0",
|
|
70
|
+
"@tinyweb_dev/agent-framework-llm": "0.3.0",
|
|
71
|
+
"@tinyweb_dev/agent-framework-protocol": "0.3.0"
|
|
72
|
+
},
|
|
73
|
+
"main": "./dist/index.cjs",
|
|
74
|
+
"module": "./dist/index.js",
|
|
75
|
+
"types": "./dist/index.d.ts"
|
|
41
76
|
}
|
package/src/agent.ts
DELETED
|
@@ -1,317 +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 { applyPermission, type PermissionAskHandler, type PermissionConfig } from "./permission"
|
|
17
|
-
import { defaultRuntime, type AgentRuntime } from "./runtime"
|
|
18
|
-
import { makeProcessor } from "./session/processor"
|
|
19
|
-
import { makeMemoryStore } from "./session/memory"
|
|
20
|
-
import type { SessionStore } from "./session/adapter"
|
|
21
|
-
import { historyToLLMMessages } from "./session/replay"
|
|
22
|
-
import { makeSSEHandler, type SSEHandlerOptions } from "./sse-handler"
|
|
23
|
-
import { loadPlugins, type Hooks, type PluginEntry } from "./plugin"
|
|
24
|
-
import { connectAllMcp, type McpConfig } from "./mcp"
|
|
25
|
-
import { loadSkills, makeSkillTool } from "./skill"
|
|
26
|
-
import { makeSessionAPI, type SessionAPI } from "./session-api"
|
|
27
|
-
import { makeHTTPHandlers, type AuthorizeFn, type ChatFormat, type HTTPHandlers } from "./http-handlers"
|
|
28
|
-
import { composeSystemPrompt, type PromptSectionsConfig } from "./prompt"
|
|
29
|
-
|
|
30
|
-
/**
|
|
31
|
-
* Auto-compaction policy. The agent estimates input tokens on every turn and,
|
|
32
|
-
* when the estimate crosses the model's usable budget, summarises the leading
|
|
33
|
-
* slice of the conversation into a marker user message before calling the LLM.
|
|
34
|
-
* On a `ContextOverflowReason` from the provider the agent retries once with
|
|
35
|
-
* a freshly compacted history.
|
|
36
|
-
*/
|
|
37
|
-
export type CompactionConfig = {
|
|
38
|
-
/** Default: true. Set to false to opt out entirely. */
|
|
39
|
-
readonly auto?: boolean
|
|
40
|
-
/** Reserved output buffer. Default `min(20_000, model.limits.output)`. */
|
|
41
|
-
readonly reservedTokens?: number
|
|
42
|
-
/** Number of trailing turns kept verbatim. Default 4. */
|
|
43
|
-
readonly preserveRecentTurns?: number
|
|
44
|
-
}
|
|
45
|
-
|
|
46
|
-
export type DefineAgentConfig<T extends Tools> = {
|
|
47
|
-
readonly name: string
|
|
48
|
-
readonly model: ModelRef
|
|
49
|
-
/**
|
|
50
|
-
* The agent's ROLE / persona block. Verbatim — no transformation.
|
|
51
|
-
*
|
|
52
|
-
* Framework-owned blocks (TOOL USE, TOOL USE GUIDELINES, RESPONSE STYLE) are
|
|
53
|
-
* automatically appended after this. Disable or tune them via
|
|
54
|
-
* `promptSections`. To skip the framework blocks entirely set
|
|
55
|
-
* `promptSections: { toolUse: false, toolUseGuidelines: false, responseStyle: false }`.
|
|
56
|
-
*/
|
|
57
|
-
readonly systemPrompt?: string
|
|
58
|
-
/**
|
|
59
|
-
* Per-section toggles for the framework-owned prompt blocks. Defaults: all
|
|
60
|
-
* enabled with chat-style response rules. See [`prompt/index.ts`](./prompt/index.ts:1).
|
|
61
|
-
*/
|
|
62
|
-
readonly promptSections?: PromptSectionsConfig
|
|
63
|
-
readonly tools?: T
|
|
64
|
-
readonly stopWhen?: StopCondition
|
|
65
|
-
readonly generation?: GenerationOptions.Input
|
|
66
|
-
readonly runtime?: AgentRuntime
|
|
67
|
-
readonly store?: SessionStore
|
|
68
|
-
readonly permission?: PermissionConfig
|
|
69
|
-
readonly askHandler?: PermissionAskHandler
|
|
70
|
-
/** Plugins to load — inline Plugin fn, path string, or [path, options] tuple */
|
|
71
|
-
readonly plugins?: PluginEntry[]
|
|
72
|
-
/** MCP servers to connect — Record<serverName, McpServerConfig> */
|
|
73
|
-
readonly mcp?: McpConfig
|
|
74
|
-
/** Extra directories to scan for SKILL.md files */
|
|
75
|
-
readonly skillDirs?: string[]
|
|
76
|
-
/** Auto-compaction tuning. Defaults are sane; pass `{ auto: false }` to disable. */
|
|
77
|
-
readonly compaction?: CompactionConfig
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
export type RunInput = {
|
|
81
|
-
readonly prompt: string
|
|
82
|
-
readonly sessionId?: string
|
|
83
|
-
readonly attachments?: ReadonlyArray<AttachmentInput>
|
|
84
|
-
}
|
|
85
|
-
|
|
86
|
-
export type RunOnceResult = {
|
|
87
|
-
readonly text: string
|
|
88
|
-
readonly usage: LLMResponse["usage"]
|
|
89
|
-
readonly events: LLMResponse["events"]
|
|
90
|
-
}
|
|
91
|
-
|
|
92
|
-
export type ToHTTPHandlersOptions = {
|
|
93
|
-
readonly authorize?: AuthorizeFn
|
|
94
|
-
readonly defaultFormat?: ChatFormat
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
export type Agent = {
|
|
98
|
-
readonly name: string
|
|
99
|
-
readonly run: (input: RunInput) => AsyncIterable<AgentEvent>
|
|
100
|
-
readonly runOnce: (input: RunInput) => Promise<RunOnceResult>
|
|
101
|
-
readonly toSSEHandler: (options?: SSEHandlerOptions) => ReturnType<typeof makeSSEHandler>
|
|
102
|
-
readonly sessions: SessionAPI
|
|
103
|
-
readonly toHTTPHandlers: (options?: ToHTTPHandlersOptions) => HTTPHandlers
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
let defaultStore: SessionStore | undefined
|
|
107
|
-
const getDefaultStore = (): SessionStore => {
|
|
108
|
-
if (defaultStore) return defaultStore
|
|
109
|
-
// Default to MemoryStore — SQLite must be opted into explicitly via
|
|
110
|
-
// `store: makeSqliteStore()` to keep this package usable in environments
|
|
111
|
-
// without bun:sqlite (e.g. Next.js/webpack server runtime).
|
|
112
|
-
defaultStore = makeMemoryStore()
|
|
113
|
-
return defaultStore
|
|
114
|
-
}
|
|
115
|
-
|
|
116
|
-
// ---------------------------------------------------------------------------
|
|
117
|
-
// buildTools — merge user tools + MCP tools + optional skill tool
|
|
118
|
-
// ---------------------------------------------------------------------------
|
|
119
|
-
|
|
120
|
-
async function buildTools(
|
|
121
|
-
config: DefineAgentConfig<Tools>,
|
|
122
|
-
loadedHooks: Hooks[],
|
|
123
|
-
): Promise<ExecutableTools> {
|
|
124
|
-
const baseTools: ExecutableTools = (config.tools ?? {}) as ExecutableTools
|
|
125
|
-
|
|
126
|
-
// MCP tools
|
|
127
|
-
let mcpTools: ExecutableTools = {}
|
|
128
|
-
if (config.mcp && Object.keys(config.mcp).length > 0) {
|
|
129
|
-
const { tools } = await connectAllMcp(config.mcp)
|
|
130
|
-
mcpTools = tools
|
|
131
|
-
}
|
|
132
|
-
|
|
133
|
-
// Skill tool
|
|
134
|
-
let skillToolRecord: ExecutableTools = {}
|
|
135
|
-
if (config.skillDirs !== undefined || Object.keys(baseTools).length > 0) {
|
|
136
|
-
const skills = await loadSkills(config.skillDirs)
|
|
137
|
-
if (skills.length > 0) skillToolRecord = { skill: makeSkillTool(skills) }
|
|
138
|
-
}
|
|
139
|
-
|
|
140
|
-
const merged: ExecutableTools = { ...skillToolRecord, ...mcpTools, ...baseTools }
|
|
141
|
-
|
|
142
|
-
// Apply plugin tool.definition hooks — mutate description/parameters per tool
|
|
143
|
-
for (const hooks of loadedHooks) {
|
|
144
|
-
if (!hooks["tool.definition"]) continue
|
|
145
|
-
for (const [toolId, tool] of Object.entries(merged)) {
|
|
146
|
-
const output = { description: tool.description, parameters: tool._definition.inputSchema }
|
|
147
|
-
await hooks["tool.definition"]!({ toolId }, output)
|
|
148
|
-
// We only propagate description mutation for now (parameters schema is read-only at runtime)
|
|
149
|
-
if (output.description !== tool.description) {
|
|
150
|
-
;(tool as { description: string }).description = output.description
|
|
151
|
-
}
|
|
152
|
-
}
|
|
153
|
-
}
|
|
154
|
-
|
|
155
|
-
return applyPermission(merged, config.permission, config.askHandler)
|
|
156
|
-
}
|
|
157
|
-
|
|
158
|
-
// ---------------------------------------------------------------------------
|
|
159
|
-
// defineAgent
|
|
160
|
-
// ---------------------------------------------------------------------------
|
|
161
|
-
|
|
162
|
-
export const defineAgent = <T extends Tools = Tools>(config: DefineAgentConfig<T>): Agent => {
|
|
163
|
-
const rt = (): AgentRuntime => config.runtime ?? defaultRuntime()
|
|
164
|
-
const store = config.store ?? getDefaultStore()
|
|
165
|
-
// Default cap is intentionally generous — agentic loops (browser automation,
|
|
166
|
-
// MCP tool chains) commonly exceed 10 rounds. The tool runtime already
|
|
167
|
-
// terminates naturally when the model's `finish_reason !== "tool-calls"`,
|
|
168
|
-
// so this is purely a safety ceiling against runaway loops. Override per
|
|
169
|
-
// agent via `stopWhen: LLM.stepCountIs(N)` if you need a different policy.
|
|
170
|
-
const stopWhen = config.stopWhen ?? LLM.stepCountIs(100)
|
|
171
|
-
// Compose final system prompt once: user-authored ROLE + framework-owned
|
|
172
|
-
// TOOL USE / GUIDELINES / RESPONSE STYLE blocks. See `./prompt/index.ts`.
|
|
173
|
-
const resolvedSystemPrompt = composeSystemPrompt({
|
|
174
|
-
role: config.systemPrompt,
|
|
175
|
-
sections: config.promptSections,
|
|
176
|
-
})
|
|
177
|
-
const compactionCfg = {
|
|
178
|
-
auto: config.compaction?.auto !== false,
|
|
179
|
-
reservedTokens: config.compaction?.reservedTokens,
|
|
180
|
-
preserveRecentTurns: config.compaction?.preserveRecentTurns,
|
|
181
|
-
}
|
|
182
|
-
|
|
183
|
-
// Build tools lazily on first use (async — MCP / skills may need network/fs)
|
|
184
|
-
let toolsPromise: Promise<ExecutableTools> | undefined
|
|
185
|
-
|
|
186
|
-
const getTools = (): Promise<ExecutableTools> => {
|
|
187
|
-
if (!toolsPromise) {
|
|
188
|
-
const pluginInput = { agentName: config.name, directory: process.cwd() }
|
|
189
|
-
toolsPromise = loadPlugins(config.plugins ?? [], pluginInput).then((loaded) => {
|
|
190
|
-
const hooks = loaded.map((l) => l.hooks)
|
|
191
|
-
return buildTools(config, hooks)
|
|
192
|
-
})
|
|
193
|
-
}
|
|
194
|
-
return toolsPromise
|
|
195
|
-
}
|
|
196
|
-
|
|
197
|
-
const run = (input: RunInput): AsyncIterable<AgentEvent> => {
|
|
198
|
-
// Return an AsyncIterable that initialises tools once then delegates to processor
|
|
199
|
-
let innerIter: AsyncIterator<AgentEvent> | undefined
|
|
200
|
-
return {
|
|
201
|
-
[Symbol.asyncIterator](): AsyncIterator<AgentEvent> {
|
|
202
|
-
return {
|
|
203
|
-
async next() {
|
|
204
|
-
if (!innerIter) {
|
|
205
|
-
const tools = await getTools()
|
|
206
|
-
const processor = makeProcessor({
|
|
207
|
-
agentName: config.name,
|
|
208
|
-
model: config.model,
|
|
209
|
-
store,
|
|
210
|
-
runtime: rt(),
|
|
211
|
-
systemPrompt: resolvedSystemPrompt,
|
|
212
|
-
tools,
|
|
213
|
-
stopWhen,
|
|
214
|
-
generation: config.generation,
|
|
215
|
-
compaction: compactionCfg,
|
|
216
|
-
})
|
|
217
|
-
innerIter = processor.runTurn(input)[Symbol.asyncIterator]()
|
|
218
|
-
}
|
|
219
|
-
return innerIter.next()
|
|
220
|
-
},
|
|
221
|
-
async return(value) {
|
|
222
|
-
return innerIter ? (innerIter.return ? innerIter.return(value) : { done: true, value }) : { done: true, value }
|
|
223
|
-
},
|
|
224
|
-
}
|
|
225
|
-
},
|
|
226
|
-
}
|
|
227
|
-
}
|
|
228
|
-
|
|
229
|
-
const runOnce = async (input: RunInput): Promise<RunOnceResult> => {
|
|
230
|
-
const tools = await getTools()
|
|
231
|
-
const budget = usable({
|
|
232
|
-
limits: config.model.limits,
|
|
233
|
-
reservedTokens: compactionCfg.reservedTokens,
|
|
234
|
-
})
|
|
235
|
-
const keepRecent = compactionCfg.preserveRecentTurns ?? 4
|
|
236
|
-
|
|
237
|
-
const result = await rt().runPromise(
|
|
238
|
-
Effect.gen(function* () {
|
|
239
|
-
const session = yield* store.upsertSession({ id: input.sessionId, agentName: config.name })
|
|
240
|
-
|
|
241
|
-
// Pre-flight: compact if estimate would overflow the usable budget.
|
|
242
|
-
if (compactionCfg.auto) {
|
|
243
|
-
const history = yield* store.getMessages(session.id)
|
|
244
|
-
const promptTokens = Math.ceil(input.prompt.length / 4)
|
|
245
|
-
const systemTokens = Math.ceil(resolvedSystemPrompt.length / 4)
|
|
246
|
-
if (estimateTokens(history) + promptTokens + systemTokens >= budget) {
|
|
247
|
-
yield* compact({
|
|
248
|
-
sessionId: session.id,
|
|
249
|
-
store,
|
|
250
|
-
model: config.model,
|
|
251
|
-
keepRecent,
|
|
252
|
-
overflow: false,
|
|
253
|
-
})
|
|
254
|
-
}
|
|
255
|
-
}
|
|
256
|
-
|
|
257
|
-
const attempt = () =>
|
|
258
|
-
Effect.gen(function* () {
|
|
259
|
-
const history = yield* store.getMessages(session.id)
|
|
260
|
-
const userContent: Array<{ type: "text"; text: string } | { type: "media"; mediaType: string; data: string; filename?: string }> = []
|
|
261
|
-
if (input.prompt.length > 0) userContent.push({ type: "text", text: input.prompt })
|
|
262
|
-
for (const a of input.attachments ?? [])
|
|
263
|
-
userContent.push({ type: "media", mediaType: a.mediaType, data: a.url ?? a.data ?? "", filename: a.filename })
|
|
264
|
-
const userMsg = userContent.length === 0 ? LLM.user(input.prompt) : LLM.user(userContent)
|
|
265
|
-
const request = LLM.request({
|
|
266
|
-
model: config.model,
|
|
267
|
-
system: resolvedSystemPrompt,
|
|
268
|
-
messages: [...historyToLLMMessages([...history]), userMsg],
|
|
269
|
-
generation: config.generation,
|
|
270
|
-
})
|
|
271
|
-
return yield* LLMClient.generate({ request, tools, stopWhen })
|
|
272
|
-
})
|
|
273
|
-
|
|
274
|
-
// Post-flight: catch ContextOverflow once, compact with overflow=true, retry once.
|
|
275
|
-
let didRetry = false
|
|
276
|
-
const response = yield* attempt().pipe(
|
|
277
|
-
Effect.catchTag("LLM.Error", (err) => {
|
|
278
|
-
if (err.reason._tag === "ContextOverflow" && compactionCfg.auto && !didRetry) {
|
|
279
|
-
didRetry = true
|
|
280
|
-
return Effect.gen(function* () {
|
|
281
|
-
yield* compact({
|
|
282
|
-
sessionId: session.id,
|
|
283
|
-
store,
|
|
284
|
-
model: config.model,
|
|
285
|
-
keepRecent,
|
|
286
|
-
overflow: true,
|
|
287
|
-
})
|
|
288
|
-
return yield* attempt()
|
|
289
|
-
})
|
|
290
|
-
}
|
|
291
|
-
return Effect.fail(err)
|
|
292
|
-
}),
|
|
293
|
-
)
|
|
294
|
-
return response
|
|
295
|
-
}),
|
|
296
|
-
)
|
|
297
|
-
return { text: result.text, usage: result.usage, events: result.events }
|
|
298
|
-
}
|
|
299
|
-
|
|
300
|
-
const toSSEHandler = (options?: SSEHandlerOptions) => makeSSEHandler(run, options)
|
|
301
|
-
|
|
302
|
-
const sessions = makeSessionAPI({
|
|
303
|
-
agentName: config.name,
|
|
304
|
-
store,
|
|
305
|
-
runtime: config.runtime,
|
|
306
|
-
})
|
|
307
|
-
|
|
308
|
-
const toHTTPHandlers = (options?: ToHTTPHandlersOptions): HTTPHandlers =>
|
|
309
|
-
makeHTTPHandlers({
|
|
310
|
-
api: sessions,
|
|
311
|
-
run: (input) => run({ prompt: input.prompt, sessionId: input.sessionId, attachments: input.attachments }),
|
|
312
|
-
authorize: options?.authorize,
|
|
313
|
-
defaultFormat: options?.defaultFormat,
|
|
314
|
-
})
|
|
315
|
-
|
|
316
|
-
return { name: config.name, run, runOnce, toSSEHandler, sessions, toHTTPHandlers }
|
|
317
|
-
}
|