@alexkroman1/aai 0.11.0 → 0.12.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.
- package/dist/{direct-executor-DAGCZOAN.js → direct-executor-ZUU0Ke4j.js} +146 -276
- package/dist/{_run-code.d.ts → host/_run-code.d.ts} +1 -1
- package/dist/{_runtime-conformance.d.ts → host/_runtime-conformance.d.ts} +4 -4
- package/dist/{_test-utils.d.ts → host/_test-utils.d.ts} +3 -3
- package/dist/{builtin-tools.d.ts → host/builtin-tools.d.ts} +2 -3
- package/dist/{direct-executor.d.ts → host/direct-executor.d.ts} +7 -7
- package/dist/{internal.d.ts → host/index.d.ts} +5 -6
- package/dist/{internal.js → host/index.js} +10 -9
- package/dist/{matchers.js → host/matchers.js} +2 -2
- package/dist/{server.d.ts → host/server.d.ts} +1 -17
- package/dist/{server.js → host/server.js} +37 -28
- package/dist/{session.d.ts → host/session.d.ts} +7 -7
- package/dist/{testing.d.ts → host/testing.d.ts} +2 -2
- package/dist/{testing.js → host/testing.js} +1 -1
- package/dist/{unstorage-kv.d.ts → host/unstorage-kv.d.ts} +1 -1
- package/dist/{vite-plugin.js → host/vite-plugin.js} +2 -1
- package/dist/{ws-handler.d.ts → host/ws-handler.d.ts} +1 -1
- package/dist/index.d.ts +2 -2
- package/dist/index.js +1 -1
- package/dist/{_internal-types.d.ts → isolate/_internal-types.d.ts} +0 -1
- package/dist/isolate/_kv-utils.d.ts +10 -0
- package/dist/{_utils.d.ts → isolate/_utils.d.ts} +0 -2
- package/dist/{_utils.js → isolate/_utils.js} +2 -13
- package/dist/{hooks.js → isolate/hooks.js} +1 -1
- package/dist/isolate/index.d.ts +18 -0
- package/dist/isolate/index.js +6 -0
- package/dist/{kv.d.ts → isolate/kv.d.ts} +0 -10
- package/dist/isolate/kv.js +1 -0
- package/dist/isolate/protocol.js +2 -0
- package/dist/{types.d.ts → isolate/types.d.ts} +1 -2
- package/dist/{types.js → isolate/types.js} +2 -3
- package/dist/{protocol.js → protocol-rcOrz7T3.js} +46 -3
- package/dist/system-prompt-CVJSQJiA.js +91 -0
- package/dist/{testing-Dmx-dudh.js → testing-Bb2B5Uob.js} +7 -7
- package/package.json +39 -34
- package/dist/constants-CwotjpJR.js +0 -45
- package/dist/kv.js +0 -33
- package/dist/memory-tools.d.ts +0 -39
- package/dist/{_mock-ws.d.ts → host/_mock-ws.d.ts} +0 -0
- package/dist/{matchers.d.ts → host/matchers.d.ts} +0 -0
- package/dist/{runtime.d.ts → host/runtime.d.ts} +0 -0
- package/dist/{s2s.d.ts → host/s2s.d.ts} +0 -0
- package/dist/{vite-plugin.d.ts → host/vite-plugin.d.ts} +0 -0
- package/dist/{constants.d.ts → isolate/constants.d.ts} +0 -0
- package/dist/{hooks.d.ts → isolate/hooks.d.ts} +0 -0
- package/dist/{protocol.d.ts → isolate/protocol.d.ts} +3 -3
- /package/dist/{system-prompt.d.ts → isolate/system-prompt.d.ts} +0 -0
|
@@ -1,117 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
import { callResolveTurnConfig, createAgentHooks } from "./hooks.js";
|
|
5
|
-
import { ClientMessageSchema, buildReadyConfig } from "./protocol.js";
|
|
6
|
-
import { matchGlob, sortAndPaginate } from "./kv.js";
|
|
1
|
+
import { a as agentToolsToSchemas, o as toAgentConfig, r as EMPTY_PARAMS, t as buildSystemPrompt } from "./system-prompt-CVJSQJiA.js";
|
|
2
|
+
import { errorDetail, errorMessage, toolError } from "./isolate/_utils.js";
|
|
3
|
+
import { C as MAX_VALUE_SIZE, S as MAX_TOOL_RESULT_CHARS, T as TOOL_EXECUTION_TIMEOUT_MS, _ as FETCH_TIMEOUT_MS, b as MAX_HTML_BYTES, g as DEFAULT_TTS_SAMPLE_RATE, h as DEFAULT_STT_SAMPLE_RATE, l as buildReadyConfig, m as DEFAULT_SHUTDOWN_TIMEOUT_MS, r as ClientMessageSchema, v as HOOK_TIMEOUT_MS, w as RUN_CODE_TIMEOUT_MS, x as MAX_PAGE_CHARS, y as MAX_GLOB_PATTERN_LENGTH } from "./protocol-rcOrz7T3.js";
|
|
4
|
+
import { callResolveTurnConfig, createAgentHooks } from "./isolate/hooks.js";
|
|
7
5
|
import { z } from "zod";
|
|
8
|
-
import WsWebSocket from "ws";
|
|
9
6
|
import pTimeout from "p-timeout";
|
|
10
7
|
import { createStorage, prefixStorage } from "unstorage";
|
|
11
8
|
import vm from "node:vm";
|
|
12
9
|
import { createNanoEvents } from "nanoevents";
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
* Runtime dependencies injected into the session pipeline.
|
|
16
|
-
*
|
|
17
|
-
* Defines the {@link Logger} interface, a default {@link consoleLogger},
|
|
18
|
-
* and the {@link S2SConfig} for Speech-to-Speech endpoint configuration.
|
|
19
|
-
*/
|
|
20
|
-
/** Default console-backed logger. */
|
|
21
|
-
const consoleLogger = {
|
|
22
|
-
info: (msg, ctx) => ctx ? console.log(msg, ctx) : console.log(msg),
|
|
23
|
-
warn: (msg, ctx) => ctx ? console.warn(msg, ctx) : console.warn(msg),
|
|
24
|
-
error: (msg, ctx) => ctx ? console.error(msg, ctx) : console.error(msg),
|
|
25
|
-
debug: (msg, ctx) => ctx ? console.debug(msg, ctx) : console.debug(msg)
|
|
26
|
-
};
|
|
27
|
-
/**
|
|
28
|
-
* Structured JSON logger for production diagnostics. Each log entry is a
|
|
29
|
-
* single-line JSON object with `timestamp`, `level`, `msg`, and any
|
|
30
|
-
* caller-provided context fields.
|
|
31
|
-
*/
|
|
32
|
-
function jsonLog(level) {
|
|
33
|
-
return (msg, ctx) => {
|
|
34
|
-
const entry = {
|
|
35
|
-
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
36
|
-
level,
|
|
37
|
-
msg
|
|
38
|
-
};
|
|
39
|
-
if (ctx) Object.assign(entry, ctx);
|
|
40
|
-
(level === "error" || level === "warn" ? process.stderr : process.stdout).write(`${JSON.stringify(entry)}\n`);
|
|
41
|
-
};
|
|
42
|
-
}
|
|
43
|
-
const jsonLogger = {
|
|
44
|
-
info: jsonLog("info"),
|
|
45
|
-
warn: jsonLog("warn"),
|
|
46
|
-
error: jsonLog("error"),
|
|
47
|
-
debug: jsonLog("debug")
|
|
48
|
-
};
|
|
49
|
-
/** Default S2S endpoint configuration. */
|
|
50
|
-
const DEFAULT_S2S_CONFIG = {
|
|
51
|
-
wssUrl: "wss://speech-to-speech.us.assemblyai.com/v1/realtime",
|
|
52
|
-
inputSampleRate: DEFAULT_STT_SAMPLE_RATE,
|
|
53
|
-
outputSampleRate: DEFAULT_TTS_SAMPLE_RATE
|
|
54
|
-
};
|
|
55
|
-
//#endregion
|
|
56
|
-
//#region _internal-types.ts
|
|
57
|
-
/**
|
|
58
|
-
* Zod schema for serializable agent configuration sent over the wire.
|
|
59
|
-
*
|
|
60
|
-
* This is the JSON-safe subset of the agent definition that can be
|
|
61
|
-
* transmitted between the worker and the host process via structured clone.
|
|
62
|
-
*/
|
|
63
|
-
const AgentConfigSchema = z.object({
|
|
64
|
-
name: z.string().min(1),
|
|
65
|
-
instructions: z.string(),
|
|
66
|
-
greeting: z.string(),
|
|
67
|
-
sttPrompt: z.string().optional(),
|
|
68
|
-
maxSteps: z.number().int().positive().optional(),
|
|
69
|
-
toolChoice: ToolChoiceSchema.optional(),
|
|
70
|
-
builtinTools: z.array(BuiltinToolSchema).readonly().optional(),
|
|
71
|
-
idleTimeoutMs: z.number().nonnegative().optional()
|
|
72
|
-
});
|
|
73
|
-
/** Extract the serializable {@link AgentConfig} subset from a source object. */
|
|
74
|
-
function toAgentConfig(src) {
|
|
75
|
-
const config = {
|
|
76
|
-
name: src.name,
|
|
77
|
-
instructions: src.instructions,
|
|
78
|
-
greeting: src.greeting
|
|
79
|
-
};
|
|
80
|
-
if (src.sttPrompt !== void 0) config.sttPrompt = src.sttPrompt;
|
|
81
|
-
if (typeof src.maxSteps !== "function" && src.maxSteps !== void 0) config.maxSteps = src.maxSteps;
|
|
82
|
-
if (src.toolChoice !== void 0) config.toolChoice = src.toolChoice;
|
|
83
|
-
if (src.builtinTools) config.builtinTools = [...src.builtinTools];
|
|
84
|
-
if (src.idleTimeoutMs !== void 0) config.idleTimeoutMs = src.idleTimeoutMs;
|
|
85
|
-
return config;
|
|
86
|
-
}
|
|
87
|
-
/**
|
|
88
|
-
* Zod schema for serialized tool definitions sent over the wire.
|
|
89
|
-
*
|
|
90
|
-
* `parameters` must be a valid JSON Schema object (with `type`, `properties`,
|
|
91
|
-
* etc.) — the Vercel AI SDK wraps it via `jsonSchema()`.
|
|
92
|
-
*/
|
|
93
|
-
const ToolSchemaSchema = z.object({
|
|
94
|
-
name: z.string().min(1),
|
|
95
|
-
description: z.string().min(1),
|
|
96
|
-
parameters: z.record(z.string(), z.unknown())
|
|
97
|
-
});
|
|
98
|
-
/** Empty Zod object schema used as default when tools have no parameters. */
|
|
99
|
-
const EMPTY_PARAMS = z.object({});
|
|
100
|
-
/**
|
|
101
|
-
* Convert agent tool definitions to JSON Schema format for wire transport.
|
|
102
|
-
*
|
|
103
|
-
* Transforms the Zod-based `parameters` of each tool into a plain JSON Schema
|
|
104
|
-
* object suitable for structured clone / JSON serialization.
|
|
105
|
-
*/
|
|
106
|
-
function agentToolsToSchemas(tools) {
|
|
107
|
-
return Object.entries(tools).map(([name, def]) => ({
|
|
108
|
-
name,
|
|
109
|
-
description: def.description,
|
|
110
|
-
parameters: z.toJSONSchema(def.parameters ?? EMPTY_PARAMS)
|
|
111
|
-
}));
|
|
112
|
-
}
|
|
113
|
-
//#endregion
|
|
114
|
-
//#region _run-code.ts
|
|
10
|
+
import WsWebSocket from "ws";
|
|
11
|
+
//#region host/_run-code.ts
|
|
115
12
|
/**
|
|
116
13
|
* run_code built-in tool — executes user JavaScript in a fresh `node:vm`
|
|
117
14
|
* context with no network, filesystem, or process access.
|
|
@@ -181,82 +78,7 @@ async function executeInIsolate(code) {
|
|
|
181
78
|
}
|
|
182
79
|
}
|
|
183
80
|
//#endregion
|
|
184
|
-
//#region
|
|
185
|
-
/**
|
|
186
|
-
* KV-backed memory tools for agent persistent state.
|
|
187
|
-
*/
|
|
188
|
-
/**
|
|
189
|
-
* Returns a standard set of KV-backed memory tools: `save_memory`,
|
|
190
|
-
* `recall_memory`, `list_memories`, and `forget_memory`.
|
|
191
|
-
*
|
|
192
|
-
* Spread the result into your agent's `tools` record.
|
|
193
|
-
*
|
|
194
|
-
* @example
|
|
195
|
-
* ```ts
|
|
196
|
-
* import { defineAgent, memoryTools } from "aai";
|
|
197
|
-
*
|
|
198
|
-
* export default defineAgent({
|
|
199
|
-
* name: "My Agent",
|
|
200
|
-
* tools: { ...memoryTools() },
|
|
201
|
-
* });
|
|
202
|
-
* ```
|
|
203
|
-
*
|
|
204
|
-
* @returns A record with four tool definitions: `save_memory`, `recall_memory`,
|
|
205
|
-
* `list_memories`, and `forget_memory`.
|
|
206
|
-
* @public
|
|
207
|
-
*/
|
|
208
|
-
function memoryTools() {
|
|
209
|
-
return {
|
|
210
|
-
save_memory: defineTool({
|
|
211
|
-
description: "Save a piece of information to persistent memory. Use a descriptive key like 'user:name' or 'project:status'.",
|
|
212
|
-
parameters: z.object({
|
|
213
|
-
key: z.string().describe("A descriptive key for this memory (e.g. 'user:name', 'preference:color')"),
|
|
214
|
-
value: z.string().describe("The information to remember")
|
|
215
|
-
}),
|
|
216
|
-
execute: async ({ key, value }, ctx) => {
|
|
217
|
-
await ctx.kv.set(key, value);
|
|
218
|
-
return { saved: key };
|
|
219
|
-
}
|
|
220
|
-
}),
|
|
221
|
-
recall_memory: defineTool({
|
|
222
|
-
description: "Retrieve a previously saved memory by its key.",
|
|
223
|
-
parameters: z.object({ key: z.string().describe("The key to look up") }),
|
|
224
|
-
execute: async ({ key }, ctx) => {
|
|
225
|
-
const value = await ctx.kv.get(key);
|
|
226
|
-
if (value === null) return {
|
|
227
|
-
found: false,
|
|
228
|
-
key
|
|
229
|
-
};
|
|
230
|
-
return {
|
|
231
|
-
found: true,
|
|
232
|
-
key,
|
|
233
|
-
value
|
|
234
|
-
};
|
|
235
|
-
}
|
|
236
|
-
}),
|
|
237
|
-
list_memories: defineTool({
|
|
238
|
-
description: "List all saved memory keys, optionally filtered by a prefix (e.g. 'user:').",
|
|
239
|
-
parameters: z.object({ prefix: z.string().describe("Prefix to filter keys (e.g. 'user:'). Use empty string for all.").optional() }),
|
|
240
|
-
execute: async ({ prefix }, ctx) => {
|
|
241
|
-
const entries = await ctx.kv.list(prefix ?? "");
|
|
242
|
-
return {
|
|
243
|
-
count: entries.length,
|
|
244
|
-
keys: entries.map((e) => e.key)
|
|
245
|
-
};
|
|
246
|
-
}
|
|
247
|
-
}),
|
|
248
|
-
forget_memory: defineTool({
|
|
249
|
-
description: "Delete a previously saved memory by its key.",
|
|
250
|
-
parameters: z.object({ key: z.string().describe("The key to delete") }),
|
|
251
|
-
execute: async ({ key }, ctx) => {
|
|
252
|
-
await ctx.kv.delete(key);
|
|
253
|
-
return { deleted: key };
|
|
254
|
-
}
|
|
255
|
-
})
|
|
256
|
-
};
|
|
257
|
-
}
|
|
258
|
-
//#endregion
|
|
259
|
-
//#region builtin-tools.ts
|
|
81
|
+
//#region host/builtin-tools.ts
|
|
260
82
|
/**
|
|
261
83
|
* Built-in tool definitions for the AAI agent SDK.
|
|
262
84
|
*
|
|
@@ -396,7 +218,6 @@ function resolveBuiltin(name, opts) {
|
|
|
396
218
|
case "visit_webpage": return [["visit_webpage", createVisitWebpage(opts?.fetch)]];
|
|
397
219
|
case "fetch_json": return [["fetch_json", createFetchJson(opts?.fetch)]];
|
|
398
220
|
case "run_code": return [["run_code", createRunCode()]];
|
|
399
|
-
case "memory": return Object.entries(memoryTools());
|
|
400
221
|
default: return [];
|
|
401
222
|
}
|
|
402
223
|
}
|
|
@@ -418,65 +239,111 @@ function getBuiltinToolSchemas(names) {
|
|
|
418
239
|
})));
|
|
419
240
|
}
|
|
420
241
|
//#endregion
|
|
421
|
-
//#region
|
|
242
|
+
//#region host/runtime.ts
|
|
243
|
+
/**
|
|
244
|
+
* Runtime dependencies injected into the session pipeline.
|
|
245
|
+
*
|
|
246
|
+
* Defines the {@link Logger} interface, a default {@link consoleLogger},
|
|
247
|
+
* and the {@link S2SConfig} for Speech-to-Speech endpoint configuration.
|
|
248
|
+
*/
|
|
249
|
+
/** Default console-backed logger. */
|
|
250
|
+
const consoleLogger = {
|
|
251
|
+
info: (msg, ctx) => ctx ? console.log(msg, ctx) : console.log(msg),
|
|
252
|
+
warn: (msg, ctx) => ctx ? console.warn(msg, ctx) : console.warn(msg),
|
|
253
|
+
error: (msg, ctx) => ctx ? console.error(msg, ctx) : console.error(msg),
|
|
254
|
+
debug: (msg, ctx) => ctx ? console.debug(msg, ctx) : console.debug(msg)
|
|
255
|
+
};
|
|
256
|
+
/**
|
|
257
|
+
* Structured JSON logger for production diagnostics. Each log entry is a
|
|
258
|
+
* single-line JSON object with `timestamp`, `level`, `msg`, and any
|
|
259
|
+
* caller-provided context fields.
|
|
260
|
+
*/
|
|
261
|
+
function jsonLog(level) {
|
|
262
|
+
return (msg, ctx) => {
|
|
263
|
+
const entry = {
|
|
264
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
265
|
+
level,
|
|
266
|
+
msg
|
|
267
|
+
};
|
|
268
|
+
if (ctx) Object.assign(entry, ctx);
|
|
269
|
+
(level === "error" || level === "warn" ? process.stderr : process.stdout).write(`${JSON.stringify(entry)}\n`);
|
|
270
|
+
};
|
|
271
|
+
}
|
|
272
|
+
const jsonLogger = {
|
|
273
|
+
info: jsonLog("info"),
|
|
274
|
+
warn: jsonLog("warn"),
|
|
275
|
+
error: jsonLog("error"),
|
|
276
|
+
debug: jsonLog("debug")
|
|
277
|
+
};
|
|
278
|
+
/** Default S2S endpoint configuration. */
|
|
279
|
+
const DEFAULT_S2S_CONFIG = {
|
|
280
|
+
wssUrl: "wss://speech-to-speech.us.assemblyai.com/v1/realtime",
|
|
281
|
+
inputSampleRate: DEFAULT_STT_SAMPLE_RATE,
|
|
282
|
+
outputSampleRate: DEFAULT_TTS_SAMPLE_RATE
|
|
283
|
+
};
|
|
284
|
+
//#endregion
|
|
285
|
+
//#region host/s2s.ts
|
|
422
286
|
const uint8ToBase64 = (bytes) => Buffer.from(bytes).toString("base64");
|
|
423
287
|
const base64ToUint8 = (base64) => new Uint8Array(Buffer.from(base64, "base64"));
|
|
424
288
|
const WS_OPEN = 1;
|
|
425
289
|
const defaultCreateS2sWebSocket = (url, opts) => new WsWebSocket(url, { headers: opts.headers });
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
type: "
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
290
|
+
const S2sMessageSchema = z.discriminatedUnion("type", [
|
|
291
|
+
z.object({
|
|
292
|
+
type: z.literal("session.ready"),
|
|
293
|
+
session_id: z.string()
|
|
294
|
+
}).passthrough(),
|
|
295
|
+
z.object({ type: z.literal("session.updated") }).passthrough(),
|
|
296
|
+
z.object({ type: z.literal("input.speech.started") }),
|
|
297
|
+
z.object({ type: z.literal("input.speech.stopped") }),
|
|
298
|
+
z.object({
|
|
299
|
+
type: z.literal("transcript.user.delta"),
|
|
300
|
+
text: z.string()
|
|
301
|
+
}),
|
|
302
|
+
z.object({
|
|
303
|
+
type: z.literal("transcript.user"),
|
|
304
|
+
item_id: z.string(),
|
|
305
|
+
text: z.string()
|
|
306
|
+
}),
|
|
307
|
+
z.object({
|
|
308
|
+
type: z.literal("reply.started"),
|
|
309
|
+
reply_id: z.string()
|
|
310
|
+
}),
|
|
311
|
+
z.object({
|
|
312
|
+
type: z.literal("transcript.agent.delta"),
|
|
313
|
+
delta: z.string()
|
|
314
|
+
}).passthrough(),
|
|
315
|
+
z.object({
|
|
316
|
+
type: z.literal("transcript.agent"),
|
|
317
|
+
text: z.string(),
|
|
318
|
+
reply_id: z.string().optional().default(""),
|
|
319
|
+
item_id: z.string().optional().default(""),
|
|
320
|
+
interrupted: z.boolean().optional().default(false)
|
|
321
|
+
}),
|
|
322
|
+
z.object({ type: z.literal("reply.content_part.started") }).passthrough(),
|
|
323
|
+
z.object({ type: z.literal("reply.content_part.done") }).passthrough(),
|
|
324
|
+
z.object({
|
|
325
|
+
type: z.literal("tool.call"),
|
|
326
|
+
call_id: z.string(),
|
|
327
|
+
name: z.string(),
|
|
328
|
+
args: z.record(z.string(), z.unknown()).optional().default({})
|
|
329
|
+
}),
|
|
330
|
+
z.object({
|
|
331
|
+
type: z.literal("reply.done"),
|
|
332
|
+
status: z.string().optional()
|
|
333
|
+
}),
|
|
334
|
+
z.object({
|
|
335
|
+
type: z.literal("session.error"),
|
|
336
|
+
code: z.string(),
|
|
337
|
+
message: z.string()
|
|
338
|
+
}),
|
|
339
|
+
z.object({
|
|
340
|
+
type: z.literal("error"),
|
|
341
|
+
message: z.string()
|
|
342
|
+
})
|
|
475
343
|
]);
|
|
476
344
|
function parseS2sMessage(obj) {
|
|
477
|
-
const
|
|
478
|
-
|
|
479
|
-
return MESSAGE_VALIDATORS.get(type)?.(obj);
|
|
345
|
+
const result = S2sMessageSchema.safeParse(obj);
|
|
346
|
+
return result.success ? result.data : void 0;
|
|
480
347
|
}
|
|
481
348
|
function dispatchS2sMessage(emitter, msg) {
|
|
482
349
|
switch (msg.type) {
|
|
@@ -667,37 +534,7 @@ function connectS2s(opts) {
|
|
|
667
534
|
});
|
|
668
535
|
}
|
|
669
536
|
//#endregion
|
|
670
|
-
//#region
|
|
671
|
-
function getFormattedDate() {
|
|
672
|
-
return (/* @__PURE__ */ new Date()).toLocaleDateString("en-US", {
|
|
673
|
-
weekday: "long",
|
|
674
|
-
year: "numeric",
|
|
675
|
-
month: "long",
|
|
676
|
-
day: "numeric"
|
|
677
|
-
});
|
|
678
|
-
}
|
|
679
|
-
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";
|
|
680
|
-
/**
|
|
681
|
-
* Build the system prompt sent to the LLM from the agent configuration.
|
|
682
|
-
*
|
|
683
|
-
* Assembles the default instructions, today's date, agent-specific instructions,
|
|
684
|
-
* and optional sections for tool usage preamble and voice output rules.
|
|
685
|
-
*
|
|
686
|
-
* @param config - The serializable agent configuration (name, instructions, etc.).
|
|
687
|
-
* @param opts.hasTools - When `true`, appends a preamble instructing the LLM to
|
|
688
|
-
* speak a brief phrase before each tool call to fill silence.
|
|
689
|
-
* @param opts.voice - When `true`, appends strict voice-specific output rules
|
|
690
|
-
* (no markdown, no bullet points, conversational tone, concise responses).
|
|
691
|
-
* @returns The assembled system prompt string.
|
|
692
|
-
*/
|
|
693
|
-
function buildSystemPrompt(config, opts) {
|
|
694
|
-
const { hasTools } = opts;
|
|
695
|
-
const agentInstructions = config.instructions && config.instructions !== DEFAULT_INSTRUCTIONS ? `\n\nAgent-Specific Instructions:\n${config.instructions}` : "";
|
|
696
|
-
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." : "";
|
|
697
|
-
return DEFAULT_INSTRUCTIONS + `\n\nToday's date is ${getFormattedDate()}.` + agentInstructions + toolPreamble + (opts.voice ? VOICE_RULES : "");
|
|
698
|
-
}
|
|
699
|
-
//#endregion
|
|
700
|
-
//#region session.ts
|
|
537
|
+
//#region host/session.ts
|
|
701
538
|
function buildCtx(opts) {
|
|
702
539
|
const { id, agentConfig, hooks, log } = opts;
|
|
703
540
|
const maxHistory = opts.maxHistory ?? 200;
|
|
@@ -1090,7 +927,36 @@ function createS2sSession(opts) {
|
|
|
1090
927
|
};
|
|
1091
928
|
}
|
|
1092
929
|
//#endregion
|
|
1093
|
-
//#region
|
|
930
|
+
//#region isolate/_kv-utils.ts
|
|
931
|
+
/** Internal KV helpers shared by kv.ts and unstorage-kv.ts. */
|
|
932
|
+
/** Sort entries by key and apply reverse/limit options. Mutates the array. */
|
|
933
|
+
function sortAndPaginate(entries, options) {
|
|
934
|
+
entries.sort((a, b) => a.key.localeCompare(b.key));
|
|
935
|
+
if (options?.reverse) entries.reverse();
|
|
936
|
+
if (options?.limit && options.limit > 0) entries.length = Math.min(entries.length, options.limit);
|
|
937
|
+
return entries;
|
|
938
|
+
}
|
|
939
|
+
/** Simple glob matcher — supports `*` as a wildcard for any characters. */
|
|
940
|
+
function matchGlob(key, pattern) {
|
|
941
|
+
if (pattern.length > 1024) throw new Error(`Glob pattern exceeds maximum length of ${MAX_GLOB_PATTERN_LENGTH}`);
|
|
942
|
+
const parts = pattern.split("*");
|
|
943
|
+
if (parts.length === 1) return key === pattern;
|
|
944
|
+
const first = parts[0];
|
|
945
|
+
if (!key.startsWith(first)) return false;
|
|
946
|
+
const last = parts.at(-1);
|
|
947
|
+
if (key.length < first.length + last.length) return false;
|
|
948
|
+
if (!key.endsWith(last)) return false;
|
|
949
|
+
let pos = first.length;
|
|
950
|
+
const end = key.length - last.length;
|
|
951
|
+
for (const part of parts.slice(1, -1)) {
|
|
952
|
+
const idx = key.indexOf(part, pos);
|
|
953
|
+
if (idx === -1 || idx > end) return false;
|
|
954
|
+
pos = idx + part.length;
|
|
955
|
+
}
|
|
956
|
+
return pos <= end;
|
|
957
|
+
}
|
|
958
|
+
//#endregion
|
|
959
|
+
//#region host/unstorage-kv.ts
|
|
1094
960
|
/**
|
|
1095
961
|
* Key-value store backed by unstorage.
|
|
1096
962
|
*
|
|
@@ -1151,7 +1017,7 @@ function createUnstorageKv(options) {
|
|
|
1151
1017
|
};
|
|
1152
1018
|
}
|
|
1153
1019
|
//#endregion
|
|
1154
|
-
//#region ws-handler.ts
|
|
1020
|
+
//#region host/ws-handler.ts
|
|
1155
1021
|
/**
|
|
1156
1022
|
* WebSocket session lifecycle handler.
|
|
1157
1023
|
*
|
|
@@ -1341,7 +1207,7 @@ function wireSessionSocket(ws, opts) {
|
|
|
1341
1207
|
});
|
|
1342
1208
|
}
|
|
1343
1209
|
//#endregion
|
|
1344
|
-
//#region direct-executor.ts
|
|
1210
|
+
//#region host/direct-executor.ts
|
|
1345
1211
|
/**
|
|
1346
1212
|
* Agent runtime — the execution engine for voice agents.
|
|
1347
1213
|
*
|
|
@@ -1511,8 +1377,12 @@ function createRuntime(opts) {
|
|
|
1511
1377
|
for (const r of results) if (r.status === "rejected") logger.warn(`Session stop failed during shutdown: ${r.reason}`);
|
|
1512
1378
|
return "done";
|
|
1513
1379
|
});
|
|
1514
|
-
|
|
1515
|
-
|
|
1380
|
+
let outcome;
|
|
1381
|
+
try {
|
|
1382
|
+
outcome = await Promise.race([graceful, timeout]);
|
|
1383
|
+
} finally {
|
|
1384
|
+
if (timer) clearTimeout(timer);
|
|
1385
|
+
}
|
|
1516
1386
|
if (outcome === "timeout") logger.warn(`Shutdown timeout (${shutdownTimeoutMs}ms) exceeded — force-closing ${sessions.size} remaining session(s)`);
|
|
1517
1387
|
sessions.clear();
|
|
1518
1388
|
}
|
|
@@ -1527,4 +1397,4 @@ function createRuntime(opts) {
|
|
|
1527
1397
|
};
|
|
1528
1398
|
}
|
|
1529
1399
|
//#endregion
|
|
1530
|
-
export {
|
|
1400
|
+
export { _internals as a, connectS2s as c, consoleLogger as d, jsonLogger as f, createUnstorageKv as i, defaultCreateS2sWebSocket as l, executeToolCall as n, buildCtx as o, wireSessionSocket as r, createS2sSession as s, createRuntime as t, DEFAULT_S2S_CONFIG as u };
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
* context with no network, filesystem, or process access.
|
|
4
4
|
*/
|
|
5
5
|
import { z } from "zod";
|
|
6
|
-
import type { ToolDef } from "
|
|
6
|
+
import type { ToolDef } from "../isolate/types.ts";
|
|
7
7
|
declare const runCodeParams: z.ZodObject<{
|
|
8
8
|
code: z.ZodString;
|
|
9
9
|
}, z.core.$strip>;
|
|
@@ -19,7 +19,7 @@
|
|
|
19
19
|
*
|
|
20
20
|
* @example Sandbox (integration test in aai-server)
|
|
21
21
|
* ```ts
|
|
22
|
-
* import { testRuntime } from "@alexkroman1/aai/
|
|
22
|
+
* import { testRuntime } from "@alexkroman1/aai/host";
|
|
23
23
|
*
|
|
24
24
|
* testRuntime("sandbox", async () => {
|
|
25
25
|
* // ... start isolate with a bundled agent
|
|
@@ -27,9 +27,9 @@
|
|
|
27
27
|
* });
|
|
28
28
|
* ```
|
|
29
29
|
*/
|
|
30
|
-
import type { ExecuteTool } from "
|
|
31
|
-
import type { AgentHooks } from "
|
|
32
|
-
import { type AgentDef } from "
|
|
30
|
+
import type { ExecuteTool } from "../isolate/_internal-types.ts";
|
|
31
|
+
import type { AgentHooks } from "../isolate/hooks.ts";
|
|
32
|
+
import { type AgentDef } from "../isolate/types.ts";
|
|
33
33
|
/**
|
|
34
34
|
* Minimal runtime surface needed for conformance tests.
|
|
35
35
|
*
|
|
@@ -1,9 +1,9 @@
|
|
|
1
|
-
import type { AgentConfig } from "
|
|
2
|
-
import type { ClientSink } from "
|
|
1
|
+
import type { AgentConfig } from "../isolate/_internal-types.ts";
|
|
2
|
+
import type { ClientSink } from "../isolate/protocol.ts";
|
|
3
|
+
import type { AgentDef, ToolContext, ToolDef } from "../isolate/types.ts";
|
|
3
4
|
import type { S2sEvents, S2sHandle } from "./s2s.ts";
|
|
4
5
|
import type { Session } from "./session.ts";
|
|
5
6
|
import { type S2sSessionOptions } from "./session.ts";
|
|
6
|
-
import type { AgentDef, ToolContext, ToolDef } from "./types.ts";
|
|
7
7
|
/** Yield to the microtask queue so pending promises settle. */
|
|
8
8
|
export declare function flush(): Promise<void>;
|
|
9
9
|
export declare function createMockToolContext(overrides?: Partial<ToolContext>): ToolContext;
|
|
@@ -6,10 +6,9 @@
|
|
|
6
6
|
* Network requests go through the host's fetch proxy (with SSRF protection).
|
|
7
7
|
*/
|
|
8
8
|
import { z } from "zod";
|
|
9
|
-
import { type ToolSchema } from "
|
|
10
|
-
import type { ToolDef } from "
|
|
9
|
+
import { type ToolSchema } from "../isolate/_internal-types.ts";
|
|
10
|
+
import type { ToolDef } from "../isolate/types.ts";
|
|
11
11
|
export { executeInIsolate } from "./_run-code.ts";
|
|
12
|
-
export { memoryTools } from "./memory-tools.ts";
|
|
13
12
|
/** Options for creating built-in tool definitions. */
|
|
14
13
|
export type BuiltinToolOptions = {
|
|
15
14
|
/** Override fetch implementation (defaults to globalThis.fetch). For testing. */
|
|
@@ -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 "
|
|
9
|
-
import { type AgentHooks } from "
|
|
10
|
-
import type { Kv } from "
|
|
11
|
-
import type { ClientSink } from "
|
|
12
|
-
import { type ReadyConfig } from "
|
|
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 "
|
|
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
|
-
*
|
|
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 "
|
|
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,13 @@
|
|
|
1
|
-
import { defineTool } from "
|
|
2
|
-
import { a as
|
|
3
|
-
import {
|
|
4
|
-
import {
|
|
5
|
-
import { callResolveTurnConfig, createAgentHooks } from "
|
|
6
|
-
import
|
|
1
|
+
import { BuiltinToolSchema, DEFAULT_GREETING, DEFAULT_INSTRUCTIONS, ToolChoiceSchema, defineAgent, defineTool, defineToolFactory } from "../isolate/types.js";
|
|
2
|
+
import { a as agentToolsToSchemas, i as ToolSchemaSchema, n as AgentConfigSchema, o as toAgentConfig, r as EMPTY_PARAMS, t as buildSystemPrompt } from "../system-prompt-CVJSQJiA.js";
|
|
3
|
+
import { errorDetail, errorMessage, toolError } from "../isolate/_utils.js";
|
|
4
|
+
import { C as MAX_VALUE_SIZE, S as MAX_TOOL_RESULT_CHARS, T as TOOL_EXECUTION_TIMEOUT_MS, _ as FETCH_TIMEOUT_MS, a as ReadyConfigSchema, b as MAX_HTML_BYTES, c as TurnConfigSchema, d as DEFAULT_IDLE_TIMEOUT_MS, f as DEFAULT_MAX_HISTORY, g as DEFAULT_TTS_SAMPLE_RATE, h as DEFAULT_STT_SAMPLE_RATE, i as KvRequestSchema, l as buildReadyConfig, m as DEFAULT_SHUTDOWN_TIMEOUT_MS, n as ClientEventSchema, o as ServerMessageSchema, p as DEFAULT_SESSION_START_TIMEOUT_MS, r as ClientMessageSchema, s as SessionErrorCodeSchema, t as AUDIO_FORMAT, u as AGENT_CSP, v as HOOK_TIMEOUT_MS, w as RUN_CODE_TIMEOUT_MS, x as MAX_PAGE_CHARS, y as MAX_GLOB_PATTERN_LENGTH } from "../protocol-rcOrz7T3.js";
|
|
5
|
+
import { callResolveTurnConfig, createAgentHooks } from "../isolate/hooks.js";
|
|
6
|
+
import "../isolate/index.js";
|
|
7
|
+
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-ZUU0Ke4j.js";
|
|
7
8
|
import { z } from "zod";
|
|
8
9
|
import { describe, expect, test } from "vitest";
|
|
9
|
-
//#region _runtime-conformance.ts
|
|
10
|
+
//#region host/_runtime-conformance.ts
|
|
10
11
|
/**
|
|
11
12
|
* Shared runtime conformance tests.
|
|
12
13
|
*
|
|
@@ -28,7 +29,7 @@ import { describe, expect, test } from "vitest";
|
|
|
28
29
|
*
|
|
29
30
|
* @example Sandbox (integration test in aai-server)
|
|
30
31
|
* ```ts
|
|
31
|
-
* import { testRuntime } from "@alexkroman1/aai/
|
|
32
|
+
* import { testRuntime } from "@alexkroman1/aai/host";
|
|
32
33
|
*
|
|
33
34
|
* testRuntime("sandbox", async () => {
|
|
34
35
|
* // ... start isolate with a bundled agent
|
|
@@ -161,4 +162,4 @@ function testRuntime(label, getContext) {
|
|
|
161
162
|
});
|
|
162
163
|
}
|
|
163
164
|
//#endregion
|
|
164
|
-
export { AGENT_CSP, AUDIO_FORMAT, AgentConfigSchema, CONFORMANCE_AGENT, 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_TIMEOUT_MS, ReadyConfigSchema, ServerMessageSchema, SessionErrorCodeSchema, TOOL_EXECUTION_TIMEOUT_MS, ToolSchemaSchema, TurnConfigSchema, _internals, agentToolsToSchemas, buildCtx, buildReadyConfig, buildSystemPrompt, callResolveTurnConfig, connectS2s, consoleLogger, createAgentHooks, createRuntime, createS2sSession, createUnstorageKv, defaultCreateS2sWebSocket, errorDetail, errorMessage, executeToolCall,
|
|
165
|
+
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, testRuntime, toAgentConfig, toolError, wireSessionSocket };
|