@alexkroman1/aai 0.10.4 → 0.11.1

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 (49) hide show
  1. package/dist/{constants-BbAOvKl_.js → constants-CpLN9WGY.js} +2 -4
  2. package/dist/{direct-executor-BfHrDdPL.js → direct-executor-DyY-Y4ZE.js} +102 -324
  3. package/dist/host/_run-code.d.ts +35 -0
  4. package/dist/host/_runtime-conformance.d.ts +55 -0
  5. package/dist/{_test-utils.d.ts → host/_test-utils.d.ts} +7 -4
  6. package/dist/{builtin-tools.d.ts → host/builtin-tools.d.ts} +3 -3
  7. package/dist/{direct-executor.d.ts → host/direct-executor.d.ts} +7 -7
  8. package/dist/{internal.d.ts → host/index.d.ts} +5 -6
  9. package/dist/{internal.js → host/index.js} +15 -57
  10. package/dist/{matchers.js → host/matchers.js} +2 -2
  11. package/dist/{server.d.ts → host/server.d.ts} +1 -17
  12. package/dist/{server.js → host/server.js} +25 -22
  13. package/dist/{session.d.ts → host/session.d.ts} +7 -7
  14. package/dist/{testing.d.ts → host/testing.d.ts} +3 -3
  15. package/dist/host/testing.js +2 -0
  16. package/dist/{unstorage-kv.d.ts → host/unstorage-kv.d.ts} +1 -1
  17. package/dist/{vite-plugin.js → host/vite-plugin.js} +1 -1
  18. package/dist/{ws-handler.d.ts → host/ws-handler.d.ts} +1 -1
  19. package/dist/index.d.ts +2 -2
  20. package/dist/index.js +1 -1
  21. package/dist/isolate/_utils.d.ts +7 -0
  22. package/dist/isolate/_utils.js +17 -0
  23. package/dist/{constants.d.ts → isolate/constants.d.ts} +0 -2
  24. package/dist/{hooks.js → isolate/hooks.js} +1 -1
  25. package/dist/isolate/index.d.ts +19 -0
  26. package/dist/isolate/index.js +8 -0
  27. package/dist/{kv.js → isolate/kv.js} +2 -2
  28. package/dist/{protocol.js → isolate/protocol.js} +2 -2
  29. package/dist/{types.js → isolate/types.js} +1 -1
  30. package/dist/system-prompt-u19j6xfA.js +166 -0
  31. package/dist/{testing-BonJtfHJ.js → testing-CNNg2-n-.js} +22 -8
  32. package/package.json +40 -36
  33. package/dist/_run-code.d.ts +0 -31
  34. package/dist/_runtime-conformance.d.ts +0 -64
  35. package/dist/_utils.d.ts +0 -21
  36. package/dist/_utils.js +0 -49
  37. package/dist/testing.js +0 -2
  38. package/dist/{_mock-ws.d.ts → host/_mock-ws.d.ts} +0 -0
  39. package/dist/{matchers.d.ts → host/matchers.d.ts} +0 -0
  40. package/dist/{runtime.d.ts → host/runtime.d.ts} +0 -0
  41. package/dist/{s2s.d.ts → host/s2s.d.ts} +0 -0
  42. package/dist/{vite-plugin.d.ts → host/vite-plugin.d.ts} +0 -0
  43. package/dist/{_internal-types.d.ts → isolate/_internal-types.d.ts} +0 -0
  44. package/dist/{hooks.d.ts → isolate/hooks.d.ts} +0 -0
  45. package/dist/{kv.d.ts → isolate/kv.d.ts} +0 -0
  46. package/dist/{memory-tools.d.ts → isolate/memory-tools.d.ts} +0 -0
  47. package/dist/{protocol.d.ts → isolate/protocol.d.ts} +3 -3
  48. /package/dist/{system-prompt.d.ts → isolate/system-prompt.d.ts} +0 -0
  49. /package/dist/{types.d.ts → isolate/types.d.ts} +0 -0
@@ -5,17 +5,17 @@
5
5
  * self-hosted servers and the platform sandbox. It wires up tool execution,
6
6
  * lifecycle hooks, and session management.
7
7
  */
8
- import { type ExecuteTool, type ToolSchema } from "./_internal-types.ts";
9
- import { type AgentHooks } from "./hooks.ts";
10
- import type { Kv } from "./kv.ts";
11
- import type { ClientSink } from "./protocol.ts";
12
- import { type ReadyConfig } from "./protocol.ts";
8
+ import { type ExecuteTool, type ToolSchema } from "../isolate/_internal-types.ts";
9
+ import { type AgentHooks } from "../isolate/hooks.ts";
10
+ import type { Kv } from "../isolate/kv.ts";
11
+ import type { ClientSink } from "../isolate/protocol.ts";
12
+ import { type ReadyConfig } from "../isolate/protocol.ts";
13
+ import type { AgentDef, Message, ToolDef } from "../isolate/types.ts";
13
14
  import type { Logger, S2SConfig } from "./runtime.ts";
14
15
  import type { CreateS2sWebSocket } from "./s2s.ts";
15
16
  import { type Session } from "./session.ts";
16
- import type { AgentDef, Message, ToolDef } from "./types.ts";
17
17
  import { type SessionWebSocket } from "./ws-handler.ts";
18
- export type { ExecuteTool } from "./_internal-types.ts";
18
+ export type { ExecuteTool } from "../isolate/_internal-types.ts";
19
19
  export type ExecuteToolCallOptions = {
20
20
  tool: ToolDef;
21
21
  env: Readonly<Record<string, string>>;
@@ -1,17 +1,16 @@
1
1
  /**
2
- * Internal barrel — re-exports all SDK internals for use by the platform
2
+ * Host barrel — re-exports all SDK internals for use by the platform
3
3
  * server (`aai-server`) and CLI. **Not a public API.**
4
4
  *
5
+ * Includes the full isolate-safe kernel plus host-only modules that
6
+ * depend on Node.js APIs (server, executor, S2S, etc.).
7
+ *
5
8
  * Consumer packages should import from the top-level `@alexkroman1/aai`
6
9
  * entry, `./server`, `./types`, `./kv`, `./protocol`, or `./testing`.
7
10
  */
8
- export * from "./_internal-types.ts";
11
+ export * from "../isolate/index.ts";
9
12
  export * from "./_runtime-conformance.ts";
10
- export * from "./_utils.ts";
11
- export * from "./constants.ts";
12
13
  export * from "./direct-executor.ts";
13
- export * from "./hooks.ts";
14
- export * from "./protocol.ts";
15
14
  export * from "./runtime.ts";
16
15
  export * from "./s2s.ts";
17
16
  export * from "./session.ts";
@@ -1,12 +1,15 @@
1
- import { defineTool } from "./types.js";
2
- import { _ as TOOL_EXECUTION_TIMEOUT_MS, a as DEFAULT_SHUTDOWN_TIMEOUT_MS, c as FETCH_TIMEOUT_MS, d as MAX_HTML_BYTES, f as MAX_PAGE_CHARS, g as RUN_CODE_TIMEOUT_MS, h as RUN_CODE_MEMORY_MB, i as DEFAULT_SESSION_START_TIMEOUT_MS, l as HOOK_TIMEOUT_MS, m as MAX_VALUE_SIZE, n as DEFAULT_IDLE_TIMEOUT_MS, o as DEFAULT_STT_SAMPLE_RATE, p as MAX_TOOL_RESULT_CHARS, r as DEFAULT_MAX_HISTORY, s as DEFAULT_TTS_SAMPLE_RATE, t as AGENT_CSP, u as MAX_GLOB_PATTERN_LENGTH } from "./constants-BbAOvKl_.js";
3
- import { _ as consoleLogger, a as _internals, c as buildSystemPrompt, d as AgentConfigSchema, f as EMPTY_PARAMS, g as DEFAULT_S2S_CONFIG, h as toAgentConfig, i as createUnstorageKv, l as connectS2s, m as agentToolsToSchemas, n as executeToolCall, o as buildCtx, p as ToolSchemaSchema, r as wireSessionSocket, s as createS2sSession, t as createRuntime, u as defaultCreateS2sWebSocket, v as jsonLogger } from "./direct-executor-BfHrDdPL.js";
4
- import { createSessionStateMap, errorDetail, errorMessage, isReadOnlyFsOp, toolError } from "./_utils.js";
5
- import { callResolveTurnConfig, createAgentHooks } from "./hooks.js";
6
- import { AUDIO_FORMAT, ClientEventSchema, ClientMessageSchema, KvRequestSchema, ReadyConfigSchema, ServerMessageSchema, SessionErrorCodeSchema, TurnConfigSchema, buildReadyConfig } from "./protocol.js";
1
+ import { BuiltinToolSchema, DEFAULT_GREETING, DEFAULT_INSTRUCTIONS, ToolChoiceSchema, defineAgent, defineTool, defineToolFactory } from "../isolate/types.js";
2
+ import { a as ToolSchemaSchema, i as EMPTY_PARAMS, n as memoryTools, o as agentToolsToSchemas, r as AgentConfigSchema, s as toAgentConfig, t as buildSystemPrompt } from "../system-prompt-u19j6xfA.js";
3
+ import { errorDetail, errorMessage, toolError } from "../isolate/_utils.js";
4
+ import { a as DEFAULT_SHUTDOWN_TIMEOUT_MS, c as FETCH_TIMEOUT_MS, d as MAX_HTML_BYTES, f as MAX_PAGE_CHARS, g as TOOL_EXECUTION_TIMEOUT_MS, h as RUN_CODE_TIMEOUT_MS, i as DEFAULT_SESSION_START_TIMEOUT_MS, l as HOOK_TIMEOUT_MS, m as MAX_VALUE_SIZE, n as DEFAULT_IDLE_TIMEOUT_MS, o as DEFAULT_STT_SAMPLE_RATE, p as MAX_TOOL_RESULT_CHARS, r as DEFAULT_MAX_HISTORY, s as DEFAULT_TTS_SAMPLE_RATE, t as AGENT_CSP, u as MAX_GLOB_PATTERN_LENGTH } from "../constants-CpLN9WGY.js";
5
+ import { callResolveTurnConfig, createAgentHooks } from "../isolate/hooks.js";
6
+ import { matchGlob, sortAndPaginate } from "../isolate/kv.js";
7
+ import { AUDIO_FORMAT, ClientEventSchema, ClientMessageSchema, KvRequestSchema, ReadyConfigSchema, ServerMessageSchema, SessionErrorCodeSchema, TurnConfigSchema, buildReadyConfig } from "../isolate/protocol.js";
8
+ import "../isolate/index.js";
9
+ import { a as _internals, c as connectS2s, d as consoleLogger, f as jsonLogger, i as createUnstorageKv, l as defaultCreateS2sWebSocket, n as executeToolCall, o as buildCtx, r as wireSessionSocket, s as createS2sSession, t as createRuntime, u as DEFAULT_S2S_CONFIG } from "../direct-executor-DyY-Y4ZE.js";
7
10
  import { z } from "zod";
8
11
  import { describe, expect, test } from "vitest";
9
- //#region _runtime-conformance.ts
12
+ //#region host/_runtime-conformance.ts
10
13
  /**
11
14
  * Shared runtime conformance tests.
12
15
  *
@@ -26,21 +29,17 @@ import { describe, expect, test } from "vitest";
26
29
  * });
27
30
  * ```
28
31
  *
29
- * @example Sandbox (integration test)
32
+ * @example Sandbox (integration test in aai-server)
30
33
  * ```ts
31
- * import { testRuntime, CONFORMANCE_AGENT_BUNDLE } from "@alexkroman1/aai/runtime-conformance";
34
+ * import { testRuntime } from "@alexkroman1/aai/host";
32
35
  *
33
36
  * testRuntime("sandbox", async () => {
34
- * // ... start isolate with CONFORMANCE_AGENT_BUNDLE
37
+ * // ... start isolate with a bundled agent
35
38
  * return { executeTool: buildExecuteTool(...), hooks: buildHookInvoker(...) };
36
39
  * });
37
40
  * ```
38
41
  */
39
- /**
40
- * Agent definition used by the conformance suite (direct executor path).
41
- *
42
- * Must be kept in sync with {@link CONFORMANCE_AGENT_BUNDLE}.
43
- */
42
+ /** Agent definition used by the conformance suite (direct executor path). */
44
43
  const CONFORMANCE_AGENT = {
45
44
  name: "conformance-test",
46
45
  instructions: "Conformance test agent.",
@@ -86,47 +85,6 @@ const CONFORMANCE_AGENT = {
86
85
  }
87
86
  };
88
87
  /**
89
- * JavaScript bundle equivalent of {@link CONFORMANCE_AGENT} for the sandbox
90
- * isolate path. Must be kept in sync with the AgentDef above.
91
- */
92
- const CONFORMANCE_AGENT_BUNDLE = `
93
- export default {
94
- name: "conformance-test",
95
- instructions: "Conformance test agent.",
96
- greeting: "Hello!",
97
- maxSteps: 5,
98
- state: () => ({ count: 0, lastTurn: "" }),
99
- tools: {
100
- echo: {
101
- description: "Echo input",
102
- execute(args) { return "echo:" + args.text; },
103
- },
104
- get_env: {
105
- description: "Get MY_VAR from env",
106
- execute(_args, ctx) { return ctx.env.MY_VAR ?? "missing"; },
107
- },
108
- get_state: {
109
- description: "Get session state",
110
- execute(_args, ctx) { return JSON.stringify(ctx.state); },
111
- },
112
- echo_messages: {
113
- description: "Return messages as JSON",
114
- execute(_args, ctx) { return JSON.stringify(ctx.messages); },
115
- },
116
- kv_roundtrip: {
117
- description: "KV set then get",
118
- async execute(args, ctx) {
119
- await ctx.kv.set("test-key", args.value);
120
- const result = await ctx.kv.get("test-key");
121
- return "stored:" + JSON.stringify(result);
122
- },
123
- },
124
- },
125
- onConnect: (ctx) => { ctx.state.count = 1; },
126
- onTurn: (text, ctx) => { ctx.state.lastTurn = text; },
127
- };
128
- `;
129
- /**
130
88
  * Run the runtime conformance test suite against a given runtime context.
131
89
  *
132
90
  * The `getContext` callback is invoked once per test to retrieve the
@@ -206,4 +164,4 @@ function testRuntime(label, getContext) {
206
164
  });
207
165
  }
208
166
  //#endregion
209
- export { AGENT_CSP, AUDIO_FORMAT, AgentConfigSchema, CONFORMANCE_AGENT, CONFORMANCE_AGENT_BUNDLE, ClientEventSchema, ClientMessageSchema, DEFAULT_IDLE_TIMEOUT_MS, DEFAULT_MAX_HISTORY, DEFAULT_S2S_CONFIG, DEFAULT_SESSION_START_TIMEOUT_MS, DEFAULT_SHUTDOWN_TIMEOUT_MS, DEFAULT_STT_SAMPLE_RATE, DEFAULT_TTS_SAMPLE_RATE, EMPTY_PARAMS, FETCH_TIMEOUT_MS, HOOK_TIMEOUT_MS, KvRequestSchema, MAX_GLOB_PATTERN_LENGTH, MAX_HTML_BYTES, MAX_PAGE_CHARS, MAX_TOOL_RESULT_CHARS, MAX_VALUE_SIZE, RUN_CODE_MEMORY_MB, RUN_CODE_TIMEOUT_MS, ReadyConfigSchema, ServerMessageSchema, SessionErrorCodeSchema, TOOL_EXECUTION_TIMEOUT_MS, ToolSchemaSchema, TurnConfigSchema, _internals, agentToolsToSchemas, buildCtx, buildReadyConfig, buildSystemPrompt, callResolveTurnConfig, connectS2s, consoleLogger, createAgentHooks, createRuntime, createS2sSession, createSessionStateMap, createUnstorageKv, defaultCreateS2sWebSocket, errorDetail, errorMessage, executeToolCall, isReadOnlyFsOp, jsonLogger, testRuntime, toAgentConfig, toolError, wireSessionSocket };
167
+ export { AGENT_CSP, AUDIO_FORMAT, AgentConfigSchema, BuiltinToolSchema, CONFORMANCE_AGENT, ClientEventSchema, ClientMessageSchema, DEFAULT_GREETING, DEFAULT_IDLE_TIMEOUT_MS, DEFAULT_INSTRUCTIONS, DEFAULT_MAX_HISTORY, DEFAULT_S2S_CONFIG, DEFAULT_SESSION_START_TIMEOUT_MS, DEFAULT_SHUTDOWN_TIMEOUT_MS, DEFAULT_STT_SAMPLE_RATE, DEFAULT_TTS_SAMPLE_RATE, EMPTY_PARAMS, FETCH_TIMEOUT_MS, HOOK_TIMEOUT_MS, KvRequestSchema, MAX_GLOB_PATTERN_LENGTH, MAX_HTML_BYTES, MAX_PAGE_CHARS, MAX_TOOL_RESULT_CHARS, MAX_VALUE_SIZE, RUN_CODE_TIMEOUT_MS, ReadyConfigSchema, ServerMessageSchema, SessionErrorCodeSchema, TOOL_EXECUTION_TIMEOUT_MS, ToolChoiceSchema, ToolSchemaSchema, TurnConfigSchema, _internals, agentToolsToSchemas, buildCtx, buildReadyConfig, buildSystemPrompt, callResolveTurnConfig, connectS2s, consoleLogger, createAgentHooks, createRuntime, createS2sSession, createUnstorageKv, defaultCreateS2sWebSocket, defineAgent, defineTool, defineTool as tool, defineToolFactory, errorDetail, errorMessage, executeToolCall, jsonLogger, matchGlob, memoryTools, sortAndPaginate, testRuntime, toAgentConfig, toolError, wireSessionSocket };
@@ -1,6 +1,6 @@
1
- import { n as TurnResult } from "./testing-BonJtfHJ.js";
1
+ import { n as TurnResult } from "../testing-CNNg2-n-.js";
2
2
  import { expect } from "vitest";
3
- //#region matchers.ts
3
+ //#region host/matchers.ts
4
4
  /**
5
5
  * Vitest custom matchers for AAI testing.
6
6
  *
@@ -4,8 +4,8 @@
4
4
  * {@link createServer} wraps a {@link Runtime} with an HTTP + WebSocket
5
5
  * server using only `node:http` and `ws` (no framework dependencies).
6
6
  */
7
+ import type { Kv } from "../isolate/kv.ts";
7
8
  import type { Runtime } from "./direct-executor.ts";
8
- import type { Kv } from "./kv.ts";
9
9
  import type { Logger } from "./runtime.ts";
10
10
  export { createRuntime, type Runtime, type RuntimeOptions } from "./direct-executor.ts";
11
11
  /**
@@ -29,20 +29,4 @@ export type AgentServer = {
29
29
  close(): Promise<void>;
30
30
  port: number | undefined;
31
31
  };
32
- /**
33
- * Create an HTTP + WebSocket server for self-hosted agent deployments.
34
- *
35
- * @example
36
- * ```ts
37
- * import { defineAgent } from "@alexkroman1/aai";
38
- * import { createRuntime, createServer } from "@alexkroman1/aai/server";
39
- *
40
- * const agent = defineAgent({ name: "my-agent" });
41
- * const runtime = createRuntime({ agent, env: process.env });
42
- * const server = createServer({ runtime, name: agent.name });
43
- * await server.listen(3000);
44
- * ```
45
- *
46
- * @public
47
- */
48
32
  export declare function createServer(options: ServerOptions): AgentServer;
@@ -1,10 +1,10 @@
1
- import { t as AGENT_CSP } from "./constants-BbAOvKl_.js";
2
- import { _ as consoleLogger, t as createRuntime } from "./direct-executor-BfHrDdPL.js";
1
+ import { t as AGENT_CSP } from "../constants-CpLN9WGY.js";
2
+ import { d as consoleLogger, t as createRuntime } from "../direct-executor-DyY-Y4ZE.js";
3
+ import { WebSocketServer } from "ws";
3
4
  import fs from "node:fs";
4
5
  import http from "node:http";
5
6
  import path from "node:path";
6
- import { WebSocketServer } from "ws";
7
- //#region server.ts
7
+ //#region host/server.ts
8
8
  /**
9
9
  * Self-hostable agent server.
10
10
  *
@@ -59,6 +59,26 @@ function serveStatic(dir, req, res) {
59
59
  *
60
60
  * @public
61
61
  */
62
+ function handleKvGet(kv, req, res) {
63
+ const key = new URL(req.url ?? "/", "http://localhost").searchParams.get("key");
64
+ if (!key) {
65
+ res.writeHead(400, { "Content-Type": "application/json" });
66
+ res.end(JSON.stringify({ error: "Missing key query parameter" }));
67
+ return;
68
+ }
69
+ kv.get(key).then((value) => {
70
+ if (value === null) {
71
+ res.writeHead(404, { "Content-Type": "application/json" });
72
+ res.end("null");
73
+ } else {
74
+ res.writeHead(200, { "Content-Type": "application/json" });
75
+ res.end(JSON.stringify(value));
76
+ }
77
+ }).catch(() => {
78
+ res.writeHead(500, { "Content-Type": "application/json" });
79
+ res.end(JSON.stringify({ error: "KV error" }));
80
+ });
81
+ }
62
82
  function createServer(options) {
63
83
  const { runtime, clientHtml, clientDir, logger = consoleLogger, kv } = options;
64
84
  const name = options.name ?? "agent";
@@ -78,24 +98,7 @@ function createServer(options) {
78
98
  return;
79
99
  }
80
100
  if (kv && method === "GET" && url === "/kv") {
81
- const key = new URL(req.url ?? "/", "http://localhost").searchParams.get("key");
82
- if (!key) {
83
- res.writeHead(400, { "Content-Type": "application/json" });
84
- res.end(JSON.stringify({ error: "Missing key query parameter" }));
85
- return;
86
- }
87
- kv.get(key).then((value) => {
88
- if (value === null) {
89
- res.writeHead(404, { "Content-Type": "application/json" });
90
- res.end("null");
91
- } else {
92
- res.writeHead(200, { "Content-Type": "application/json" });
93
- res.end(JSON.stringify(value));
94
- }
95
- }).catch(() => {
96
- res.writeHead(500, { "Content-Type": "application/json" });
97
- res.end(JSON.stringify({ error: "KV error" }));
98
- });
101
+ handleKvGet(kv, req, res);
99
102
  return;
100
103
  }
101
104
  if (clientDir && serveStatic(clientDir, req, res)) return;
@@ -1,10 +1,10 @@
1
1
  /** S2S session — relays audio between client and AssemblyAI S2S API. */
2
- import type { AgentConfig, ExecuteTool, ToolSchema } from "./_internal-types.ts";
3
- import type { AgentHookMap, AgentHooks } from "./hooks.ts";
4
- import type { ClientSink } from "./protocol.ts";
2
+ import type { AgentConfig, ExecuteTool, ToolSchema } from "../isolate/_internal-types.ts";
3
+ import type { AgentHookMap, AgentHooks } from "../isolate/hooks.ts";
4
+ import type { ClientSink } from "../isolate/protocol.ts";
5
+ import type { Message } from "../isolate/types.ts";
5
6
  import type { Logger, S2SConfig } from "./runtime.ts";
6
7
  import { type CreateS2sWebSocket, connectS2s, type S2sHandle } from "./s2s.ts";
7
- import type { Message } from "./types.ts";
8
8
  export type { S2sHandle } from "./s2s.ts";
9
9
  type PendingTool = {
10
10
  callId: string;
@@ -63,9 +63,9 @@ export declare function buildCtx(opts: {
63
63
  log: Logger;
64
64
  maxHistory?: number | undefined;
65
65
  }): S2sSessionCtx;
66
- export type { AgentHookMap, AgentHooks } from "./hooks.ts";
67
- export { callResolveTurnConfig, createAgentHooks } from "./hooks.ts";
68
- export { buildSystemPrompt } from "./system-prompt.ts";
66
+ export type { AgentHookMap, AgentHooks } from "../isolate/hooks.ts";
67
+ export { callResolveTurnConfig, createAgentHooks } from "../isolate/hooks.ts";
68
+ export { buildSystemPrompt } from "../isolate/system-prompt.ts";
69
69
  /**
70
70
  * A voice session managing the Speech-to-Speech connection for one client.
71
71
  *
@@ -35,11 +35,11 @@
35
35
  *
36
36
  * @packageDocumentation
37
37
  */
38
+ import type { Kv } from "../isolate/kv.ts";
39
+ import type { AgentDef, Message } from "../isolate/types.ts";
38
40
  import { type Runtime } from "./direct-executor.ts";
39
- import type { Kv } from "./kv.ts";
40
- import type { AgentDef, Message } from "./types.ts";
41
41
  export { installMockWebSocket, MockWebSocket } from "./_mock-ws.ts";
42
- export { flush } from "./_test-utils.ts";
42
+ export { flush, makeStubSession } from "./_test-utils.ts";
43
43
  /**
44
44
  * A single tool call recorded during a turn.
45
45
  *
@@ -0,0 +1,2 @@
1
+ import { a as makeStubSession, i as flush, n as TurnResult, o as MockWebSocket, r as createTestHarness, s as installMockWebSocket, t as TestHarness } from "../testing-CNNg2-n-.js";
2
+ export { MockWebSocket, TestHarness, TurnResult, createTestHarness, flush, installMockWebSocket, makeStubSession };
@@ -4,7 +4,7 @@
4
4
  * Works with any unstorage driver (memory, fs, S3/R2, etc.).
5
5
  */
6
6
  import { type Storage } from "unstorage";
7
- import type { Kv } from "./kv.ts";
7
+ import type { Kv } from "../isolate/kv.ts";
8
8
  /**
9
9
  * Options for creating an unstorage-backed KV store.
10
10
  */
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import fs from "node:fs/promises";
3
- //#region vite-plugin.ts
3
+ //#region host/vite-plugin.ts
4
4
  /**
5
5
  * Vite plugin for AAI agent development.
6
6
  *
@@ -3,7 +3,7 @@
3
3
  *
4
4
  * Audio validation is handled at the host transport layer (see server.ts).
5
5
  */
6
- import type { ClientSink, ReadyConfig } from "./protocol.ts";
6
+ import type { ClientSink, ReadyConfig } from "../isolate/protocol.ts";
7
7
  import type { Logger } from "./runtime.ts";
8
8
  import type { Session } from "./session.ts";
9
9
  /**
package/dist/index.d.ts CHANGED
@@ -19,5 +19,5 @@
19
19
  * });
20
20
  * ```
21
21
  */
22
- export type { Kv, KvEntry, KvListOptions } from "./kv.ts";
23
- export { type AgentDef, type AgentOptions, type BuiltinTool, defineAgent, defineTool, defineToolFactory, type HookContext, type Message, type ToolChoice, type ToolContext, type ToolDef, type ToolResultMap, tool, } from "./types.ts";
22
+ export type { Kv, KvEntry, KvListOptions } from "./isolate/kv.ts";
23
+ export { type AgentDef, type AgentOptions, type BuiltinTool, defineAgent, defineTool, defineToolFactory, type HookContext, type Message, type ToolChoice, type ToolContext, type ToolDef, type ToolResultMap, tool, } from "./isolate/types.ts";
package/dist/index.js CHANGED
@@ -1,2 +1,2 @@
1
- import { defineAgent, defineTool, defineToolFactory } from "./types.js";
1
+ import { defineAgent, defineTool, defineToolFactory } from "./isolate/types.js";
2
2
  export { defineAgent, defineTool, defineTool as tool, defineToolFactory };
@@ -0,0 +1,7 @@
1
+ /** Shared utility functions. */
2
+ /** Extract an error message from an unknown thrown value. */
3
+ export declare function errorMessage(err: unknown): string;
4
+ /** Extract a detailed error string (message + stack) for diagnostic logging. */
5
+ export declare function errorDetail(err: unknown): string;
6
+ /** Return a JSON error string for the LLM: `'{"error":"<message>"}'`. */
7
+ export declare function toolError(message: string): string;
@@ -0,0 +1,17 @@
1
+ //#region isolate/_utils.ts
2
+ /** Shared utility functions. */
3
+ /** Extract an error message from an unknown thrown value. */
4
+ function errorMessage(err) {
5
+ return err instanceof Error ? err.message : String(err);
6
+ }
7
+ /** Extract a detailed error string (message + stack) for diagnostic logging. */
8
+ function errorDetail(err) {
9
+ if (err instanceof Error) return err.stack ?? err.message;
10
+ return String(err);
11
+ }
12
+ /** Return a JSON error string for the LLM: `'{"error":"<message>"}'`. */
13
+ function toolError(message) {
14
+ return JSON.stringify({ error: message });
15
+ }
16
+ //#endregion
17
+ export { errorDetail, errorMessage, toolError };
@@ -34,8 +34,6 @@ export declare const MAX_VALUE_SIZE = 65536;
34
34
  export declare const MAX_GLOB_PATTERN_LENGTH = 1024;
35
35
  /** Maximum conversation messages to retain (sliding window). */
36
36
  export declare const DEFAULT_MAX_HISTORY = 200;
37
- /** Memory limit for run_code isolates (MB). */
38
- export declare const RUN_CODE_MEMORY_MB = 32;
39
37
  /**
40
38
  * Content-Security-Policy applied to agent UI pages (both self-hosted and
41
39
  * platform). Single source of truth — used by `secureHeaders` middleware
@@ -1,5 +1,5 @@
1
1
  import { createHooks } from "hookable";
2
- //#region hooks.ts
2
+ //#region isolate/hooks.ts
3
3
  /**
4
4
  * Hookable-based lifecycle hook system.
5
5
  *
@@ -0,0 +1,19 @@
1
+ /**
2
+ * Isolate-safe barrel — re-exports all SDK modules that are guaranteed to
3
+ * run inside secure-exec V8 isolates (no `node:*` dependencies).
4
+ *
5
+ * This directory is compiled under a restricted `tsconfig.json` that excludes
6
+ * `@types/node`. Any accidental `node:*` import becomes a type error.
7
+ *
8
+ * Host-only code (server, executor, S2S, etc.) lives at the package root
9
+ * and is re-exported via `./host`.
10
+ */
11
+ export * from "./_internal-types.ts";
12
+ export * from "./_utils.ts";
13
+ export * from "./constants.ts";
14
+ export * from "./hooks.ts";
15
+ export * from "./kv.ts";
16
+ export * from "./memory-tools.ts";
17
+ export * from "./protocol.ts";
18
+ export * from "./system-prompt.ts";
19
+ export * from "./types.ts";
@@ -0,0 +1,8 @@
1
+ import { BuiltinToolSchema, DEFAULT_GREETING, DEFAULT_INSTRUCTIONS, ToolChoiceSchema, defineAgent, defineTool, defineToolFactory } from "./types.js";
2
+ import { a as ToolSchemaSchema, i as EMPTY_PARAMS, n as memoryTools, o as agentToolsToSchemas, r as AgentConfigSchema, s as toAgentConfig, t as buildSystemPrompt } from "../system-prompt-u19j6xfA.js";
3
+ import { errorDetail, errorMessage, toolError } from "./_utils.js";
4
+ import { a as DEFAULT_SHUTDOWN_TIMEOUT_MS, c as FETCH_TIMEOUT_MS, d as MAX_HTML_BYTES, f as MAX_PAGE_CHARS, g as TOOL_EXECUTION_TIMEOUT_MS, h as RUN_CODE_TIMEOUT_MS, i as DEFAULT_SESSION_START_TIMEOUT_MS, l as HOOK_TIMEOUT_MS, m as MAX_VALUE_SIZE, n as DEFAULT_IDLE_TIMEOUT_MS, o as DEFAULT_STT_SAMPLE_RATE, p as MAX_TOOL_RESULT_CHARS, r as DEFAULT_MAX_HISTORY, s as DEFAULT_TTS_SAMPLE_RATE, t as AGENT_CSP, u as MAX_GLOB_PATTERN_LENGTH } from "../constants-CpLN9WGY.js";
5
+ import { callResolveTurnConfig, createAgentHooks } from "./hooks.js";
6
+ import { matchGlob, sortAndPaginate } from "./kv.js";
7
+ import { AUDIO_FORMAT, ClientEventSchema, ClientMessageSchema, KvRequestSchema, ReadyConfigSchema, ServerMessageSchema, SessionErrorCodeSchema, TurnConfigSchema, buildReadyConfig } from "./protocol.js";
8
+ export { AGENT_CSP, AUDIO_FORMAT, AgentConfigSchema, BuiltinToolSchema, ClientEventSchema, ClientMessageSchema, DEFAULT_GREETING, DEFAULT_IDLE_TIMEOUT_MS, DEFAULT_INSTRUCTIONS, DEFAULT_MAX_HISTORY, DEFAULT_SESSION_START_TIMEOUT_MS, DEFAULT_SHUTDOWN_TIMEOUT_MS, DEFAULT_STT_SAMPLE_RATE, DEFAULT_TTS_SAMPLE_RATE, EMPTY_PARAMS, FETCH_TIMEOUT_MS, HOOK_TIMEOUT_MS, KvRequestSchema, MAX_GLOB_PATTERN_LENGTH, MAX_HTML_BYTES, MAX_PAGE_CHARS, MAX_TOOL_RESULT_CHARS, MAX_VALUE_SIZE, RUN_CODE_TIMEOUT_MS, ReadyConfigSchema, ServerMessageSchema, SessionErrorCodeSchema, TOOL_EXECUTION_TIMEOUT_MS, ToolChoiceSchema, ToolSchemaSchema, TurnConfigSchema, agentToolsToSchemas, buildReadyConfig, buildSystemPrompt, callResolveTurnConfig, createAgentHooks, defineAgent, defineTool, defineTool as tool, defineToolFactory, errorDetail, errorMessage, matchGlob, memoryTools, sortAndPaginate, toAgentConfig, toolError };
@@ -1,5 +1,5 @@
1
- import { m as MAX_VALUE_SIZE, u as MAX_GLOB_PATTERN_LENGTH } from "./constants-BbAOvKl_.js";
2
- //#region kv.ts
1
+ import { m as MAX_VALUE_SIZE, u as MAX_GLOB_PATTERN_LENGTH } from "../constants-CpLN9WGY.js";
2
+ //#region isolate/kv.ts
3
3
  /**
4
4
  * Key-value storage interface and shared utilities.
5
5
  */
@@ -1,6 +1,6 @@
1
- import { p as MAX_TOOL_RESULT_CHARS } from "./constants-BbAOvKl_.js";
1
+ import { p as MAX_TOOL_RESULT_CHARS } from "../constants-CpLN9WGY.js";
2
2
  import { z } from "zod";
3
- //#region protocol.ts
3
+ //#region isolate/protocol.ts
4
4
  /**
5
5
  * WebSocket wire-format types shared by server and client.
6
6
  *
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- //#region types.ts
2
+ //#region isolate/types.ts
3
3
  /**
4
4
  * Core type definitions for the AAI agent SDK.
5
5
  */
@@ -0,0 +1,166 @@
1
+ import { BuiltinToolSchema, DEFAULT_INSTRUCTIONS, ToolChoiceSchema, defineTool } from "./isolate/types.js";
2
+ import { z } from "zod";
3
+ //#region isolate/_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
+ //#region isolate/memory-tools.ts
62
+ /**
63
+ * KV-backed memory tools for agent persistent state.
64
+ */
65
+ /**
66
+ * Returns a standard set of KV-backed memory tools: `save_memory`,
67
+ * `recall_memory`, `list_memories`, and `forget_memory`.
68
+ *
69
+ * Spread the result into your agent's `tools` record.
70
+ *
71
+ * @example
72
+ * ```ts
73
+ * import { defineAgent, memoryTools } from "aai";
74
+ *
75
+ * export default defineAgent({
76
+ * name: "My Agent",
77
+ * tools: { ...memoryTools() },
78
+ * });
79
+ * ```
80
+ *
81
+ * @returns A record with four tool definitions: `save_memory`, `recall_memory`,
82
+ * `list_memories`, and `forget_memory`.
83
+ * @public
84
+ */
85
+ function memoryTools() {
86
+ return {
87
+ save_memory: defineTool({
88
+ description: "Save a piece of information to persistent memory. Use a descriptive key like 'user:name' or 'project:status'.",
89
+ parameters: z.object({
90
+ key: z.string().describe("A descriptive key for this memory (e.g. 'user:name', 'preference:color')"),
91
+ value: z.string().describe("The information to remember")
92
+ }),
93
+ execute: async ({ key, value }, ctx) => {
94
+ await ctx.kv.set(key, value);
95
+ return { saved: key };
96
+ }
97
+ }),
98
+ recall_memory: defineTool({
99
+ description: "Retrieve a previously saved memory by its key.",
100
+ parameters: z.object({ key: z.string().describe("The key to look up") }),
101
+ execute: async ({ key }, ctx) => {
102
+ const value = await ctx.kv.get(key);
103
+ if (value === null) return {
104
+ found: false,
105
+ key
106
+ };
107
+ return {
108
+ found: true,
109
+ key,
110
+ value
111
+ };
112
+ }
113
+ }),
114
+ list_memories: defineTool({
115
+ description: "List all saved memory keys, optionally filtered by a prefix (e.g. 'user:').",
116
+ parameters: z.object({ prefix: z.string().describe("Prefix to filter keys (e.g. 'user:'). Use empty string for all.").optional() }),
117
+ execute: async ({ prefix }, ctx) => {
118
+ const entries = await ctx.kv.list(prefix ?? "");
119
+ return {
120
+ count: entries.length,
121
+ keys: entries.map((e) => e.key)
122
+ };
123
+ }
124
+ }),
125
+ forget_memory: defineTool({
126
+ description: "Delete a previously saved memory by its key.",
127
+ parameters: z.object({ key: z.string().describe("The key to delete") }),
128
+ execute: async ({ key }, ctx) => {
129
+ await ctx.kv.delete(key);
130
+ return { deleted: key };
131
+ }
132
+ })
133
+ };
134
+ }
135
+ //#endregion
136
+ //#region isolate/system-prompt.ts
137
+ function getFormattedDate() {
138
+ return (/* @__PURE__ */ new Date()).toLocaleDateString("en-US", {
139
+ weekday: "long",
140
+ year: "numeric",
141
+ month: "long",
142
+ day: "numeric"
143
+ });
144
+ }
145
+ const VOICE_RULES = "\n\nCRITICAL OUTPUT RULES — you MUST follow these for EVERY response:\nYour response will be spoken aloud by a TTS system and displayed as plain text.\n- NEVER use markdown: no **, no *, no _, no #, no `, no [](), no ---\n- NEVER use bullet points (-, *, •) or numbered lists (1., 2.)\n- NEVER use code blocks or inline code\n- NEVER mention tools, search, APIs, or technical failures to the user. If a tool returns no results, just answer naturally without explaining why.\n- Write exactly as you would say it out loud to a friend\n- Use short conversational sentences. To list things, say \"First,\" \"Next,\" \"Finally,\"\n- Keep responses concise — 1 to 3 sentences max";
146
+ /**
147
+ * Build the system prompt sent to the LLM from the agent configuration.
148
+ *
149
+ * Assembles the default instructions, today's date, agent-specific instructions,
150
+ * and optional sections for tool usage preamble and voice output rules.
151
+ *
152
+ * @param config - The serializable agent configuration (name, instructions, etc.).
153
+ * @param opts.hasTools - When `true`, appends a preamble instructing the LLM to
154
+ * speak a brief phrase before each tool call to fill silence.
155
+ * @param opts.voice - When `true`, appends strict voice-specific output rules
156
+ * (no markdown, no bullet points, conversational tone, concise responses).
157
+ * @returns The assembled system prompt string.
158
+ */
159
+ function buildSystemPrompt(config, opts) {
160
+ const { hasTools } = opts;
161
+ const agentInstructions = config.instructions && config.instructions !== DEFAULT_INSTRUCTIONS ? `\n\nAgent-Specific Instructions:\n${config.instructions}` : "";
162
+ const toolPreamble = hasTools ? "\n\nWhen you decide to use a tool, ALWAYS say a brief natural phrase BEFORE the tool call (e.g. \"Let me look that up\" or \"One moment while I check\"). This fills silence while the tool executes. Keep preambles to one short sentence." : "";
163
+ return DEFAULT_INSTRUCTIONS + `\n\nToday's date is ${getFormattedDate()}.` + agentInstructions + toolPreamble + (opts.voice ? VOICE_RULES : "");
164
+ }
165
+ //#endregion
166
+ export { ToolSchemaSchema as a, EMPTY_PARAMS as i, memoryTools as n, agentToolsToSchemas as o, AgentConfigSchema as r, toAgentConfig as s, buildSystemPrompt as t };