@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
@@ -1,10 +1,10 @@
1
1
  /**
2
2
  * Vector store interface and in-memory implementation.
3
- *
4
- * @module
5
3
  */
6
4
  /**
7
5
  * A single vector search result entry.
6
+ *
7
+ * @public
8
8
  */
9
9
  export type VectorEntry = {
10
10
  /** The unique identifier for this entry. */
@@ -19,8 +19,8 @@ export type VectorEntry = {
19
19
  /**
20
20
  * Async vector store interface used by agents.
21
21
  *
22
- * Agents access the vector store via {@linkcode ToolContext.vector} or
23
- * {@linkcode HookContext.vector}. Backed by Upstash Vector with built-in
22
+ * Agents access the vector store via `ToolContext.vector` or
23
+ * `HookContext.vector`. Backed by Upstash Vector with built-in
24
24
  * embeddings — raw text is sent and vectorized server-side.
25
25
  *
26
26
  * @example
@@ -35,6 +35,8 @@ export type VectorEntry = {
35
35
  * },
36
36
  * };
37
37
  * ```
38
+ *
39
+ * @public
38
40
  */
39
41
  export type VectorStore = {
40
42
  /**
@@ -42,9 +44,9 @@ export type VectorStore = {
42
44
  *
43
45
  * The text is automatically embedded by the server's vector database.
44
46
  *
45
- * @param id Unique identifier for this entry.
46
- * @param data The text content to store and embed.
47
- * @param metadata Optional metadata to store alongside the vector.
47
+ * @param id - Unique identifier for this entry.
48
+ * @param data - The text content to store and embed.
49
+ * @param metadata - Optional metadata to store alongside the vector.
48
50
  */
49
51
  upsert(id: string, data: string, metadata?: Record<string, unknown>): Promise<void>;
50
52
  /**
@@ -52,11 +54,9 @@ export type VectorStore = {
52
54
  *
53
55
  * Returns the most similar entries ranked by score.
54
56
  *
55
- * @param text The query text to search for.
56
- * @param options Optional query parameters.
57
- * @param options.topK Maximum number of results (default: 10).
58
- * @param options.filter Metadata filter expression.
59
- * @returns An array of matching {@linkcode VectorEntry} objects.
57
+ * @param text - The query text to search for.
58
+ * @param options - Optional query parameters. `topK` sets the maximum number of results (default: 10). `filter` is a metadata filter expression.
59
+ * @returns An array of matching {@link VectorEntry} objects.
60
60
  */
61
61
  query(text: string, options?: {
62
62
  topK?: number;
@@ -65,7 +65,7 @@ export type VectorStore = {
65
65
  /**
66
66
  * Remove entries by ID.
67
67
  *
68
- * @param ids A single ID or array of IDs to remove.
68
+ * @param ids - A single ID or array of IDs to remove.
69
69
  */
70
70
  remove(ids: string | string[]): Promise<void>;
71
71
  };
@@ -75,7 +75,7 @@ export type VectorStore = {
75
75
  * Uses brute-force substring matching instead of real vector similarity.
76
76
  * Good enough for testing the plumbing but not for production use.
77
77
  *
78
- * @returns A {@linkcode VectorStore} instance backed by in-memory storage.
78
+ * @returns A {@link VectorStore} instance backed by in-memory storage.
79
79
  *
80
80
  * @example
81
81
  * ```ts
@@ -87,4 +87,3 @@ export type VectorStore = {
87
87
  * ```
88
88
  */
89
89
  export declare function createMemoryVectorStore(): VectorStore;
90
- //# sourceMappingURL=vector.d.ts.map
package/dist/vector.js ADDED
@@ -0,0 +1,56 @@
1
+ //#region vector.ts
2
+ /**
3
+ * Create an in-memory vector store for testing and local development.
4
+ *
5
+ * Uses brute-force substring matching instead of real vector similarity.
6
+ * Good enough for testing the plumbing but not for production use.
7
+ *
8
+ * @returns A {@link VectorStore} instance backed by in-memory storage.
9
+ *
10
+ * @example
11
+ * ```ts
12
+ * import { createMemoryVectorStore } from "aai";
13
+ *
14
+ * const vector = createMemoryVectorStore();
15
+ * await vector.upsert("doc-1", "The capital of France is Paris.");
16
+ * const results = await vector.query("France capital");
17
+ * ```
18
+ */
19
+ function createMemoryVectorStore() {
20
+ const store = /* @__PURE__ */ new Map();
21
+ return {
22
+ upsert(id, data, metadata) {
23
+ store.set(id, {
24
+ data,
25
+ metadata
26
+ });
27
+ return Promise.resolve();
28
+ },
29
+ async query(text, options) {
30
+ const topK = options?.topK ?? 10;
31
+ const words = text.toLowerCase().split(/\s+/).filter(Boolean);
32
+ const results = [];
33
+ let i = 0;
34
+ for (const [id, entry] of store) {
35
+ if (++i % 500 === 0) await new Promise((r) => setTimeout(r, 0));
36
+ const data = entry.data.toLowerCase();
37
+ const matches = words.filter((w) => data.includes(w)).length;
38
+ if (matches > 0) results.push({
39
+ id,
40
+ score: matches / Math.max(words.length, 1),
41
+ data: entry.data,
42
+ metadata: entry.metadata
43
+ });
44
+ }
45
+ results.sort((a, b) => b.score - a.score);
46
+ return results.slice(0, topK);
47
+ },
48
+ remove(ids) {
49
+ const idArray = Array.isArray(ids) ? ids : [ids];
50
+ for (const id of idArray) store.delete(id);
51
+ return Promise.resolve();
52
+ }
53
+ };
54
+ }
55
+ //#endregion
56
+ export { createMemoryVectorStore };
@@ -1,7 +1,5 @@
1
1
  /**
2
2
  * Worker entry point — shared tool execution logic.
3
- *
4
- * @module
5
3
  */
6
4
  import type { Kv } from "./kv.ts";
7
5
  import type { Message, ToolDef } from "./types.ts";
@@ -16,7 +14,7 @@ import type { VectorStore } from "./vector.ts";
16
14
  * @returns The tool's string result, or an error message string.
17
15
  */
18
16
  export type ExecuteTool = (name: string, args: Readonly<Record<string, unknown>>, sessionId?: string, messages?: readonly Message[]) => Promise<string>;
19
- /** Options for {@linkcode executeToolCall}. */
17
+ /** Options for {@link executeToolCall}. */
20
18
  export type ExecuteToolCallOptions = {
21
19
  tool: ToolDef;
22
20
  env: Readonly<Record<string, string>>;
@@ -29,7 +27,7 @@ export type ExecuteToolCallOptions = {
29
27
  * Execute a tool call with argument validation and error handling.
30
28
  *
31
29
  * Validates the provided arguments against the tool's Zod parameter schema,
32
- * constructs a {@linkcode ToolContext}, invokes the tool's `execute` function,
30
+ * constructs a {@link ToolContext}, invokes the tool's `execute` function,
33
31
  * and serializes the result to a string. Errors are caught and returned as
34
32
  * `"Error: ..."` strings rather than thrown.
35
33
  *
@@ -39,4 +37,3 @@ export type ExecuteToolCallOptions = {
39
37
  * @returns The tool's result serialized as a string, or an error message.
40
38
  */
41
39
  export declare function executeToolCall(name: string, args: Readonly<Record<string, unknown>>, options: ExecuteToolCallOptions): Promise<string>;
42
- //# sourceMappingURL=worker_entry.d.ts.map
@@ -0,0 +1,59 @@
1
+ import { EMPTY_PARAMS } from "./_internal-types.js";
2
+ import { errorMessage } from "./_utils.js";
3
+ import { TOOL_EXECUTION_TIMEOUT_MS } from "./protocol.js";
4
+ //#region worker-entry.ts
5
+ /** Yield to the event loop so pending I/O (e.g. WebSocket frames) can be processed. */
6
+ const yieldTick = () => new Promise((r) => setTimeout(r, 0));
7
+ function buildToolContext(opts) {
8
+ const { env, state, kv, vector, messages } = opts;
9
+ return {
10
+ env: { ...env },
11
+ state: state ?? {},
12
+ get kv() {
13
+ if (!kv) throw new Error("KV not available");
14
+ return kv;
15
+ },
16
+ get vector() {
17
+ if (!vector) throw new Error("Vector store not available");
18
+ return vector;
19
+ },
20
+ messages: messages ?? []
21
+ };
22
+ }
23
+ /**
24
+ * Execute a tool call with argument validation and error handling.
25
+ *
26
+ * Validates the provided arguments against the tool's Zod parameter schema,
27
+ * constructs a {@link ToolContext}, invokes the tool's `execute` function,
28
+ * and serializes the result to a string. Errors are caught and returned as
29
+ * `"Error: ..."` strings rather than thrown.
30
+ *
31
+ * @param name - The name of the tool being invoked.
32
+ * @param args - Raw arguments from the LLM to validate and pass to the tool.
33
+ * @param options - Tool definition, environment, and optional context.
34
+ * @returns The tool's result serialized as a string, or an error message.
35
+ */
36
+ async function executeToolCall(name, args, options) {
37
+ const { tool } = options;
38
+ const parsed = (tool.parameters ?? EMPTY_PARAMS).safeParse(args);
39
+ if (!parsed.success) return `Error: Invalid arguments for tool "${name}": ${(parsed.error?.issues ?? []).map((i) => `${i.path.map(String).join(".")}: ${i.message}`).join(", ")}`;
40
+ let timer;
41
+ try {
42
+ const ctx = buildToolContext(options);
43
+ await yieldTick();
44
+ const timeout = new Promise((_, reject) => {
45
+ timer = setTimeout(() => reject(/* @__PURE__ */ new Error(`Tool "${name}" timed out after ${TOOL_EXECUTION_TIMEOUT_MS}ms`)), TOOL_EXECUTION_TIMEOUT_MS);
46
+ });
47
+ const result = await Promise.race([Promise.resolve(tool.execute(parsed.data, ctx)), timeout]);
48
+ await yieldTick();
49
+ if (result == null) return "null";
50
+ return typeof result === "string" ? result : JSON.stringify(result);
51
+ } catch (err) {
52
+ console.warn(`[tool-executor] Tool execution failed: ${name}`, err);
53
+ return `Error: ${errorMessage(err)}`;
54
+ } finally {
55
+ clearTimeout(timer);
56
+ }
57
+ }
58
+ //#endregion
59
+ export { executeToolCall };
@@ -1,24 +1,27 @@
1
1
  /**
2
2
  * WebSocket session lifecycle handler.
3
3
  *
4
- * Cross-runtime: accepts a Logger parameter instead of importing `@std/log`.
5
4
  * Audio validation is handled at the host transport layer (see host.ts).
6
- *
7
- * @module
8
5
  */
9
6
  import type { ClientSink, ReadyConfig } from "./protocol.ts";
10
7
  import type { Logger } from "./runtime.ts";
11
8
  import type { Session } from "./session.ts";
12
9
  /**
13
- * Minimal WebSocket interface accepted by {@linkcode wireSessionSocket}.
10
+ * Minimal WebSocket interface accepted by {@link wireSessionSocket}.
14
11
  *
15
- * Satisfied by the standard `WebSocket`, `BridgedWebSocket` (capnweb),
16
- * and the `ws` npm package's WebSocket.
12
+ * Satisfied by the standard `WebSocket` and the `ws` npm package's WebSocket.
17
13
  */
18
14
  export type SessionWebSocket = {
19
15
  readonly readyState: number;
20
16
  send(data: string | ArrayBuffer | Uint8Array): void;
21
- addEventListener(type: string, listener: EventListenerOrEventListenerObject): void;
17
+ addEventListener(type: "open", listener: () => void): void;
18
+ addEventListener(type: "message", listener: (event: {
19
+ data: unknown;
20
+ }) => void): void;
21
+ addEventListener(type: "close", listener: () => void): void;
22
+ addEventListener(type: "error", listener: (event: {
23
+ message?: string;
24
+ }) => void): void;
22
25
  };
23
26
  /** Options for wiring a WebSocket to a session. */
24
27
  export type WsSessionOptions = {
@@ -47,4 +50,3 @@ export type WsSessionOptions = {
47
50
  * 3. If reconnecting → client sends `{ type: "history", messages: [...] }`
48
51
  */
49
52
  export declare function wireSessionSocket(ws: SessionWebSocket, opts: WsSessionOptions): void;
50
- //# sourceMappingURL=ws_handler.d.ts.map
@@ -0,0 +1,155 @@
1
+ import { errorMessage } from "./_utils.js";
2
+ import { ClientMessageSchema } from "./protocol.js";
3
+ import { consoleLogger } from "./runtime.js";
4
+ //#region ws-handler.ts
5
+ /**
6
+ * WebSocket session lifecycle handler.
7
+ *
8
+ * Audio validation is handled at the host transport layer (see host.ts).
9
+ */
10
+ /**
11
+ * Creates a {@link ClientSink} backed by a plain WebSocket.
12
+ *
13
+ * Text events are sent as JSON text frames; audio chunks are sent as
14
+ * binary frames (zero-copy).
15
+ */
16
+ function createClientSink(ws) {
17
+ /** Send data over ws, tolerating races where the socket closes between readyState check and send. */
18
+ function safeSend(data) {
19
+ try {
20
+ if (ws.readyState === 1) ws.send(data);
21
+ } catch {}
22
+ }
23
+ return {
24
+ get open() {
25
+ return ws.readyState === 1;
26
+ },
27
+ event(e) {
28
+ safeSend(JSON.stringify(e));
29
+ },
30
+ playAudioChunk(chunk) {
31
+ safeSend(chunk);
32
+ },
33
+ playAudioDone() {
34
+ safeSend(JSON.stringify({ type: "audio_done" }));
35
+ }
36
+ };
37
+ }
38
+ function handleBinaryAudio(data, session) {
39
+ if (data instanceof Uint8Array) {
40
+ session.onAudio(data);
41
+ return true;
42
+ }
43
+ if (data instanceof ArrayBuffer) {
44
+ session.onAudio(new Uint8Array(data));
45
+ return true;
46
+ }
47
+ return false;
48
+ }
49
+ function handleTextMessage(data, session, log, ctx, sid) {
50
+ if (typeof data !== "string") return;
51
+ let json;
52
+ try {
53
+ json = JSON.parse(data);
54
+ } catch {
55
+ log.warn("Invalid JSON from client", {
56
+ ...ctx,
57
+ sid
58
+ });
59
+ return;
60
+ }
61
+ const parsed = ClientMessageSchema.safeParse(json);
62
+ if (!parsed.success) {
63
+ log.warn("Invalid client message", {
64
+ ...ctx,
65
+ sid,
66
+ error: parsed.error.message
67
+ });
68
+ return;
69
+ }
70
+ const msg = parsed.data;
71
+ switch (msg.type) {
72
+ case "audio_ready":
73
+ session.onAudioReady();
74
+ break;
75
+ case "cancel":
76
+ session.onCancel();
77
+ break;
78
+ case "reset":
79
+ session.onReset();
80
+ break;
81
+ case "history":
82
+ session.onHistory(msg.messages);
83
+ break;
84
+ }
85
+ }
86
+ /**
87
+ * Attaches session lifecycle handlers to a native WebSocket using
88
+ * plain JSON text frames and binary audio frames.
89
+ *
90
+ * Connection flow:
91
+ * 1. WebSocket opens → server sends `{ type: "config", ...ReadyConfig }`
92
+ * 2. Client sets up audio → sends `{ type: "audio_ready" }`
93
+ * 3. If reconnecting → client sends `{ type: "history", messages: [...] }`
94
+ */
95
+ function wireSessionSocket(ws, opts) {
96
+ const { sessions, logger: log = consoleLogger } = opts;
97
+ const sessionId = crypto.randomUUID();
98
+ const sid = sessionId.slice(0, 8);
99
+ const ctx = opts.logContext ?? {};
100
+ let session = null;
101
+ function onOpen() {
102
+ opts.onOpen?.();
103
+ log.info("Session connected", {
104
+ ...ctx,
105
+ sid
106
+ });
107
+ const client = createClientSink(ws);
108
+ session = opts.createSession(sessionId, client);
109
+ sessions.set(sessionId, session);
110
+ ws.send(JSON.stringify({
111
+ type: "config",
112
+ ...opts.readyConfig
113
+ }));
114
+ session.start().then(() => {
115
+ log.info("Session ready", {
116
+ ...ctx,
117
+ sid
118
+ });
119
+ }).catch((err) => {
120
+ log.error("Session start failed", {
121
+ ...ctx,
122
+ sid,
123
+ error: errorMessage(err)
124
+ });
125
+ });
126
+ }
127
+ if (ws.readyState === 1) onOpen();
128
+ else ws.addEventListener("open", onOpen);
129
+ ws.addEventListener("message", (event) => {
130
+ if (!session) return;
131
+ const { data } = event;
132
+ if (handleBinaryAudio(data, session)) return;
133
+ handleTextMessage(data, session, log, ctx, sid);
134
+ });
135
+ ws.addEventListener("close", () => {
136
+ log.info("Session disconnected", {
137
+ ...ctx,
138
+ sid
139
+ });
140
+ if (session) session.stop().finally(() => {
141
+ sessions.delete(sessionId);
142
+ });
143
+ opts.onClose?.();
144
+ });
145
+ ws.addEventListener("error", (ev) => {
146
+ const msg = typeof ev.message === "string" ? ev.message : "WebSocket error";
147
+ log.error("WebSocket error", {
148
+ ...ctx,
149
+ sid,
150
+ error: msg
151
+ });
152
+ });
153
+ }
154
+ //#endregion
155
+ export { wireSessionSocket };