@speeq/server 0.0.0-stage → 0.2.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.
@@ -0,0 +1,220 @@
1
+ import { AgentUser, AgentContext, KnowledgeSource, NewConversationEvent, LLMProvider, ConversationStore, TelemetryTransport } from '@speeq/core';
2
+ export { AgentContext, AgentUser, SpeeqError } from '@speeq/core';
3
+ import { z } from 'zod';
4
+
5
+ /** `read` tools only look things up. `write` tools change data and need confirmation by default. */
6
+ type ToolRisk = "read" | "write";
7
+ /** A developer-defined action the agent can run. Create one with {@link defineTool}. */
8
+ interface ToolDefinition<TInput extends z.ZodType = z.ZodType, TUser extends AgentUser = AgentUser> {
9
+ /** Name the model calls, `[a-zA-Z0-9_-]{1,64}`, e.g. `count_questions`. */
10
+ name: string;
11
+ /** Tells the model what the tool does and when to use it. */
12
+ description: string;
13
+ /** Zod schema for the arguments. The model's arguments are validated against it. */
14
+ input: TInput;
15
+ /** Default `read`. */
16
+ risk?: ToolRisk;
17
+ /** Ask the user before running. Defaults to `true` for `write` tools, `false` otherwise. */
18
+ requiresConfirmation?: boolean;
19
+ /** Text for the confirmation dialog, e.g. `Bookmark question 12?`. */
20
+ confirmationSummary?(input: z.output<TInput>): string;
21
+ /** Overrides `guardrails.toolTimeoutMs` for this tool. */
22
+ timeoutMs?: number;
23
+ /**
24
+ * Runs in your backend with your DB and the signed-in user in `ctx.user`, so apply the same
25
+ * permission checks your website applies. Throw `SpeeqError("FORBIDDEN")` to refuse. The return
26
+ * value is serialized to JSON, truncated, and shown to the model as untrusted data.
27
+ */
28
+ handler(input: z.output<TInput>, ctx: AgentContext<TUser>): unknown;
29
+ }
30
+ /**
31
+ * Defines a tool with full type inference for `input` in the handler.
32
+ *
33
+ * @example
34
+ * defineTool({
35
+ * name: "count_questions",
36
+ * description: "Count questions for a subject",
37
+ * input: z.object({ subject: z.string() }),
38
+ * handler: async ({ subject }, ctx) => ({ count: await db.count(subject, ctx.user) }),
39
+ * });
40
+ */
41
+ declare function defineTool<TInput extends z.ZodType, TUser extends AgentUser = AgentUser>(tool: ToolDefinition<TInput, TUser>): ToolDefinition<TInput, TUser>;
42
+ /** A page the agent may navigate to. Create one with {@link defineRoute}. */
43
+ interface RouteDefinition {
44
+ /** Stable id the model uses, e.g. `practice`. */
45
+ id: string;
46
+ /** Path pattern. `:name` segments are filled from params, e.g. `/subjects/:slug`. */
47
+ path: string;
48
+ /** Human title, e.g. `Practice`. */
49
+ title: string;
50
+ /** Helps the model choose the right page. */
51
+ description?: string;
52
+ /**
53
+ * Zod object schema for params. Keys used in `path` fill the path; other keys become the query
54
+ * string. Omit it for routes without params.
55
+ */
56
+ params?: z.ZodObject;
57
+ }
58
+ /** Defines a navigable route (validated at startup). */
59
+ declare function defineRoute(route: RouteDefinition): RouteDefinition;
60
+ /** Defines a searchable knowledge source. */
61
+ declare function defineKnowledgeSource<TUser extends AgentUser = AgentUser>(source: KnowledgeSource<TUser>): KnowledgeSource<TUser>;
62
+
63
+ /** Minimal logger. Defaults to `console` with a `[speeq]` prefix. */
64
+ interface SpeeqLogger {
65
+ error(message: string, detail?: unknown): void;
66
+ warn(message: string, detail?: unknown): void;
67
+ }
68
+ /** Agent behavior. */
69
+ interface AgentConfig {
70
+ /** Shown to users and used in the system prompt, e.g. `Helper`. */
71
+ name: string;
72
+ /** Your own system instructions (tone, scope, rules). */
73
+ instructions: string;
74
+ /** BCP 47 tags the agent may answer in. Default `["en-IN", "te-IN", "hi-IN"]`. */
75
+ languages?: string[];
76
+ /** Default `languages[0]`. */
77
+ defaultLanguage?: string;
78
+ /** Maximum LLM calls per turn (tool round-trips). Default 5. */
79
+ maxSteps?: number;
80
+ /** How many previous user turns are sent to the model. Default 8. */
81
+ historyTurns?: number;
82
+ temperature?: number;
83
+ }
84
+ /** Audit-log options. */
85
+ interface AuditConfig {
86
+ /**
87
+ * Who may read the audit log through `GET /audit/*`. **Without this, audit routes return 404.**
88
+ * Typically checks that the request comes from one of your admins.
89
+ */
90
+ authorize?(request: Request): boolean | Promise<boolean>;
91
+ /**
92
+ * Runs on every event before it is stored. Return a modified copy (e.g. with secrets removed),
93
+ * or `null` to not store the event. Stored events are also the history the model sees later.
94
+ * Secret-looking keys (`password`, `token`, …) in tool args are always redacted first.
95
+ */
96
+ redact?(event: NewConversationEvent): NewConversationEvent | null;
97
+ /** Delete sessions older than this many days (best effort, see `purgeExpired`). */
98
+ retentionDays?: number;
99
+ }
100
+ /** Limits that keep turns small, fast and safe. */
101
+ interface GuardrailsConfig {
102
+ /** Tool output longer than this is truncated before the model sees it. Default 8000. */
103
+ maxToolOutputChars?: number;
104
+ /** Default 8000 ms. */
105
+ toolTimeoutMs?: number;
106
+ /** Best-effort, per instance (see docs). Default 20 turns per minute per user/IP and per session. */
107
+ rateLimit?: {
108
+ turnsPerMinute?: number;
109
+ sessionsPerMinute?: number;
110
+ } | false;
111
+ /** Maximum JSON body size. Default 32 KiB. */
112
+ maxRequestBytes?: number;
113
+ /** Session token lifetime. Default 12 hours. */
114
+ sessionTtlSeconds?: number;
115
+ }
116
+ /** Anonymous usage telemetry (see docs/reference/telemetry.md). */
117
+ interface TelemetryConfig {
118
+ /** Default `true`. `SPEEQ_TELEMETRY=0` also disables it. */
119
+ enabled?: boolean;
120
+ /** Platform base URL. Defaults to `SPEEQ_PLATFORM_URL`. Nothing is sent without one. */
121
+ endpoint?: string;
122
+ /** Custom transport (tests, proxies). */
123
+ transport?: TelemetryTransport;
124
+ /** Minimum time between sends. Default 60 s. */
125
+ flushIntervalMs?: number;
126
+ }
127
+ /** Everything `createSpeeq` accepts. */
128
+ interface SpeeqConfig<TUser extends AgentUser = AgentUser> {
129
+ /** Public project key (`pk_…`) from the speeq platform. Used only for telemetry. */
130
+ projectKey?: string;
131
+ /** Signs session tokens. Required when `NODE_ENV=production`. Use 32+ random characters. */
132
+ secret?: string;
133
+ agent: AgentConfig;
134
+ llm: LLMProvider;
135
+ store: ConversationStore;
136
+ /** Returns the signed-in user for a request (e.g. from your NextAuth session), or `null`. */
137
+ resolveUser?(request: Request): TUser | null | Promise<TUser | null>;
138
+ /** Allow sessions without a user. Default: `true` if `resolveUser` is not set, else `false`. */
139
+ allowAnonymous?: boolean;
140
+ routes?: RouteDefinition[];
141
+ tools?: ToolDefinition<any, TUser>[];
142
+ knowledge?: KnowledgeSource<TUser>[];
143
+ audit?: AuditConfig;
144
+ guardrails?: GuardrailsConfig;
145
+ telemetry?: TelemetryConfig;
146
+ /** Check npm once for a newer SDK during development. Default true. */
147
+ updateCheck?: boolean;
148
+ /** Extra origins allowed to call the API (CORS). Same-origin only by default. */
149
+ allowedOrigins?: string[];
150
+ /** Hand background work to the platform (e.g. Vercel `waitUntil`) so it survives the response. */
151
+ waitUntil?(promise: Promise<unknown>): void;
152
+ logger?: SpeeqLogger;
153
+ }
154
+
155
+ /** What a session token proves: this session belongs to this user until `exp`. */
156
+ interface SessionClaims {
157
+ /** Session id. */
158
+ sid: string;
159
+ /** User id, or `null` for anonymous sessions. */
160
+ uid: string | null;
161
+ /** Expiry, seconds since the epoch. */
162
+ exp: number;
163
+ }
164
+ /**
165
+ * Signs claims into a compact token `base64url(json).base64url(hmac-sha256)`. Stateless: no
166
+ * session lookup is needed to authenticate a request.
167
+ */
168
+ declare function signSessionToken(claims: SessionClaims, secret: string): Promise<string>;
169
+ /**
170
+ * Verifies a token and returns its claims. Throws `UNAUTHENTICATED` for malformed or tampered
171
+ * tokens and `SESSION_EXPIRED` for expired ones. The signature check (`crypto.subtle.verify`)
172
+ * runs in constant time.
173
+ */
174
+ declare function verifySessionToken(token: string, secret: string, nowMs?: number): Promise<SessionClaims>;
175
+ /** Compares two strings in constant time (for secrets such as passwords or keys). */
176
+ declare function timingSafeEqual(a: string, b: string): boolean;
177
+
178
+ /** A web-standard request handler. */
179
+ type SpeeqHandler = (request: Request) => Promise<Response>;
180
+
181
+ /** The installed `@speeq/server` version. */
182
+ declare const SDK_VERSION: string;
183
+
184
+ /**
185
+ * `@speeq/server`: the speeq runtime that runs in **your** backend. Tools run here with your
186
+ * database and your user's permissions; conversations are stored in your store.
187
+ * @packageDocumentation
188
+ */
189
+
190
+ /** A configured speeq instance. */
191
+ interface Speeq {
192
+ /** Web-standard handler: mount it at a catch-all route such as `/api/speeq/[[...speeq]]`. */
193
+ handler: SpeeqHandler;
194
+ /**
195
+ * Deletes sessions older than `audit.retentionDays`. It also runs at most daily per instance
196
+ * when sessions start. Call it from a cron job if you need retention to be reliable.
197
+ */
198
+ purgeExpired(): Promise<{
199
+ sessions: number;
200
+ events: number;
201
+ }>;
202
+ }
203
+ /**
204
+ * Creates a speeq instance from your configuration.
205
+ *
206
+ * @example
207
+ * export const speeq = createSpeeq({
208
+ * secret: process.env.SPEEQ_SECRET,
209
+ * agent: { name: "Helper", instructions: "You help students use this site." },
210
+ * llm: createOpenAICompatibleProvider({ baseURL, apiKey, model }),
211
+ * store: createMongoStore({ db }),
212
+ * resolveUser: async (req) => getUserFromSession(req),
213
+ * routes: [defineRoute({ id: "practice", path: "/practice", title: "Practice" })],
214
+ * tools: [countQuestions],
215
+ * });
216
+ */
217
+ declare function createSpeeq<TUser extends AgentUser = AgentUser>(config: SpeeqConfig<TUser>): Speeq;
218
+
219
+ export { SDK_VERSION, createSpeeq, defineKnowledgeSource, defineRoute, defineTool, signSessionToken, timingSafeEqual, verifySessionToken };
220
+ export type { AgentConfig, AuditConfig, GuardrailsConfig, RouteDefinition, SessionClaims, Speeq, SpeeqConfig, SpeeqHandler, SpeeqLogger, TelemetryConfig, ToolDefinition, ToolRisk };