@alexkroman1/aai 0.10.3 → 0.10.4

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 (73) hide show
  1. package/dist/_internal-types.d.ts +8 -1
  2. package/dist/_runtime-conformance.d.ts +64 -0
  3. package/dist/_test-utils.d.ts +70 -0
  4. package/dist/_utils.d.ts +1 -8
  5. package/dist/_utils.js +49 -2
  6. package/dist/builtin-tools.d.ts +1 -5
  7. package/dist/constants-BbAOvKl_.js +47 -0
  8. package/dist/constants.d.ts +44 -0
  9. package/dist/direct-executor-BfHrDdPL.js +1589 -0
  10. package/dist/direct-executor.d.ts +90 -31
  11. package/dist/hooks.d.ts +44 -0
  12. package/dist/hooks.js +58 -0
  13. package/dist/index.d.ts +1 -2
  14. package/dist/index.js +2 -2
  15. package/dist/internal.d.ts +19 -0
  16. package/dist/internal.js +209 -0
  17. package/dist/kv.d.ts +1 -1
  18. package/dist/kv.js +32 -1
  19. package/dist/matchers.js +1 -1
  20. package/dist/protocol.d.ts +3 -29
  21. package/dist/protocol.js +140 -2
  22. package/dist/server.d.ts +27 -40
  23. package/dist/server.js +117 -145
  24. package/dist/session.d.ts +65 -44
  25. package/dist/{testing-BbitshLb.js → testing-BonJtfHJ.js} +25 -43
  26. package/dist/testing.d.ts +9 -14
  27. package/dist/testing.js +2 -2
  28. package/dist/types.d.ts +24 -226
  29. package/dist/types.js +176 -2
  30. package/dist/types.test-d.d.ts +7 -0
  31. package/dist/vite-plugin.d.ts +15 -0
  32. package/dist/vite-plugin.js +82 -0
  33. package/dist/ws-handler.d.ts +1 -2
  34. package/package.json +28 -88
  35. package/dist/_embeddings.d.ts +0 -31
  36. package/dist/_internal-types-IfPcaJd5.js +0 -61
  37. package/dist/_internal-types.js +0 -2
  38. package/dist/_session-ctx.d.ts +0 -73
  39. package/dist/_session-otel.d.ts +0 -43
  40. package/dist/_session-persist.d.ts +0 -30
  41. package/dist/_ssrf-DCp_27V4.js +0 -123
  42. package/dist/_ssrf.d.ts +0 -30
  43. package/dist/_ssrf.js +0 -2
  44. package/dist/_utils-DgzpOMSV.js +0 -61
  45. package/dist/direct-executor-B-5mq3cu.js +0 -570
  46. package/dist/kv-iXtikQmR.js +0 -32
  47. package/dist/middleware-core-BwyBIPed.js +0 -107
  48. package/dist/middleware-core.d.ts +0 -47
  49. package/dist/middleware-core.js +0 -2
  50. package/dist/middleware.d.ts +0 -37
  51. package/dist/protocol-B-H2Q4ox.js +0 -162
  52. package/dist/runtime-CxcwaK68.js +0 -58
  53. package/dist/runtime.js +0 -2
  54. package/dist/s2s-M7JqtgFw.js +0 -272
  55. package/dist/s2s.js +0 -2
  56. package/dist/session-BYlwcrya.js +0 -683
  57. package/dist/session.js +0 -2
  58. package/dist/telemetry-CJlaDFNc.js +0 -95
  59. package/dist/telemetry.d.ts +0 -49
  60. package/dist/telemetry.js +0 -2
  61. package/dist/types-D8ZBxTL_.js +0 -192
  62. package/dist/unstorage-kv-CDgP-frt.js +0 -64
  63. package/dist/unstorage-kv.js +0 -2
  64. package/dist/unstorage-vector-Cj5llNhg.js +0 -172
  65. package/dist/unstorage-vector.d.ts +0 -47
  66. package/dist/unstorage-vector.js +0 -2
  67. package/dist/vector.d.ts +0 -86
  68. package/dist/vector.js +0 -49
  69. package/dist/worker-entry-2jaiqIj0.js +0 -70
  70. package/dist/worker-entry.d.ts +0 -47
  71. package/dist/worker-entry.js +0 -2
  72. package/dist/ws-handler-C0Q6eSay.js +0 -207
  73. package/dist/ws-handler.js +0 -2
package/dist/types.js CHANGED
@@ -1,2 +1,176 @@
1
- import { a as createToolFactory, i as ToolChoiceSchema, n as DEFAULT_GREETING, o as defineAgent, r as DEFAULT_INSTRUCTIONS, s as defineTool, t as BuiltinToolSchema } from "./types-D8ZBxTL_.js";
2
- export { BuiltinToolSchema, DEFAULT_GREETING, DEFAULT_INSTRUCTIONS, ToolChoiceSchema, createToolFactory, defineAgent, defineTool, defineTool as tool };
1
+ import { z } from "zod";
2
+ //#region types.ts
3
+ /**
4
+ * Core type definitions for the AAI agent SDK.
5
+ */
6
+ /**
7
+ * Identity helper that preserves the Zod schema generic for type inference.
8
+ *
9
+ * When tools are defined inline in `defineAgent({ tools: { ... } })`, the
10
+ * generic `P` gets widened to the base `ZodObject` type, so `args` in
11
+ * `execute` loses its specific shape. Wrapping a tool definition in
12
+ * `defineTool()` lets TypeScript infer `P` from `parameters` and type
13
+ * `args` correctly.
14
+ *
15
+ * @example
16
+ * ```ts
17
+ * import { defineAgent, defineTool } from "aai";
18
+ * import { z } from "zod";
19
+ *
20
+ * export default defineAgent({
21
+ * name: "my-agent",
22
+ * tools: {
23
+ * greet: defineTool({
24
+ * description: "Greet the user",
25
+ * parameters: z.object({ name: z.string() }),
26
+ * execute: ({ name }) => `Hello, ${name}!`, // name is string
27
+ * }),
28
+ * },
29
+ * });
30
+ * ```
31
+ *
32
+ * @public
33
+ */
34
+ function defineTool(def) {
35
+ return def;
36
+ }
37
+ /**
38
+ * Create a typed `defineTool` helper with the session state type baked in.
39
+ *
40
+ * When tools need access to typed session state, you'd normally have to write
41
+ * verbose generics on every `defineTool` call. `defineToolFactory` eliminates
42
+ * that boilerplate by returning a `defineTool` variant that already knows `S`.
43
+ *
44
+ * @example
45
+ * ```ts
46
+ * import { defineToolFactory, defineAgent } from "aai";
47
+ * import { z } from "zod";
48
+ *
49
+ * interface PortfolioState { holdings: Map<string, number> }
50
+ *
51
+ * const tool = defineToolFactory<PortfolioState>();
52
+ *
53
+ * export default defineAgent<PortfolioState>({
54
+ * name: "portfolio",
55
+ * state: () => ({ holdings: new Map() }),
56
+ * tools: {
57
+ * buy: tool({
58
+ * description: "Buy shares",
59
+ * parameters: z.object({ symbol: z.string(), qty: z.number() }),
60
+ * execute: (args, ctx) => {
61
+ * // args.symbol is string, ctx.state is PortfolioState
62
+ * ctx.state.holdings.set(args.symbol, args.qty);
63
+ * },
64
+ * }),
65
+ * },
66
+ * });
67
+ * ```
68
+ *
69
+ * @public
70
+ */
71
+ function defineToolFactory() {
72
+ return (def) => def;
73
+ }
74
+ /**
75
+ * Default system prompt used when `instructions` is not provided.
76
+ *
77
+ * Optimized for voice-first interactions: short sentences, no visual
78
+ * formatting, confident tone, and concise answers.
79
+ */
80
+ const DEFAULT_INSTRUCTIONS = `\
81
+ You are AAI, a helpful AI assistant.
82
+
83
+ Voice-First Rules:
84
+ - Optimize for natural speech. Avoid jargon unless central to the answer. \
85
+ Use short, punchy sentences.
86
+ - Never mention "search results," "sources," or "the provided text." \
87
+ Speak as if the knowledge is your own.
88
+ - No visual formatting. Do not say "bullet point," "bold," or "bracketed one." \
89
+ If you need to list items, say "First," "Next," and "Finally."
90
+ - Start with the most important information. No introductory filler.
91
+ - Be concise. Keep answers to 1-3 sentences. For complex topics, provide a high-level summary.
92
+ - Be confident. Avoid hedging phrases like "It seems that" or "I believe."
93
+ - If you don't have enough information, say so directly rather than guessing.
94
+ - Never use exclamation points. Keep your tone calm and conversational.`;
95
+ /** Default greeting spoken when a session starts. */
96
+ const DEFAULT_GREETING = "Hey there. I'm a voice assistant. What can I help you with?";
97
+ /** @internal Zod schema for {@link BuiltinTool}. Exported for reuse in internal schemas. */
98
+ const BuiltinToolSchema = z.enum([
99
+ "web_search",
100
+ "visit_webpage",
101
+ "fetch_json",
102
+ "run_code",
103
+ "memory"
104
+ ]);
105
+ /** @internal Zod schema for {@link ToolChoice}. Exported for reuse in internal schemas. */
106
+ const ToolChoiceSchema = z.union([z.enum([
107
+ "auto",
108
+ "required",
109
+ "none"
110
+ ]), z.object({
111
+ type: z.literal("tool"),
112
+ toolName: z.string().min(1)
113
+ })]);
114
+ const ToolDefSchema = z.object({
115
+ description: z.string().min(1, "Tool description must be non-empty"),
116
+ parameters: z.custom((val) => val === void 0 || val instanceof z.ZodType, "Expected a Zod schema").optional(),
117
+ execute: z.function()
118
+ });
119
+ const AgentOptionsSchema = z.object({
120
+ name: z.string().min(1, "Agent name must be non-empty"),
121
+ instructions: z.string().optional(),
122
+ greeting: z.string().optional(),
123
+ sttPrompt: z.string().optional(),
124
+ maxSteps: z.union([z.number().int().positive(), z.function()]).optional(),
125
+ toolChoice: ToolChoiceSchema.optional(),
126
+ builtinTools: z.array(BuiltinToolSchema).optional(),
127
+ tools: z.record(z.string(), ToolDefSchema).optional(),
128
+ state: z.function().optional(),
129
+ onConnect: z.function().optional(),
130
+ onDisconnect: z.function().optional(),
131
+ onError: z.function().optional(),
132
+ onTurn: z.function().optional(),
133
+ idleTimeoutMs: z.number().nonnegative().optional()
134
+ });
135
+ /**
136
+ * Create an agent definition from the given options, applying sensible defaults.
137
+ *
138
+ * This is the main entry point for defining a voice agent. The returned
139
+ * `AgentDef` is consumed by the AAI server at deploy time.
140
+ *
141
+ * @param options - Configuration for the agent including name, instructions,
142
+ * tools, hooks, and other settings.
143
+ * @returns A fully resolved agent definition with all defaults applied.
144
+ *
145
+ * @public
146
+ *
147
+ * @example Basic agent with a custom tool
148
+ * ```ts
149
+ * import { defineAgent } from "aai";
150
+ * import { z } from "zod";
151
+ *
152
+ * export default defineAgent({
153
+ * name: "greeter",
154
+ * instructions: "You greet people warmly.",
155
+ * tools: {
156
+ * greet: {
157
+ * description: "Greet a user by name",
158
+ * parameters: z.object({ name: z.string() }),
159
+ * execute: ({ name }) => `Hello, ${name}!`,
160
+ * },
161
+ * },
162
+ * });
163
+ * ```
164
+ */
165
+ function defineAgent(options) {
166
+ AgentOptionsSchema.parse(options);
167
+ return {
168
+ ...options,
169
+ instructions: options.instructions ?? DEFAULT_INSTRUCTIONS,
170
+ greeting: options.greeting ?? "Hey there. I'm a voice assistant. What can I help you with?",
171
+ maxSteps: options.maxSteps ?? 5,
172
+ tools: options.tools ?? {}
173
+ };
174
+ }
175
+ //#endregion
176
+ export { BuiltinToolSchema, DEFAULT_GREETING, DEFAULT_INSTRUCTIONS, ToolChoiceSchema, defineAgent, defineTool, defineTool as tool, defineToolFactory };
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Type-level tests for the public API surface of @alexkroman1/aai.
3
+ *
4
+ * These are checked by tsc (via vitest typecheck) but never executed.
5
+ * A failure here means a public type contract has regressed.
6
+ */
7
+ export {};
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Vite plugin for AAI agent development.
3
+ *
4
+ * In dev mode: boots the agent backend server and configures proxy.
5
+ * Handles .env loading, runtime creation, and WebSocket proxying
6
+ * so `vite` alone gives you a working dev server.
7
+ */
8
+ import type { Plugin } from "vite";
9
+ export type AaiPluginOptions = {
10
+ /** Path to agent entry (default: "agent.ts") */
11
+ agent?: string;
12
+ /** Backend port (default: Vite port + 1) */
13
+ backendPort?: number;
14
+ };
15
+ export declare function aai(options?: AaiPluginOptions): Plugin;
@@ -0,0 +1,82 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+ //#region vite-plugin.ts
4
+ /**
5
+ * Vite plugin for AAI agent development.
6
+ *
7
+ * In dev mode: boots the agent backend server and configures proxy.
8
+ * Handles .env loading, runtime creation, and WebSocket proxying
9
+ * so `vite` alone gives you a working dev server.
10
+ */
11
+ function parseEnvFile(content) {
12
+ const entries = {};
13
+ for (const raw of content.split("\n")) {
14
+ const line = raw.trim();
15
+ if (!line || line.startsWith("#")) continue;
16
+ const eq = line.indexOf("=");
17
+ if (eq === -1) continue;
18
+ const key = line.slice(0, eq).trim();
19
+ if (key) entries[key] = line.slice(eq + 1);
20
+ }
21
+ return entries;
22
+ }
23
+ async function resolveAgentEnv(root) {
24
+ let fileEntries = {};
25
+ try {
26
+ fileEntries = parseEnvFile(await fs.readFile(path.join(root, ".env"), "utf-8"));
27
+ } catch {}
28
+ const env = {};
29
+ for (const [key, fileVal] of Object.entries(fileEntries)) env[key] = process.env[key] ?? fileVal;
30
+ if (!env.ASSEMBLYAI_API_KEY && process.env.ASSEMBLYAI_API_KEY) env.ASSEMBLYAI_API_KEY = process.env.ASSEMBLYAI_API_KEY;
31
+ return env;
32
+ }
33
+ function aai(options) {
34
+ const agentEntry = options?.agent ?? "agent.ts";
35
+ let backendPort = options?.backendPort;
36
+ let server = null;
37
+ return {
38
+ name: "aai",
39
+ apply: "serve",
40
+ config(config) {
41
+ const vitePort = config.server?.port ?? 3e3;
42
+ const envPort = Number(process.env.AAI_BACKEND_PORT);
43
+ backendPort = backendPort ?? (envPort > 0 ? envPort : vitePort + 1);
44
+ const target = `http://localhost:${backendPort}`;
45
+ return { server: { proxy: {
46
+ "/health": target,
47
+ "/websocket": {
48
+ target,
49
+ ws: true
50
+ }
51
+ } } };
52
+ },
53
+ async configureServer(viteServer) {
54
+ const root = viteServer.config.root;
55
+ const agentPath = path.resolve(root, agentEntry);
56
+ const { createRuntime, createServer } = await import("./server.js");
57
+ const agentDef = (await viteServer.ssrLoadModule(agentPath)).default;
58
+ if (!agentDef?.name) {
59
+ viteServer.config.logger.error("agent.ts must export a default defineAgent() call");
60
+ return;
61
+ }
62
+ const agentServer = createServer({
63
+ runtime: createRuntime({
64
+ agent: agentDef,
65
+ env: await resolveAgentEnv(root)
66
+ }),
67
+ name: agentDef.name
68
+ });
69
+ await agentServer.listen(backendPort);
70
+ server = agentServer;
71
+ viteServer.config.logger.info(`Agent backend on port ${backendPort}`);
72
+ },
73
+ async buildEnd() {
74
+ if (server) {
75
+ await server.close();
76
+ server = null;
77
+ }
78
+ }
79
+ };
80
+ }
81
+ //#endregion
82
+ export { aai };
@@ -40,8 +40,7 @@ export type WsSessionOptions = {
40
40
  logger?: Logger;
41
41
  /** Timeout in ms for session.start(). Defaults to 10 000 (10s). */
42
42
  sessionStartTimeoutMs?: number;
43
- /** Old session ID to resume from. When set, the persisted session data
44
- * (state, messages, S2S session ID) is restored from KV. */
43
+ /** Old session ID to resume. When set, reuses this ID instead of generating a new UUID. */
45
44
  resumeFrom?: string;
46
45
  };
47
46
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexkroman1/aai",
3
- "version": "0.10.3",
3
+ "version": "0.10.4",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"
@@ -11,6 +11,11 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js"
13
13
  },
14
+ "./server": {
15
+ "source": "./server.ts",
16
+ "types": "./dist/server.d.ts",
17
+ "import": "./dist/server.js"
18
+ },
14
19
  "./types": {
15
20
  "source": "./types.ts",
16
21
  "types": "./dist/types.d.ts",
@@ -21,10 +26,10 @@
21
26
  "types": "./dist/kv.d.ts",
22
27
  "import": "./dist/kv.js"
23
28
  },
24
- "./vector": {
25
- "source": "./vector.ts",
26
- "types": "./dist/vector.d.ts",
27
- "import": "./dist/vector.js"
29
+ "./protocol": {
30
+ "source": "./protocol.ts",
31
+ "types": "./dist/protocol.d.ts",
32
+ "import": "./dist/protocol.js"
28
33
  },
29
34
  "./testing": {
30
35
  "source": "./testing.ts",
@@ -36,115 +41,50 @@
36
41
  "types": "./dist/matchers.d.ts",
37
42
  "import": "./dist/matchers.js"
38
43
  },
39
- "./server": {
40
- "source": "./server.ts",
41
- "types": "./dist/server.d.ts",
42
- "import": "./dist/server.js"
43
- },
44
- "./protocol": {
45
- "source": "./protocol.ts",
46
- "types": "./dist/protocol.d.ts",
47
- "import": "./dist/protocol.js"
44
+ "./internal": {
45
+ "source": "./internal.ts",
46
+ "types": "./dist/internal.d.ts",
47
+ "import": "./dist/internal.js"
48
48
  },
49
- "./s2s": {
50
- "source": "./s2s.ts",
51
- "types": "./dist/s2s.d.ts",
52
- "import": "./dist/s2s.js"
53
- },
54
- "./session": {
55
- "source": "./session.ts",
56
- "types": "./dist/session.d.ts",
57
- "import": "./dist/session.js"
58
- },
59
- "./internal-types": {
60
- "source": "./_internal-types.ts",
61
- "types": "./dist/_internal-types.d.ts",
62
- "import": "./dist/_internal-types.js"
63
- },
64
- "./runtime": {
65
- "source": "./runtime.ts",
66
- "types": "./dist/runtime.d.ts",
67
- "import": "./dist/runtime.js"
68
- },
69
- "./worker-entry": {
70
- "source": "./worker-entry.ts",
71
- "types": "./dist/worker-entry.d.ts",
72
- "import": "./dist/worker-entry.js"
73
- },
74
- "./ws-handler": {
75
- "source": "./ws-handler.ts",
76
- "types": "./dist/ws-handler.d.ts",
77
- "import": "./dist/ws-handler.js"
78
- },
79
- "./telemetry": {
80
- "source": "./telemetry.ts",
81
- "types": "./dist/telemetry.d.ts",
82
- "import": "./dist/telemetry.js"
49
+ "./hooks": {
50
+ "source": "./hooks.ts",
51
+ "types": "./dist/hooks.d.ts",
52
+ "import": "./dist/hooks.js"
83
53
  },
84
54
  "./utils": {
85
55
  "source": "./_utils.ts",
86
56
  "types": "./dist/_utils.d.ts",
87
57
  "import": "./dist/_utils.js"
88
58
  },
89
- "./ssrf": {
90
- "source": "./_ssrf.ts",
91
- "types": "./dist/_ssrf.d.ts",
92
- "import": "./dist/_ssrf.js"
93
- },
94
- "./middleware-core": {
95
- "source": "./middleware-core.ts",
96
- "types": "./dist/middleware-core.d.ts",
97
- "import": "./dist/middleware-core.js"
98
- },
99
- "./unstorage-kv": {
100
- "source": "./unstorage-kv.ts",
101
- "types": "./dist/unstorage-kv.d.ts",
102
- "import": "./dist/unstorage-kv.js"
103
- },
104
- "./unstorage-vector": {
105
- "source": "./unstorage-vector.ts",
106
- "types": "./dist/unstorage-vector.d.ts",
107
- "import": "./dist/unstorage-vector.js"
59
+ "./vite-plugin": {
60
+ "source": "./vite-plugin.ts",
61
+ "types": "./dist/vite-plugin.d.ts",
62
+ "import": "./dist/vite-plugin.js"
108
63
  }
109
64
  },
110
65
  "dependencies": {
111
- "@huggingface/transformers": "^3.8.1",
112
- "html-to-text": "^9.0.5",
66
+ "hookable": "^6.1.0",
113
67
  "nanoevents": "^9.1.0",
68
+ "p-timeout": "^7.0.1",
114
69
  "secure-exec": "^0.1.0",
115
70
  "unstorage": "^1.17.5",
116
71
  "ws": "^8.20.0",
117
72
  "zod": "^4.3.6"
118
73
  },
119
74
  "peerDependencies": {
120
- "@hono/node-server": "^1.19.11",
121
- "@hono/node-ws": "^1.3.0",
122
- "@opentelemetry/api": "^1.9.1",
123
- "hono": "^4.12.9",
124
75
  "vitest": "^4.1.1"
125
76
  },
126
77
  "peerDependenciesMeta": {
127
- "@hono/node-server": {
128
- "optional": true
129
- },
130
- "@hono/node-ws": {
131
- "optional": true
132
- },
133
- "@opentelemetry/api": {
134
- "optional": true
135
- },
136
- "hono": {
137
- "optional": true
138
- },
139
78
  "vitest": {
140
79
  "optional": true
141
80
  }
142
81
  },
143
82
  "devDependencies": {
144
- "@types/html-to-text": "^9.0.4",
145
83
  "@types/json-schema": "^7.0.15",
84
+ "@types/node": "^25.5.0",
146
85
  "@types/ws": "^8.18.1",
147
- "tsdown": "^0.21.5"
86
+ "tsdown": "^0.21.5",
87
+ "vite": "^8.0.3"
148
88
  },
149
89
  "engines": {
150
90
  "node": ">=22.6"
@@ -158,7 +98,7 @@
158
98
  "build": "tsdown && tsc -p tsconfig.build.json",
159
99
  "typecheck": "tsc --noEmit",
160
100
  "lint": "biome check .",
161
- "check:api": "api-extractor run -c api-extractor.json",
101
+ "check:publint": "publint",
162
102
  "check:attw": "attw --pack --profile esm-only"
163
103
  }
164
104
  }
@@ -1,31 +0,0 @@
1
- /**
2
- * Shared embedding helpers for vector stores.
3
- *
4
- * Provides local embedding via `all-MiniLM-L6-v2` (384 dims),
5
- * a deterministic test embedding function, and cosine similarity.
6
- */
7
- /** Function that converts text into an embedding vector. */
8
- export type EmbedFn = (text: string) => Promise<number[]>;
9
- export declare const DEFAULT_DIMENSIONS = 384;
10
- /**
11
- * Create a local embedding function using `all-MiniLM-L6-v2`.
12
- *
13
- * The model is downloaded on first use (~86 MB) and cached locally.
14
- * Subsequent calls load from cache in ~90ms. Each embedding takes <2ms.
15
- */
16
- export declare function createLocalEmbedFn(cacheDir: string): EmbedFn;
17
- /**
18
- * Create a deterministic hash-based embedding function for testing.
19
- *
20
- * Produces repeatable vectors where similar text yields similar embeddings.
21
- * Not suitable for production — use the default local model instead.
22
- *
23
- * @param dimensions - Vector dimensions (default: 384).
24
- */
25
- export declare function createTestEmbedFn(dimensions?: number): EmbedFn;
26
- /** Cosine similarity between two Float32Array vectors. */
27
- export declare function cosineSimilarity(a: Float32Array, b: Float32Array): number;
28
- /** Encode an embedding as a base64 string. */
29
- export declare function encodeEmbedding(vec: Float32Array | number[]): string;
30
- /** Decode a base64 string back to a Float32Array embedding. */
31
- export declare function decodeEmbedding(b64: string): Float32Array;
@@ -1,61 +0,0 @@
1
- import { i as ToolChoiceSchema, t as BuiltinToolSchema } from "./types-D8ZBxTL_.js";
2
- import { z } from "zod";
3
- //#region _internal-types.ts
4
- /**
5
- * Zod schema for serializable agent configuration sent over the wire.
6
- *
7
- * This is the JSON-safe subset of the agent definition that can be
8
- * transmitted between the worker and the host process via structured clone.
9
- */
10
- const AgentConfigSchema = z.object({
11
- name: z.string().min(1),
12
- instructions: z.string(),
13
- greeting: z.string(),
14
- sttPrompt: z.string().optional(),
15
- maxSteps: z.number().int().positive().optional(),
16
- toolChoice: ToolChoiceSchema.optional(),
17
- builtinTools: z.array(BuiltinToolSchema).readonly().optional(),
18
- idleTimeoutMs: z.number().nonnegative().optional()
19
- });
20
- /** Extract the serializable {@link AgentConfig} subset from a source object. */
21
- function toAgentConfig(src) {
22
- const config = {
23
- name: src.name,
24
- instructions: src.instructions,
25
- greeting: src.greeting
26
- };
27
- if (src.sttPrompt !== void 0) config.sttPrompt = src.sttPrompt;
28
- if (typeof src.maxSteps !== "function" && src.maxSteps !== void 0) config.maxSteps = src.maxSteps;
29
- if (src.toolChoice !== void 0) config.toolChoice = src.toolChoice;
30
- if (src.builtinTools) config.builtinTools = [...src.builtinTools];
31
- if (src.idleTimeoutMs !== void 0) config.idleTimeoutMs = src.idleTimeoutMs;
32
- return config;
33
- }
34
- /**
35
- * Zod schema for serialized tool definitions sent over the wire.
36
- *
37
- * `parameters` must be a valid JSON Schema object (with `type`, `properties`,
38
- * etc.) — the Vercel AI SDK wraps it via `jsonSchema()`.
39
- */
40
- const ToolSchemaSchema = z.object({
41
- name: z.string().min(1),
42
- description: z.string().min(1),
43
- parameters: z.record(z.string(), z.unknown())
44
- });
45
- /** Empty Zod object schema used as default when tools have no parameters. */
46
- const EMPTY_PARAMS = z.object({});
47
- /**
48
- * Convert agent tool definitions to JSON Schema format for wire transport.
49
- *
50
- * Transforms the Zod-based `parameters` of each tool into a plain JSON Schema
51
- * object suitable for structured clone / JSON serialization.
52
- */
53
- function agentToolsToSchemas(tools) {
54
- return Object.entries(tools).map(([name, def]) => ({
55
- name,
56
- description: def.description,
57
- parameters: z.toJSONSchema(def.parameters ?? EMPTY_PARAMS)
58
- }));
59
- }
60
- //#endregion
61
- export { toAgentConfig as a, agentToolsToSchemas as i, EMPTY_PARAMS as n, ToolSchemaSchema as r, AgentConfigSchema as t };
@@ -1,2 +0,0 @@
1
- import { a as toAgentConfig, i as agentToolsToSchemas, n as EMPTY_PARAMS, r as ToolSchemaSchema, t as AgentConfigSchema } from "./_internal-types-IfPcaJd5.js";
2
- export { AgentConfigSchema, EMPTY_PARAMS, ToolSchemaSchema, agentToolsToSchemas, toAgentConfig };
@@ -1,73 +0,0 @@
1
- /**
2
- * Session context builder.
3
- *
4
- * Extracted from session.ts to keep it under the file-length lint limit.
5
- * Builds the shared mutable state object threaded through all session helpers.
6
- */
7
- import type { AgentConfig } from "./_internal-types.ts";
8
- import type { HookInvoker } from "./middleware.ts";
9
- import type { ClientSink } from "./protocol.ts";
10
- import type { Logger } from "./runtime.ts";
11
- import type { S2sHandle } from "./s2s.ts";
12
- import type { Message } from "./types.ts";
13
- import type { ExecuteTool } from "./worker-entry.ts";
14
- type PendingTool = {
15
- callId: string;
16
- result: string;
17
- };
18
- /**
19
- * Mutable state and dependencies shared across session helper functions.
20
- *
21
- * Created once per session by `buildCtx` and threaded through `setupListeners`,
22
- * `handleToolCall`, and other internal helpers. Contains both immutable
23
- * dependencies (logger, executor) and mutable per-turn state (pending tools,
24
- * generation counters).
25
- */
26
- export type S2sSessionCtx = {
27
- readonly id: string;
28
- readonly agent: string;
29
- readonly client: ClientSink;
30
- readonly agentConfig: AgentConfig;
31
- readonly executeTool: ExecuteTool;
32
- readonly hookInvoker: HookInvoker | undefined;
33
- readonly log: Logger;
34
- s2s: S2sHandle | null;
35
- pendingTools: PendingTool[];
36
- toolCallCount: number;
37
- turnPromise: Promise<void> | null;
38
- conversationMessages: Message[];
39
- /** Maximum number of messages to retain in conversationMessages. */
40
- readonly maxHistory: number;
41
- /** The `reply_id` from the most recent `reply.started` event. Tool calls
42
- * capture this at start; finishToolCall only pushes to pendingTools if the
43
- * reply ID still matches, preventing stale results from interrupted replies
44
- * from leaking into subsequent replies. Set to `null` on close/reset. */
45
- currentReplyId: string | null;
46
- /** Resolve per-turn configuration (dynamic `maxSteps`). */
47
- resolveTurnConfig(): Promise<{
48
- maxSteps?: number;
49
- } | null>;
50
- /** Increment the tool call counter and check whether the call should be refused. */
51
- consumeToolCallStep(turnConfig: {
52
- maxSteps?: number;
53
- } | null, name: string, replyId: string | null): string | null;
54
- /** Fire a lifecycle hook asynchronously. Errors are logged but never propagated. */
55
- fireHook(name: string, fn: (h: HookInvoker) => Promise<void>): void;
56
- /** Await all in-flight hook promises. Used during shutdown. */
57
- drainHooks(): Promise<void>;
58
- /** Push one or more messages and trim to maxHistory. */
59
- pushMessages(...msgs: Message[]): void;
60
- /** Sequential promise chain for filterOutput calls, ensuring ordering. */
61
- filterChain: Promise<void>;
62
- };
63
- export declare function buildCtx(opts: {
64
- id: string;
65
- agent: string;
66
- client: ClientSink;
67
- agentConfig: AgentConfig;
68
- executeTool: ExecuteTool;
69
- hookInvoker: HookInvoker | undefined;
70
- log: Logger;
71
- maxHistory?: number | undefined;
72
- }): S2sSessionCtx;
73
- export {};