@alexkroman1/aai 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.
Files changed (79) hide show
  1. package/LICENSE +21 -0
  2. package/dist/cli.js +3436 -0
  3. package/package.json +78 -0
  4. package/sdk/_internal_types.ts +89 -0
  5. package/sdk/_mock_ws.ts +172 -0
  6. package/sdk/_timeout.ts +24 -0
  7. package/sdk/builtin_tools.ts +309 -0
  8. package/sdk/capnweb.ts +341 -0
  9. package/sdk/define_agent.ts +70 -0
  10. package/sdk/direct_executor.ts +195 -0
  11. package/sdk/kv.ts +183 -0
  12. package/sdk/mod.ts +35 -0
  13. package/sdk/protocol.ts +313 -0
  14. package/sdk/runtime.ts +65 -0
  15. package/sdk/s2s.ts +271 -0
  16. package/sdk/server.ts +198 -0
  17. package/sdk/session.ts +438 -0
  18. package/sdk/system_prompt.ts +47 -0
  19. package/sdk/types.ts +406 -0
  20. package/sdk/vector.ts +133 -0
  21. package/sdk/winterc_server.ts +141 -0
  22. package/sdk/worker_entry.ts +99 -0
  23. package/sdk/worker_shim.ts +170 -0
  24. package/sdk/ws_handler.ts +190 -0
  25. package/templates/_shared/.env.example +5 -0
  26. package/templates/_shared/package.json +17 -0
  27. package/templates/code-interpreter/agent.ts +27 -0
  28. package/templates/code-interpreter/client.tsx +2 -0
  29. package/templates/dispatch-center/agent.ts +1536 -0
  30. package/templates/dispatch-center/client.tsx +504 -0
  31. package/templates/embedded-assets/agent.ts +49 -0
  32. package/templates/embedded-assets/client.tsx +2 -0
  33. package/templates/embedded-assets/knowledge.json +20 -0
  34. package/templates/health-assistant/agent.ts +160 -0
  35. package/templates/health-assistant/client.tsx +2 -0
  36. package/templates/infocom-adventure/agent.ts +164 -0
  37. package/templates/infocom-adventure/client.tsx +299 -0
  38. package/templates/math-buddy/agent.ts +21 -0
  39. package/templates/math-buddy/client.tsx +2 -0
  40. package/templates/memory-agent/agent.ts +74 -0
  41. package/templates/memory-agent/client.tsx +2 -0
  42. package/templates/night-owl/agent.ts +98 -0
  43. package/templates/night-owl/client.tsx +28 -0
  44. package/templates/personal-finance/agent.ts +26 -0
  45. package/templates/personal-finance/client.tsx +2 -0
  46. package/templates/simple/agent.ts +6 -0
  47. package/templates/simple/client.tsx +2 -0
  48. package/templates/smart-research/agent.ts +164 -0
  49. package/templates/smart-research/client.tsx +2 -0
  50. package/templates/support/README.md +62 -0
  51. package/templates/support/agent.ts +19 -0
  52. package/templates/support/client.tsx +2 -0
  53. package/templates/travel-concierge/agent.ts +29 -0
  54. package/templates/travel-concierge/client.tsx +2 -0
  55. package/templates/web-researcher/agent.ts +17 -0
  56. package/templates/web-researcher/client.tsx +2 -0
  57. package/ui/_components/app.tsx +37 -0
  58. package/ui/_components/chat_view.tsx +36 -0
  59. package/ui/_components/controls.tsx +32 -0
  60. package/ui/_components/error_banner.tsx +18 -0
  61. package/ui/_components/message_bubble.tsx +21 -0
  62. package/ui/_components/message_list.tsx +61 -0
  63. package/ui/_components/state_indicator.tsx +17 -0
  64. package/ui/_components/thinking_indicator.tsx +19 -0
  65. package/ui/_components/tool_call_block.tsx +110 -0
  66. package/ui/_components/tool_icons.tsx +101 -0
  67. package/ui/_components/transcript.tsx +20 -0
  68. package/ui/audio.ts +170 -0
  69. package/ui/components.ts +49 -0
  70. package/ui/components_mod.ts +37 -0
  71. package/ui/mod.ts +48 -0
  72. package/ui/mount.tsx +112 -0
  73. package/ui/mount_context.ts +19 -0
  74. package/ui/session.ts +456 -0
  75. package/ui/session_mod.ts +27 -0
  76. package/ui/signals.ts +111 -0
  77. package/ui/types.ts +50 -0
  78. package/ui/worklets/capture-processor.js +62 -0
  79. package/ui/worklets/playback-processor.js +110 -0
package/package.json ADDED
@@ -0,0 +1,78 @@
1
+ {
2
+ "name": "@alexkroman1/aai",
3
+ "version": "0.3.0",
4
+ "type": "module",
5
+ "bin": {
6
+ "aai": "dist/cli.js"
7
+ },
8
+ "exports": {
9
+ ".": "./sdk/mod.ts",
10
+ "./types": "./sdk/types.ts",
11
+ "./define-agent": "./sdk/define_agent.ts",
12
+ "./kv": "./sdk/kv.ts",
13
+ "./vector": "./sdk/vector.ts",
14
+ "./testing": "./sdk/_mock_ws.ts",
15
+ "./server": "./sdk/server.ts",
16
+ "./runtime": "./sdk/runtime.ts",
17
+ "./ui": "./ui/mod.ts",
18
+ "./ui/session": "./ui/session_mod.ts",
19
+ "./ui/components": "./ui/components_mod.ts",
20
+ "./internal-types": "./sdk/_internal_types.ts",
21
+ "./protocol": "./sdk/protocol.ts",
22
+ "./worker-entry": "./sdk/worker_entry.ts",
23
+ "./timeout": "./sdk/_timeout.ts",
24
+ "./builtin-tools": "./sdk/builtin_tools.ts",
25
+ "./s2s": "./sdk/s2s.ts",
26
+ "./session": "./sdk/session.ts",
27
+ "./system-prompt": "./sdk/system_prompt.ts",
28
+ "./ws-handler": "./sdk/ws_handler.ts",
29
+ "./direct-executor": "./sdk/direct_executor.ts",
30
+ "./capnweb": "./sdk/capnweb.ts",
31
+ "./winterc-server": "./sdk/winterc_server.ts",
32
+ "./worker-shim": "./sdk/worker_shim.ts"
33
+ },
34
+ "dependencies": {
35
+ "@chonkiejs/core": "^0",
36
+ "@inkjs/ui": "^2",
37
+ "@preact/preset-vite": "~2.9",
38
+ "@preact/signals": "^2.8.2",
39
+ "@tailwindcss/vite": "^4",
40
+ "@types/json-schema": "^7.0.15",
41
+ "chalk": "^5.4",
42
+ "fast-glob": "^3.3",
43
+ "fs-extra": "^11.3",
44
+ "human-id": "^4.1",
45
+ "ink": "^5",
46
+ "minimist": "^1.2",
47
+ "p-limit": "^7.3.0",
48
+ "p-timeout": "^7.0.1",
49
+ "preact": "^10.29.0",
50
+ "react": "^18",
51
+ "ts-morph": "^25",
52
+ "vite": "^6",
53
+ "vite-plugin-singlefile": "^2",
54
+ "zod": "^4.3.6"
55
+ },
56
+ "devDependencies": {
57
+ "@biomejs/biome": "^2.4.7",
58
+ "@types/fs-extra": "^11",
59
+ "@types/minimist": "^1.2",
60
+ "@types/node": "^22",
61
+ "@types/react": "^18",
62
+ "ink-testing-library": "^4",
63
+ "linkedom": "^0.18.10",
64
+ "typescript": "^5.7",
65
+ "vitest": "^3.1"
66
+ },
67
+ "engines": {
68
+ "node": ">=20"
69
+ },
70
+ "scripts": {
71
+ "setup": "git config core.hooksPath .githooks",
72
+ "build:cli": "node scripts/build-cli.mjs",
73
+ "test": "vitest run",
74
+ "lint": "biome check sdk/ ui/ cli/",
75
+ "lint:fix": "biome check --write sdk/ ui/ cli/",
76
+ "check": "biome check sdk/ ui/ cli/ && vitest run"
77
+ }
78
+ }
@@ -0,0 +1,89 @@
1
+ // Copyright 2025 the AAI authors. MIT license.
2
+ /**
3
+ * Internal type definitions shared by server and CLI.
4
+ *
5
+ * Note: this module is for internal use only and should not be used directly.
6
+ *
7
+ * @module
8
+ */
9
+
10
+ import type { JSONSchema7 } from "json-schema";
11
+ import { z } from "zod";
12
+ import type { BuiltinTool, ToolChoice, ToolDef, Transport } from "./types.ts";
13
+
14
+ /**
15
+ * Serializable agent configuration sent over the wire.
16
+ *
17
+ * This is the JSON-safe subset of the agent definition that can be
18
+ * transmitted between the worker and the host process via structured clone.
19
+ */
20
+ export type AgentConfig = {
21
+ name: string;
22
+ instructions: string;
23
+ greeting: string;
24
+ voice: string;
25
+ mode?: "s2s" | undefined;
26
+ sttPrompt?: string | undefined;
27
+ maxSteps?: number | undefined;
28
+ toolChoice?: ToolChoice | undefined;
29
+ transport?: readonly Transport[] | undefined;
30
+ builtinTools?: readonly BuiltinTool[] | undefined;
31
+ /** Default set of active tools. Can be overridden per-turn via `onBeforeStep`. */
32
+ activeTools?: readonly string[] | undefined;
33
+ };
34
+
35
+ /**
36
+ * Serialized tool schema sent over the wire.
37
+ * `parameters` must be a valid JSON Schema object (with `type`, `properties`,
38
+ * etc.) — the Vercel AI SDK wraps it via `jsonSchema()`.
39
+ */
40
+ export type ToolSchema = {
41
+ name: string;
42
+ description: string;
43
+ parameters: JSONSchema7;
44
+ };
45
+
46
+ /**
47
+ * Request body for the deploy endpoint.
48
+ *
49
+ * Sent by the CLI to the server when deploying a bundled agent.
50
+ */
51
+ export type DeployBody = {
52
+ /** Env vars are optional at deploy time — set separately via `aai env add`. */
53
+ env?: Readonly<Record<string, string>> | undefined;
54
+ worker: string;
55
+ html: string;
56
+ transport?: readonly Transport[] | undefined;
57
+ /** Agent configuration extracted at build time. */
58
+ config: AgentConfig;
59
+ /** Tool schemas extracted at build time. */
60
+ toolSchemas: ToolSchema[];
61
+ };
62
+
63
+ /** Environment variables required by the agent runtime. */
64
+ export type AgentEnv = {
65
+ ASSEMBLYAI_API_KEY: string;
66
+ [key: string]: string | undefined;
67
+ };
68
+
69
+ /** Configuration + tool schemas bundle returned by the worker's getConfig RPC. */
70
+ export type WorkerConfig = {
71
+ config: AgentConfig;
72
+ toolSchemas: ToolSchema[];
73
+ };
74
+
75
+ const EMPTY_PARAMS = z.object({});
76
+
77
+ /**
78
+ * Convert agent tool definitions to JSON Schema format for wire transport.
79
+ *
80
+ * Transforms the Zod-based `parameters` of each tool into a plain JSON Schema
81
+ * object suitable for structured clone / JSON serialization.
82
+ */
83
+ export function agentToolsToSchemas(tools: Readonly<Record<string, ToolDef>>): ToolSchema[] {
84
+ return Object.entries(tools).map(([name, def]) => ({
85
+ name,
86
+ description: def.description,
87
+ parameters: z.toJSONSchema(def.parameters ?? EMPTY_PARAMS) as JSONSchema7,
88
+ }));
89
+ }
@@ -0,0 +1,172 @@
1
+ // Copyright 2025 the AAI authors. MIT license.
2
+ /**
3
+ * A mock WebSocket implementation for testing.
4
+ *
5
+ * Extends `EventTarget` to simulate WebSocket behavior without a real
6
+ * network connection. Records all sent messages in the {@linkcode sent}
7
+ * array and provides helper methods to simulate incoming messages,
8
+ * connection events, and errors.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * const ws = new MockWebSocket("wss://example.com");
13
+ * ws.send(JSON.stringify({ type: "ping" }));
14
+ * ws.simulateMessage(JSON.stringify({ type: "pong" }));
15
+ * assertEquals(ws.sentJson(), [{ type: "ping" }]);
16
+ * ```
17
+ */
18
+ export class MockWebSocket extends EventTarget {
19
+ // mirrors the WebSocket API
20
+ static readonly CONNECTING = 0;
21
+ // mirrors the WebSocket API
22
+ static readonly OPEN = 1;
23
+ // mirrors the WebSocket API
24
+ static readonly CLOSING = 2;
25
+ // mirrors the WebSocket API
26
+ static readonly CLOSED = 3;
27
+
28
+ readyState = MockWebSocket.CONNECTING;
29
+ binaryType = "arraybuffer";
30
+ /** All messages passed to {@linkcode send}, in order. */
31
+ sent: (string | ArrayBuffer | Uint8Array)[] = [];
32
+ url: string;
33
+
34
+ /**
35
+ * Create a new MockWebSocket.
36
+ *
37
+ * Automatically transitions to `OPEN` state on the next microtask,
38
+ * dispatching an `"open"` event.
39
+ *
40
+ * @param url - The WebSocket URL.
41
+ * @param _protocols - Ignored; accepted for API compatibility.
42
+ */
43
+ constructor(url: string | URL, _protocols?: string | string[] | Record<string, unknown>) {
44
+ super();
45
+ this.url = typeof url === "string" ? url : url.toString();
46
+ queueMicrotask(() => {
47
+ if (this.readyState === MockWebSocket.CONNECTING) {
48
+ this.readyState = MockWebSocket.OPEN;
49
+ this.dispatchEvent(new Event("open"));
50
+ }
51
+ });
52
+ }
53
+
54
+ /**
55
+ * Record a sent message without transmitting it.
56
+ *
57
+ * @param data - The message data to record.
58
+ */
59
+ send(data: string | ArrayBuffer | Uint8Array) {
60
+ this.sent.push(data);
61
+ }
62
+
63
+ /**
64
+ * Transition to `CLOSED` state and dispatch a `"close"` event.
65
+ *
66
+ * @param code - The close code (defaults to 1000).
67
+ * @param _reason - Ignored; accepted for API compatibility.
68
+ */
69
+ close(code?: number, _reason?: string) {
70
+ this.readyState = MockWebSocket.CLOSED;
71
+ this.dispatchEvent(new CloseEvent("close", { code: code ?? 1000 }));
72
+ }
73
+
74
+ /**
75
+ * Simulate receiving a message from the server.
76
+ *
77
+ * @param data - The message data (string or binary).
78
+ */
79
+ simulateMessage(data: string | ArrayBuffer) {
80
+ this.dispatchEvent(new MessageEvent("message", { data }));
81
+ }
82
+
83
+ /** Transition to `OPEN` state and dispatch an `"open"` event. */
84
+ open() {
85
+ this.readyState = MockWebSocket.OPEN;
86
+ this.dispatchEvent(new Event("open"));
87
+ }
88
+
89
+ /**
90
+ * Shorthand for {@linkcode simulateMessage}.
91
+ *
92
+ * @param data - The message data to dispatch.
93
+ */
94
+ msg(data: string | ArrayBuffer) {
95
+ this.dispatchEvent(new MessageEvent("message", { data }));
96
+ }
97
+
98
+ /**
99
+ * Simulate a connection close from the server.
100
+ *
101
+ * @param code - The close code (defaults to 1000).
102
+ */
103
+ disconnect(code = 1000) {
104
+ this.dispatchEvent(new CloseEvent("close", { code }));
105
+ }
106
+
107
+ /** Dispatch an `"error"` event on this socket. */
108
+ error() {
109
+ this.dispatchEvent(new Event("error"));
110
+ }
111
+
112
+ /**
113
+ * Return all sent string messages parsed as JSON objects.
114
+ *
115
+ * Binary messages are filtered out.
116
+ *
117
+ * @returns An array of parsed JSON objects from sent string messages.
118
+ */
119
+ sentJson(): Record<string, unknown>[] {
120
+ return this.sent.filter((d): d is string => typeof d === "string").map((s) => JSON.parse(s));
121
+ }
122
+ }
123
+
124
+ const g: { WebSocket: unknown } = globalThis;
125
+
126
+ /**
127
+ * Replace `globalThis.WebSocket` with {@linkcode MockWebSocket} for testing.
128
+ *
129
+ * Returns a handle that tracks all created mock sockets and can restore the
130
+ * original `WebSocket` constructor. Supports the `using` declaration via
131
+ * `Symbol.dispose` for automatic cleanup.
132
+ *
133
+ * @returns An object with `created` array, `lastWs` getter, `restore()`, and `[Symbol.dispose]()`.
134
+ *
135
+ * @example
136
+ * ```ts
137
+ * using mock = installMockWebSocket();
138
+ * const session = new Session("wss://example.com");
139
+ * const ws = mock.lastWs!;
140
+ * ws.simulateMessage(JSON.stringify({ type: "ready" }));
141
+ * // mock automatically restores WebSocket when disposed
142
+ * ```
143
+ */
144
+ export function installMockWebSocket(): {
145
+ restore: () => void;
146
+ created: MockWebSocket[];
147
+ get lastWs(): MockWebSocket | null;
148
+ [Symbol.dispose]: () => void;
149
+ } {
150
+ const saved = globalThis.WebSocket;
151
+ const created: MockWebSocket[] = [];
152
+
153
+ g.WebSocket = class extends MockWebSocket {
154
+ constructor(url: string | URL, protocols?: string | string[] | Record<string, unknown>) {
155
+ super(url, protocols);
156
+ created.push(this);
157
+ }
158
+ };
159
+
160
+ return {
161
+ created,
162
+ get lastWs() {
163
+ return created.length > 0 ? created[created.length - 1]! : null;
164
+ },
165
+ restore() {
166
+ globalThis.WebSocket = saved;
167
+ },
168
+ [Symbol.dispose]() {
169
+ globalThis.WebSocket = saved;
170
+ },
171
+ };
172
+ }
@@ -0,0 +1,24 @@
1
+ // Copyright 2025 the AAI authors. MIT license.
2
+ /**
3
+ * Timeout wrapper for promises, used by both worker-side and host-side RPC.
4
+ *
5
+ * @module
6
+ */
7
+
8
+ import pTimeout from "p-timeout";
9
+
10
+ /**
11
+ * Wrap a promise with a timeout. Rejects with `Error` if the promise
12
+ * does not settle within `timeoutMs` milliseconds.
13
+ *
14
+ * If `timeoutMs` is `undefined` or `0`, the original promise is returned
15
+ * unchanged.
16
+ */
17
+ export function withTimeout<T>(promise: Promise<T>, timeoutMs?: number): Promise<T> {
18
+ const normalized = Promise.resolve(promise);
19
+ if (!timeoutMs) return normalized;
20
+ return pTimeout(normalized, {
21
+ milliseconds: timeoutMs,
22
+ message: `RPC timed out after ${timeoutMs}ms`,
23
+ });
24
+ }
@@ -0,0 +1,309 @@
1
+ // Copyright 2025 the AAI authors. MIT license.
2
+ /**
3
+ * Built-in tool definitions for the AAI agent SDK.
4
+ *
5
+ * These tools run inside the sandboxed worker alongside custom tools.
6
+ * Network requests go through the host's fetch proxy (with SSRF protection).
7
+ *
8
+ * @module
9
+ */
10
+
11
+ import { z } from "zod";
12
+ import type { ToolSchema } from "./_internal_types.ts";
13
+ import type { ToolDef } from "./types.ts";
14
+
15
+ const EMPTY_PARAMS = z.object({});
16
+
17
+ // ─── HTML to text ──────────────────────────────────────────────────────────
18
+
19
+ function htmlToText(html: string): string {
20
+ return html
21
+ .replace(/<script[^>]*>[\s\S]*?<\/script>/gi, "")
22
+ .replace(/<style[^>]*>[\s\S]*?<\/style>/gi, "")
23
+ .replace(/<(br|hr)\s*\/?>/gi, "\n")
24
+ .replace(/<\/(p|div|li|h[1-6]|tr|blockquote)>/gi, "\n")
25
+ .replace(/<[^>]+>/g, " ")
26
+ .replace(/&nbsp;/g, " ")
27
+ .replace(/&amp;/g, "&")
28
+ .replace(/&lt;/g, "<")
29
+ .replace(/&gt;/g, ">")
30
+ .replace(/&quot;/g, '"')
31
+ .replace(/&#0?39;/g, "'")
32
+ .replace(/[ \t]+/g, " ")
33
+ .replace(/\n /g, "\n")
34
+ .replace(/\n{3,}/g, "\n\n")
35
+ .trim();
36
+ }
37
+
38
+ // ─── web_search ────────────────────────────────────────────────────────────
39
+
40
+ const webSearchParams = z.object({
41
+ query: z.string().describe("The search query"),
42
+ max_results: z.number().describe("Maximum number of results to return (default 5)").optional(),
43
+ });
44
+
45
+ const BRAVE_SEARCH_URL = "https://api.search.brave.com/res/v1/web/search";
46
+
47
+ const BraveSearchResponseSchema = z.object({
48
+ web: z
49
+ .object({
50
+ results: z.array(
51
+ z.object({
52
+ title: z.string(),
53
+ url: z.string(),
54
+ description: z.string(),
55
+ }),
56
+ ),
57
+ })
58
+ .optional(),
59
+ });
60
+
61
+ function createWebSearch(): ToolDef {
62
+ return {
63
+ description:
64
+ "Search the web for current information, facts, news, or answers to questions. Returns a list of results with title, URL, and description. Use this when the user asks about something you don't know, need up-to-date information, or want to verify facts.",
65
+ parameters: webSearchParams,
66
+ async execute(args, ctx) {
67
+ const { query, max_results: maxResults = 5 } = args;
68
+ const apiKey = ctx.env.BRAVE_API_KEY ?? "";
69
+ if (!apiKey) {
70
+ return { error: "BRAVE_API_KEY is not set — web search unavailable" };
71
+ }
72
+ const url = `${BRAVE_SEARCH_URL}?${new URLSearchParams({
73
+ q: query,
74
+ count: String(maxResults),
75
+ text_decorations: "false",
76
+ })}`;
77
+ const resp = await fetch(url, {
78
+ headers: { "X-Subscription-Token": apiKey },
79
+ signal: ctx.abortSignal ?? AbortSignal.timeout(15_000),
80
+ });
81
+ if (!resp.ok) return [];
82
+ const raw = await resp.json();
83
+ const data = BraveSearchResponseSchema.safeParse(raw);
84
+ if (!data.success) return [];
85
+ return (data.data.web?.results ?? []).slice(0, maxResults).map((r) => ({
86
+ title: r.title,
87
+ url: r.url,
88
+ description: r.description,
89
+ }));
90
+ },
91
+ };
92
+ }
93
+
94
+ // ─── visit_webpage ─────────────────────────────────────────────────────────
95
+
96
+ const MAX_PAGE_CHARS = 10_000;
97
+ const MAX_HTML_BYTES = 200_000;
98
+
99
+ const visitWebpageParams = z.object({
100
+ url: z.string().describe("The full URL to fetch (e.g., 'https://example.com/page')"),
101
+ });
102
+
103
+ function createVisitWebpage(): ToolDef {
104
+ return {
105
+ description:
106
+ "Fetch a webpage and return its content as clean text. Use this to read the full content of a URL found via web_search, or any link the user shares. Good for reading articles, documentation, blog posts, or product pages.",
107
+ parameters: visitWebpageParams,
108
+ async execute(args, ctx) {
109
+ const { url } = args;
110
+ const resp = await fetch(url, {
111
+ headers: {
112
+ "User-Agent":
113
+ "Mozilla/5.0 (compatible; VoiceAgent/1.0; +https://github.com/AssemblyAI/aai)",
114
+ Accept: "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8",
115
+ },
116
+ redirect: "follow",
117
+ signal: ctx.abortSignal ?? AbortSignal.timeout(15_000),
118
+ });
119
+ if (!resp.ok) {
120
+ return { error: `Failed to fetch: ${resp.status} ${resp.statusText}`, url };
121
+ }
122
+ const htmlContent = await resp.text();
123
+ const trimmedHtml =
124
+ htmlContent.length > MAX_HTML_BYTES ? htmlContent.slice(0, MAX_HTML_BYTES) : htmlContent;
125
+ const text = htmlToText(trimmedHtml);
126
+ const truncated = text.length > MAX_PAGE_CHARS;
127
+ const content = truncated ? text.slice(0, MAX_PAGE_CHARS) : text;
128
+ return {
129
+ url,
130
+ content,
131
+ ...(truncated ? { truncated: true, totalChars: text.length } : {}),
132
+ };
133
+ },
134
+ };
135
+ }
136
+
137
+ // ─── fetch_json ────────────────────────────────────────────────────────────
138
+
139
+ const fetchJsonParams = z.object({
140
+ url: z.string().describe("The URL to fetch JSON from"),
141
+ headers: z
142
+ .record(z.string(), z.string())
143
+ .describe("Optional HTTP headers to include in the request")
144
+ .optional(),
145
+ });
146
+
147
+ function createFetchJson(): ToolDef {
148
+ return {
149
+ description:
150
+ "Call a REST API endpoint via HTTP GET and return the JSON response. Use this to fetch structured data from APIs — for example, weather data, stock prices, exchange rates, or any public JSON API. Supports custom headers for authenticated APIs.",
151
+ parameters: fetchJsonParams,
152
+ async execute(args, ctx) {
153
+ const { url, headers } = args;
154
+ const resp = await fetch(url, {
155
+ ...(headers && { headers }),
156
+ signal: ctx.abortSignal ?? AbortSignal.timeout(15_000),
157
+ });
158
+ if (!resp.ok) {
159
+ return { error: `HTTP ${resp.status} ${resp.statusText}`, url };
160
+ }
161
+ try {
162
+ return await resp.json();
163
+ } catch {
164
+ return { error: "Response was not valid JSON", url };
165
+ }
166
+ },
167
+ };
168
+ }
169
+
170
+ // ─── run_code ──────────────────────────────────────────────────────────────
171
+
172
+ const runCodeParams = z.object({
173
+ code: z.string().describe("JavaScript code to execute. Use console.log() for output."),
174
+ });
175
+
176
+ function createRunCode(): ToolDef {
177
+ return {
178
+ description:
179
+ "Execute JavaScript code in a secure sandbox and return the output. Use this for calculations, data transformations, string manipulation, or any task that benefits from running code. Output is captured from console.log(). No network or filesystem access.",
180
+ parameters: runCodeParams,
181
+ async execute(args) {
182
+ const { code } = args;
183
+ const output: string[] = [];
184
+ function capture(...captureArgs: unknown[]) {
185
+ output.push(captureArgs.map(String).join(" "));
186
+ }
187
+ const fakeConsole = {
188
+ log: capture,
189
+ info: capture,
190
+ warn: capture,
191
+ error: capture,
192
+ debug: capture,
193
+ };
194
+ const AsyncFunction = Object.getPrototypeOf(async () => {}).constructor;
195
+ try {
196
+ const fn = new AsyncFunction("console", code);
197
+ await fn(fakeConsole);
198
+ const result = output.join("\n").trim();
199
+ return result || "Code ran successfully (no output)";
200
+ } catch (err: unknown) {
201
+ return { error: err instanceof Error ? err.message : String(err) };
202
+ }
203
+ },
204
+ };
205
+ }
206
+
207
+ // ─── vector_search ─────────────────────────────────────────────────────────
208
+
209
+ const vectorSearchParams = z.object({
210
+ query: z
211
+ .string()
212
+ .describe(
213
+ "Short keyword query to search the knowledge base. Use specific topic " +
214
+ "terms, not full sentences. Do NOT include the company or product name " +
215
+ "since all documents are from the same source. For example, if the user " +
216
+ 'asks "how much does Acme cost", search for "pricing plans rates".',
217
+ ),
218
+ topK: z.number().describe("Maximum results to return (default: 5)").optional(),
219
+ });
220
+
221
+ /** Callback for proxying vector search through the host RPC. */
222
+ export type VectorSearchFn = (query: string, topK: number) => Promise<string>;
223
+
224
+ function createVectorSearch(vectorSearchFn: VectorSearchFn): ToolDef {
225
+ return {
226
+ description:
227
+ "Search the agent's knowledge base for relevant information. Use this when the user asks a question that might be answered by previously ingested documents or data. Returns the most relevant matches ranked by similarity.",
228
+ parameters: vectorSearchParams,
229
+ async execute(args) {
230
+ const { query, topK = 5 } = args;
231
+ return vectorSearchFn(query, topK);
232
+ },
233
+ };
234
+ }
235
+
236
+ // ─── Public API ────────────────────────────────────────────────────────────
237
+
238
+ /** Options for creating built-in tool definitions. */
239
+ export type BuiltinToolOptions = {
240
+ /** RPC callback for vector_search (proxied through host). */
241
+ vectorSearch?: VectorSearchFn;
242
+ };
243
+
244
+ /**
245
+ * Create built-in tool definitions for the given tool names.
246
+ *
247
+ * @param names - Built-in tool names from the agent config.
248
+ * @param opts - Options including RPC callbacks for host-proxied tools.
249
+ * @returns A record of tool name → ToolDef.
250
+ */
251
+ export function getBuiltinToolDefs(
252
+ names: readonly string[],
253
+ opts?: BuiltinToolOptions,
254
+ ): Record<string, ToolDef> {
255
+ const defs: Record<string, ToolDef> = {};
256
+ for (const name of names) {
257
+ switch (name) {
258
+ case "web_search":
259
+ defs[name] = createWebSearch();
260
+ break;
261
+ case "visit_webpage":
262
+ defs[name] = createVisitWebpage();
263
+ break;
264
+ case "fetch_json":
265
+ defs[name] = createFetchJson();
266
+ break;
267
+ case "run_code":
268
+ defs[name] = createRunCode();
269
+ break;
270
+ case "vector_search":
271
+ if (opts?.vectorSearch) {
272
+ defs[name] = createVectorSearch(opts.vectorSearch);
273
+ }
274
+ break;
275
+ }
276
+ }
277
+ return defs;
278
+ }
279
+
280
+ /** All available tool creators, keyed by builtin tool name. */
281
+ const TOOL_CREATORS: Record<string, () => ToolDef> = {
282
+ web_search: createWebSearch,
283
+ visit_webpage: createVisitWebpage,
284
+ fetch_json: createFetchJson,
285
+ run_code: createRunCode,
286
+ // vector_search uses a stub for schema generation
287
+ vector_search: () => createVectorSearch(async () => ""),
288
+ };
289
+
290
+ /**
291
+ * Returns JSON tool schemas for the specified builtin tools.
292
+ *
293
+ * Used by both the worker (to report schemas) and the server (to
294
+ * assemble tool lists for the LLM).
295
+ */
296
+ export function getBuiltinToolSchemas(names: readonly string[]): ToolSchema[] {
297
+ return names.flatMap((name) => {
298
+ const creator = TOOL_CREATORS[name];
299
+ if (!creator) return [];
300
+ const def = creator();
301
+ return [
302
+ {
303
+ name,
304
+ description: def.description,
305
+ parameters: z.toJSONSchema(def.parameters ?? EMPTY_PARAMS) as ToolSchema["parameters"],
306
+ },
307
+ ];
308
+ });
309
+ }