@n-dream/builders-sdk 0.1.0 → 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.
- package/README.md +5 -2
- package/dist/index.d.ts +69 -9
- package/dist/index.js +372 -55
- package/package.json +2 -2
package/README.md
CHANGED
|
@@ -13,7 +13,7 @@ Apps import the package as `@builders/sdk`. Use an npm alias in
|
|
|
13
13
|
|
|
14
14
|
```json
|
|
15
15
|
"dependencies": {
|
|
16
|
-
"@builders/sdk": "npm:@n-dream/builders-sdk@^0.
|
|
16
|
+
"@builders/sdk": "npm:@n-dream/builders-sdk@^0.2.0"
|
|
17
17
|
}
|
|
18
18
|
```
|
|
19
19
|
|
|
@@ -24,7 +24,7 @@ later.
|
|
|
24
24
|
|
|
25
25
|
```ts
|
|
26
26
|
import { currentUser } from "@builders/sdk/next"; // server code only
|
|
27
|
-
import { db, ai, storage, notify } from "@builders/sdk";
|
|
27
|
+
import { db, ai, storage, notify, secrets } from "@builders/sdk";
|
|
28
28
|
|
|
29
29
|
const user = await currentUser(); // { email, name }
|
|
30
30
|
const notes = db.collection<{ text: string; author: string }>("notes");
|
|
@@ -32,8 +32,11 @@ await notes.add({ text: "Hello", author: user.email });
|
|
|
32
32
|
await notes.where("author", "==", user.email).limit(20).list();
|
|
33
33
|
|
|
34
34
|
await ai.ask("Summarise: ...", { model: "fast" }); // AI add-on
|
|
35
|
+
await ai.json("Sort: ...", { schema: z.object({ tag: z.string() }) }); // a checked object
|
|
36
|
+
await ai.image("A robot mascot"); // also ai.chat, ai.stream, ai.speak, ai.transcribe
|
|
35
37
|
await storage.upload("files/a.pdf", bytes); // storage add-on
|
|
36
38
|
await notify.slack("Done"); // notify add-on
|
|
39
|
+
await secrets.get("HUBSPOT_API_KEY"); // set in the portal
|
|
37
40
|
```
|
|
38
41
|
|
|
39
42
|
- `db` uses Firestore on the platform. In `next dev` and in tests, it uses
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
export { G as GetUserOptions, H as HeaderSource, U as User, g as getUser, n as nameFromEmail } from './chunks/user-Dr8gM34m.js';
|
|
2
|
+
import { z } from 'zod';
|
|
2
3
|
import 'jose';
|
|
3
4
|
|
|
4
5
|
declare const ADDONS: readonly ["ai", "storage", "cron", "notify", "internet"];
|
|
@@ -13,6 +14,9 @@ declare const CLAUDE_MODELS: {
|
|
|
13
14
|
};
|
|
14
15
|
type AiModelChoice = keyof typeof CLAUDE_MODELS;
|
|
15
16
|
|
|
17
|
+
declare const ATTACHMENT_TYPES: readonly ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
|
|
18
|
+
type AttachmentType = (typeof ATTACHMENT_TYPES)[number];
|
|
19
|
+
|
|
16
20
|
declare function resetMemoryDb(): void;
|
|
17
21
|
|
|
18
22
|
declare const MAX_QUERY_LIMIT = 500;
|
|
@@ -42,28 +46,75 @@ declare const db: {
|
|
|
42
46
|
};
|
|
43
47
|
|
|
44
48
|
type AiModel = AiModelChoice;
|
|
49
|
+
type Attachment = {
|
|
50
|
+
data: Uint8Array | string;
|
|
51
|
+
mediaType: AttachmentType;
|
|
52
|
+
} | {
|
|
53
|
+
storagePath: string;
|
|
54
|
+
mediaType: AttachmentType;
|
|
55
|
+
};
|
|
45
56
|
interface AskOptions {
|
|
46
57
|
system?: string;
|
|
47
58
|
model?: AiModel;
|
|
48
59
|
maxTokens?: number;
|
|
60
|
+
temperature?: number;
|
|
61
|
+
attachments?: Attachment[];
|
|
49
62
|
signal?: AbortSignal;
|
|
50
63
|
}
|
|
51
|
-
interface
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
model: AiModel;
|
|
55
|
-
maxTokens: number;
|
|
64
|
+
interface JsonOptions<T> extends AskOptions {
|
|
65
|
+
schema: z.ZodType<T>;
|
|
66
|
+
description?: string;
|
|
56
67
|
}
|
|
57
|
-
|
|
68
|
+
type Message = {
|
|
69
|
+
role: "user" | "assistant";
|
|
70
|
+
content: string;
|
|
71
|
+
attachments?: Attachment[];
|
|
72
|
+
};
|
|
73
|
+
interface ChatResult {
|
|
58
74
|
text: string;
|
|
59
|
-
|
|
75
|
+
stopReason: string | null;
|
|
60
76
|
usage: {
|
|
61
77
|
inputTokens: number;
|
|
62
78
|
outputTokens: number;
|
|
63
79
|
};
|
|
64
80
|
}
|
|
81
|
+
interface ImageOptions {
|
|
82
|
+
aspectRatio?: "1:1" | "3:2" | "2:3" | "3:4" | "4:3" | "4:5" | "5:4" | "9:16" | "16:9" | "21:9";
|
|
83
|
+
size?: "512" | "1K" | "2K";
|
|
84
|
+
images?: Attachment[];
|
|
85
|
+
signal?: AbortSignal;
|
|
86
|
+
}
|
|
87
|
+
interface GeneratedImage {
|
|
88
|
+
mediaType: string;
|
|
89
|
+
data: Buffer;
|
|
90
|
+
text: string;
|
|
91
|
+
}
|
|
92
|
+
interface SpeakOptions {
|
|
93
|
+
voice?: "Kore" | "Puck" | "Charon" | "Fenrir" | "Aoede" | "Leda" | "Orus" | "Zephyr";
|
|
94
|
+
style?: string;
|
|
95
|
+
signal?: AbortSignal;
|
|
96
|
+
}
|
|
97
|
+
interface TranscribeOptions {
|
|
98
|
+
mediaType: "audio/wav" | "audio/mpeg" | "audio/mp3" | "audio/flac" | "audio/ogg" | "audio/webm" | "audio/mp4" | "audio/m4a";
|
|
99
|
+
languages?: string[];
|
|
100
|
+
signal?: AbortSignal;
|
|
101
|
+
}
|
|
65
102
|
declare const ai: {
|
|
66
103
|
ask(prompt: string, opts?: AskOptions): Promise<string>;
|
|
104
|
+
chat(messages: Message[], opts?: AskOptions): Promise<ChatResult>;
|
|
105
|
+
json<T>(prompt: string, opts: JsonOptions<T>): Promise<T>;
|
|
106
|
+
stream(prompt: string | Message[], opts?: AskOptions): AsyncGenerator<string, ChatResult>;
|
|
107
|
+
image(prompt: string, opts?: ImageOptions): Promise<GeneratedImage>;
|
|
108
|
+
speak(text: string, opts?: SpeakOptions): Promise<{
|
|
109
|
+
mediaType: "audio/wav";
|
|
110
|
+
data: Buffer;
|
|
111
|
+
}>;
|
|
112
|
+
transcribe(audio: Uint8Array | {
|
|
113
|
+
storagePath: string;
|
|
114
|
+
}, opts: TranscribeOptions): Promise<{
|
|
115
|
+
text: string;
|
|
116
|
+
seconds: number;
|
|
117
|
+
}>;
|
|
67
118
|
};
|
|
68
119
|
|
|
69
120
|
declare const storage: {
|
|
@@ -87,6 +138,11 @@ declare const notify: {
|
|
|
87
138
|
slack(text: string): Promise<void>;
|
|
88
139
|
};
|
|
89
140
|
|
|
141
|
+
declare const secrets: {
|
|
142
|
+
get(name: string): Promise<string>;
|
|
143
|
+
clearCache(): void;
|
|
144
|
+
};
|
|
145
|
+
|
|
90
146
|
declare class BuildersError extends Error {
|
|
91
147
|
readonly status: number;
|
|
92
148
|
constructor(message: string, status?: number);
|
|
@@ -102,5 +158,9 @@ declare class AddOnNotEnabledError extends BuildersError {
|
|
|
102
158
|
constructor(addOn: AddOn);
|
|
103
159
|
}
|
|
104
160
|
|
|
105
|
-
|
|
106
|
-
|
|
161
|
+
declare class NotOnBuildersError extends BuildersError {
|
|
162
|
+
constructor(what: string);
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
export { AddOnNotEnabledError, BuildersError, IDENTITY_HEADER, MAX_QUERY_LIMIT, NotFoundError, NotOnBuildersError, NotSignedInError, ai, db, dbMode, notify, secrets, storage };
|
|
166
|
+
export type { AiModel, AskOptions, Attachment, ChatResult, Collection, DbMode, Doc, GeneratedImage, ImageOptions, JsonOptions, Message, Query, SpeakOptions, TranscribeOptions, WhereOp };
|
package/dist/index.js
CHANGED
|
@@ -8,6 +8,18 @@ import {
|
|
|
8
8
|
nameFromEmail
|
|
9
9
|
} from "./chunks/chunk-AXQENVKW.js";
|
|
10
10
|
|
|
11
|
+
// ../core/src/ai.ts
|
|
12
|
+
var CLAUDE_MODELS = {
|
|
13
|
+
fast: "claude-haiku-5-5",
|
|
14
|
+
// simple, fast and cheap
|
|
15
|
+
balanced: "claude-sonnet-5-5",
|
|
16
|
+
// the default
|
|
17
|
+
best: "claude-opus-5-5"
|
|
18
|
+
// hard tasks only; it costs the most
|
|
19
|
+
};
|
|
20
|
+
var AI_MODEL_CHOICES = Object.keys(CLAUDE_MODELS);
|
|
21
|
+
var PLATFORM_MODEL = CLAUDE_MODELS.balanced;
|
|
22
|
+
|
|
11
23
|
// ../core/src/firestore-indexes.ts
|
|
12
24
|
import { z } from "zod";
|
|
13
25
|
var INDEXES_FILE = "firestore.indexes.json";
|
|
@@ -146,6 +158,108 @@ function indexKey(ix) {
|
|
|
146
158
|
return `${ix.collectionGroup}|${ix.queryScope}|${fields.join(",")}`;
|
|
147
159
|
}
|
|
148
160
|
|
|
161
|
+
// ../core/src/app-ai.ts
|
|
162
|
+
import { z as z2 } from "zod";
|
|
163
|
+
var APP_HEADER = "x-builders-app";
|
|
164
|
+
var APP_ENV = {
|
|
165
|
+
tenant: "BUILDERS_TENANT",
|
|
166
|
+
app: "BUILDERS_APP",
|
|
167
|
+
// The app's own GCP project (Secret Manager of `secrets`).
|
|
168
|
+
project: "BUILDERS_GCP_PROJECT",
|
|
169
|
+
aiGateway: "AI_GATEWAY_URL",
|
|
170
|
+
// ai add-on and notify add-on
|
|
171
|
+
bucket: "STORAGE_BUCKET",
|
|
172
|
+
// storage add-on
|
|
173
|
+
// "preview" (a v-<n> revision, no secrets) or "live" (core RevisionKind).
|
|
174
|
+
revision: "BUILDERS_REVISION"
|
|
175
|
+
};
|
|
176
|
+
var APP_AI_LIMITS = {
|
|
177
|
+
// The request body (attachments are base64 in it).
|
|
178
|
+
maxBodyBytes: 20 * 1024 * 1024,
|
|
179
|
+
maxMessages: 200,
|
|
180
|
+
maxTextChars: 4e5,
|
|
181
|
+
maxAttachments: 20,
|
|
182
|
+
maxOutputTokens: 16e3,
|
|
183
|
+
// JSON Schema of ai.json, as JSON text.
|
|
184
|
+
maxSchemaChars: 64e3,
|
|
185
|
+
maxImageInputs: 6,
|
|
186
|
+
maxSpeechChars: 5e3,
|
|
187
|
+
// Speech-to-Text "recognize" takes audio up to one minute.
|
|
188
|
+
maxAudioBytes: 10 * 1024 * 1024,
|
|
189
|
+
maxSlackChars: 3e3,
|
|
190
|
+
maxEmailRecipients: 20,
|
|
191
|
+
maxEmailChars: 2e4
|
|
192
|
+
};
|
|
193
|
+
var ATTACHMENT_TYPES = ["image/png", "image/jpeg", "image/gif", "image/webp", "application/pdf"];
|
|
194
|
+
var Base64 = z2.string().regex(/^[A-Za-z0-9+/]*={0,2}$/, "Not base64.");
|
|
195
|
+
var ContentPartSchema = z2.discriminatedUnion("type", [
|
|
196
|
+
z2.object({ type: z2.literal("text"), text: z2.string().min(1) }),
|
|
197
|
+
z2.object({ type: z2.literal("file"), mediaType: z2.enum(ATTACHMENT_TYPES), data: Base64.min(1) })
|
|
198
|
+
]);
|
|
199
|
+
var ChatMessageSchema = z2.object({
|
|
200
|
+
role: z2.enum(["user", "assistant"]),
|
|
201
|
+
content: z2.union([z2.string().min(1), z2.array(ContentPartSchema).min(1).max(APP_AI_LIMITS.maxAttachments + 10)])
|
|
202
|
+
});
|
|
203
|
+
var ModelChoice = z2.enum(AI_MODEL_CHOICES);
|
|
204
|
+
var MessagesRequestSchema = z2.object({
|
|
205
|
+
model: ModelChoice.default("balanced"),
|
|
206
|
+
system: z2.string().max(APP_AI_LIMITS.maxTextChars).optional(),
|
|
207
|
+
messages: z2.array(ChatMessageSchema).min(1).max(APP_AI_LIMITS.maxMessages),
|
|
208
|
+
maxTokens: z2.number().int().min(1).max(APP_AI_LIMITS.maxOutputTokens).default(1024),
|
|
209
|
+
temperature: z2.number().min(0).max(1).optional(),
|
|
210
|
+
// Structured output: Claude must answer with JSON for this JSON Schema
|
|
211
|
+
// (an object schema). The SDK checks the answer with the app's zod schema.
|
|
212
|
+
json: z2.object({ schema: z2.record(z2.string(), z2.unknown()), description: z2.string().max(1e3).optional() }).optional(),
|
|
213
|
+
// Server-sent events: "text" deltas, then "done" (or "error").
|
|
214
|
+
stream: z2.boolean().default(false)
|
|
215
|
+
}).strict().refine((r) => r.messages[0].role === "user", "The first message must be from the user.").refine((r) => !(r.json && r.stream), "A JSON answer cannot stream.");
|
|
216
|
+
var IMAGE_ASPECT_RATIOS = ["1:1", "3:2", "2:3", "3:4", "4:3", "4:5", "5:4", "9:16", "16:9", "21:9"];
|
|
217
|
+
var IMAGE_SIZES = ["512", "1K", "2K"];
|
|
218
|
+
var ImageRequestSchema = z2.object({
|
|
219
|
+
prompt: z2.string().min(1).max(2e4),
|
|
220
|
+
aspectRatio: z2.enum(IMAGE_ASPECT_RATIOS).default("1:1"),
|
|
221
|
+
size: z2.enum(IMAGE_SIZES).default("1K"),
|
|
222
|
+
// Images to edit or to use as a reference.
|
|
223
|
+
images: z2.array(z2.object({ mediaType: z2.enum(["image/png", "image/jpeg", "image/webp"]), data: Base64.min(1) })).max(APP_AI_LIMITS.maxImageInputs).default([])
|
|
224
|
+
}).strict();
|
|
225
|
+
var SPEECH_VOICES = [
|
|
226
|
+
"Kore",
|
|
227
|
+
"Puck",
|
|
228
|
+
"Charon",
|
|
229
|
+
"Fenrir",
|
|
230
|
+
"Aoede",
|
|
231
|
+
"Leda",
|
|
232
|
+
"Orus",
|
|
233
|
+
"Zephyr"
|
|
234
|
+
];
|
|
235
|
+
var SpeechRequestSchema = z2.object({
|
|
236
|
+
text: z2.string().min(1).max(APP_AI_LIMITS.maxSpeechChars),
|
|
237
|
+
voice: z2.enum(SPEECH_VOICES).default("Kore"),
|
|
238
|
+
// How to speak, for example "Say cheerfully" (Gemini TTS follows it).
|
|
239
|
+
style: z2.string().max(500).optional()
|
|
240
|
+
}).strict();
|
|
241
|
+
var AUDIO_TYPES = ["audio/wav", "audio/x-wav", "audio/mpeg", "audio/mp3", "audio/flac", "audio/ogg", "audio/webm", "audio/mp4", "audio/m4a"];
|
|
242
|
+
var TranscribeRequestSchema = z2.object({
|
|
243
|
+
mediaType: z2.enum(AUDIO_TYPES),
|
|
244
|
+
data: Base64.min(1),
|
|
245
|
+
// BCP-47 codes, for example ["de-CH", "en-US"]. Default: detect.
|
|
246
|
+
languages: z2.array(z2.string().regex(/^[A-Za-z]{2,3}(-[A-Za-z0-9]{2,8})*$/)).min(1).max(3).optional()
|
|
247
|
+
}).strict();
|
|
248
|
+
var SlackRequestSchema = z2.object({ text: z2.string().min(1).max(APP_AI_LIMITS.maxSlackChars) }).strict();
|
|
249
|
+
var EmailRequestSchema = z2.object({
|
|
250
|
+
to: z2.array(z2.string().email().max(254)).min(1).max(APP_AI_LIMITS.maxEmailRecipients),
|
|
251
|
+
subject: z2.string().min(1).max(200).refine((s) => !/[\r\n]/.test(s), "One line."),
|
|
252
|
+
text: z2.string().min(1).max(APP_AI_LIMITS.maxEmailChars)
|
|
253
|
+
}).strict();
|
|
254
|
+
var SECRET_NAME = /^[A-Z][A-Z0-9_]{0,63}$/;
|
|
255
|
+
var PLATFORM_SECRET_PREFIX = "BUILDERS_";
|
|
256
|
+
var MAX_SECRET_BYTES = 16 * 1024;
|
|
257
|
+
function secretNameError(name) {
|
|
258
|
+
if (!SECRET_NAME.test(name)) return "Use capital letters, digits and _, starting with a letter (for example HUBSPOT_API_KEY).";
|
|
259
|
+
if (name.startsWith(PLATFORM_SECRET_PREFIX)) return `Names that start with ${PLATFORM_SECRET_PREFIX} are for the platform.`;
|
|
260
|
+
return null;
|
|
261
|
+
}
|
|
262
|
+
|
|
149
263
|
// src/db-limit.ts
|
|
150
264
|
var MAX_QUERY_LIMIT = 500;
|
|
151
265
|
function checkLimit(n) {
|
|
@@ -398,66 +512,101 @@ var db = {
|
|
|
398
512
|
reset: resetMemoryDb
|
|
399
513
|
};
|
|
400
514
|
|
|
401
|
-
// src/
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
515
|
+
// src/ai.ts
|
|
516
|
+
import { z as z3 } from "zod";
|
|
517
|
+
|
|
518
|
+
// src/platform.ts
|
|
519
|
+
var METADATA = "http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default";
|
|
520
|
+
var idTokens = /* @__PURE__ */ new Map();
|
|
521
|
+
var accessToken;
|
|
522
|
+
function jwtExp(token) {
|
|
523
|
+
try {
|
|
524
|
+
const payload = JSON.parse(Buffer.from(token.split(".")[1] ?? "", "base64url").toString("utf8"));
|
|
525
|
+
return typeof payload.exp === "number" ? payload.exp * 1e3 : 0;
|
|
526
|
+
} catch {
|
|
527
|
+
return 0;
|
|
528
|
+
}
|
|
406
529
|
}
|
|
407
|
-
async function
|
|
530
|
+
async function metadata(path) {
|
|
408
531
|
let res;
|
|
409
532
|
try {
|
|
410
|
-
res = await fetch(
|
|
533
|
+
res = await fetch(`${METADATA}${path}`, { headers: { "Metadata-Flavor": "Google" }, signal: AbortSignal.timeout(5e3) });
|
|
534
|
+
} catch {
|
|
535
|
+
throw new NotOnBuildersError("This");
|
|
536
|
+
}
|
|
537
|
+
if (!res.ok) throw new BuildersError(`The app's identity is not available (${res.status}).`, 503);
|
|
538
|
+
return res;
|
|
539
|
+
}
|
|
540
|
+
async function idToken(audience) {
|
|
541
|
+
const hit = idTokens.get(audience);
|
|
542
|
+
if (hit && hit.exp - Date.now() > 5 * 6e4) return hit.token;
|
|
543
|
+
const res = await metadata(`/identity?audience=${encodeURIComponent(audience)}&format=full`);
|
|
544
|
+
const token = (await res.text()).trim();
|
|
545
|
+
idTokens.set(audience, { token, exp: jwtExp(token) });
|
|
546
|
+
return token;
|
|
547
|
+
}
|
|
548
|
+
async function googleAccessToken() {
|
|
549
|
+
if (accessToken && accessToken.exp - Date.now() > 6e4) return accessToken.token;
|
|
550
|
+
const res = await metadata("/token");
|
|
551
|
+
const j = await res.json();
|
|
552
|
+
if (!j.access_token) throw new BuildersError("The app's identity gave no access token.", 503);
|
|
553
|
+
accessToken = { token: j.access_token, exp: Date.now() + (j.expires_in ?? 300) * 1e3 };
|
|
554
|
+
return accessToken.token;
|
|
555
|
+
}
|
|
556
|
+
var NotOnBuildersError = class extends BuildersError {
|
|
557
|
+
constructor(what) {
|
|
558
|
+
super(`${what} works only in a saved version or the live app on Builders, not in the Studio preview or on this computer. Save a version and try it there.`, 503);
|
|
559
|
+
this.name = "NotOnBuildersError";
|
|
560
|
+
}
|
|
561
|
+
};
|
|
562
|
+
var WHAT = { ai: "AI", notify: "Sending notifications" };
|
|
563
|
+
function gateway(addOn) {
|
|
564
|
+
const tenant = process.env[APP_ENV.tenant];
|
|
565
|
+
const app = process.env[APP_ENV.app];
|
|
566
|
+
if (!tenant || !app) throw new NotOnBuildersError(WHAT[addOn] ?? "This");
|
|
567
|
+
const url = process.env[APP_ENV.aiGateway];
|
|
568
|
+
if (!url) throw new AddOnNotEnabledError(addOn);
|
|
569
|
+
return { url: url.replace(/\/+$/, ""), app: `${tenant}/${app}` };
|
|
570
|
+
}
|
|
571
|
+
function errorOf(status, body, fallback) {
|
|
572
|
+
const msg = body?.error?.message ?? fallback;
|
|
573
|
+
return new BuildersError(msg, status === 429 && body?.error?.code === "budget" ? 402 : status);
|
|
574
|
+
}
|
|
575
|
+
async function gatewayFetch(t, path, body, o = {}) {
|
|
576
|
+
const token = await idToken(t.url);
|
|
577
|
+
let res;
|
|
578
|
+
try {
|
|
579
|
+
res = await fetch(`${t.url}${path}`, {
|
|
411
580
|
method: "POST",
|
|
412
|
-
headers: {
|
|
413
|
-
"content-type": "application/json",
|
|
414
|
-
...opts.key ? { authorization: `Bearer ${opts.key}` } : {}
|
|
415
|
-
},
|
|
581
|
+
headers: { "content-type": "application/json", authorization: `Bearer ${token}`, [APP_HEADER]: t.app },
|
|
416
582
|
body: JSON.stringify(body),
|
|
417
|
-
signal:
|
|
583
|
+
signal: o.signal ?? AbortSignal.timeout(o.timeoutMs ?? 12e4)
|
|
418
584
|
});
|
|
419
585
|
} catch (e) {
|
|
420
|
-
throw new BuildersError(`Could not reach the
|
|
421
|
-
}
|
|
422
|
-
const text = await res.text();
|
|
423
|
-
let json = void 0;
|
|
424
|
-
try {
|
|
425
|
-
json = text ? JSON.parse(text) : void 0;
|
|
426
|
-
} catch {
|
|
586
|
+
throw new BuildersError(`Could not reach the platform's AI service: ${e.message}`, 502);
|
|
427
587
|
}
|
|
428
588
|
if (!res.ok) {
|
|
429
|
-
const
|
|
430
|
-
|
|
431
|
-
|
|
589
|
+
const text = await res.text();
|
|
590
|
+
let j;
|
|
591
|
+
try {
|
|
592
|
+
j = JSON.parse(text);
|
|
593
|
+
} catch {
|
|
432
594
|
}
|
|
433
|
-
throw
|
|
595
|
+
throw errorOf(res.status, j, `The platform's AI service answered ${res.status}.`);
|
|
434
596
|
}
|
|
435
|
-
return
|
|
597
|
+
return res;
|
|
598
|
+
}
|
|
599
|
+
async function gatewayJson(addOn, path, body, o = {}) {
|
|
600
|
+
const res = await gatewayFetch(gateway(addOn), path, body, o);
|
|
601
|
+
return await res.json();
|
|
436
602
|
}
|
|
437
603
|
|
|
438
|
-
// src/
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
if (!Object.hasOwn(MODELS, model)) {
|
|
445
|
-
throw new BuildersError(`Unknown AI model "${model}". Use "fast", "balanced" or "best".`, 400);
|
|
446
|
-
}
|
|
447
|
-
const body = {
|
|
448
|
-
prompt,
|
|
449
|
-
system: opts.system,
|
|
450
|
-
model,
|
|
451
|
-
maxTokens: opts.maxTokens ?? 1024
|
|
452
|
-
};
|
|
453
|
-
const res = await postJson("AI service", `${url.replace(/\/+$/, "")}/v1/ask`, body, {
|
|
454
|
-
key: key2,
|
|
455
|
-
timeoutMs: 12e4,
|
|
456
|
-
signal: opts.signal
|
|
457
|
-
});
|
|
458
|
-
return res.text;
|
|
459
|
-
}
|
|
460
|
-
};
|
|
604
|
+
// src/http.ts
|
|
605
|
+
function requireEnv(addOn, ...names) {
|
|
606
|
+
const values = names.map((n) => process.env[n]);
|
|
607
|
+
if (values.some((v) => !v)) throw new AddOnNotEnabledError(addOn);
|
|
608
|
+
return values;
|
|
609
|
+
}
|
|
461
610
|
|
|
462
611
|
// src/storage.ts
|
|
463
612
|
var cached;
|
|
@@ -505,19 +654,185 @@ var storage = {
|
|
|
505
654
|
}
|
|
506
655
|
};
|
|
507
656
|
|
|
657
|
+
// src/ai.ts
|
|
658
|
+
var MODELS = new Set(AI_MODEL_CHOICES);
|
|
659
|
+
function model(m) {
|
|
660
|
+
const v = m ?? "balanced";
|
|
661
|
+
if (!MODELS.has(v)) throw new BuildersError(`Unknown AI model "${v}". Use "fast", "balanced" or "best".`, 400);
|
|
662
|
+
return v;
|
|
663
|
+
}
|
|
664
|
+
async function base64(a) {
|
|
665
|
+
if ("storagePath" in a) return (await storage.download(a.storagePath)).toString("base64");
|
|
666
|
+
return typeof a.data === "string" ? a.data : Buffer.from(a.data).toString("base64");
|
|
667
|
+
}
|
|
668
|
+
async function content(text, attachments = []) {
|
|
669
|
+
if (!attachments.length) return text;
|
|
670
|
+
const files = await Promise.all(attachments.map(async (a) => ({ type: "file", mediaType: a.mediaType, data: await base64(a) })));
|
|
671
|
+
return [...files, { type: "text", text }];
|
|
672
|
+
}
|
|
673
|
+
async function request(messages, o, extra = {}) {
|
|
674
|
+
return {
|
|
675
|
+
model: model(o.model),
|
|
676
|
+
...o.system ? { system: o.system } : {},
|
|
677
|
+
maxTokens: o.maxTokens ?? 1024,
|
|
678
|
+
...o.temperature !== void 0 ? { temperature: o.temperature } : {},
|
|
679
|
+
messages: await Promise.all(messages.map(async (m) => ({ role: m.role, content: await content(m.content, m.attachments) }))),
|
|
680
|
+
...extra
|
|
681
|
+
};
|
|
682
|
+
}
|
|
683
|
+
function toJsonSchema(schema) {
|
|
684
|
+
if (!schema || typeof schema !== "object" || !("_zod" in schema)) {
|
|
685
|
+
throw new BuildersError("ai.json needs a zod 4 schema, e.g. z.object({ city: z.string() }).", 400);
|
|
686
|
+
}
|
|
687
|
+
let js;
|
|
688
|
+
try {
|
|
689
|
+
js = z3.toJSONSchema(schema, { io: "input", unrepresentable: "throw" });
|
|
690
|
+
} catch (e) {
|
|
691
|
+
throw new BuildersError(
|
|
692
|
+
`ai.json cannot use this schema: ${e.message}. Use types that JSON can hold, for example z.iso.datetime() or z.coerce.date() instead of z.date().`,
|
|
693
|
+
400
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
delete js.$schema;
|
|
697
|
+
if (js.type !== "object") throw new BuildersError("ai.json needs an object schema (z.object({...})). Put a list in a field.", 400);
|
|
698
|
+
return js;
|
|
699
|
+
}
|
|
700
|
+
var ai = {
|
|
701
|
+
// One question, the answer as text.
|
|
702
|
+
async ask(prompt, opts = {}) {
|
|
703
|
+
return (await ai.chat([{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }], opts)).text;
|
|
704
|
+
},
|
|
705
|
+
// A conversation: the earlier messages, then the new question.
|
|
706
|
+
async chat(messages, opts = {}) {
|
|
707
|
+
const body = await request(messages, opts);
|
|
708
|
+
const r = await gatewayJson("ai", "/v1/messages", body, { signal: opts.signal, timeoutMs: 3e5 });
|
|
709
|
+
return { text: r.text, stopReason: r.stopReason, usage: r.usage };
|
|
710
|
+
},
|
|
711
|
+
// A typed object instead of text, checked with the schema. If the first
|
|
712
|
+
// answer does not match, Claude gets the problem and tries once more.
|
|
713
|
+
async json(prompt, opts) {
|
|
714
|
+
const schema = toJsonSchema(opts.schema);
|
|
715
|
+
const messages = [{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }];
|
|
716
|
+
let last = "";
|
|
717
|
+
for (let attempt = 0; attempt < 2; attempt++) {
|
|
718
|
+
const body = await request(messages, { ...opts, maxTokens: opts.maxTokens ?? 4096 }, { json: { schema, ...opts.description ? { description: opts.description } : {} } });
|
|
719
|
+
const r = await gatewayJson("ai", "/v1/messages", body, { signal: opts.signal, timeoutMs: 3e5 });
|
|
720
|
+
if (r.stopReason === "max_tokens") {
|
|
721
|
+
throw new BuildersError(`The AI answer was too long and was cut off. Raise maxTokens (now ${body.maxTokens}) or ask for less.`, 502);
|
|
722
|
+
}
|
|
723
|
+
const parsed = opts.schema.safeParse(r.json);
|
|
724
|
+
if (parsed.success) return parsed.data;
|
|
725
|
+
last = parsed.error.issues.slice(0, 5).map((i) => `${i.path.join(".") || "answer"}: ${i.message}`).join("; ");
|
|
726
|
+
messages.push({ role: "assistant", content: JSON.stringify(r.json ?? null).slice(0, 2e4) }, { role: "user", content: `That answer does not match the schema (${last}). Answer again with the tool, matching the schema exactly.` });
|
|
727
|
+
}
|
|
728
|
+
throw new BuildersError(`The AI answer did not match the schema: ${last}`, 502);
|
|
729
|
+
},
|
|
730
|
+
// The answer as it is written, piece by piece:
|
|
731
|
+
// for await (const piece of ai.stream("Write a poem")) send(piece);
|
|
732
|
+
async *stream(prompt, opts = {}) {
|
|
733
|
+
const messages = typeof prompt === "string" ? [{ role: "user", content: prompt, ...opts.attachments ? { attachments: opts.attachments } : {} }] : prompt;
|
|
734
|
+
const body = await request(messages, opts, { stream: true });
|
|
735
|
+
const res = await gatewayFetch(gateway("ai"), "/v1/messages", body, { signal: opts.signal, timeoutMs: 9e5 });
|
|
736
|
+
const reader = res.body.getReader();
|
|
737
|
+
const dec = new TextDecoder();
|
|
738
|
+
let buf = "";
|
|
739
|
+
let text = "";
|
|
740
|
+
let ended = false;
|
|
741
|
+
try {
|
|
742
|
+
for (; ; ) {
|
|
743
|
+
const { done, value } = await reader.read();
|
|
744
|
+
if (done) break;
|
|
745
|
+
buf += dec.decode(value, { stream: true });
|
|
746
|
+
let i;
|
|
747
|
+
while ((i = buf.indexOf("\n\n")) >= 0) {
|
|
748
|
+
const block = buf.slice(0, i);
|
|
749
|
+
buf = buf.slice(i + 2);
|
|
750
|
+
const line = block.split("\n").find((l) => l.startsWith("data:"));
|
|
751
|
+
if (!line) continue;
|
|
752
|
+
const ev = JSON.parse(line.slice(5));
|
|
753
|
+
if (ev.type === "text") {
|
|
754
|
+
text += ev.text;
|
|
755
|
+
yield ev.text;
|
|
756
|
+
} else if (ev.type === "done") {
|
|
757
|
+
ended = true;
|
|
758
|
+
return { text, stopReason: ev.stopReason, usage: ev.usage };
|
|
759
|
+
} else if (ev.type === "error") {
|
|
760
|
+
throw new BuildersError(ev.message, 502);
|
|
761
|
+
}
|
|
762
|
+
}
|
|
763
|
+
}
|
|
764
|
+
throw new BuildersError("The AI answer stopped early. Try again.", 502);
|
|
765
|
+
} finally {
|
|
766
|
+
if (!ended) await reader.cancel().catch(() => {
|
|
767
|
+
});
|
|
768
|
+
}
|
|
769
|
+
},
|
|
770
|
+
// A new image from a prompt, or a changed image (opts.images).
|
|
771
|
+
async image(prompt, opts = {}) {
|
|
772
|
+
const images = await Promise.all((opts.images ?? []).map(async (a) => ({ mediaType: a.mediaType, data: await base64(a) })));
|
|
773
|
+
const r = await gatewayJson("ai", "/v1/image", { prompt, ...opts.aspectRatio ? { aspectRatio: opts.aspectRatio } : {}, ...opts.size ? { size: opts.size } : {}, images }, { signal: opts.signal, timeoutMs: 3e5 });
|
|
774
|
+
const first = r.images[0];
|
|
775
|
+
if (!first) throw new BuildersError("The AI made no image. Change the prompt and try again.", 502);
|
|
776
|
+
return { mediaType: first.mediaType, data: Buffer.from(first.data, "base64"), text: r.text };
|
|
777
|
+
},
|
|
778
|
+
// Text to speech, as WAV audio.
|
|
779
|
+
async speak(text, opts = {}) {
|
|
780
|
+
const r = await gatewayJson("ai", "/v1/speech", { text, ...opts.voice ? { voice: opts.voice } : {}, ...opts.style ? { style: opts.style } : {} }, { signal: opts.signal, timeoutMs: 3e5 });
|
|
781
|
+
return { mediaType: "audio/wav", data: Buffer.from(r.data, "base64") };
|
|
782
|
+
},
|
|
783
|
+
// Speech to text, for audio up to one minute.
|
|
784
|
+
async transcribe(audio, opts) {
|
|
785
|
+
const data = "storagePath" in audio && !(audio instanceof Uint8Array) ? (await storage.download(audio.storagePath)).toString("base64") : Buffer.from(audio).toString("base64");
|
|
786
|
+
const r = await gatewayJson("ai", "/v1/transcribe", { mediaType: opts.mediaType, data, ...opts.languages ? { languages: opts.languages } : {} }, { signal: opts.signal, timeoutMs: 12e4 });
|
|
787
|
+
return { text: r.text, seconds: r.seconds };
|
|
788
|
+
}
|
|
789
|
+
};
|
|
790
|
+
|
|
508
791
|
// src/notify.ts
|
|
509
792
|
var notify = {
|
|
510
793
|
async email(to, subject, text) {
|
|
511
|
-
|
|
512
|
-
await postJson("notification service", `${url.replace(/\/+$/, "")}/v1/email`, {
|
|
513
|
-
to: Array.isArray(to) ? to : [to],
|
|
514
|
-
subject,
|
|
515
|
-
text
|
|
516
|
-
}, { key: process.env.NOTIFY_KEY });
|
|
794
|
+
await gatewayJson("notify", "/v1/notify/email", { to: Array.isArray(to) ? to : [to], subject, text }, { timeoutMs: 3e4 });
|
|
517
795
|
},
|
|
518
796
|
async slack(text) {
|
|
519
|
-
|
|
520
|
-
|
|
797
|
+
await gatewayJson("notify", "/v1/notify/slack", { text }, { timeoutMs: 3e4 });
|
|
798
|
+
}
|
|
799
|
+
};
|
|
800
|
+
|
|
801
|
+
// src/secrets.ts
|
|
802
|
+
var cache2 = /* @__PURE__ */ new Map();
|
|
803
|
+
var TTL_MS = 5 * 6e4;
|
|
804
|
+
var secrets = {
|
|
805
|
+
async get(name) {
|
|
806
|
+
const bad = secretNameError(name);
|
|
807
|
+
if (bad) throw new BuildersError(`"${name}" is not a secret name. ${bad}`, 400);
|
|
808
|
+
if (process.env[APP_ENV.revision] === "preview") {
|
|
809
|
+
throw new BuildersError(`Secrets work only in the live app, not in a version preview. Publish the version to use ${name}; until then show a message instead.`, 503);
|
|
810
|
+
}
|
|
811
|
+
const project = process.env[APP_ENV.project];
|
|
812
|
+
if (!project) {
|
|
813
|
+
const v = process.env.NODE_ENV !== "production" ? process.env[name] : void 0;
|
|
814
|
+
if (v) return v;
|
|
815
|
+
throw new NotFoundError(`The secret ${name} is not available here. Secrets work in versions and the live app; for pnpm dev put ${name}=... in .env.local.`);
|
|
816
|
+
}
|
|
817
|
+
const hit = cache2.get(name);
|
|
818
|
+
if (hit && Date.now() - hit.at < TTL_MS) return hit.value;
|
|
819
|
+
const url = `https://secretmanager.googleapis.com/v1/projects/${encodeURIComponent(project)}/secrets/${name}/versions/latest:access`;
|
|
820
|
+
let res;
|
|
821
|
+
try {
|
|
822
|
+
res = await fetch(url, { headers: { authorization: `Bearer ${await googleAccessToken()}` }, signal: AbortSignal.timeout(1e4) });
|
|
823
|
+
} catch (e) {
|
|
824
|
+
throw new BuildersError(`Could not read the secret ${name}: ${e.message}`, 502);
|
|
825
|
+
}
|
|
826
|
+
if (res.status === 404 || res.status === 403) throw new NotFoundError(`The secret ${name} is not set. The app owner or an admin can set it in the Builders portal (app page, Secrets).`);
|
|
827
|
+
if (!res.ok) throw new BuildersError(`Could not read the secret ${name} (${res.status}).`, 502);
|
|
828
|
+
const j = await res.json();
|
|
829
|
+
const value = Buffer.from(j.payload?.data ?? "", "base64").toString("utf8");
|
|
830
|
+
cache2.set(name, { value, at: Date.now() });
|
|
831
|
+
return value;
|
|
832
|
+
},
|
|
833
|
+
// For tests.
|
|
834
|
+
clearCache() {
|
|
835
|
+
cache2.clear();
|
|
521
836
|
}
|
|
522
837
|
};
|
|
523
838
|
export {
|
|
@@ -526,6 +841,7 @@ export {
|
|
|
526
841
|
IDENTITY_HEADER,
|
|
527
842
|
MAX_QUERY_LIMIT,
|
|
528
843
|
NotFoundError,
|
|
844
|
+
NotOnBuildersError,
|
|
529
845
|
NotSignedInError,
|
|
530
846
|
ai,
|
|
531
847
|
db,
|
|
@@ -533,5 +849,6 @@ export {
|
|
|
533
849
|
getUser,
|
|
534
850
|
nameFromEmail,
|
|
535
851
|
notify,
|
|
852
|
+
secrets,
|
|
536
853
|
storage
|
|
537
854
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@n-dream/builders-sdk",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.2.0",
|
|
4
4
|
"description": "Builders platform helpers for app code: signed-in user, database, AI, file storage, notifications.",
|
|
5
5
|
"license": "UNLICENSED",
|
|
6
6
|
"homepage": "https://builders.n-dream.com",
|
|
@@ -33,7 +33,7 @@
|
|
|
33
33
|
"@google-cloud/firestore": "^9.4.0",
|
|
34
34
|
"@google-cloud/storage": "^8.4.0",
|
|
35
35
|
"jose": "^6.0.0",
|
|
36
|
-
"zod": "^
|
|
36
|
+
"zod": "^4.6.7"
|
|
37
37
|
},
|
|
38
38
|
"peerDependencies": {
|
|
39
39
|
"next": ">=15"
|