@teable/app 7.0.10 → 8.0.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 CHANGED
@@ -160,8 +160,9 @@ Secrets go with `http`: write `{{secret:STRIPE_KEY}}` where a key goes in a
160
160
  request's URL, a header or a text body, and the platform fills it in as the
161
161
  request leaves, only towards the hosts the secret allows. The app's code
162
162
  never holds the value. The app's creators set secrets in the builder
163
- (Settings › Secrets); locally and in tests the placeholder goes out as
164
- written.
163
+ (Settings › Secrets). In `bun run dev`, `teable()` fills them in from the
164
+ app's `.dev.vars` (`STRIPE_KEY=sk_test_...`, one per line, never committed),
165
+ towards any host; in tests the placeholder goes out as written.
165
166
 
166
167
  ## Sign-in and pages
167
168
 
package/dist/ai.d.ts ADDED
@@ -0,0 +1,74 @@
1
+ /**
2
+ * The `ai` capability as apps use it: tasks have it as `ctx.ai`, the app's
3
+ * Worker as `appOf(ctx).ai`. It asks the platform's model, which the app's
4
+ * space pays for, and holds the answer to a schema when given one: a zod
5
+ * schema, or any schema that converts itself to JSON Schema (Standard JSON
6
+ * Schema, `~standard`), so this module needs no schema library of its own.
7
+ */
8
+ import { type AiCapability, type AiMessage, type AiModel } from "./protocol.js";
9
+ /** A schema an answer is held to: `z.object({ ... })`, or any Standard JSON Schema. */
10
+ interface AnswerSchema<T = unknown> {
11
+ readonly "~standard": {
12
+ readonly validate: (value: unknown) => Checked<T> | Promise<Checked<T>>;
13
+ readonly jsonSchema: {
14
+ readonly output: (options: {
15
+ readonly target: "draft-2020-12";
16
+ }) => Record<string, unknown>;
17
+ };
18
+ };
19
+ }
20
+ type Checked<T> = {
21
+ readonly value: T;
22
+ readonly issues?: undefined;
23
+ } | {
24
+ readonly issues: ReadonlyArray<{
25
+ readonly message: string;
26
+ readonly path?: ReadonlyArray<PropertyKey | {
27
+ readonly key: PropertyKey;
28
+ }> | undefined;
29
+ }>;
30
+ };
31
+ /** What to ask, and how. */
32
+ export interface AiAsk {
33
+ /** The question or the task, as a person would write it. */
34
+ prompt?: string;
35
+ /** The conversation so far, oldest first; `prompt`, when given, comes after it. */
36
+ messages?: AiMessage[];
37
+ /** How the model should answer: its role, the rules, the tone. */
38
+ system?: string;
39
+ /** `standard` unless said; `lite` is faster and cheaper, for simple work. */
40
+ model?: AiModel;
41
+ /** The longest answer, in tokens: 2048 unless said, at most 8192. */
42
+ maxTokens?: number;
43
+ /** From 0 to 2: lower answers alike each time, higher varies more. */
44
+ temperature?: number;
45
+ }
46
+ /** The model's answer. */
47
+ export interface AiReply {
48
+ /** The answer, as the model wrote it. */
49
+ text: string;
50
+ model: AiModel;
51
+ /** The answer was cut off at `maxTokens`. */
52
+ truncated: boolean;
53
+ usage: {
54
+ inputTokens: number;
55
+ outputTokens: number;
56
+ };
57
+ }
58
+ /** A language model, run by the platform for the app and charged to its space's credits. */
59
+ export interface AppAi {
60
+ /**
61
+ * Ask for a value that fits `schema` (extract, classify, score): `data`,
62
+ * checked against the schema. Throws when the answer does not fit.
63
+ */
64
+ chat<T>(ask: AiAsk & {
65
+ schema: AnswerSchema<T>;
66
+ }): Promise<AiReply & {
67
+ data: T;
68
+ }>;
69
+ /** Ask, and read the answer in `text`. */
70
+ chat(ask: AiAsk): Promise<AiReply>;
71
+ }
72
+ /** The `ai` capability's binding, as tasks and the Worker use it. */
73
+ export declare function appAi(binding: AiCapability): AppAi;
74
+ export {};
package/dist/build/cli.js CHANGED
@@ -2,8 +2,8 @@
2
2
  import {
3
3
  buildServer,
4
4
  buildWorker
5
- } from "../chunks/NUNZDM2R.js";
6
- import "../chunks/VBS7QVKG.js";
5
+ } from "../chunks/3VL2R635.js";
6
+ import "../chunks/4CAHKYS4.js";
7
7
 
8
8
  // src/build/cli.ts
9
9
  import { mkdirSync, rmSync, writeFileSync } from "node:fs";
@@ -40,6 +40,17 @@ export declare function sqlAsText(): {
40
40
  map: null;
41
41
  } | undefined;
42
42
  };
43
+ /** What `writeBundle` is told of the output: where it went and how its files were named. */
44
+ interface PagesOutput {
45
+ dir?: string;
46
+ entryFileNames?: unknown;
47
+ chunkFileNames?: unknown;
48
+ assetFileNames?: unknown;
49
+ }
50
+ /** What `writeBundle` is told of the files written, by path: a chunk's source map is beside it. */
51
+ type PagesBundle = Record<string, {
52
+ sourcemapFileName?: string | null;
53
+ }>;
43
54
  /**
44
55
  * `teable()`, the Vite plugin that stands in for the runtime while an app
45
56
  * is developed (ADR 0014, 7.), on Vite's own host, as `@teable/app/testing`
@@ -51,7 +62,9 @@ export declare function sqlAsText(): {
51
62
  * non-member, signed out), a development session only this plugin trusts.
52
63
  * - `${APPS_PATH}/<appId>/` is the app's API, answered by the stand-in in
53
64
  * `../dev/host.ts`, which runs the app's server code in workerd on a local
54
- * database (`.teable/`), and runs it again after every change to it.
65
+ * database (`.teable/`), and runs it again after every change to it. The
66
+ * requests it sends out get the app's secrets from `.dev.vars` (`NAME=value`
67
+ * lines, never committed), read again whenever it changes.
55
68
  * - The app's own Worker (`src/worker/index.ts`) runs in workerd with the
56
69
  * props it gets on the platform, for what no page file answers and the
57
70
  * paths `public/_routes.json` includes.
@@ -59,6 +72,9 @@ export declare function sqlAsText(): {
59
72
  * With `remote`, the API is a runtime's instead (this repository's `bun run
60
73
  * dev` points it at the local runtime): calls carry the token given, or
61
74
  * none once the developer signs out, and there is no Worker.
75
+ *
76
+ * Built, the pages name the app they were built for, and their `_headers`
77
+ * keep the files named by their hash for good.
62
78
  */
63
79
  export interface TeableOptions {
64
80
  /** The app's id; `teable.json`'s by default. */
@@ -157,6 +173,16 @@ export declare function teable(options?: TeableOptions): {
157
173
  };
158
174
  injectTo: string;
159
175
  })[];
176
+ /**
177
+ * Built, the pages keep the files named by their hash for good (their
178
+ * `_headers`, cachedHeaders): a later build names its files anew, and
179
+ * without it every visit asks again for each, as Cloudflare has
180
+ * browsers do. After the other plugins, which may write files of their own.
181
+ */
182
+ writeBundle: {
183
+ order: "post";
184
+ handler(output: PagesOutput, bundle: PagesBundle): void;
185
+ };
160
186
  configureServer(server: DevServer): (() => void) | undefined;
161
187
  };
162
188
  export {};
@@ -3,8 +3,8 @@ import {
3
3
  buildWorker,
4
4
  sqlAsText,
5
5
  teable
6
- } from "../chunks/NUNZDM2R.js";
7
- import "../chunks/VBS7QVKG.js";
6
+ } from "../chunks/3VL2R635.js";
7
+ import "../chunks/4CAHKYS4.js";
8
8
  export {
9
9
  buildServer,
10
10
  buildWorker,
@@ -5,18 +5,20 @@ import {
5
5
  BRIDGE_PATH,
6
6
  DEV_PATHS,
7
7
  PAGES_APP_META,
8
+ SECRET_NAME,
8
9
  SESSION_PATH,
9
10
  checkAccess,
10
11
  isMember,
11
12
  pagesBridge,
12
13
  spaceRoleOf
13
- } from "./VBS7QVKG.js";
14
+ } from "./4CAHKYS4.js";
14
15
 
15
16
  // src/build/index.ts
16
- import { existsSync, readFileSync } from "node:fs";
17
+ import { existsSync, readdirSync, readFileSync, statSync, writeFileSync } from "node:fs";
17
18
  import { createServer } from "node:net";
18
19
  import { join, relative, sep } from "node:path";
19
20
  import { fileURLToPath } from "node:url";
21
+ import { parseEnv } from "node:util";
20
22
  import { build } from "esbuild";
21
23
  var SERVER_ENTRY = "src/server/index.ts";
22
24
  var WORKER_ENTRY = "src/worker/index.ts";
@@ -83,6 +85,45 @@ function sqlAsText() {
83
85
  }
84
86
  };
85
87
  }
88
+ var IMMUTABLE = "public, max-age=31536000, immutable";
89
+ var HEADER_RULES = 100;
90
+ function hashedFolder(output) {
91
+ const patterns = [output.entryFileNames, output.chunkFileNames, output.assetFileNames];
92
+ const folders = new Set(
93
+ patterns.map((pattern) => {
94
+ if (typeof pattern !== "string" || !/\[hash(:\d+)?\]/.test(pattern)) return null;
95
+ const folder = pattern.slice(0, Math.max(pattern.lastIndexOf("/"), 0));
96
+ return folder === "" || /[[\]*]/.test(folder) ? null : folder;
97
+ })
98
+ );
99
+ return folders.size === 1 ? [...folders][0] ?? null : null;
100
+ }
101
+ function cachedHeaders(dir, output, bundle) {
102
+ const folder = hashedFolder(output);
103
+ if (folder === null) return null;
104
+ const written = new Set(Object.keys(bundle));
105
+ for (const file2 of Object.values(bundle)) {
106
+ if (file2.sourcemapFileName) written.add(file2.sourcemapFileName);
107
+ }
108
+ const at = join(dir, folder);
109
+ const present = existsSync(at) ? readdirSync(at, { recursive: true, encoding: "utf8" }) : [];
110
+ const others = present.filter((file2) => {
111
+ const path = join(at, file2);
112
+ return statSync(path).isFile() && !written.has(relative(dir, path).split(sep).join("/"));
113
+ });
114
+ if (others.length > 0) return null;
115
+ const file = join(dir, "_headers");
116
+ const own = existsSync(file) ? readFileSync(file, "utf8") : "";
117
+ const lines = own.split(/\r?\n/);
118
+ if (lines.some((line) => /^\s*!?\s*cache-control\s*(:|$)/i.test(line))) return null;
119
+ if (lines.filter((line) => /^[^\s#]/.test(line)).length >= HEADER_RULES) return null;
120
+ const rule = `/${folder}/*
121
+ Cache-Control: ${IMMUTABLE}
122
+ `;
123
+ return own.trim() === "" ? rule : `${own.trimEnd()}
124
+
125
+ ${rule}`;
126
+ }
86
127
  var DEV_SESSION = "teable_dev_session";
87
128
  function appIdOf(root) {
88
129
  try {
@@ -203,6 +244,20 @@ function teable(options = {}) {
203
244
  };
204
245
  return [bridge, meta];
205
246
  },
247
+ /**
248
+ * Built, the pages keep the files named by their hash for good (their
249
+ * `_headers`, cachedHeaders): a later build names its files anew, and
250
+ * without it every visit asks again for each, as Cloudflare has
251
+ * browsers do. After the other plugins, which may write files of their own.
252
+ */
253
+ writeBundle: {
254
+ order: "post",
255
+ handler(output, bundle) {
256
+ if (output.dir === void 0) return;
257
+ const headers = cachedHeaders(output.dir, output, bundle);
258
+ if (headers !== null) writeFileSync(join(output.dir, "_headers"), headers);
259
+ }
260
+ },
206
261
  configureServer(server) {
207
262
  if (builder !== null) {
208
263
  const script = pagesBridge([builder]);
@@ -245,6 +300,25 @@ function localRuntime(server, appId, workerd) {
245
300
  }
246
301
  log.info(`teable: ${appId} runs here${hasWorker ? ", with its Worker" : ""}`);
247
302
  };
303
+ const secrets = async () => {
304
+ const file = join(root, ".dev.vars");
305
+ const values = existsSync(file) ? parseEnv(readFileSync(file, "utf8")) : {};
306
+ const names = Object.keys(values);
307
+ for (const name of names.filter((name2) => !SECRET_NAME.test(name2))) {
308
+ log.error(
309
+ `teable: .dev.vars: ${name} cannot name a secret: a capital letter, then capitals, digits and _, as STRIPE_KEY`
310
+ );
311
+ }
312
+ const named = names.filter((name) => SECRET_NAME.test(name));
313
+ const sent = await fetch(`${workerd}${DEV_PATHS.secrets}`, {
314
+ method: "PUT",
315
+ body: JSON.stringify(Object.fromEntries(named.map((name) => [name, values[name] ?? ""])))
316
+ });
317
+ if (!sent.ok) throw new Error(`.dev.vars not read: ${await sent.text()}`);
318
+ if (named.length > 0) {
319
+ log.info(`teable: the app's requests get ${named.join(", ")} from .dev.vars`);
320
+ }
321
+ };
248
322
  const start = async () => {
249
323
  const address = server.httpServer?.address();
250
324
  const { Miniflare, convertV4MiniflareOptions } = await import("miniflare");
@@ -274,6 +348,7 @@ function localRuntime(server, appId, workerd) {
274
348
  })
275
349
  );
276
350
  await mf.ready;
351
+ await secrets().catch((error) => log.error(`teable: ${String(error)}`));
277
352
  await deploy().catch((error) => log.error(`teable: not started: ${String(error)}`));
278
353
  };
279
354
  server.httpServer?.once("listening", () => {
@@ -283,12 +358,16 @@ function localRuntime(server, appId, workerd) {
283
358
  );
284
359
  });
285
360
  });
286
- const redeploy = (file) => {
361
+ const changed = (file) => {
287
362
  const path = relative(root, file).split(sep).join("/");
363
+ if (path === ".dev.vars") {
364
+ void started?.then(secrets).catch((error) => log.error(`teable: ${String(error)}`));
365
+ return;
366
+ }
288
367
  if (!/^(src\/(server|worker)|drizzle)\//.test(path)) return;
289
368
  void started?.then(deploy).catch((error) => log.error(`teable: not started: ${String(error)}`));
290
369
  };
291
- for (const event of ["change", "add", "unlink"]) server.watcher.on(event, redeploy);
370
+ for (const event of ["change", "add", "unlink"]) server.watcher.on(event, changed);
292
371
  const isWorkerFirst = workerFirst(root);
293
372
  server.middlewares.use((req, res, next) => {
294
373
  void (async () => {
@@ -1,12 +1,15 @@
1
1
  import {
2
2
  describeTables
3
- } from "./GFYV4PFY.js";
3
+ } from "./HS3KLGIJ.js";
4
+ import {
5
+ appAi
6
+ } from "./AFVNQ2KL.js";
4
7
  import {
5
8
  CAPABILITIES,
6
9
  PROTOCOL_VERSION,
7
10
  admit,
8
11
  isPageAccess
9
- } from "./VBS7QVKG.js";
12
+ } from "./4CAHKYS4.js";
10
13
 
11
14
  // src/server/errors.ts
12
15
  import { z } from "zod";
@@ -1019,9 +1022,10 @@ function capabilitiesFrom(env) {
1019
1022
  )
1020
1023
  }
1021
1024
  );
1022
- return Object.fromEntries(
1025
+ const bindings = Object.fromEntries(
1023
1026
  CAPABILITIES.map((name) => [name, each(name)])
1024
1027
  );
1028
+ return { ...bindings, ai: appAi(bindings.ai) };
1025
1029
  }
1026
1030
  function describeMethod(name, method, tableOf) {
1027
1031
  const input = z2.toJSONSchema(method.input, {
@@ -1,8 +1,12 @@
1
1
  // src/protocol.ts
2
- var PROTOCOL_VERSION = 7;
2
+ var PROTOCOL_VERSION = 8;
3
+ var OLDEST_PROTOCOL_VERSION = 7;
4
+ function hostRuns(protocol) {
5
+ return typeof protocol === "number" && Number.isInteger(protocol) && protocol >= OLDEST_PROTOCOL_VERSION && protocol <= PROTOCOL_VERSION;
6
+ }
3
7
  var APP_COMPATIBILITY_DATE = "2026-12-01";
4
8
  var SPACE_ROLES = ["owner", "creator", "editor", "commenter", "viewer"];
5
- var EVERY_CAPABILITY = { files: true, http: true };
9
+ var EVERY_CAPABILITY = { files: true, http: true, ai: true };
6
10
  var CAPABILITIES = Object.keys(EVERY_CAPABILITY);
7
11
  var ERROR_CODES = [
8
12
  "BAD_INPUT",
@@ -15,6 +19,9 @@ var ERROR_CODES = [
15
19
  "RATE_LIMITED",
16
20
  "INTERNAL"
17
21
  ];
22
+ function asksModel(messages) {
23
+ return messages.some((message) => message.role === "user");
24
+ }
18
25
  var DEFAULT_CURRENCY = "USD";
19
26
  var MINOR_UNITS = {
20
27
  BIF: 0,
@@ -65,7 +72,8 @@ function isPageAccess(access) {
65
72
  var DEV_PATHS = {
66
73
  deploy: "/__teable/deploy",
67
74
  gate: "/__teable/gate",
68
- worker: "/__teable/worker"
75
+ worker: "/__teable/worker",
76
+ secrets: "/__teable/secrets"
69
77
  };
70
78
  var ASSETS_HEADER = "X-Teable-Assets";
71
79
  var SESSION_PATH = "/.teable";
@@ -296,6 +304,7 @@ var SITE_ICON_TYPES = [
296
304
  "image/x-icon",
297
305
  "image/vnd.microsoft.icon"
298
306
  ];
307
+ var USAGE_KINDS = ["call", "task", "http", "ai"];
299
308
  var VISIT_PERIODS = [7, 30];
300
309
  var SECRET_NAME_PATTERN = "[A-Z][A-Z0-9_]{0,63}";
301
310
  var SECRET_NAME = new RegExp(`^${SECRET_NAME_PATTERN}$`);
@@ -306,6 +315,92 @@ var SECRET_PLACEHOLDER = new RegExp(
306
315
  `(?:\\{\\{|%7[Bb]%7[Bb])secret(?::|%3[Aa])(${SECRET_NAME_PATTERN})(?:\\}\\}|%7[Dd]%7[Dd])`,
307
316
  "g"
308
317
  );
318
+ function secretNamesIn(texts) {
319
+ const names = texts.flatMap(
320
+ (text) => Array.from(text.matchAll(SECRET_PLACEHOLDER), (match) => match[1] ?? "")
321
+ );
322
+ return [...new Set(names)];
323
+ }
324
+ var MAX_FILLED_BODY_BYTES = 1024 * 1024;
325
+ function bodyKind(contentType) {
326
+ const type = contentType?.split(";")[0]?.trim().toLowerCase() ?? "";
327
+ if (type === "application/json" || type.endsWith("+json")) return "json";
328
+ if (type === "application/x-www-form-urlencoded") return "form";
329
+ if (type.startsWith("text/") || type === "application/xml" || type.endsWith("+xml")) {
330
+ return "text";
331
+ }
332
+ return null;
333
+ }
334
+ var WRITE = {
335
+ json: (value, encoded) => encoded ? encodeURIComponent(value) : JSON.stringify(value).slice(1, -1),
336
+ form: (value) => encodeURIComponent(value),
337
+ text: (value, encoded) => encoded ? encodeURIComponent(value) : value
338
+ };
339
+ async function textUpTo(request, limit) {
340
+ const body = request.clone().body;
341
+ if (body === null) return null;
342
+ const reader = body.getReader();
343
+ const decoder = new TextDecoder();
344
+ let text = "";
345
+ let size = 0;
346
+ for (; ; ) {
347
+ const { done, value } = await reader.read();
348
+ if (done) return text + decoder.decode();
349
+ size += value.byteLength;
350
+ if (size > limit) {
351
+ await reader.cancel();
352
+ return null;
353
+ }
354
+ text += decoder.decode(value, { stream: true });
355
+ }
356
+ }
357
+ function allows(hosts, hostname) {
358
+ return hosts === null || hosts.some(
359
+ (host) => host.startsWith("*.") ? hostname.endsWith(host.slice(1)) : host === hostname
360
+ );
361
+ }
362
+ async function fillSecrets(request, secretsOf, whereSet) {
363
+ const kind = bodyKind(request.headers.get("Content-Type"));
364
+ const body = kind === null ? null : await textUpTo(request, MAX_FILLED_BODY_BYTES);
365
+ const headers = [...request.headers];
366
+ const names = secretNamesIn([request.url, ...headers.map(([, value]) => value), body ?? ""]);
367
+ if (names.length === 0) return request;
368
+ const secrets = await secretsOf(names);
369
+ const { host, hostname } = new URL(request.url);
370
+ for (const name of names) {
371
+ const secret = secrets.get(name);
372
+ if (secret === void 0) {
373
+ throw new Error(`The secret ${name} is not set: ${whereSet(name)}`);
374
+ }
375
+ if (!allows(secret.hosts, hostname)) {
376
+ throw new Error(
377
+ `The secret ${name} may not be sent to ${hostname}, only to ${secret.hosts?.join(", ")}`
378
+ );
379
+ }
380
+ }
381
+ const fill = (text, write) => text.replace(SECRET_PLACEHOLDER, (placeholder, name) => {
382
+ const secret = secrets.get(name);
383
+ return secret === void 0 ? placeholder : write(secret.value, placeholder.startsWith("%"));
384
+ });
385
+ const url = fill(request.url, (value) => encodeURIComponent(value));
386
+ if (new URL(url).host !== host) throw new Error("A secret cannot be part of a request's host");
387
+ let filled;
388
+ try {
389
+ filled = new Headers(headers.map(([key, value]) => [key, fill(value, (secret) => secret)]));
390
+ } catch {
391
+ throw new Error("A secret in a header cannot hold a line break");
392
+ }
393
+ const filledBody = kind !== null && body !== null && secretNamesIn([body]).length > 0;
394
+ if (filledBody) filled.delete("Content-Length");
395
+ return new Request(url, {
396
+ method: request.method,
397
+ headers: filled,
398
+ body: filledBody ? fill(body, WRITE[kind]) : request.body,
399
+ // As the app sent it: its own fetch follows a redirect, through here
400
+ // again, so a secret is checked again for where it leads.
401
+ redirect: "manual"
402
+ });
403
+ }
309
404
  function checkAccess(caller, access) {
310
405
  if (caller.kind === "system") return null;
311
406
  if (access === "internal") return "FORBIDDEN";
@@ -351,10 +446,13 @@ function rolesBelow(role) {
351
446
 
352
447
  export {
353
448
  PROTOCOL_VERSION,
449
+ OLDEST_PROTOCOL_VERSION,
450
+ hostRuns,
354
451
  APP_COMPATIBILITY_DATE,
355
452
  SPACE_ROLES,
356
453
  CAPABILITIES,
357
454
  ERROR_CODES,
455
+ asksModel,
358
456
  DEFAULT_CURRENCY,
359
457
  currencyDigits,
360
458
  ERROR_STATUS,
@@ -382,10 +480,13 @@ export {
382
480
  BADGE_RULES,
383
481
  SITE_LIMITS,
384
482
  SITE_ICON_TYPES,
483
+ USAGE_KINDS,
385
484
  VISIT_PERIODS,
386
485
  SECRET_NAME,
387
486
  secretPlaceholder,
388
487
  SECRET_PLACEHOLDER,
488
+ secretNamesIn,
489
+ fillSecrets,
389
490
  checkAccess,
390
491
  admit,
391
492
  isMember,
@@ -0,0 +1,66 @@
1
+ import {
2
+ asksModel
3
+ } from "./4CAHKYS4.js";
4
+
5
+ // src/ai.ts
6
+ function where(path = []) {
7
+ return ["answer", ...path.map((part) => String(typeof part === "object" ? part.key : part))].join(
8
+ "."
9
+ );
10
+ }
11
+ function jsonSchemaOf(schema) {
12
+ let converted;
13
+ try {
14
+ converted = schema["~standard"].jsonSchema.output({ target: "draft-2020-12" });
15
+ } catch (error) {
16
+ const reason = error instanceof Error ? error.message : String(error);
17
+ throw new Error(`The answer's schema cannot be written as JSON Schema: ${reason}`);
18
+ }
19
+ const { $schema: _, ...rest } = converted;
20
+ return rest;
21
+ }
22
+ function appAi(binding) {
23
+ return {
24
+ async chat(ask) {
25
+ const { prompt, messages = [], system, schema, model, maxTokens, temperature } = ask;
26
+ const conversation = [
27
+ ...system === void 0 ? [] : [{ role: "system", content: system }],
28
+ ...messages,
29
+ ...prompt === void 0 ? [] : [{ role: "user", content: prompt }]
30
+ ];
31
+ if (!asksModel(conversation)) {
32
+ throw new Error("Ask the model something: give a prompt, or messages with a user's");
33
+ }
34
+ const answered = await binding.chat({
35
+ messages: conversation,
36
+ ...model === void 0 ? {} : { model },
37
+ ...maxTokens === void 0 ? {} : { maxTokens },
38
+ ...temperature === void 0 ? {} : { temperature },
39
+ ...schema === void 0 ? {} : { schema: jsonSchemaOf(schema) }
40
+ });
41
+ if (!answered.ok) throw new Error(answered.error.message);
42
+ const answer = answered.value;
43
+ const reply = {
44
+ text: answer.text,
45
+ model: answer.model,
46
+ truncated: answer.truncated,
47
+ usage: answer.usage
48
+ };
49
+ if (schema === void 0) return reply;
50
+ const cut = answer.truncated ? " (it was cut off at maxTokens: allow more)" : "";
51
+ if (answer.json === void 0) {
52
+ throw new Error(`The model's answer is not JSON${cut}: ${answer.text.slice(0, 200)}`);
53
+ }
54
+ const checked = await schema["~standard"].validate(answer.json);
55
+ if (checked.issues) {
56
+ const issues = checked.issues.map((issue) => `${where(issue.path)}: ${issue.message}`);
57
+ throw new Error(`The model's answer does not fit the schema${cut}: ${issues.join("; ")}`);
58
+ }
59
+ return { ...reply, data: checked.value };
60
+ }
61
+ };
62
+ }
63
+
64
+ export {
65
+ appAi
66
+ };
@@ -5,7 +5,7 @@ import {
5
5
  PREVIEW_QUERY,
6
6
  SESSION_PATH,
7
7
  fileKeyPath
8
- } from "./VBS7QVKG.js";
8
+ } from "./4CAHKYS4.js";
9
9
 
10
10
  // src/client.ts
11
11
  var MethodError = class extends Error {
@@ -1,7 +1,7 @@
1
1
  import {
2
2
  DEFAULT_CURRENCY,
3
3
  currencyDigits
4
- } from "./VBS7QVKG.js";
4
+ } from "./4CAHKYS4.js";
5
5
 
6
6
  // src/schema.ts
7
7
  import { getTableColumns, getTableName, is } from "drizzle-orm";
package/dist/client.d.ts CHANGED
@@ -74,10 +74,11 @@ export declare class MethodError extends Error {
74
74
  }
75
75
  /**
76
76
  * What `subscribe` reports: the runtime's realtime messages (`changes` after a
77
- * call changed data, `deployed` after a new version went live), and
78
- * `reconnected` when the connection is back after dropping, since what
79
- * happened in between went unreported. After `deployed` or `reconnected`
80
- * anything may have changed, the manifest included.
77
+ * call changed data, `deployed` after a new version went live, `restored`
78
+ * after the data was put back to a backup), and `reconnected` when the
79
+ * connection is back after dropping, since what happened in between went
80
+ * unreported. After anything but `changes`, anything may have changed, the
81
+ * manifest included.
81
82
  */
82
83
  export type RealtimeEvent = RealtimeMessage | {
83
84
  type: "reconnected";
package/dist/client.js CHANGED
@@ -1,8 +1,8 @@
1
1
  import {
2
2
  MethodError,
3
3
  createClient
4
- } from "./chunks/IECAZUW6.js";
5
- import "./chunks/VBS7QVKG.js";
4
+ } from "./chunks/CNFVLNBK.js";
5
+ import "./chunks/4CAHKYS4.js";
6
6
  export {
7
7
  MethodError,
8
8
  createClient
@@ -8,10 +8,12 @@
8
8
  * gets on the platform. The app's server code runs as a facet of a host
9
9
  * Durable Object on a local database, as on the platform: calls are
10
10
  * admitted with the protocol's `admit`, tasks run from the host's alarm,
11
- * and realtime tells open pages what changed.
11
+ * and realtime tells open pages what changed. Its requests out are filled
12
+ * in with the app's secrets as on the platform (ADR 0015), from the values
13
+ * in the app's `.dev.vars` the plugin sends.
12
14
  */
13
15
  import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
14
- import { type AppAccount, type AppManifest, type Attachment, type Caller, type FilesCapability, type JsonValue, type MethodValue, type PublicLink, type Result } from "../protocol.js";
16
+ import { type AiAnswer, type AiCapability, type AppAccount, type AppManifest, type Attachment, type Caller, type FilesCapability, type JsonValue, type MethodValue, type PublicLink, type Result } from "../protocol.js";
15
17
  interface DevEnv {
16
18
  HOST: DurableObjectNamespace;
17
19
  LOADER: WorkerLoader;
@@ -46,6 +48,16 @@ export declare class DevHost extends DurableObject<DevEnv> {
46
48
  sendCode(email: string): Promise<void>;
47
49
  /** Sign in with the code printed for the email, once; null for another code. */
48
50
  redeem(email: string, code: string): Promise<AppAccount | null>;
51
+ /** The values of the app's secrets, as `.dev.vars` has them now: those before go. */
52
+ setSecrets(values: Record<string, string>): Promise<void>;
53
+ /**
54
+ * The secrets a request the app sends out names that have a value, for
55
+ * Outbound to fill in. Any host may have them: they are the developer's.
56
+ */
57
+ secretsFor(names: string[]): Promise<Map<string, {
58
+ value: string;
59
+ hosts: null;
60
+ }>>;
49
61
  alarm(): Promise<void>;
50
62
  fetch(): Promise<Response>;
51
63
  }
@@ -65,6 +77,22 @@ export declare class Files extends WorkerEntrypoint<DevEnv> implements FilesCapa
65
77
  expiresInSeconds?: number;
66
78
  }): Promise<PublicLink>;
67
79
  }
80
+ /**
81
+ * The app's network (the `http` capability): its own `fetch()` and
82
+ * `http.fetch`, with its secrets filled in as on the platform (ADR 0015),
83
+ * from the values in `.dev.vars`, towards any host.
84
+ */
85
+ export declare class Outbound extends WorkerEntrypoint<DevEnv> {
86
+ fetch(request: Request): Promise<Response>;
87
+ }
88
+ /**
89
+ * The `ai` capability, which only Teable runs: the model is the platform's,
90
+ * and its space pays for it. Here every question is refused, saying where it
91
+ * is answered.
92
+ */
93
+ export declare class Ai extends WorkerEntrypoint<DevEnv> implements AiCapability {
94
+ chat(): Promise<Result<AiAnswer>>;
95
+ }
68
96
  /** The pages' files for the app's Worker (`env.ASSETS`): what Vite serves. */
69
97
  export declare class Assets extends WorkerEntrypoint<DevEnv> {
70
98
  fetch(request: Request): Promise<Response>;
package/dist/dev/host.js CHANGED
@@ -9,8 +9,9 @@ import {
9
9
  admit,
10
10
  callableMethods,
11
11
  checkAccess,
12
+ fillSecrets,
12
13
  isMember
13
- } from "../chunks/VBS7QVKG.js";
14
+ } from "../chunks/4CAHKYS4.js";
14
15
 
15
16
  // src/dev/host.ts
16
17
  import { DurableObject, WorkerEntrypoint } from "cloudflare:workers";
@@ -62,7 +63,8 @@ var KV = {
62
63
  worker: "worker",
63
64
  manifest: "manifest",
64
65
  version: "version",
65
- accounts: "accounts"
66
+ accounts: "accounts",
67
+ secrets: "secrets"
66
68
  };
67
69
  function emailOf(value) {
68
70
  const email = typeof value === "string" ? value.trim().toLowerCase() : "";
@@ -162,6 +164,23 @@ var DevHost = class extends DurableObject {
162
164
  return this.signIn(email);
163
165
  }
164
166
  #codes = /* @__PURE__ */ new Map();
167
+ /** The values of the app's secrets, as `.dev.vars` has them now: those before go. */
168
+ async setSecrets(values) {
169
+ this.ctx.storage.kv.put(KV.secrets, values);
170
+ }
171
+ /**
172
+ * The secrets a request the app sends out names that have a value, for
173
+ * Outbound to fill in. Any host may have them: they are the developer's.
174
+ */
175
+ async secretsFor(names) {
176
+ const values = this.#kv(KV.secrets) ?? {};
177
+ return new Map(
178
+ names.flatMap((name) => {
179
+ const value = Object.hasOwn(values, name) ? values[name] : void 0;
180
+ return value === void 0 ? [] : [[name, { value, hosts: null }]];
181
+ })
182
+ );
183
+ }
165
184
  async alarm() {
166
185
  if (this.#kv(KV.code) === void 0) return;
167
186
  const { failed, effects } = await this.#facet().wake(Date.now());
@@ -200,15 +219,21 @@ var DevHost = class extends DurableObject {
200
219
  #facet() {
201
220
  const code = this.#kv(KV.code) ?? "";
202
221
  const declared = this.#kv(KV.manifest)?.capabilities ?? [];
203
- const files = this.ctx.exports.Files;
222
+ const exports = this.ctx.exports;
223
+ const http = declared.includes("http");
204
224
  const stub = this.ctx.facets.get("live", () => {
205
225
  const worker = this.env.LOADER.get(`${this.#kv(KV.codeId)}+${declared.join(",")}`, () => ({
206
226
  compatibilityDate: APP_COMPATIBILITY_DATE,
207
227
  mainModule: "app.js",
208
228
  modules: { "app.js": code },
209
- env: declared.includes("files") ? { files: files({ props: {} }) } : {},
210
- // The developer's machine: an app that declared `http` reaches the internet.
211
- globalOutbound: declared.includes("http") ? void 0 : null
229
+ env: {
230
+ ...declared.includes("files") && { files: exports.Files({ props: {} }) },
231
+ ...http && { http: exports.Outbound({ props: {} }) },
232
+ ...declared.includes("ai") && { ai: exports.Ai({ props: {} }) }
233
+ },
234
+ // The developer's machine: an app that declared `http` reaches the
235
+ // internet, through Outbound, which fills in its secrets.
236
+ globalOutbound: http ? exports.Outbound({ props: {} }) : null
212
237
  }));
213
238
  return { class: worker.getDurableObjectClass("App") };
214
239
  });
@@ -245,6 +270,22 @@ var Files = class extends WorkerEntrypoint {
245
270
  return shareFile(this.env, key, options?.expiresInSeconds);
246
271
  }
247
272
  };
273
+ var Outbound = class extends WorkerEntrypoint {
274
+ async fetch(request) {
275
+ const sent = await fillSecrets(
276
+ request,
277
+ (names) => host(this.env).secretsFor(names),
278
+ (name) => `in development, add ${name}=<its value> to the app's .dev.vars`
279
+ );
280
+ return fetch(sent);
281
+ }
282
+ };
283
+ var Ai = class extends WorkerEntrypoint {
284
+ async chat() {
285
+ const message = "AI answers only on Teable, not in bun run dev: preview the app to ask it from the Worker, or publish it to ask it from tasks";
286
+ return { ok: false, error: { code: "FORBIDDEN", message } };
287
+ }
288
+ };
248
289
  var Assets = class extends WorkerEntrypoint {
249
290
  async fetch(request) {
250
291
  const url = new URL(request.url);
@@ -468,7 +509,8 @@ async function toWorker(request, env, ctx, url) {
468
509
  caller,
469
510
  asCaller: exports.AsCaller({ props: { caller } }),
470
511
  asApp: exports.AsApp({ props: {} }),
471
- ...described.manifest.capabilities.includes("files") ? { files: exports.Files({ props: {} }) } : {}
512
+ ...described.manifest.capabilities.includes("files") ? { files: exports.Files({ props: {} }) } : {},
513
+ ...described.manifest.capabilities.includes("ai") ? { ai: exports.Ai({ props: {} }) } : {}
472
514
  };
473
515
  const code = described.worker;
474
516
  const worker = env.LOADER.get(`worker-${await sha256(code)}`, () => ({
@@ -488,6 +530,13 @@ var host_default = {
488
530
  const { server, worker } = await request.json();
489
531
  return answer(await host(env).deploy(server, worker));
490
532
  }
533
+ if (url.pathname === DEV_PATHS.secrets && request.method === "PUT") {
534
+ const values = await request.json().catch(() => null);
535
+ const strings = typeof values === "object" && values !== null && !Array.isArray(values) && Object.values(values).every((value) => typeof value === "string");
536
+ if (!strings) return errorBody("BAD_INPUT", "Send the secrets as JSON: { NAME: value }");
537
+ await host(env).setSecrets(values);
538
+ return new Response(null, { status: 204 });
539
+ }
491
540
  if (url.pathname === DEV_PATHS.gate) return gate(request, env, url);
492
541
  if (url.pathname === DEV_PATHS.worker || url.pathname.startsWith(`${DEV_PATHS.worker}/`)) {
493
542
  return toWorker(request, env, ctx, url);
@@ -498,10 +547,12 @@ var host_default = {
498
547
  }
499
548
  };
500
549
  export {
550
+ Ai,
501
551
  AsApp,
502
552
  AsCaller,
503
553
  Assets,
504
554
  DevHost,
505
555
  Files,
556
+ Outbound,
506
557
  host_default as default
507
558
  };
package/dist/index.d.ts CHANGED
@@ -6,7 +6,8 @@
6
6
  * can load outside workerd.
7
7
  */
8
8
  export { z } from "zod";
9
- export type { Access, AppManifest, Attachment, Caller, Capability, ColumnInfo, ColumnKind, ErrorCode, FilesCapability, HttpCapability, MethodInfo, SpaceRole, TableInfo, } from "./protocol.js";
9
+ export type { AiAsk, AiReply, AppAi } from "./ai.js";
10
+ export type { Access, AiCapability, AiModel, AppManifest, Attachment, Caller, Capability, ColumnInfo, ColumnKind, ErrorCode, FilesCapability, HttpCapability, MethodInfo, SpaceRole, TableInfo, } from "./protocol.js";
10
11
  export { createApp, type Database, type ReadContext, type ReadMethod, type TaskContext, type TaskMethod, type WriteContext, type WriteMethod, } from "./server/app.js";
11
12
  export { fail } from "./server/errors.js";
12
13
  export type { Migrations } from "./server/migrations.js";
package/dist/index.js CHANGED
@@ -1,9 +1,10 @@
1
1
  import {
2
2
  createApp,
3
3
  fail
4
- } from "./chunks/OAU5HBAB.js";
5
- import "./chunks/GFYV4PFY.js";
6
- import "./chunks/VBS7QVKG.js";
4
+ } from "./chunks/4BYDBXKF.js";
5
+ import "./chunks/HS3KLGIJ.js";
6
+ import "./chunks/AFVNQ2KL.js";
7
+ import "./chunks/4CAHKYS4.js";
7
8
 
8
9
  // src/index.ts
9
10
  import { z } from "zod";
@@ -9,11 +9,24 @@
9
9
  * depend on it.
10
10
  */
11
11
  /**
12
- * The version of the host ↔ app contract (the region below). A host deploys
13
- * and starts only apps built for its own version, so a change to the contract
14
- * comes with a new version, and every app is deployed again.
12
+ * The version of the host ↔ app contract (the region below): the one the
13
+ * SDK builds apps for, and the newest a host runs. Every change to the
14
+ * contract comes with a new version. A host runs apps built for any version
15
+ * from `OLDEST_PROTOCOL_VERSION` up (ADR 0035), so a change that only adds
16
+ * (a capability, say) bumps this one alone, and published apps keep running.
15
17
  */
16
- export declare const PROTOCOL_VERSION = 7;
18
+ export declare const PROTOCOL_VERSION = 8;
19
+ /**
20
+ * The oldest version of the contract a host still runs (ADR 0035). A change
21
+ * that apps built for it would notice raises it, with an ADR: apps built
22
+ * before stop until they are published again with the current SDK.
23
+ */
24
+ export declare const OLDEST_PROTOCOL_VERSION = 7;
25
+ /**
26
+ * Whether a host runs apps built for `protocol`: any version from the oldest
27
+ * it keeps to its own (ADR 0035). Deploys, starts and rollbacks hold to it.
28
+ */
29
+ export declare function hostRuns(protocol: unknown): boolean;
17
30
  /**
18
31
  * The workerd compatibility date every app runs with: the host loads app code
19
32
  * with it, and the SDK's and templates' tests run with it. Bump deliberately,
@@ -139,7 +152,7 @@ export interface TableInfo {
139
152
  columns: ColumnInfo[];
140
153
  }
141
154
  export interface AppManifest {
142
- /** The PROTOCOL_VERSION the app was built for; a host runs only its own. */
155
+ /** The PROTOCOL_VERSION the app was built for: a host runs it if `hostRuns` (ADR 0035). */
143
156
  protocol: number;
144
157
  methods: MethodInfo[];
145
158
  tables: TableInfo[];
@@ -199,6 +212,12 @@ export interface Capabilities {
199
212
  * `ctx.http.fetch` is the same.
200
213
  */
201
214
  http: HttpCapability;
215
+ /**
216
+ * Ask a language model: summarize, classify, extract, draft. Declare
217
+ * `capabilities: ["ai"]` in createApp. The platform runs the model and
218
+ * charges the app's space's credits; the app holds no key.
219
+ */
220
+ ai: AiCapability;
202
221
  }
203
222
  export type Capability = keyof Capabilities;
204
223
  /** Every capability, by name. */
@@ -226,6 +245,48 @@ export interface FilesCapability {
226
245
  export interface HttpCapability {
227
246
  fetch(input: string | URL | Request, init?: RequestInit): Promise<Response>;
228
247
  }
248
+ /**
249
+ * A language model, for tasks and the app's Worker, which the platform runs
250
+ * for the calling app and charges to its space. Apps call it through the
251
+ * SDK's `ai.chat`, which takes a prompt and a zod schema, and throws what is
252
+ * refused: a request that is not a question (BAD_INPUT), too many of them
253
+ * (RATE_LIMITED), a space out of credits (FORBIDDEN), a model that did not
254
+ * answer (INTERNAL).
255
+ */
256
+ export interface AiCapability {
257
+ chat(request: AiRequest): Promise<Result<AiAnswer>>;
258
+ }
259
+ /** Which model answers: `standard` unless said, or `lite`, faster and cheaper, for simple work. */
260
+ export type AiModel = "standard" | "lite";
261
+ /** One message of a conversation with the model. */
262
+ export interface AiMessage {
263
+ role: "system" | "user" | "assistant";
264
+ content: string;
265
+ }
266
+ export interface AiRequest {
267
+ /** The conversation so far, oldest first; the model answers the last. */
268
+ messages: AiMessage[];
269
+ model?: AiModel;
270
+ /** A JSON Schema the answer must fit: the answer is then JSON, in `json`. */
271
+ schema?: JsonSchema;
272
+ /** The longest answer, in tokens. */
273
+ maxTokens?: number;
274
+ /** From 0 to 2: lower answers alike each time, higher varies more. */
275
+ temperature?: number;
276
+ }
277
+ export interface AiAnswer {
278
+ /** The answer, as the model wrote it. */
279
+ text: string;
280
+ /** With a schema: the answer, parsed. */
281
+ json?: JsonValue;
282
+ model: AiModel;
283
+ /** The answer was cut off at `maxTokens`. */
284
+ truncated: boolean;
285
+ usage: {
286
+ inputTokens: number;
287
+ outputTokens: number;
288
+ };
289
+ }
229
290
  /** A link anyone can open to read one file, until `expiresAt` (epoch seconds). */
230
291
  export interface PublicLink {
231
292
  url: string;
@@ -324,6 +385,12 @@ export type Result<T> = {
324
385
  ok: false;
325
386
  error: AppErrorShape;
326
387
  };
388
+ /**
389
+ * Whether a conversation asks the model something (ADR 0036): a user's
390
+ * message is in it. The SDK checks before it asks, and the runtime again,
391
+ * since an app's code may send anything.
392
+ */
393
+ export declare function asksModel(messages: readonly AiMessage[]): boolean;
327
394
  /**
328
395
  * What methods' JSON Schemas tell the builder beside `KindKeywords`, so its
329
396
  * Data view edits rows in place and starts writes from a row: the column a
@@ -394,12 +461,15 @@ export declare function isPageAccess(access: unknown): access is PageAccess;
394
461
  * `{ server, worker }`;
395
462
  * - `gate`: whether a navigation may see the pages, 204, or the redirect or
396
463
  * page that says why not;
397
- * - `worker`: a request for the app's own Worker, its path after this.
464
+ * - `worker`: a request for the app's own Worker, its path after this;
465
+ * - `secrets`: the values of the app's secrets from its `.dev.vars`, PUT
466
+ * as JSON `{ NAME: value }`, all of them each time; nothing reads them back.
398
467
  */
399
468
  export declare const DEV_PATHS: {
400
469
  readonly deploy: "/__teable/deploy";
401
470
  readonly gate: "/__teable/gate";
402
471
  readonly worker: "/__teable/worker";
472
+ readonly secrets: "/__teable/secrets";
403
473
  };
404
474
  /** On the app's Worker's requests for its pages' files (`env.ASSETS`), in development: never sent back to it. */
405
475
  export declare const ASSETS_HEADER = "X-Teable-Assets";
@@ -569,9 +639,10 @@ export type PagesMessage = {
569
639
  export declare function pagesBridge(origins: readonly string[]): string;
570
640
  /**
571
641
  * Sent on `GET {APPS_PATH}/:appId/realtime`: `changes` after every call that
572
- * changed data, and `deployed` after a new version went live, which can change
573
- * both the data (its migrations are not in the changefeed) and the manifest,
574
- * so pages read everything again.
642
+ * changed data; `deployed` after a new version went live, which can change
643
+ * both the data (its migrations are not in the changefeed) and the manifest;
644
+ * and `restored` after the data was put back to a backup (ADR 0034), which
645
+ * changes any of it. After either, pages read everything again.
575
646
  */
576
647
  export type RealtimeMessage = {
577
648
  type: "changes";
@@ -580,6 +651,8 @@ export type RealtimeMessage = {
580
651
  } | {
581
652
  type: "deployed";
582
653
  version: number;
654
+ } | {
655
+ type: "restored";
583
656
  };
584
657
  /**
585
658
  * Where every app's API lives on the platform's hosts: `${APPS_PATH}/:appId/...`
@@ -716,11 +789,44 @@ export interface VersionInfo {
716
789
  commit: string | null;
717
790
  /** That commit's subject; for a rollback, the version it brought back. */
718
791
  message: string | null;
719
- /** The app protocol it was built for: a runtime starts only versions built for its own. */
792
+ /** The app protocol it was built for: a runtime starts it, or rolls back to it, if `hostRuns`. */
720
793
  protocol: number;
721
794
  /** Whether it is the version that serves the app now. */
722
795
  live: boolean;
723
796
  }
797
+ /**
798
+ * Why a backup of an app's data was taken (ADR 0034): before a version went
799
+ * live (`publish`: a publish, a rollback, the preview published), before a
800
+ * restore put other data in its place (`restore`), once a day while the data
801
+ * changes (`daily`), or because someone asked for one (`manual`).
802
+ */
803
+ export type BackupReason = "publish" | "restore" | "daily" | "manual";
804
+ /**
805
+ * A copy of an app's live data (ADR 0034), as `GET {APPS_PATH}/:appId/backups`
806
+ * lists them for those who may publish the app, newest first. `POST
807
+ * {APPS_PATH}/:appId/backups` takes one now (201); `POST
808
+ * {APPS_PATH}/:appId/backups/:id/restore` puts the live data back to one.
809
+ */
810
+ export interface BackupInfo {
811
+ id: number;
812
+ /** When it was taken, in epoch milliseconds. */
813
+ createdAt: number;
814
+ reason: BackupReason;
815
+ /** The version that was live then: its data has that version's migrations. */
816
+ version: number;
817
+ /** For a backup taken before a publish, the version that went live then; null for the others. */
818
+ published: number | null;
819
+ /** The user who published, restored or asked for it, or "platform"; null for the day's. */
820
+ createdBy: string | null;
821
+ }
822
+ /**
823
+ * A restore's answer (200): the backup whose data is live now, and the one
824
+ * taken of the data it replaced, which restoring undoes the restore.
825
+ */
826
+ export interface RestoreResponse {
827
+ restored: BackupInfo;
828
+ backup: BackupInfo;
829
+ }
724
830
  /**
725
831
  * An app's code is a git repository (ADR 0029): one in Cloudflare
726
832
  * Artifacts, named after the app, which the runtime keeps. Those who may
@@ -994,19 +1100,22 @@ export declare const SITE_LIMITS: {
994
1100
  };
995
1101
  /** The types an app's icon may be. */
996
1102
  export declare const SITE_ICON_TYPES: readonly ["image/png", "image/jpeg", "image/webp", "image/svg+xml", "image/x-icon", "image/vnd.microsoft.icon"];
1103
+ /** What is metered, as usage names it. */
1104
+ export declare const USAGE_KINDS: readonly ["call", "task", "http", "ai"];
1105
+ export type UsageKind = (typeof USAGE_KINDS)[number];
997
1106
  /**
998
1107
  * An app's usage (ADR 0006), as `GET {APPS_PATH}/:appId/usage` says it to
999
1108
  * its creators: per UTC day and kind, the calls its methods ran (`call`),
1000
- * its task runs (`task`) and the requests it sent out (`http`), with how
1001
- * long they took, from `from` to `to` (YYYY-MM-DD, both counted). Days
1002
- * without use are left out.
1109
+ * its task runs (`task`), the requests it sent out (`http`) and the answers
1110
+ * it asked AI for (`ai`), with how long they took, from `from` to `to`
1111
+ * (YYYY-MM-DD, both counted). Days without use are left out.
1003
1112
  */
1004
1113
  export interface AppUsage {
1005
1114
  from: string;
1006
1115
  to: string;
1007
1116
  days: {
1008
1117
  day: string;
1009
- kind: "call" | "task" | "http";
1118
+ kind: UsageKind;
1010
1119
  quantity: number;
1011
1120
  durationMs: number;
1012
1121
  }[];
@@ -1084,6 +1193,23 @@ export declare function secretPlaceholder(name: string): string;
1084
1193
  * `replace` and `matchAll`.
1085
1194
  */
1086
1195
  export declare const SECRET_PLACEHOLDER: RegExp;
1196
+ /** The names of the secrets the texts write, each once, in the order they come. */
1197
+ export declare function secretNamesIn(texts: readonly string[]): string[];
1198
+ /**
1199
+ * A request an app sends out, as it leaves (ADR 0015): each placeholder in
1200
+ * its URL, its headers and its text body (up to 1 MiB) filled in with its
1201
+ * secret, or the request itself when it has none. `secretsOf` gives those
1202
+ * of the names that are set, each with the hosts it may go to (null: any);
1203
+ * `whereSet` ends the message for one that is not set. Throws, for the app
1204
+ * to see, when a secret is not set or may not go to the request's host. A
1205
+ * redirect goes back to the app, whose own fetch follows it with what its
1206
+ * code wrote, so through here again. The runtime's Outbound fills with
1207
+ * this, and so does the dev host.
1208
+ */
1209
+ export declare function fillSecrets(request: Request, secretsOf: (names: string[]) => Promise<ReadonlyMap<string, {
1210
+ value: string;
1211
+ hosts: readonly string[] | null;
1212
+ }>>, whereSet: (name: string) => string): Promise<Request>;
1087
1213
  /**
1088
1214
  * The one access rule: may this caller invoke a method with this access level?
1089
1215
  * Returns the error code to report, or null when the call is allowed.
package/dist/protocol.js CHANGED
@@ -15,6 +15,7 @@ import {
15
15
  GITHUB_CHANNEL,
16
16
  GITHUB_CONFLICT_BRANCH,
17
17
  MAX_FILE_BYTES,
18
+ OLDEST_PROTOCOL_VERSION,
18
19
  PAGES_APP_META,
19
20
  PREVIEW_QUERY,
20
21
  PROTOCOL_VERSION,
@@ -26,12 +27,16 @@ import {
26
27
  SITE_ICON_TYPES,
27
28
  SITE_LIMITS,
28
29
  SPACE_ROLES,
30
+ USAGE_KINDS,
29
31
  VISIT_PERIODS,
30
32
  admit,
33
+ asksModel,
31
34
  callableMethods,
32
35
  checkAccess,
33
36
  currencyDigits,
34
37
  fileKeyPath,
38
+ fillSecrets,
39
+ hostRuns,
35
40
  isDomainName,
36
41
  isExposed,
37
42
  isMember,
@@ -41,10 +46,11 @@ import {
41
46
  pagesBridge,
42
47
  roleAsAsked,
43
48
  rolesBelow,
49
+ secretNamesIn,
44
50
  secretPlaceholder,
45
51
  signedInAsAsked,
46
52
  spaceRoleOf
47
- } from "./chunks/VBS7QVKG.js";
53
+ } from "./chunks/4CAHKYS4.js";
48
54
  export {
49
55
  APPS_PATH,
50
56
  APP_COMPATIBILITY_DATE,
@@ -62,6 +68,7 @@ export {
62
68
  GITHUB_CHANNEL,
63
69
  GITHUB_CONFLICT_BRANCH,
64
70
  MAX_FILE_BYTES,
71
+ OLDEST_PROTOCOL_VERSION,
65
72
  PAGES_APP_META,
66
73
  PREVIEW_QUERY,
67
74
  PROTOCOL_VERSION,
@@ -73,12 +80,16 @@ export {
73
80
  SITE_ICON_TYPES,
74
81
  SITE_LIMITS,
75
82
  SPACE_ROLES,
83
+ USAGE_KINDS,
76
84
  VISIT_PERIODS,
77
85
  admit,
86
+ asksModel,
78
87
  callableMethods,
79
88
  checkAccess,
80
89
  currencyDigits,
81
90
  fileKeyPath,
91
+ fillSecrets,
92
+ hostRuns,
82
93
  isDomainName,
83
94
  isExposed,
84
95
  isMember,
@@ -88,6 +99,7 @@ export {
88
99
  pagesBridge,
89
100
  roleAsAsked,
90
101
  rolesBelow,
102
+ secretNamesIn,
91
103
  secretPlaceholder,
92
104
  signedInAsAsked,
93
105
  spaceRoleOf
package/dist/schema.js CHANGED
@@ -3,8 +3,8 @@ import {
3
3
  col,
4
4
  describeTables,
5
5
  schemaOf
6
- } from "./chunks/GFYV4PFY.js";
7
- import "./chunks/VBS7QVKG.js";
6
+ } from "./chunks/HS3KLGIJ.js";
7
+ import "./chunks/4CAHKYS4.js";
8
8
  export {
9
9
  attachment,
10
10
  col,
@@ -2,6 +2,7 @@ import { DurableObject } from "cloudflare:workers";
2
2
  import { type DrizzleSqliteDODatabase } from "drizzle-orm/durable-sqlite";
3
3
  import type { SQLiteTable } from "drizzle-orm/sqlite-core";
4
4
  import { z } from "zod";
5
+ import { type AppAi } from "../ai.js";
5
6
  import { type Access, type AppFacet, type AppManifest, type Caller, type Capabilities, type Capability, type PageAccess } from "../protocol.js";
6
7
  import { type Migrations } from "./migrations.js";
7
8
  type Schema = Record<string, unknown>;
@@ -42,7 +43,9 @@ export interface WriteContext<S extends Schema, I> extends ReadContext<S, I> {
42
43
  }): void;
43
44
  }
44
45
  /** What a task gets: its input, and every platform capability (declared ones work). */
45
- export interface TaskContext<I> extends Capabilities {
46
+ export interface TaskContext<I> extends Omit<Capabilities, "ai"> {
47
+ /** A language model (`capabilities: ["ai"]`): `ai.chat({ prompt, schema })`. */
48
+ ai: AppAi;
46
49
  input: I;
47
50
  /** 1 on the first run; tasks are retried with backoff until they succeed. */
48
51
  attempt: number;
package/dist/testing.js CHANGED
@@ -1,13 +1,14 @@
1
1
  import {
2
2
  methodName
3
- } from "./chunks/OAU5HBAB.js";
4
- import "./chunks/GFYV4PFY.js";
3
+ } from "./chunks/4BYDBXKF.js";
4
+ import "./chunks/HS3KLGIJ.js";
5
+ import "./chunks/AFVNQ2KL.js";
5
6
  import {
6
7
  MethodError
7
- } from "./chunks/IECAZUW6.js";
8
+ } from "./chunks/CNFVLNBK.js";
8
9
  import {
9
10
  ERROR_STATUS
10
- } from "./chunks/VBS7QVKG.js";
11
+ } from "./chunks/4CAHKYS4.js";
11
12
 
12
13
  // src/testing.ts
13
14
  var OWNER = { kind: "user", userId: "test-owner", role: "owner", via: "api" };
package/dist/worker.d.ts CHANGED
@@ -25,6 +25,7 @@
25
25
  * through its methods, as the visitor (`asCaller`, under the method's access)
26
26
  * or as the app (`asApp`, internal methods too). Never change data on GET.
27
27
  */
28
+ import { type AppAi } from "./ai.js";
28
29
  import { type AppMethodName, type MethodInput, type MethodName, type MethodOutput, type ServerModule, type Untyped } from "./client.js";
29
30
  import { type Caller, type FilesCapability } from "./protocol.js";
30
31
  /** The Worker's env: its pages' files, and nothing else. */
@@ -48,6 +49,12 @@ export interface AppWorker<S> {
48
49
  };
49
50
  /** The app's files, when it declares `capabilities: ["files"]`. */
50
51
  readonly files: FilesCapability;
52
+ /**
53
+ * A language model, when the app declares `capabilities: ["ai"]`:
54
+ * `ai.chat({ prompt, schema })`. Each answer is charged to the app's
55
+ * space, so ask it only for those who should.
56
+ */
57
+ readonly ai: AppAi;
51
58
  }
52
59
  /**
53
60
  * The app as this request's Worker reaches it, typed from the app's server
package/dist/worker.js CHANGED
@@ -1,9 +1,12 @@
1
+ import {
2
+ appAi
3
+ } from "./chunks/AFVNQ2KL.js";
1
4
  import {
2
5
  MethodError
3
- } from "./chunks/IECAZUW6.js";
6
+ } from "./chunks/CNFVLNBK.js";
4
7
  import {
5
8
  ERROR_STATUS
6
- } from "./chunks/VBS7QVKG.js";
9
+ } from "./chunks/4CAHKYS4.js";
7
10
 
8
11
  // src/worker.ts
9
12
  function thrower(caller) {
@@ -15,9 +18,11 @@ function thrower(caller) {
15
18
  }
16
19
  };
17
20
  }
18
- var undeclared = new Proxy({}, {
19
- get: () => () => Promise.reject(new Error('Declare capabilities: ["files"] in createApp to use files'))
20
- });
21
+ function undeclared(name) {
22
+ return new Proxy({}, {
23
+ get: () => () => Promise.reject(new Error(`Declare capabilities: ["${name}"] in createApp to use ${name}`))
24
+ });
25
+ }
21
26
  function appOf(ctx) {
22
27
  const props = ctx.props;
23
28
  return {
@@ -25,7 +30,8 @@ function appOf(ctx) {
25
30
  caller: props.caller,
26
31
  asCaller: thrower(props.asCaller),
27
32
  asApp: thrower(props.asApp),
28
- files: props.files ?? undeclared
33
+ files: props.files ?? undeclared("files"),
34
+ ai: appAi(props.ai ?? undeclared("ai"))
29
35
  };
30
36
  }
31
37
  export {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@teable/app",
3
- "version": "7.0.10",
3
+ "version": "8.0.0",
4
4
  "description": "Write a Teable app as a Drizzle schema plus methods",
5
5
  "license": "MIT",
6
6
  "repository": {