@alexkroman1/aai 0.8.7 → 0.9.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 (288) hide show
  1. package/dist/{sdk/_internal_types.d.ts → _internal-types.d.ts} +0 -3
  2. package/dist/_internal-types.js +19 -0
  3. package/dist/{sdk/_mock_ws.d.ts → _mock-ws.d.ts} +16 -5
  4. package/dist/_mock-ws.js +158 -0
  5. package/dist/{sdk/_utils.d.ts → _utils.d.ts} +1 -2
  6. package/dist/_utils.js +8 -0
  7. package/dist/{sdk/builtin_tools.d.ts → builtin-tools.d.ts} +5 -8
  8. package/dist/builtin-tools.js +270 -0
  9. package/dist/{sdk/direct_executor.d.ts → direct-executor.d.ts} +3 -7
  10. package/dist/direct-executor.js +125 -0
  11. package/dist/{sdk/mod.d.ts → index.d.ts} +0 -4
  12. package/dist/index.js +2 -0
  13. package/dist/{sdk/kv.d.ts → kv.d.ts} +23 -20
  14. package/dist/kv.js +99 -0
  15. package/dist/{sdk/protocol.d.ts → protocol.d.ts} +67 -31
  16. package/dist/protocol.js +142 -0
  17. package/dist/runtime.d.ts +18 -0
  18. package/dist/runtime.js +16 -0
  19. package/dist/s2s.d.ts +110 -0
  20. package/dist/s2s.js +242 -0
  21. package/dist/{sdk/server.d.ts → server.d.ts} +3 -23
  22. package/dist/server.js +105 -0
  23. package/dist/{sdk/session.d.ts → session.d.ts} +4 -11
  24. package/dist/session.js +312 -0
  25. package/dist/tsdown.config.d.ts +2 -0
  26. package/dist/{sdk/types.d.ts → types.d.ts} +41 -25
  27. package/dist/types.js +139 -0
  28. package/dist/{sdk/vector.d.ts → vector.d.ts} +14 -15
  29. package/dist/vector.js +56 -0
  30. package/dist/{sdk/worker_entry.d.ts → worker-entry.d.ts} +2 -5
  31. package/dist/worker-entry.js +59 -0
  32. package/dist/{sdk/ws_handler.d.ts → ws-handler.d.ts} +10 -8
  33. package/dist/ws-handler.js +155 -0
  34. package/package.json +66 -149
  35. package/README.md +0 -34
  36. package/dist/aai.js +0 -3
  37. package/dist/cli/tsconfig.tsbuildinfo +0 -1
  38. package/dist/cli.js +0 -2811
  39. package/dist/sdk/_internal_types.d.ts.map +0 -1
  40. package/dist/sdk/_internal_types.js +0 -25
  41. package/dist/sdk/_internal_types.js.map +0 -1
  42. package/dist/sdk/_mock_ws.d.ts.map +0 -1
  43. package/dist/sdk/_mock_ws.js +0 -154
  44. package/dist/sdk/_mock_ws.js.map +0 -1
  45. package/dist/sdk/_render_check.d.ts +0 -10
  46. package/dist/sdk/_render_check.d.ts.map +0 -1
  47. package/dist/sdk/_render_check.js +0 -72
  48. package/dist/sdk/_render_check.js.map +0 -1
  49. package/dist/sdk/_utils.d.ts.map +0 -1
  50. package/dist/sdk/_utils.js +0 -7
  51. package/dist/sdk/_utils.js.map +0 -1
  52. package/dist/sdk/builtin_tools.d.ts.map +0 -1
  53. package/dist/sdk/builtin_tools.js +0 -309
  54. package/dist/sdk/builtin_tools.js.map +0 -1
  55. package/dist/sdk/capnweb.d.ts +0 -102
  56. package/dist/sdk/capnweb.d.ts.map +0 -1
  57. package/dist/sdk/capnweb.js +0 -219
  58. package/dist/sdk/capnweb.js.map +0 -1
  59. package/dist/sdk/define_agent.d.ts +0 -36
  60. package/dist/sdk/define_agent.d.ts.map +0 -1
  61. package/dist/sdk/define_agent.js +0 -71
  62. package/dist/sdk/define_agent.js.map +0 -1
  63. package/dist/sdk/direct_executor.d.ts.map +0 -1
  64. package/dist/sdk/direct_executor.js +0 -145
  65. package/dist/sdk/direct_executor.js.map +0 -1
  66. package/dist/sdk/host.d.ts +0 -59
  67. package/dist/sdk/host.d.ts.map +0 -1
  68. package/dist/sdk/host.js +0 -131
  69. package/dist/sdk/host.js.map +0 -1
  70. package/dist/sdk/kv.d.ts.map +0 -1
  71. package/dist/sdk/kv.js +0 -94
  72. package/dist/sdk/kv.js.map +0 -1
  73. package/dist/sdk/memory_tools.d.ts +0 -38
  74. package/dist/sdk/memory_tools.d.ts.map +0 -1
  75. package/dist/sdk/memory_tools.js +0 -77
  76. package/dist/sdk/memory_tools.js.map +0 -1
  77. package/dist/sdk/mod.d.ts.map +0 -1
  78. package/dist/sdk/mod.js +0 -27
  79. package/dist/sdk/mod.js.map +0 -1
  80. package/dist/sdk/protocol.d.ts.map +0 -1
  81. package/dist/sdk/protocol.js +0 -133
  82. package/dist/sdk/protocol.js.map +0 -1
  83. package/dist/sdk/runtime.d.ts +0 -36
  84. package/dist/sdk/runtime.d.ts.map +0 -1
  85. package/dist/sdk/runtime.js +0 -27
  86. package/dist/sdk/runtime.js.map +0 -1
  87. package/dist/sdk/s2s.d.ts +0 -74
  88. package/dist/sdk/s2s.d.ts.map +0 -1
  89. package/dist/sdk/s2s.js +0 -218
  90. package/dist/sdk/s2s.js.map +0 -1
  91. package/dist/sdk/server.d.ts.map +0 -1
  92. package/dist/sdk/server.js +0 -144
  93. package/dist/sdk/server.js.map +0 -1
  94. package/dist/sdk/session.d.ts.map +0 -1
  95. package/dist/sdk/session.js +0 -303
  96. package/dist/sdk/session.js.map +0 -1
  97. package/dist/sdk/system_prompt.d.ts +0 -6
  98. package/dist/sdk/system_prompt.d.ts.map +0 -1
  99. package/dist/sdk/system_prompt.js +0 -35
  100. package/dist/sdk/system_prompt.js.map +0 -1
  101. package/dist/sdk/tsconfig.tsbuildinfo +0 -1
  102. package/dist/sdk/types.d.ts.map +0 -1
  103. package/dist/sdk/types.js +0 -96
  104. package/dist/sdk/types.js.map +0 -1
  105. package/dist/sdk/vector.d.ts.map +0 -1
  106. package/dist/sdk/vector.js +0 -63
  107. package/dist/sdk/vector.js.map +0 -1
  108. package/dist/sdk/winterc_server.d.ts +0 -56
  109. package/dist/sdk/winterc_server.d.ts.map +0 -1
  110. package/dist/sdk/winterc_server.js +0 -77
  111. package/dist/sdk/winterc_server.js.map +0 -1
  112. package/dist/sdk/worker_entry.d.ts.map +0 -1
  113. package/dist/sdk/worker_entry.js +0 -68
  114. package/dist/sdk/worker_entry.js.map +0 -1
  115. package/dist/sdk/worker_shim.d.ts +0 -19
  116. package/dist/sdk/worker_shim.d.ts.map +0 -1
  117. package/dist/sdk/worker_shim.js +0 -141
  118. package/dist/sdk/worker_shim.js.map +0 -1
  119. package/dist/sdk/ws_handler.d.ts.map +0 -1
  120. package/dist/sdk/ws_handler.js +0 -158
  121. package/dist/sdk/ws_handler.js.map +0 -1
  122. package/dist/ui/_cn.d.ts +0 -5
  123. package/dist/ui/_cn.d.ts.map +0 -1
  124. package/dist/ui/_cn.js +0 -22
  125. package/dist/ui/_cn.js.map +0 -1
  126. package/dist/ui/_components/app.d.ts +0 -5
  127. package/dist/ui/_components/app.d.ts.map +0 -1
  128. package/dist/ui/_components/app.js +0 -12
  129. package/dist/ui/_components/app.js.map +0 -1
  130. package/dist/ui/_components/button.d.ts +0 -11
  131. package/dist/ui/_components/button.d.ts.map +0 -1
  132. package/dist/ui/_components/button.js +0 -17
  133. package/dist/ui/_components/button.js.map +0 -1
  134. package/dist/ui/_components/chat_view.d.ts +0 -5
  135. package/dist/ui/_components/chat_view.d.ts.map +0 -1
  136. package/dist/ui/_components/chat_view.js +0 -15
  137. package/dist/ui/_components/chat_view.js.map +0 -1
  138. package/dist/ui/_components/controls.d.ts +0 -4
  139. package/dist/ui/_components/controls.d.ts.map +0 -1
  140. package/dist/ui/_components/controls.js +0 -10
  141. package/dist/ui/_components/controls.js.map +0 -1
  142. package/dist/ui/_components/error_banner.d.ts +0 -8
  143. package/dist/ui/_components/error_banner.d.ts.map +0 -1
  144. package/dist/ui/_components/error_banner.js +0 -8
  145. package/dist/ui/_components/error_banner.js.map +0 -1
  146. package/dist/ui/_components/message_bubble.d.ts +0 -7
  147. package/dist/ui/_components/message_bubble.d.ts.map +0 -1
  148. package/dist/ui/_components/message_bubble.js +0 -11
  149. package/dist/ui/_components/message_bubble.js.map +0 -1
  150. package/dist/ui/_components/message_list.d.ts +0 -4
  151. package/dist/ui/_components/message_list.d.ts.map +0 -1
  152. package/dist/ui/_components/message_list.js +0 -45
  153. package/dist/ui/_components/message_list.js.map +0 -1
  154. package/dist/ui/_components/sidebar_layout.d.ts +0 -20
  155. package/dist/ui/_components/sidebar_layout.d.ts.map +0 -1
  156. package/dist/ui/_components/sidebar_layout.js +0 -19
  157. package/dist/ui/_components/sidebar_layout.js.map +0 -1
  158. package/dist/ui/_components/start_screen.d.ts +0 -25
  159. package/dist/ui/_components/start_screen.d.ts.map +0 -1
  160. package/dist/ui/_components/start_screen.js +0 -28
  161. package/dist/ui/_components/start_screen.js.map +0 -1
  162. package/dist/ui/_components/state_indicator.d.ts +0 -8
  163. package/dist/ui/_components/state_indicator.d.ts.map +0 -1
  164. package/dist/ui/_components/state_indicator.js +0 -6
  165. package/dist/ui/_components/state_indicator.js.map +0 -1
  166. package/dist/ui/_components/thinking_indicator.d.ts +0 -5
  167. package/dist/ui/_components/thinking_indicator.d.ts.map +0 -1
  168. package/dist/ui/_components/thinking_indicator.js +0 -10
  169. package/dist/ui/_components/thinking_indicator.js.map +0 -1
  170. package/dist/ui/_components/tool_call_block.d.ts +0 -7
  171. package/dist/ui/_components/tool_call_block.d.ts.map +0 -1
  172. package/dist/ui/_components/tool_call_block.js +0 -46
  173. package/dist/ui/_components/tool_call_block.js.map +0 -1
  174. package/dist/ui/_components/tool_icons.d.ts +0 -18
  175. package/dist/ui/_components/tool_icons.d.ts.map +0 -1
  176. package/dist/ui/_components/tool_icons.js +0 -26
  177. package/dist/ui/_components/tool_icons.js.map +0 -1
  178. package/dist/ui/_components/transcript.d.ts +0 -7
  179. package/dist/ui/_components/transcript.d.ts.map +0 -1
  180. package/dist/ui/_components/transcript.js +0 -9
  181. package/dist/ui/_components/transcript.js.map +0 -1
  182. package/dist/ui/_dom_shim.d.ts +0 -7
  183. package/dist/ui/_dom_shim.d.ts.map +0 -1
  184. package/dist/ui/_dom_shim.js +0 -21
  185. package/dist/ui/_dom_shim.js.map +0 -1
  186. package/dist/ui/_hooks.d.ts +0 -21
  187. package/dist/ui/_hooks.d.ts.map +0 -1
  188. package/dist/ui/_hooks.js +0 -35
  189. package/dist/ui/_hooks.js.map +0 -1
  190. package/dist/ui/_jsdom_setup.d.ts +0 -1
  191. package/dist/ui/_jsdom_setup.d.ts.map +0 -1
  192. package/dist/ui/_jsdom_setup.js +0 -6
  193. package/dist/ui/_jsdom_setup.js.map +0 -1
  194. package/dist/ui/_test_utils.js +0 -272
  195. package/dist/ui/_test_utils.js.map +0 -1
  196. package/dist/ui/audio.d.ts +0 -46
  197. package/dist/ui/audio.d.ts.map +0 -1
  198. package/dist/ui/audio.js +0 -130
  199. package/dist/ui/audio.js.map +0 -1
  200. package/dist/ui/components.d.ts +0 -14
  201. package/dist/ui/components.d.ts.map +0 -1
  202. package/dist/ui/components.js +0 -15
  203. package/dist/ui/components.js.map +0 -1
  204. package/dist/ui/components_mod.d.ts +0 -34
  205. package/dist/ui/components_mod.d.ts.map +0 -1
  206. package/dist/ui/components_mod.js +0 -32
  207. package/dist/ui/components_mod.js.map +0 -1
  208. package/dist/ui/mod.d.ts +0 -23
  209. package/dist/ui/mod.d.ts.map +0 -1
  210. package/dist/ui/mod.js +0 -22
  211. package/dist/ui/mod.js.map +0 -1
  212. package/dist/ui/mount.d.ts +0 -44
  213. package/dist/ui/mount.d.ts.map +0 -1
  214. package/dist/ui/mount.js +0 -61
  215. package/dist/ui/mount.js.map +0 -1
  216. package/dist/ui/mount_context.d.ts +0 -22
  217. package/dist/ui/mount_context.d.ts.map +0 -1
  218. package/dist/ui/mount_context.js +0 -10
  219. package/dist/ui/mount_context.js.map +0 -1
  220. package/dist/ui/session.d.ts +0 -96
  221. package/dist/ui/session.d.ts.map +0 -1
  222. package/dist/ui/session.js +0 -379
  223. package/dist/ui/session.js.map +0 -1
  224. package/dist/ui/session_mod.d.ts +0 -19
  225. package/dist/ui/session_mod.d.ts.map +0 -1
  226. package/dist/ui/session_mod.js +0 -18
  227. package/dist/ui/session_mod.js.map +0 -1
  228. package/dist/ui/signals.d.ts +0 -80
  229. package/dist/ui/signals.d.ts.map +0 -1
  230. package/dist/ui/signals.js +0 -137
  231. package/dist/ui/signals.js.map +0 -1
  232. package/dist/ui/tsconfig.tsbuildinfo +0 -1
  233. package/dist/ui/types.d.ts +0 -36
  234. package/dist/ui/types.d.ts.map +0 -1
  235. package/dist/ui/types.js +0 -4
  236. package/dist/ui/types.js.map +0 -1
  237. package/dist/ui/worklets/capture-processor.d.ts +0 -3
  238. package/dist/ui/worklets/capture-processor.d.ts.map +0 -1
  239. package/dist/ui/worklets/capture-processor.js +0 -61
  240. package/dist/ui/worklets/capture-processor.js.map +0 -1
  241. package/dist/ui/worklets/playback-processor.d.ts +0 -3
  242. package/dist/ui/worklets/playback-processor.d.ts.map +0 -1
  243. package/dist/ui/worklets/playback-processor.js +0 -109
  244. package/dist/ui/worklets/playback-processor.js.map +0 -1
  245. package/templates/.env +0 -1
  246. package/templates/_shared/.env.example +0 -5
  247. package/templates/_shared/CLAUDE.md +0 -1073
  248. package/templates/_shared/biome.json +0 -32
  249. package/templates/_shared/global.d.ts +0 -1
  250. package/templates/_shared/index.html +0 -16
  251. package/templates/_shared/package.json +0 -22
  252. package/templates/_shared/tsconfig.json +0 -16
  253. package/templates/code-interpreter/agent.ts +0 -27
  254. package/templates/code-interpreter/client.tsx +0 -3
  255. package/templates/dispatch-center/agent.ts +0 -1223
  256. package/templates/dispatch-center/client.tsx +0 -505
  257. package/templates/embedded-assets/agent.ts +0 -48
  258. package/templates/embedded-assets/client.tsx +0 -3
  259. package/templates/embedded-assets/knowledge.json +0 -20
  260. package/templates/health-assistant/agent.ts +0 -160
  261. package/templates/health-assistant/client.tsx +0 -3
  262. package/templates/infocom-adventure/agent.ts +0 -164
  263. package/templates/infocom-adventure/client.tsx +0 -300
  264. package/templates/math-buddy/agent.ts +0 -21
  265. package/templates/math-buddy/client.tsx +0 -3
  266. package/templates/memory-agent/agent.ts +0 -20
  267. package/templates/memory-agent/client.tsx +0 -3
  268. package/templates/night-owl/agent.ts +0 -98
  269. package/templates/night-owl/client.tsx +0 -12
  270. package/templates/personal-finance/agent.ts +0 -26
  271. package/templates/personal-finance/client.tsx +0 -3
  272. package/templates/pizza-ordering/agent.ts +0 -214
  273. package/templates/pizza-ordering/client.tsx +0 -264
  274. package/templates/simple/agent.ts +0 -6
  275. package/templates/simple/client.tsx +0 -3
  276. package/templates/smart-research/agent.ts +0 -164
  277. package/templates/smart-research/client.tsx +0 -3
  278. package/templates/solo-rpg/agent.ts +0 -1240
  279. package/templates/solo-rpg/client.tsx +0 -698
  280. package/templates/support/README.md +0 -62
  281. package/templates/support/agent.ts +0 -19
  282. package/templates/support/client.tsx +0 -3
  283. package/templates/travel-concierge/agent.ts +0 -29
  284. package/templates/travel-concierge/client.tsx +0 -3
  285. package/templates/tsconfig.json +0 -1
  286. package/templates/web-researcher/agent.ts +0 -17
  287. package/templates/web-researcher/client.tsx +0 -3
  288. package/ui/styles.css +0 -74
@@ -0,0 +1,125 @@
1
+ import { createMemoryKv } from "./kv.js";
2
+ import { createMemoryVectorStore } from "./vector.js";
3
+ import { agentToolsToSchemas } from "./_internal-types.js";
4
+ import { getBuiltinToolDefs, getBuiltinToolSchemas } from "./builtin-tools.js";
5
+ import { DEFAULT_S2S_CONFIG, consoleLogger } from "./runtime.js";
6
+ import { createS2sSession } from "./session.js";
7
+ import { executeToolCall } from "./worker-entry.js";
8
+ //#region direct-executor.ts
9
+ /**
10
+ * Direct tool execution for self-hosted mode.
11
+ *
12
+ * In self-hosted mode, agent code is trusted (you're running your own code).
13
+ * Tools execute directly in-process — no sandbox, no RPC.
14
+ */
15
+ /** Build a serializable AgentConfig from an AgentDef. */
16
+ function buildAgentConfig(agent) {
17
+ const config = {
18
+ name: agent.name,
19
+ instructions: agent.instructions,
20
+ greeting: agent.greeting
21
+ };
22
+ if (agent.sttPrompt !== void 0) config.sttPrompt = agent.sttPrompt;
23
+ if (typeof agent.maxSteps !== "function") config.maxSteps = agent.maxSteps;
24
+ if (agent.toolChoice !== void 0) config.toolChoice = agent.toolChoice;
25
+ if (agent.builtinTools) config.builtinTools = [...agent.builtinTools];
26
+ if (agent.activeTools) config.activeTools = [...agent.activeTools];
27
+ return config;
28
+ }
29
+ /** Create a direct (in-process) tool executor and hook invoker for an agent. */
30
+ function createDirectExecutor(opts) {
31
+ const { agent, env, kv = createMemoryKv(), vector = createMemoryVectorStore(), vectorSearch, createWebSocket, logger = consoleLogger, s2sConfig = DEFAULT_S2S_CONFIG } = opts;
32
+ const agentConfig = buildAgentConfig(agent);
33
+ const allTools = {
34
+ ...getBuiltinToolDefs(agent.builtinTools ?? [], vectorSearch ? { vectorSearch } : void 0),
35
+ ...agent.tools
36
+ };
37
+ const customSchemas = agentToolsToSchemas(agent.tools ?? {});
38
+ const builtinSchemas = getBuiltinToolSchemas(agent.builtinTools ?? []);
39
+ const toolSchemas = [...customSchemas, ...builtinSchemas];
40
+ const sessionState = /* @__PURE__ */ new Map();
41
+ const frozenEnv = Object.freeze({ ...env });
42
+ function getState(sessionId) {
43
+ if (!sessionState.has(sessionId) && agent.state) sessionState.set(sessionId, agent.state());
44
+ return sessionState.get(sessionId) ?? {};
45
+ }
46
+ function makeHookContext(sessionId) {
47
+ return {
48
+ env: frozenEnv,
49
+ state: getState(sessionId),
50
+ get kv() {
51
+ return kv;
52
+ },
53
+ get vector() {
54
+ return vector;
55
+ }
56
+ };
57
+ }
58
+ const executeTool = async (name, args, sessionId, messages) => {
59
+ const tool = allTools[name];
60
+ if (!tool) return JSON.stringify({ error: `Unknown tool: ${name}` });
61
+ return executeToolCall(name, args, {
62
+ tool,
63
+ env: frozenEnv,
64
+ state: getState(sessionId ?? ""),
65
+ kv,
66
+ vector,
67
+ messages
68
+ });
69
+ };
70
+ const hookInvoker = {
71
+ async onConnect(sessionId) {
72
+ await agent.onConnect?.(makeHookContext(sessionId));
73
+ },
74
+ async onDisconnect(sessionId) {
75
+ await agent.onDisconnect?.(makeHookContext(sessionId));
76
+ sessionState.delete(sessionId);
77
+ },
78
+ async onTurn(sessionId, text) {
79
+ await agent.onTurn?.(text, makeHookContext(sessionId));
80
+ },
81
+ async onError(sessionId, error) {
82
+ await agent.onError?.(new Error(error.message), makeHookContext(sessionId));
83
+ },
84
+ async onStep(sessionId, step) {
85
+ await agent.onStep?.(step, makeHookContext(sessionId));
86
+ },
87
+ async resolveTurnConfig(sessionId) {
88
+ const ctx = makeHookContext(sessionId);
89
+ let maxSteps;
90
+ let activeTools;
91
+ if (typeof agent.maxSteps === "function") maxSteps = await agent.maxSteps(ctx) ?? void 0;
92
+ if (agent.onBeforeStep) activeTools = (await agent.onBeforeStep(0, ctx))?.activeTools;
93
+ if (maxSteps === void 0 && activeTools === void 0) return null;
94
+ const config = {};
95
+ if (maxSteps !== void 0) config.maxSteps = maxSteps;
96
+ if (activeTools !== void 0) config.activeTools = activeTools;
97
+ return config;
98
+ }
99
+ };
100
+ function createSession(sessionOpts) {
101
+ const apiKey = frozenEnv.ASSEMBLYAI_API_KEY ?? "";
102
+ return createS2sSession({
103
+ id: sessionOpts.id,
104
+ agent: sessionOpts.agent,
105
+ client: sessionOpts.client,
106
+ agentConfig,
107
+ toolSchemas,
108
+ apiKey,
109
+ s2sConfig,
110
+ executeTool,
111
+ ...createWebSocket ? { createWebSocket } : {},
112
+ hookInvoker,
113
+ skipGreeting: sessionOpts.skipGreeting ?? false,
114
+ logger
115
+ });
116
+ }
117
+ return {
118
+ executeTool,
119
+ hookInvoker,
120
+ toolSchemas,
121
+ createSession
122
+ };
123
+ }
124
+ //#endregion
125
+ export { buildAgentConfig, createDirectExecutor };
@@ -18,10 +18,6 @@
18
18
  * },
19
19
  * });
20
20
  * ```
21
- *
22
- * @module
23
21
  */
24
- export { memoryTools } from "./builtin_tools.ts";
25
22
  export { type AgentOptions, type BeforeStepResult, type BuiltinTool, defineAgent, type HookContext, type Message, type StepInfo, type ToolContext, type ToolDef, tool, } from "./types.ts";
26
23
  export type { VectorEntry, VectorStore } from "./vector.ts";
27
- //# sourceMappingURL=mod.d.ts.map
package/dist/index.js ADDED
@@ -0,0 +1,2 @@
1
+ import { defineAgent, tool } from "./types.js";
2
+ export { defineAgent, tool };
@@ -1,12 +1,10 @@
1
1
  /**
2
2
  * Key-value storage interface and in-memory implementation.
3
- *
4
- * @module
5
3
  */
6
4
  /**
7
- * A single key-value entry returned by {@linkcode Kv.list}.
5
+ * A single key-value entry returned by {@link Kv.list}.
8
6
  *
9
- * @typeParam T The type of the stored value. Defaults to `unknown`.
7
+ * @typeParam T - The type of the stored value. Defaults to `unknown`.
10
8
  */
11
9
  export type KvEntry<T = unknown> = {
12
10
  /** The key under which the value is stored. */
@@ -17,7 +15,7 @@ export type KvEntry<T = unknown> = {
17
15
  /**
18
16
  * Options for listing keys from the KV store.
19
17
  *
20
- * Used with {@linkcode Kv.list} to control result ordering and pagination.
18
+ * Used with {@link Kv.list} to control result ordering and pagination.
21
19
  */
22
20
  export type KvListOptions = {
23
21
  /** Maximum number of entries to return. */
@@ -28,8 +26,8 @@ export type KvListOptions = {
28
26
  /**
29
27
  * Async key-value store interface used by agents.
30
28
  *
31
- * Agents access the KV store via {@linkcode ToolContext.kv} or
32
- * {@linkcode HookContext.kv}. Values are JSON-serialized and stored as
29
+ * Agents access the KV store via {@link ToolContext.kv} or
30
+ * {@link HookContext.kv}. Values are JSON-serialized and stored as
33
31
  * strings with an optional TTL.
34
32
  *
35
33
  * @example
@@ -49,8 +47,8 @@ export type Kv = {
49
47
  /**
50
48
  * Get a value by key, or `null` if not found.
51
49
  *
52
- * @typeParam T The expected type of the stored value.
53
- * @param key The key to look up.
50
+ * @typeParam T - The expected type of the stored value.
51
+ * @param key - The key to look up.
54
52
  * @returns The deserialized value, or `null` if the key does not exist
55
53
  * or has expired.
56
54
  */
@@ -58,10 +56,9 @@ export type Kv = {
58
56
  /**
59
57
  * Set a value, optionally with a TTL in milliseconds.
60
58
  *
61
- * @param key The key to store the value under.
62
- * @param value The value to store. Must be JSON-serializable.
63
- * @param options Optional settings.
64
- * @param options.expireIn Time-to-live in milliseconds. The entry is
59
+ * @param key - The key to store the value under.
60
+ * @param value - The value to store. Must be JSON-serializable.
61
+ * @param options - Optional settings. `expireIn` sets the time-to-live in milliseconds. The entry is
65
62
  * automatically removed after this duration.
66
63
  * @throws {Error} If the serialized value exceeds 65,536 bytes.
67
64
  */
@@ -71,7 +68,7 @@ export type Kv = {
71
68
  /**
72
69
  * Delete a key.
73
70
  *
74
- * @param key The key to remove. No-op if the key does not exist.
71
+ * @param key - The key to remove. No-op if the key does not exist.
75
72
  */
76
73
  delete(key: string): Promise<void>;
77
74
  /**
@@ -79,12 +76,19 @@ export type Kv = {
79
76
  *
80
77
  * Results are sorted by key in ascending lexicographic order by default.
81
78
  *
82
- * @typeParam T The expected type of the stored values.
83
- * @param prefix Key prefix to filter by. Use `""` to list all entries.
84
- * @param options Optional pagination and ordering settings.
85
- * @returns An array of matching {@linkcode KvEntry} objects.
79
+ * @typeParam T - The expected type of the stored values.
80
+ * @param prefix - Key prefix to filter by. Use `""` to list all entries.
81
+ * @param options - Optional pagination and ordering settings.
82
+ * @returns An array of matching {@link KvEntry} objects.
86
83
  */
87
84
  list<T = unknown>(prefix: string, options?: KvListOptions): Promise<KvEntry<T>[]>;
85
+ /**
86
+ * List all keys, optionally filtered by a glob-style pattern.
87
+ *
88
+ * @param pattern - Optional glob pattern (e.g. `"user:*"`). If omitted, all keys are returned.
89
+ * @returns An array of matching key strings.
90
+ */
91
+ keys(pattern?: string): Promise<string[]>;
88
92
  };
89
93
  export declare const MAX_VALUE_SIZE = 65536;
90
94
  /** Sort entries by key and apply reverse/limit options. Mutates the array. */
@@ -100,7 +104,7 @@ export declare function sortAndPaginate<T extends {
100
104
  * Data is stored in a plain `Map` and does not persist across restarts.
101
105
  * TTL expiration is checked lazily on reads and list operations.
102
106
  *
103
- * @returns A {@linkcode Kv} instance backed by in-memory storage.
107
+ * @returns A {@link Kv} instance backed by in-memory storage.
104
108
  *
105
109
  * @example
106
110
  * ```ts
@@ -120,4 +124,3 @@ export declare function sortAndPaginate<T extends {
120
124
  * ```
121
125
  */
122
126
  export declare function createMemoryKv(): Kv;
123
- //# sourceMappingURL=kv.d.ts.map
package/dist/kv.js ADDED
@@ -0,0 +1,99 @@
1
+ //#region kv.ts
2
+ const MAX_VALUE_SIZE = 65536;
3
+ /** Sort entries by key and apply reverse/limit options. Mutates the array. */
4
+ function sortAndPaginate(entries, options) {
5
+ entries.sort((a, b) => a.key < b.key ? -1 : a.key > b.key ? 1 : 0);
6
+ if (options?.reverse) entries.reverse();
7
+ if (options?.limit && options.limit > 0) entries.length = Math.min(entries.length, options.limit);
8
+ return entries;
9
+ }
10
+ /** Simple glob matcher — supports `*` as a wildcard for any characters. */
11
+ function matchGlob(key, pattern) {
12
+ const escaped = pattern.replace(/[.+^${}()|[\]\\]/g, "\\$&").replace(/\*/g, ".*");
13
+ return new RegExp(`^${escaped}$`).test(key);
14
+ }
15
+ /**
16
+ * Create an in-memory KV store (useful for testing and local development).
17
+ *
18
+ * Data is stored in a plain `Map` and does not persist across restarts.
19
+ * TTL expiration is checked lazily on reads and list operations.
20
+ *
21
+ * @returns A {@link Kv} instance backed by in-memory storage.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { createMemoryKv } from "./kv.ts";
26
+ *
27
+ * const kv = createMemoryKv();
28
+ * await kv.set("greeting", "hello");
29
+ * const value = await kv.get<string>("greeting"); // "hello"
30
+ * ```
31
+ *
32
+ * @example With TTL
33
+ * ```ts
34
+ * import { createMemoryKv } from "./kv.ts";
35
+ *
36
+ * const kv = createMemoryKv();
37
+ * await kv.set("temp", "expires soon", { expireIn: 5000 });
38
+ * ```
39
+ */
40
+ function createMemoryKv() {
41
+ const store = /* @__PURE__ */ new Map();
42
+ function isExpired(entry) {
43
+ return entry.expiresAt !== void 0 && entry.expiresAt <= Date.now();
44
+ }
45
+ return {
46
+ get(key) {
47
+ const entry = store.get(key);
48
+ if (!entry || isExpired(entry)) {
49
+ if (entry) store.delete(key);
50
+ return Promise.resolve(null);
51
+ }
52
+ return Promise.resolve(JSON.parse(entry.raw));
53
+ },
54
+ set(key, value, options) {
55
+ const raw = JSON.stringify(value);
56
+ if (raw.length > 65536) throw new Error(`Value exceeds max size of ${MAX_VALUE_SIZE} bytes`);
57
+ const expireIn = options?.expireIn;
58
+ const entry = { raw };
59
+ if (expireIn && expireIn > 0) entry.expiresAt = Date.now() + expireIn;
60
+ store.set(key, entry);
61
+ return Promise.resolve();
62
+ },
63
+ delete(key) {
64
+ store.delete(key);
65
+ return Promise.resolve();
66
+ },
67
+ async list(prefix, options) {
68
+ const now = Date.now();
69
+ const entries = [];
70
+ let i = 0;
71
+ for (const [key, entry] of store) {
72
+ if (++i % 500 === 0) await new Promise((r) => setTimeout(r, 0));
73
+ if (entry.expiresAt && entry.expiresAt <= now) {
74
+ store.delete(key);
75
+ continue;
76
+ }
77
+ if (key.startsWith(prefix)) entries.push({
78
+ key,
79
+ value: JSON.parse(entry.raw)
80
+ });
81
+ }
82
+ return sortAndPaginate(entries, options);
83
+ },
84
+ async keys(pattern) {
85
+ const now = Date.now();
86
+ const result = [];
87
+ for (const [key, entry] of store) {
88
+ if (entry.expiresAt && entry.expiresAt <= now) {
89
+ store.delete(key);
90
+ continue;
91
+ }
92
+ if (!pattern || matchGlob(key, pattern)) result.push(key);
93
+ }
94
+ return result.sort();
95
+ }
96
+ };
97
+ }
98
+ //#endregion
99
+ export { MAX_VALUE_SIZE, createMemoryKv, sortAndPaginate };
@@ -2,8 +2,6 @@
2
2
  * WebSocket wire-format types shared by server and client.
3
3
  *
4
4
  * Note: this module is for internal use only and should not be used directly.
5
- *
6
- * @module
7
5
  */
8
6
  import { z } from "zod";
9
7
  /**
@@ -55,23 +53,6 @@ export declare const KvRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
55
53
  }, z.core.$strip>], "op">;
56
54
  /** KV operation request — discriminated union on the `op` field. */
57
55
  export type KvRequest = z.infer<typeof KvRequestSchema>;
58
- /** Zod schema for vector operation requests. */
59
- export declare const VectorRequestSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
60
- op: z.ZodLiteral<"upsert">;
61
- id: z.ZodString;
62
- data: z.ZodString;
63
- metadata: z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodUnknown>>;
64
- }, z.core.$strip>, z.ZodObject<{
65
- op: z.ZodLiteral<"query">;
66
- text: z.ZodString;
67
- topK: z.ZodOptional<z.ZodNumber>;
68
- filter: z.ZodOptional<z.ZodString>;
69
- }, z.core.$strip>, z.ZodObject<{
70
- op: z.ZodLiteral<"remove">;
71
- ids: z.ZodArray<z.ZodString>;
72
- }, z.core.$strip>], "op">;
73
- /** Vector operation request — discriminated union on the `op` field. */
74
- export type VectorRequest = z.infer<typeof VectorRequestSchema>;
75
56
  /** Default timeout for agent lifecycle hooks (onConnect, onTurn, etc). */
76
57
  export declare const HOOK_TIMEOUT_MS = 5000;
77
58
  /** Default timeout for tool execution in the worker. */
@@ -79,17 +60,21 @@ export declare const TOOL_EXECUTION_TIMEOUT_MS = 30000;
79
60
  /** Zod schema for session error codes. */
80
61
  export declare const SessionErrorCodeSchema: z.ZodEnum<{
81
62
  tool: "tool";
82
- audio: "audio";
63
+ connection: "connection";
83
64
  stt: "stt";
84
65
  llm: "llm";
85
66
  tts: "tts";
86
67
  protocol: "protocol";
87
- connection: "connection";
68
+ audio: "audio";
88
69
  internal: "internal";
89
70
  }>;
90
- /** Error codes for categorizing session errors on the wire. */
71
+ /**
72
+ * Error codes for categorizing session errors on the wire.
73
+ *
74
+ * @public
75
+ */
91
76
  export type SessionErrorCode = z.infer<typeof SessionErrorCodeSchema>;
92
- /** Zod schema for {@linkcode ClientEvent}. */
77
+ /** Zod schema for {@link ClientEvent}. */
93
78
  export declare const ClientEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
94
79
  type: z.ZodLiteral<"speech_started">;
95
80
  }, z.core.$strip>, z.ZodObject<{
@@ -128,12 +113,12 @@ export declare const ClientEventSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
128
113
  type: z.ZodLiteral<"error">;
129
114
  code: z.ZodEnum<{
130
115
  tool: "tool";
131
- audio: "audio";
116
+ connection: "connection";
132
117
  stt: "stt";
133
118
  llm: "llm";
134
119
  tts: "tts";
135
120
  protocol: "protocol";
136
- connection: "connection";
121
+ audio: "audio";
137
122
  internal: "internal";
138
123
  }>;
139
124
  message: z.ZodString;
@@ -163,12 +148,64 @@ export type ReadyConfig = {
163
148
  sampleRate: number;
164
149
  ttsSampleRate: number;
165
150
  };
151
+ /** Zod schema for server→client text messages. */
152
+ export declare const ServerMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
153
+ type: z.ZodLiteral<"config">;
154
+ audioFormat: z.ZodString;
155
+ sampleRate: z.ZodNumber;
156
+ ttsSampleRate: z.ZodNumber;
157
+ }, z.core.$strip>, z.ZodObject<{
158
+ type: z.ZodLiteral<"audio_done">;
159
+ }, z.core.$strip>, z.ZodObject<{
160
+ type: z.ZodLiteral<"speech_started">;
161
+ }, z.core.$strip>, z.ZodObject<{
162
+ type: z.ZodLiteral<"speech_stopped">;
163
+ }, z.core.$strip>, z.ZodObject<{
164
+ type: z.ZodLiteral<"transcript">;
165
+ text: z.ZodString;
166
+ isFinal: z.ZodBoolean;
167
+ turnOrder: z.ZodOptional<z.ZodNumber>;
168
+ }, z.core.$strip>, z.ZodObject<{
169
+ type: z.ZodLiteral<"turn">;
170
+ text: z.ZodString;
171
+ turnOrder: z.ZodOptional<z.ZodNumber>;
172
+ }, z.core.$strip>, z.ZodObject<{
173
+ type: z.ZodLiteral<"chat">;
174
+ text: z.ZodString;
175
+ }, z.core.$strip>, z.ZodObject<{
176
+ type: z.ZodLiteral<"chat_delta">;
177
+ text: z.ZodString;
178
+ }, z.core.$strip>, z.ZodObject<{
179
+ type: z.ZodLiteral<"tool_call_start">;
180
+ toolCallId: z.ZodString;
181
+ toolName: z.ZodString;
182
+ args: z.ZodRecord<z.ZodString, z.ZodUnknown>;
183
+ }, z.core.$strip>, z.ZodObject<{
184
+ type: z.ZodLiteral<"tool_call_done">;
185
+ toolCallId: z.ZodString;
186
+ result: z.ZodString;
187
+ }, z.core.$strip>, z.ZodObject<{
188
+ type: z.ZodLiteral<"tts_done">;
189
+ }, z.core.$strip>, z.ZodObject<{
190
+ type: z.ZodLiteral<"cancelled">;
191
+ }, z.core.$strip>, z.ZodObject<{
192
+ type: z.ZodLiteral<"reset">;
193
+ }, z.core.$strip>, z.ZodObject<{
194
+ type: z.ZodLiteral<"error">;
195
+ code: z.ZodEnum<{
196
+ tool: "tool";
197
+ connection: "connection";
198
+ stt: "stt";
199
+ llm: "llm";
200
+ tts: "tts";
201
+ protocol: "protocol";
202
+ audio: "audio";
203
+ internal: "internal";
204
+ }>;
205
+ message: z.ZodString;
206
+ }, z.core.$strip>], "type">;
166
207
  /** Server→client text messages (binary frames carry raw PCM16 audio). */
167
- export type ServerMessage = ({
168
- type: "config";
169
- } & ReadyConfig) | {
170
- type: "audio_done";
171
- } | ClientEvent;
208
+ export type ServerMessage = z.infer<typeof ServerMessageSchema>;
172
209
  /** Zod schema for client→server text messages. */
173
210
  export declare const ClientMessageSchema: z.ZodDiscriminatedUnion<[z.ZodObject<{
174
211
  type: z.ZodLiteral<"audio_ready">;
@@ -193,4 +230,3 @@ export type TurnConfig = {
193
230
  maxSteps?: number;
194
231
  activeTools?: string[];
195
232
  };
196
- //# sourceMappingURL=protocol.d.ts.map
@@ -0,0 +1,142 @@
1
+ import { z } from "zod";
2
+ //#region protocol.ts
3
+ /**
4
+ * WebSocket wire-format types shared by server and client.
5
+ *
6
+ * Note: this module is for internal use only and should not be used directly.
7
+ */
8
+ /**
9
+ * Default sample rate for speech-to-text audio in Hz.
10
+ *
11
+ * This is the sample rate expected by the STT provider (AssemblyAI).
12
+ */
13
+ const DEFAULT_STT_SAMPLE_RATE = 16e3;
14
+ /**
15
+ * Default sample rate for text-to-speech audio in Hz.
16
+ *
17
+ * This is the sample rate produced by the TTS provider.
18
+ */
19
+ const DEFAULT_TTS_SAMPLE_RATE = 24e3;
20
+ /**
21
+ * Audio codec identifier used in the wire protocol.
22
+ *
23
+ * All audio frames are 16-bit signed PCM, little-endian, mono.
24
+ */
25
+ const AUDIO_FORMAT = "pcm16";
26
+ /** Specification for binary audio frames exchanged over WebSocket. */
27
+ const AudioFrameSpec = {
28
+ format: AUDIO_FORMAT,
29
+ bitsPerSample: 16,
30
+ endianness: "little",
31
+ channels: 1,
32
+ bytesPerSample: 2
33
+ };
34
+ /** Zod schema for KV operation requests from the worker to the host. */
35
+ const KvRequestSchema = z.discriminatedUnion("op", [
36
+ z.object({
37
+ op: z.literal("get"),
38
+ key: z.string().min(1)
39
+ }),
40
+ z.object({
41
+ op: z.literal("set"),
42
+ key: z.string().min(1),
43
+ value: z.string(),
44
+ ttl: z.number().int().positive().optional()
45
+ }),
46
+ z.object({
47
+ op: z.literal("del"),
48
+ key: z.string().min(1)
49
+ }),
50
+ z.object({
51
+ op: z.literal("list"),
52
+ prefix: z.string(),
53
+ limit: z.number().int().positive().optional(),
54
+ reverse: z.boolean().optional()
55
+ }),
56
+ z.object({
57
+ op: z.literal("keys"),
58
+ pattern: z.string().optional()
59
+ })
60
+ ]);
61
+ /** Default timeout for agent lifecycle hooks (onConnect, onTurn, etc). */
62
+ const HOOK_TIMEOUT_MS = 5e3;
63
+ /** Default timeout for tool execution in the worker. */
64
+ const TOOL_EXECUTION_TIMEOUT_MS = 3e4;
65
+ /** Zod schema for session error codes. */
66
+ const SessionErrorCodeSchema = z.enum([
67
+ "stt",
68
+ "llm",
69
+ "tts",
70
+ "tool",
71
+ "protocol",
72
+ "connection",
73
+ "audio",
74
+ "internal"
75
+ ]);
76
+ /** Helper: simple event with only a type field. */
77
+ const ev = (t) => z.object({ type: z.literal(t) });
78
+ /** Helper: event with type + text. */
79
+ const textEv = (t) => z.object({
80
+ type: z.literal(t),
81
+ text: z.string()
82
+ });
83
+ const turnOrder = z.number().int().nonnegative().optional();
84
+ /** Zod schema for {@link ClientEvent}. */
85
+ const ClientEventSchema = z.discriminatedUnion("type", [
86
+ ev("speech_started"),
87
+ ev("speech_stopped"),
88
+ z.object({
89
+ type: z.literal("transcript"),
90
+ text: z.string(),
91
+ isFinal: z.boolean(),
92
+ turnOrder
93
+ }),
94
+ textEv("turn").extend({ turnOrder }),
95
+ textEv("chat"),
96
+ textEv("chat_delta"),
97
+ z.object({
98
+ type: z.literal("tool_call_start"),
99
+ toolCallId: z.string(),
100
+ toolName: z.string(),
101
+ args: z.record(z.string(), z.unknown())
102
+ }),
103
+ z.object({
104
+ type: z.literal("tool_call_done"),
105
+ toolCallId: z.string(),
106
+ result: z.string().max(4e3)
107
+ }),
108
+ ev("tts_done"),
109
+ ev("cancelled"),
110
+ ev("reset"),
111
+ z.object({
112
+ type: z.literal("error"),
113
+ code: SessionErrorCodeSchema,
114
+ message: z.string()
115
+ })
116
+ ]);
117
+ /** Zod schema for server→client text messages. */
118
+ const ServerMessageSchema = z.discriminatedUnion("type", [
119
+ z.object({
120
+ type: z.literal("config"),
121
+ audioFormat: z.string(),
122
+ sampleRate: z.number(),
123
+ ttsSampleRate: z.number()
124
+ }),
125
+ ev("audio_done"),
126
+ ...ClientEventSchema.options
127
+ ]);
128
+ /** Zod schema for client→server text messages. */
129
+ const ClientMessageSchema = z.discriminatedUnion("type", [
130
+ ev("audio_ready"),
131
+ ev("cancel"),
132
+ ev("reset"),
133
+ z.object({
134
+ type: z.literal("history"),
135
+ messages: z.array(z.object({
136
+ role: z.enum(["user", "assistant"]),
137
+ text: z.string().max(1e5)
138
+ })).max(200)
139
+ })
140
+ ]);
141
+ //#endregion
142
+ export { AUDIO_FORMAT, AudioFrameSpec, ClientEventSchema, ClientMessageSchema, DEFAULT_STT_SAMPLE_RATE, DEFAULT_TTS_SAMPLE_RATE, HOOK_TIMEOUT_MS, KvRequestSchema, ServerMessageSchema, SessionErrorCodeSchema, TOOL_EXECUTION_TIMEOUT_MS };
@@ -0,0 +1,18 @@
1
+ /** Structured context attached to log messages. */
2
+ export type LogContext = Record<string, unknown>;
3
+ /** Structured logger interface. Used by tests to suppress output. */
4
+ export type Logger = {
5
+ info(msg: string, ctx?: LogContext): void;
6
+ warn(msg: string, ctx?: LogContext): void;
7
+ error(msg: string, ctx?: LogContext): void;
8
+ debug(msg: string, ctx?: LogContext): void;
9
+ };
10
+ export declare const consoleLogger: Logger;
11
+ /** S2S endpoint configuration. */
12
+ export type S2SConfig = {
13
+ wssUrl: string;
14
+ inputSampleRate: number;
15
+ outputSampleRate: number;
16
+ };
17
+ /** Default S2S endpoint configuration. */
18
+ export declare const DEFAULT_S2S_CONFIG: S2SConfig;
@@ -0,0 +1,16 @@
1
+ import { DEFAULT_TTS_SAMPLE_RATE } from "./protocol.js";
2
+ //#region runtime.ts
3
+ const consoleLogger = {
4
+ info: (msg, ctx) => console.log(msg, ...ctx ? [ctx] : []),
5
+ warn: (msg, ctx) => console.warn(msg, ...ctx ? [ctx] : []),
6
+ error: (msg, ctx) => console.error(msg, ...ctx ? [ctx] : []),
7
+ debug: (msg, ctx) => console.debug(msg, ...ctx ? [ctx] : [])
8
+ };
9
+ /** Default S2S endpoint configuration. */
10
+ const DEFAULT_S2S_CONFIG = {
11
+ wssUrl: "wss://speech-to-speech.us.assemblyai.com/v1/realtime",
12
+ inputSampleRate: DEFAULT_TTS_SAMPLE_RATE,
13
+ outputSampleRate: DEFAULT_TTS_SAMPLE_RATE
14
+ };
15
+ //#endregion
16
+ export { DEFAULT_S2S_CONFIG, consoleLogger };