@alexkroman1/aai 0.10.2 → 0.10.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (60) hide show
  1. package/dist/_internal-types.d.ts +8 -1
  2. package/dist/_runtime-conformance.d.ts +64 -0
  3. package/dist/_test-utils.d.ts +70 -0
  4. package/dist/_utils.d.ts +1 -8
  5. package/dist/_utils.js +1 -13
  6. package/dist/builtin-tools.d.ts +1 -5
  7. package/dist/constants-BbAOvKl_.js +47 -0
  8. package/dist/constants.d.ts +44 -0
  9. package/dist/direct-executor-BfHrDdPL.js +1589 -0
  10. package/dist/direct-executor.d.ts +90 -31
  11. package/dist/hooks.d.ts +44 -0
  12. package/dist/hooks.js +58 -0
  13. package/dist/index.d.ts +1 -2
  14. package/dist/index.js +2 -2
  15. package/dist/internal.d.ts +19 -0
  16. package/dist/internal.js +209 -0
  17. package/dist/kv.d.ts +1 -1
  18. package/dist/kv.js +5 -4
  19. package/dist/matchers.js +1 -1
  20. package/dist/protocol.d.ts +3 -29
  21. package/dist/protocol.js +2 -24
  22. package/dist/server.d.ts +25 -38
  23. package/dist/server.js +114 -138
  24. package/dist/session.d.ts +65 -44
  25. package/dist/{testing-MRl3SXsI.js → testing-BonJtfHJ.js} +26 -46
  26. package/dist/testing.d.ts +9 -14
  27. package/dist/testing.js +2 -2
  28. package/dist/types.d.ts +24 -226
  29. package/dist/types.js +6 -22
  30. package/dist/types.test-d.d.ts +7 -0
  31. package/dist/unstorage-kv.d.ts +33 -0
  32. package/dist/vite-plugin.d.ts +15 -0
  33. package/dist/vite-plugin.js +82 -0
  34. package/dist/ws-handler.d.ts +1 -2
  35. package/package.json +29 -84
  36. package/dist/_internal-types.js +0 -61
  37. package/dist/_session-ctx.d.ts +0 -73
  38. package/dist/_session-otel.d.ts +0 -43
  39. package/dist/_session-persist.d.ts +0 -30
  40. package/dist/_ssrf.d.ts +0 -30
  41. package/dist/_ssrf.js +0 -123
  42. package/dist/direct-executor-Ca0wt5H0.js +0 -572
  43. package/dist/middleware-core.d.ts +0 -47
  44. package/dist/middleware-core.js +0 -107
  45. package/dist/middleware.d.ts +0 -37
  46. package/dist/runtime.js +0 -53
  47. package/dist/s2s.js +0 -272
  48. package/dist/session-BkN9u0ni.js +0 -683
  49. package/dist/session.js +0 -2
  50. package/dist/sqlite-kv.d.ts +0 -34
  51. package/dist/sqlite-kv.js +0 -133
  52. package/dist/sqlite-vector.d.ts +0 -58
  53. package/dist/sqlite-vector.js +0 -149
  54. package/dist/telemetry.d.ts +0 -49
  55. package/dist/telemetry.js +0 -95
  56. package/dist/vector.d.ts +0 -85
  57. package/dist/vector.js +0 -49
  58. package/dist/worker-entry.d.ts +0 -47
  59. package/dist/worker-entry.js +0 -70
  60. package/dist/ws-handler.js +0 -207
@@ -0,0 +1,7 @@
1
+ /**
2
+ * Type-level tests for the public API surface of @alexkroman1/aai.
3
+ *
4
+ * These are checked by tsc (via vitest typecheck) but never executed.
5
+ * A failure here means a public type contract has regressed.
6
+ */
7
+ export {};
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Key-value store backed by unstorage.
3
+ *
4
+ * Works with any unstorage driver (memory, fs, S3/R2, etc.).
5
+ */
6
+ import { type Storage } from "unstorage";
7
+ import type { Kv } from "./kv.ts";
8
+ /**
9
+ * Options for creating an unstorage-backed KV store.
10
+ */
11
+ export type UnstorageKvOptions = {
12
+ /** Configured unstorage Storage instance. */
13
+ storage: Storage;
14
+ /** Key prefix prepended to all operations (e.g. `"agents/my-agent/kv"`). */
15
+ prefix?: string;
16
+ };
17
+ /**
18
+ * Create a KV store backed by any unstorage driver.
19
+ *
20
+ * @param options - See {@link UnstorageKvOptions}.
21
+ * @returns A {@link Kv} instance.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * import { createStorage } from "unstorage";
26
+ * import { createUnstorageKv } from "@alexkroman1/aai/unstorage-kv";
27
+ *
28
+ * const kv = createUnstorageKv({ storage: createStorage() });
29
+ * await kv.set("greeting", "hello");
30
+ * const value = await kv.get<string>("greeting"); // "hello"
31
+ * ```
32
+ */
33
+ export declare function createUnstorageKv(options: UnstorageKvOptions): Kv;
@@ -0,0 +1,15 @@
1
+ /**
2
+ * Vite plugin for AAI agent development.
3
+ *
4
+ * In dev mode: boots the agent backend server and configures proxy.
5
+ * Handles .env loading, runtime creation, and WebSocket proxying
6
+ * so `vite` alone gives you a working dev server.
7
+ */
8
+ import type { Plugin } from "vite";
9
+ export type AaiPluginOptions = {
10
+ /** Path to agent entry (default: "agent.ts") */
11
+ agent?: string;
12
+ /** Backend port (default: Vite port + 1) */
13
+ backendPort?: number;
14
+ };
15
+ export declare function aai(options?: AaiPluginOptions): Plugin;
@@ -0,0 +1,82 @@
1
+ import path from "node:path";
2
+ import fs from "node:fs/promises";
3
+ //#region vite-plugin.ts
4
+ /**
5
+ * Vite plugin for AAI agent development.
6
+ *
7
+ * In dev mode: boots the agent backend server and configures proxy.
8
+ * Handles .env loading, runtime creation, and WebSocket proxying
9
+ * so `vite` alone gives you a working dev server.
10
+ */
11
+ function parseEnvFile(content) {
12
+ const entries = {};
13
+ for (const raw of content.split("\n")) {
14
+ const line = raw.trim();
15
+ if (!line || line.startsWith("#")) continue;
16
+ const eq = line.indexOf("=");
17
+ if (eq === -1) continue;
18
+ const key = line.slice(0, eq).trim();
19
+ if (key) entries[key] = line.slice(eq + 1);
20
+ }
21
+ return entries;
22
+ }
23
+ async function resolveAgentEnv(root) {
24
+ let fileEntries = {};
25
+ try {
26
+ fileEntries = parseEnvFile(await fs.readFile(path.join(root, ".env"), "utf-8"));
27
+ } catch {}
28
+ const env = {};
29
+ for (const [key, fileVal] of Object.entries(fileEntries)) env[key] = process.env[key] ?? fileVal;
30
+ if (!env.ASSEMBLYAI_API_KEY && process.env.ASSEMBLYAI_API_KEY) env.ASSEMBLYAI_API_KEY = process.env.ASSEMBLYAI_API_KEY;
31
+ return env;
32
+ }
33
+ function aai(options) {
34
+ const agentEntry = options?.agent ?? "agent.ts";
35
+ let backendPort = options?.backendPort;
36
+ let server = null;
37
+ return {
38
+ name: "aai",
39
+ apply: "serve",
40
+ config(config) {
41
+ const vitePort = config.server?.port ?? 3e3;
42
+ const envPort = Number(process.env.AAI_BACKEND_PORT);
43
+ backendPort = backendPort ?? (envPort > 0 ? envPort : vitePort + 1);
44
+ const target = `http://localhost:${backendPort}`;
45
+ return { server: { proxy: {
46
+ "/health": target,
47
+ "/websocket": {
48
+ target,
49
+ ws: true
50
+ }
51
+ } } };
52
+ },
53
+ async configureServer(viteServer) {
54
+ const root = viteServer.config.root;
55
+ const agentPath = path.resolve(root, agentEntry);
56
+ const { createRuntime, createServer } = await import("./server.js");
57
+ const agentDef = (await viteServer.ssrLoadModule(agentPath)).default;
58
+ if (!agentDef?.name) {
59
+ viteServer.config.logger.error("agent.ts must export a default defineAgent() call");
60
+ return;
61
+ }
62
+ const agentServer = createServer({
63
+ runtime: createRuntime({
64
+ agent: agentDef,
65
+ env: await resolveAgentEnv(root)
66
+ }),
67
+ name: agentDef.name
68
+ });
69
+ await agentServer.listen(backendPort);
70
+ server = agentServer;
71
+ viteServer.config.logger.info(`Agent backend on port ${backendPort}`);
72
+ },
73
+ async buildEnd() {
74
+ if (server) {
75
+ await server.close();
76
+ server = null;
77
+ }
78
+ }
79
+ };
80
+ }
81
+ //#endregion
82
+ export { aai };
@@ -40,8 +40,7 @@ export type WsSessionOptions = {
40
40
  logger?: Logger;
41
41
  /** Timeout in ms for session.start(). Defaults to 10 000 (10s). */
42
42
  sessionStartTimeoutMs?: number;
43
- /** Old session ID to resume from. When set, the persisted session data
44
- * (state, messages, S2S session ID) is restored from KV. */
43
+ /** Old session ID to resume. When set, reuses this ID instead of generating a new UUID. */
45
44
  resumeFrom?: string;
46
45
  };
47
46
  /**
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@alexkroman1/aai",
3
- "version": "0.10.2",
3
+ "version": "0.10.4",
4
4
  "type": "module",
5
5
  "files": [
6
6
  "dist"
@@ -11,6 +11,11 @@
11
11
  "types": "./dist/index.d.ts",
12
12
  "import": "./dist/index.js"
13
13
  },
14
+ "./server": {
15
+ "source": "./server.ts",
16
+ "types": "./dist/server.d.ts",
17
+ "import": "./dist/server.js"
18
+ },
14
19
  "./types": {
15
20
  "source": "./types.ts",
16
21
  "types": "./dist/types.d.ts",
@@ -21,10 +26,10 @@
21
26
  "types": "./dist/kv.d.ts",
22
27
  "import": "./dist/kv.js"
23
28
  },
24
- "./vector": {
25
- "source": "./vector.ts",
26
- "types": "./dist/vector.d.ts",
27
- "import": "./dist/vector.js"
29
+ "./protocol": {
30
+ "source": "./protocol.ts",
31
+ "types": "./dist/protocol.d.ts",
32
+ "import": "./dist/protocol.js"
28
33
  },
29
34
  "./testing": {
30
35
  "source": "./testing.ts",
@@ -36,110 +41,50 @@
36
41
  "types": "./dist/matchers.d.ts",
37
42
  "import": "./dist/matchers.js"
38
43
  },
39
- "./server": {
40
- "source": "./server.ts",
41
- "types": "./dist/server.d.ts",
42
- "import": "./dist/server.js"
44
+ "./internal": {
45
+ "source": "./internal.ts",
46
+ "types": "./dist/internal.d.ts",
47
+ "import": "./dist/internal.js"
43
48
  },
44
- "./protocol": {
45
- "source": "./protocol.ts",
46
- "types": "./dist/protocol.d.ts",
47
- "import": "./dist/protocol.js"
48
- },
49
- "./s2s": {
50
- "source": "./s2s.ts",
51
- "types": "./dist/s2s.d.ts",
52
- "import": "./dist/s2s.js"
53
- },
54
- "./session": {
55
- "source": "./session.ts",
56
- "types": "./dist/session.d.ts",
57
- "import": "./dist/session.js"
58
- },
59
- "./internal-types": {
60
- "source": "./_internal-types.ts",
61
- "types": "./dist/_internal-types.d.ts",
62
- "import": "./dist/_internal-types.js"
63
- },
64
- "./runtime": {
65
- "source": "./runtime.ts",
66
- "types": "./dist/runtime.d.ts",
67
- "import": "./dist/runtime.js"
68
- },
69
- "./worker-entry": {
70
- "source": "./worker-entry.ts",
71
- "types": "./dist/worker-entry.d.ts",
72
- "import": "./dist/worker-entry.js"
73
- },
74
- "./ws-handler": {
75
- "source": "./ws-handler.ts",
76
- "types": "./dist/ws-handler.d.ts",
77
- "import": "./dist/ws-handler.js"
78
- },
79
- "./telemetry": {
80
- "source": "./telemetry.ts",
81
- "types": "./dist/telemetry.d.ts",
82
- "import": "./dist/telemetry.js"
49
+ "./hooks": {
50
+ "source": "./hooks.ts",
51
+ "types": "./dist/hooks.d.ts",
52
+ "import": "./dist/hooks.js"
83
53
  },
84
54
  "./utils": {
85
55
  "source": "./_utils.ts",
86
56
  "types": "./dist/_utils.d.ts",
87
57
  "import": "./dist/_utils.js"
88
58
  },
89
- "./ssrf": {
90
- "source": "./_ssrf.ts",
91
- "types": "./dist/_ssrf.d.ts",
92
- "import": "./dist/_ssrf.js"
93
- },
94
- "./middleware-core": {
95
- "source": "./middleware-core.ts",
96
- "types": "./dist/middleware-core.d.ts",
97
- "import": "./dist/middleware-core.js"
98
- },
99
- "./sqlite-kv": {
100
- "source": "./sqlite-kv.ts",
101
- "types": "./dist/sqlite-kv.d.ts",
102
- "import": "./dist/sqlite-kv.js"
103
- },
104
- "./sqlite-vector": {
105
- "source": "./sqlite-vector.ts",
106
- "types": "./dist/sqlite-vector.d.ts",
107
- "import": "./dist/sqlite-vector.js"
59
+ "./vite-plugin": {
60
+ "source": "./vite-plugin.ts",
61
+ "types": "./dist/vite-plugin.d.ts",
62
+ "import": "./dist/vite-plugin.js"
108
63
  }
109
64
  },
110
65
  "dependencies": {
111
- "@huggingface/transformers": "^3.8.1",
112
- "html-to-text": "^9.0.5",
66
+ "hookable": "^6.1.0",
113
67
  "nanoevents": "^9.1.0",
68
+ "p-timeout": "^7.0.1",
114
69
  "secure-exec": "^0.1.0",
70
+ "unstorage": "^1.17.5",
115
71
  "ws": "^8.20.0",
116
72
  "zod": "^4.3.6"
117
73
  },
118
74
  "peerDependencies": {
119
- "@hono/node-server": "^1.19.11",
120
- "@opentelemetry/api": "^1.9.1",
121
- "hono": "^4.12.9",
122
75
  "vitest": "^4.1.1"
123
76
  },
124
77
  "peerDependenciesMeta": {
125
- "@hono/node-server": {
126
- "optional": true
127
- },
128
- "@opentelemetry/api": {
129
- "optional": true
130
- },
131
- "hono": {
132
- "optional": true
133
- },
134
78
  "vitest": {
135
79
  "optional": true
136
80
  }
137
81
  },
138
82
  "devDependencies": {
139
- "@types/html-to-text": "^9.0.4",
140
83
  "@types/json-schema": "^7.0.15",
84
+ "@types/node": "^25.5.0",
141
85
  "@types/ws": "^8.18.1",
142
- "tsdown": "^0.21.5"
86
+ "tsdown": "^0.21.5",
87
+ "vite": "^8.0.3"
143
88
  },
144
89
  "engines": {
145
90
  "node": ">=22.6"
@@ -153,7 +98,7 @@
153
98
  "build": "tsdown && tsc -p tsconfig.build.json",
154
99
  "typecheck": "tsc --noEmit",
155
100
  "lint": "biome check .",
156
- "check:api": "api-extractor run -c api-extractor.json",
101
+ "check:publint": "publint",
157
102
  "check:attw": "attw --pack --profile esm-only"
158
103
  }
159
104
  }
@@ -1,61 +0,0 @@
1
- import { BuiltinToolSchema, ToolChoiceSchema } from "./types.js";
2
- import { z } from "zod";
3
- //#region _internal-types.ts
4
- /**
5
- * Zod schema for serializable agent configuration sent over the wire.
6
- *
7
- * This is the JSON-safe subset of the agent definition that can be
8
- * transmitted between the worker and the host process via structured clone.
9
- */
10
- const AgentConfigSchema = z.object({
11
- name: z.string().min(1),
12
- instructions: z.string(),
13
- greeting: z.string(),
14
- sttPrompt: z.string().optional(),
15
- maxSteps: z.number().int().positive().optional(),
16
- toolChoice: ToolChoiceSchema.optional(),
17
- builtinTools: z.array(BuiltinToolSchema).readonly().optional(),
18
- idleTimeoutMs: z.number().nonnegative().optional()
19
- });
20
- /** Extract the serializable {@link AgentConfig} subset from a source object. */
21
- function toAgentConfig(src) {
22
- const config = {
23
- name: src.name,
24
- instructions: src.instructions,
25
- greeting: src.greeting
26
- };
27
- if (src.sttPrompt !== void 0) config.sttPrompt = src.sttPrompt;
28
- if (typeof src.maxSteps !== "function" && src.maxSteps !== void 0) config.maxSteps = src.maxSteps;
29
- if (src.toolChoice !== void 0) config.toolChoice = src.toolChoice;
30
- if (src.builtinTools) config.builtinTools = [...src.builtinTools];
31
- if (src.idleTimeoutMs !== void 0) config.idleTimeoutMs = src.idleTimeoutMs;
32
- return config;
33
- }
34
- /**
35
- * Zod schema for serialized tool definitions sent over the wire.
36
- *
37
- * `parameters` must be a valid JSON Schema object (with `type`, `properties`,
38
- * etc.) — the Vercel AI SDK wraps it via `jsonSchema()`.
39
- */
40
- const ToolSchemaSchema = z.object({
41
- name: z.string().min(1),
42
- description: z.string().min(1),
43
- parameters: z.record(z.string(), z.unknown())
44
- });
45
- /** Empty Zod object schema used as default when tools have no parameters. */
46
- const EMPTY_PARAMS = z.object({});
47
- /**
48
- * Convert agent tool definitions to JSON Schema format for wire transport.
49
- *
50
- * Transforms the Zod-based `parameters` of each tool into a plain JSON Schema
51
- * object suitable for structured clone / JSON serialization.
52
- */
53
- function agentToolsToSchemas(tools) {
54
- return Object.entries(tools).map(([name, def]) => ({
55
- name,
56
- description: def.description,
57
- parameters: z.toJSONSchema(def.parameters ?? EMPTY_PARAMS)
58
- }));
59
- }
60
- //#endregion
61
- export { AgentConfigSchema, EMPTY_PARAMS, ToolSchemaSchema, agentToolsToSchemas, toAgentConfig };
@@ -1,73 +0,0 @@
1
- /**
2
- * Session context builder.
3
- *
4
- * Extracted from session.ts to keep it under the file-length lint limit.
5
- * Builds the shared mutable state object threaded through all session helpers.
6
- */
7
- import type { AgentConfig } from "./_internal-types.ts";
8
- import type { HookInvoker } from "./middleware.ts";
9
- import type { ClientSink } from "./protocol.ts";
10
- import type { Logger } from "./runtime.ts";
11
- import type { S2sHandle } from "./s2s.ts";
12
- import type { Message } from "./types.ts";
13
- import type { ExecuteTool } from "./worker-entry.ts";
14
- type PendingTool = {
15
- callId: string;
16
- result: string;
17
- };
18
- /**
19
- * Mutable state and dependencies shared across session helper functions.
20
- *
21
- * Created once per session by `buildCtx` and threaded through `setupListeners`,
22
- * `handleToolCall`, and other internal helpers. Contains both immutable
23
- * dependencies (logger, executor) and mutable per-turn state (pending tools,
24
- * generation counters).
25
- */
26
- export type S2sSessionCtx = {
27
- readonly id: string;
28
- readonly agent: string;
29
- readonly client: ClientSink;
30
- readonly agentConfig: AgentConfig;
31
- readonly executeTool: ExecuteTool;
32
- readonly hookInvoker: HookInvoker | undefined;
33
- readonly log: Logger;
34
- s2s: S2sHandle | null;
35
- pendingTools: PendingTool[];
36
- toolCallCount: number;
37
- turnPromise: Promise<void> | null;
38
- conversationMessages: Message[];
39
- /** Maximum number of messages to retain in conversationMessages. */
40
- readonly maxHistory: number;
41
- /** The `reply_id` from the most recent `reply.started` event. Tool calls
42
- * capture this at start; finishToolCall only pushes to pendingTools if the
43
- * reply ID still matches, preventing stale results from interrupted replies
44
- * from leaking into subsequent replies. Set to `null` on close/reset. */
45
- currentReplyId: string | null;
46
- /** Resolve per-turn configuration (dynamic `maxSteps`). */
47
- resolveTurnConfig(): Promise<{
48
- maxSteps?: number;
49
- } | null>;
50
- /** Increment the tool call counter and check whether the call should be refused. */
51
- consumeToolCallStep(turnConfig: {
52
- maxSteps?: number;
53
- } | null, name: string, replyId: string | null): string | null;
54
- /** Fire a lifecycle hook asynchronously. Errors are logged but never propagated. */
55
- fireHook(name: string, fn: (h: HookInvoker) => Promise<void>): void;
56
- /** Await all in-flight hook promises. Used during shutdown. */
57
- drainHooks(): Promise<void>;
58
- /** Push one or more messages and trim to maxHistory. */
59
- pushMessages(...msgs: Message[]): void;
60
- /** Sequential promise chain for filterOutput calls, ensuring ordering. */
61
- filterChain: Promise<void>;
62
- };
63
- export declare function buildCtx(opts: {
64
- id: string;
65
- agent: string;
66
- client: ClientSink;
67
- agentConfig: AgentConfig;
68
- executeTool: ExecuteTool;
69
- hookInvoker: HookInvoker | undefined;
70
- log: Logger;
71
- maxHistory?: number | undefined;
72
- }): S2sSessionCtx;
73
- export {};
@@ -1,43 +0,0 @@
1
- /**
2
- * OpenTelemetry-instrumented session helpers.
3
- *
4
- * Extracted from session.ts to keep it under the file-length lint limit.
5
- * These functions add trace spans and metric counters to the S2S session
6
- * pipeline: tool calls, user turns, barge-ins, and session lifecycle.
7
- */
8
- import type { S2sSessionCtx } from "./_session-ctx.ts";
9
- import type { S2sHandle, S2sToolCall } from "./s2s.ts";
10
- export { activeSessionsUpDown, sessionCounter } from "./telemetry.ts";
11
- /**
12
- * Orchestrate the full tool call pipeline for a single S2S tool invocation.
13
- *
14
- * Steps: resolve per-turn config → check step/tool limits → run middleware
15
- * `interceptToolCall` (which may block, return a cached result, or modify args)
16
- * → execute the tool → run `afterToolCall` middleware → record metrics and
17
- * finish via {@link finishToolCall}. Each step is wrapped in an OpenTelemetry
18
- * span (`tool.call`) with agent/session/tool attributes.
19
- *
20
- * @param ctx - The shared mutable session context (see {@link S2sSessionCtx}).
21
- * @param detail - The tool call details from the S2S API (call ID, name, parsed args).
22
- */
23
- export declare function handleToolCall(ctx: S2sSessionCtx, detail: S2sToolCall): Promise<void>;
24
- /** Options for customizing S2S event listener behavior. */
25
- export type SetupListenersOptions = {
26
- /** Custom handler for session expiration. When provided, replaces the
27
- * default behavior of closing the handle. Used by resume logic to
28
- * fall back to a fresh session when S2S resume fails. */
29
- onSessionExpired?: () => void;
30
- };
31
- /**
32
- * Wire all S2S events to the client sink, hooks, and session state.
33
- *
34
- * Registers listeners on the S2S handle for: ready, session expiry, speech
35
- * start/stop, user/agent transcripts, reply lifecycle, tool calls, audio
36
- * chunks, errors, and close. Each listener delegates to a focused handler
37
- * function that updates `ctx` and emits client events.
38
- *
39
- * @param ctx - The shared mutable session context.
40
- * @param handle - The S2S WebSocket handle to listen on.
41
- * @param opts - Optional overrides for listener behavior.
42
- */
43
- export declare function setupListeners(ctx: S2sSessionCtx, handle: S2sHandle, opts?: SetupListenersOptions): void;
@@ -1,30 +0,0 @@
1
- /**
2
- * Session persistence helpers.
3
- *
4
- * Saves and restores session state, conversation messages, and S2S session ID
5
- * to/from the KV store for cross-reconnect session recovery.
6
- */
7
- import type { Kv } from "./kv.ts";
8
- import type { Logger } from "./runtime.ts";
9
- import type { Message } from "./types.ts";
10
- export declare function persistKey(sessionId: string): string;
11
- export type PersistedSession = {
12
- s2sSessionId: string | null;
13
- messages: Message[];
14
- state: Record<string, unknown>;
15
- };
16
- export type SessionPersistence = {
17
- kv: Kv;
18
- ttl: number;
19
- getState: () => Record<string, unknown>;
20
- setState: (state: Record<string, unknown>) => void;
21
- };
22
- type PersistCtx = {
23
- pushMessages(...msgs: Message[]): void;
24
- conversationMessages: Message[];
25
- };
26
- export declare function restorePersistedSession(persistence: SessionPersistence, resumeFrom: string, ctx: PersistCtx, log: Logger): Promise<string | null>;
27
- export declare function saveSessionData(persistence: SessionPersistence, sessionId: string, ctx: PersistCtx, s2sSessionId: string | null, log: Logger,
28
- /** Old session key to clean up (from a previous session we resumed from). */
29
- cleanupKey?: string): Promise<void>;
30
- export {};
package/dist/_ssrf.d.ts DELETED
@@ -1,30 +0,0 @@
1
- /**
2
- * Check whether an IP address falls within a private or reserved range.
3
- *
4
- * @param ip - An IPv4 or IPv6 address string.
5
- * @returns `true` if the address is in a private/reserved range.
6
- */
7
- export declare function isPrivateIp(ip: string): boolean;
8
- /**
9
- * SSRF guard: assert that a URL targets a public internet address.
10
- *
11
- * Blocks requests to:
12
- * - Private IPv4 ranges (RFC 1918: 10.0.0.0/8, 172.16.0.0/12, 192.168.0.0/16)
13
- * - Loopback (127.0.0.0/8), link-local (169.254.0.0/16), shared (100.64.0.0/10)
14
- * - IPv4-mapped IPv6 addresses embedding private IPs (e.g. `::ffff:127.0.0.1`)
15
- * - IPv6 loopback (`::1`), ULA (`fc00::/7`), link-local (`fe80::/10`)
16
- * - `localhost`, `.local` (mDNS), `.internal` domains
17
- * - Cloud metadata endpoints (`169.254.169.254`, `metadata.google.internal`)
18
- * - Non-http(s) schemes (e.g. `file:`, `ftp:`)
19
- * - Hostnames that resolve to private IPs via DNS (prevents DNS rebinding)
20
- *
21
- * @param url - The URL to validate (must be parseable by `new URL()`).
22
- * @throws {Error} If the URL targets a private/reserved address or uses a
23
- * disallowed protocol scheme.
24
- */
25
- export declare function assertPublicUrl(url: string): Promise<void>;
26
- /**
27
- * Fetch with SSRF-safe redirect handling: validates each redirect URL
28
- * against private/reserved IP ranges before following.
29
- */
30
- export declare function ssrfSafeFetch(url: string, init: RequestInit, fetchFn: typeof globalThis.fetch): Promise<Response>;