@simple-ai-lab/sdk 0.3.0 → 0.4.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js CHANGED
@@ -1,3 +1,20 @@
1
+ import {
2
+ DataClient,
3
+ MAX_BATCH_ROWS,
4
+ MAX_QUERY_SIZE,
5
+ SIMPLE_ACTION_BRAND,
6
+ SimpleAI,
7
+ SimpleAIError,
8
+ batchUpsertRowsSchema,
9
+ dataColumnPathSchema,
10
+ dataFilterSchema,
11
+ defineAction,
12
+ listOptionsSchema,
13
+ queryInputSchema,
14
+ recordPayloadSchema,
15
+ tableNameSchema
16
+ } from "./chunk-V4E5PSKB.js";
17
+
1
18
  // src/actions.ts
2
19
  import { z } from "zod";
3
20
  function isRecord(value) {
@@ -190,7 +207,7 @@ function compileCodeAction(config) {
190
207
  language: "typescript",
191
208
  source: typeof config.source === "string" ? config.source : requireSourceFile({ reference: config.source, options }),
192
209
  compiledJs: null,
193
- runtime: "node22",
210
+ runtime: "cloudflare-worker",
194
211
  timeoutMs: config.timeoutMs ?? 3e4
195
212
  }
196
213
  })
@@ -1134,252 +1151,6 @@ function compileAgent(definition, options = {}) {
1134
1151
  };
1135
1152
  }
1136
1153
 
1137
- // src/schemas.ts
1138
- import { z as z3 } from "zod";
1139
- var MAX_QUERY_SIZE = 50;
1140
- var MAX_BATCH_ROWS = 1e3;
1141
- var tableNameSchema = z3.string().regex(/^[a-z0-9_]+$/, "Table names are lowercase snake_case identifiers");
1142
- var filterValueSchema = z3.union([z3.string(), z3.number(), z3.boolean()]);
1143
- var dataColumnPathSchema = z3.string().trim().min(1).max(1024).refine((path) => path.split(".").every((segment) => segment.length > 0), {
1144
- message: "Must be a dot-separated column path with no empty segments"
1145
- });
1146
- var dataFilterSchema = z3.object({
1147
- column: dataColumnPathSchema,
1148
- values: z3.array(filterValueSchema)
1149
- });
1150
- var queryInputSchema = z3.object({
1151
- tableName: tableNameSchema,
1152
- filters: z3.array(dataFilterSchema).optional(),
1153
- text: z3.string().max(5e3).optional(),
1154
- size: z3.number().int().min(0).max(MAX_QUERY_SIZE).optional(),
1155
- from: z3.number().int().min(0).optional()
1156
- });
1157
- var listOptionsSchema = z3.object({
1158
- page: z3.number().int().min(1).optional(),
1159
- perPage: z3.number().int().min(1).max(200).optional(),
1160
- orderBy: z3.string().optional(),
1161
- orderDirection: z3.enum(["asc", "desc"]).optional(),
1162
- /** Column-name → value equality filters applied server-side. */
1163
- filters: z3.record(z3.string(), z3.string()).optional()
1164
- });
1165
- var recordPayloadSchema = z3.record(z3.string(), z3.unknown());
1166
- var batchUpsertRowsSchema = z3.array(recordPayloadSchema).min(1).max(MAX_BATCH_ROWS);
1167
-
1168
- // src/data.ts
1169
- function encodeTable(tableName) {
1170
- return encodeURIComponent(tableNameSchema.parse(tableName));
1171
- }
1172
- var DataClient = class {
1173
- #http;
1174
- constructor(http) {
1175
- this.#http = http;
1176
- }
1177
- /** Facet-filtered search over an indexed table (Elasticsearch-backed, max 50 hits). */
1178
- async query(input) {
1179
- const parsed = queryInputSchema.parse(input);
1180
- const result = await this.#http.request({ method: "POST", path: "/data/query", body: parsed });
1181
- return result;
1182
- }
1183
- /** Facet values for an indexed table. */
1184
- async facets(tableName) {
1185
- const result = await this.#http.request({ method: "GET", path: `/data/facets/${encodeTable(tableName)}` });
1186
- return result;
1187
- }
1188
- /** Paginated listing straight from the relational store. */
1189
- async list(tableName, options = {}) {
1190
- const parsed = listOptionsSchema.parse(options);
1191
- const query = { ...parsed.filters ?? {} };
1192
- if (parsed.page !== void 0) {
1193
- query.page = String(parsed.page);
1194
- }
1195
- if (parsed.perPage !== void 0) {
1196
- query.per_page = String(parsed.perPage);
1197
- }
1198
- if (parsed.orderBy !== void 0) {
1199
- query.order_by = parsed.orderBy;
1200
- }
1201
- if (parsed.orderDirection !== void 0) {
1202
- query.order_direction = parsed.orderDirection;
1203
- }
1204
- const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}`, query });
1205
- return result;
1206
- }
1207
- async get(tableName, id) {
1208
- const result = await this.#http.request({ method: "GET", path: `/data/${encodeTable(tableName)}/${id}` });
1209
- return result;
1210
- }
1211
- async create(tableName, payload) {
1212
- const result = await this.#http.request({
1213
- method: "PUT",
1214
- path: `/data/${encodeTable(tableName)}`,
1215
- body: recordPayloadSchema.parse(payload)
1216
- });
1217
- return result;
1218
- }
1219
- async update(tableName, id, payload) {
1220
- const result = await this.#http.request({
1221
- method: "PATCH",
1222
- path: `/data/${encodeTable(tableName)}/${id}`,
1223
- body: recordPayloadSchema.parse(payload)
1224
- });
1225
- return result;
1226
- }
1227
- async delete(tableName, id) {
1228
- const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}/${id}` });
1229
- return result;
1230
- }
1231
- /** Deletes every record in the table. Irreversible. */
1232
- async deleteAll(tableName) {
1233
- const result = await this.#http.request({ method: "DELETE", path: `/data/${encodeTable(tableName)}` });
1234
- return result;
1235
- }
1236
- /**
1237
- * Asynchronous bulk upsert (max 1000 rows per call). Rows are FULL-ROW
1238
- * REPLACE on key conflict — omitted columns are cleared, not preserved.
1239
- * Returns a batch handle; poll `getBatch` for completion.
1240
- */
1241
- async batchUpsert(tableName, rows) {
1242
- const result = await this.#http.request({
1243
- method: "PUT",
1244
- path: `/data/${encodeTable(tableName)}/batch`,
1245
- body: { rows: batchUpsertRowsSchema.parse(rows) }
1246
- });
1247
- return result;
1248
- }
1249
- /** Status of an async upsert batch created by `batchUpsert`. */
1250
- async getBatch(ingestBatchId) {
1251
- const result = await this.#http.request({
1252
- method: "GET",
1253
- path: `/data/_batches/${encodeURIComponent(ingestBatchId)}`
1254
- });
1255
- return result;
1256
- }
1257
- };
1258
-
1259
- // src/errors.ts
1260
- var SimpleAIError = class extends Error {
1261
- /** HTTP status code, or 0 when the request never reached the API. */
1262
- status;
1263
- /** Machine-readable error code from the API body, when present. */
1264
- code;
1265
- /** The parsed response body (JSON when possible, otherwise raw text). */
1266
- body;
1267
- constructor({
1268
- message,
1269
- status,
1270
- code,
1271
- body,
1272
- cause
1273
- }) {
1274
- super(message, cause === void 0 ? void 0 : { cause });
1275
- this.name = "SimpleAIError";
1276
- this.status = status;
1277
- this.code = code;
1278
- this.body = body;
1279
- }
1280
- };
1281
-
1282
- // src/http.ts
1283
- function parseBody(text) {
1284
- if (text.length === 0) {
1285
- return null;
1286
- }
1287
- try {
1288
- return JSON.parse(text);
1289
- } catch {
1290
- return text;
1291
- }
1292
- }
1293
- function errorDetails(body) {
1294
- if (body !== null && typeof body === "object") {
1295
- const record = body;
1296
- const code = typeof record.code === "string" ? record.code : null;
1297
- const message = typeof record.message === "string" ? record.message : typeof record.error === "string" ? record.error : null;
1298
- return { code, message };
1299
- }
1300
- return { code: null, message: typeof body === "string" && body.length > 0 ? body : null };
1301
- }
1302
- function createHttpClient({
1303
- baseUrl,
1304
- apiKey,
1305
- fetchImplementation
1306
- }) {
1307
- const normalizedBase = baseUrl.replace(/\/+$/, "");
1308
- return {
1309
- request: async ({ method, path, query, body }) => {
1310
- const queryString = query === void 0 || Object.keys(query).length === 0 ? "" : `?${new URLSearchParams(query).toString()}`;
1311
- const url = `${normalizedBase}${path}${queryString}`;
1312
- let response;
1313
- try {
1314
- response = await fetchImplementation(url, {
1315
- method,
1316
- headers: {
1317
- authorization: `Bearer ${apiKey}`,
1318
- "content-type": "application/json",
1319
- accept: "application/json"
1320
- },
1321
- ...body === void 0 ? {} : { body: JSON.stringify(body) }
1322
- });
1323
- } catch (e) {
1324
- throw new SimpleAIError({
1325
- message: `Request to ${method} ${path} failed: ${e instanceof Error ? e.message : String(e)}`,
1326
- status: 0,
1327
- code: "network_error",
1328
- body: null,
1329
- cause: e
1330
- });
1331
- }
1332
- const parsed = parseBody(await response.text());
1333
- if (!response.ok) {
1334
- const { code, message } = errorDetails(parsed);
1335
- throw new SimpleAIError({
1336
- message: message ?? `Request to ${method} ${path} failed with status ${response.status}`,
1337
- status: response.status,
1338
- code,
1339
- body: parsed
1340
- });
1341
- }
1342
- return parsed;
1343
- }
1344
- };
1345
- }
1346
-
1347
- // src/client.ts
1348
- var DEFAULT_BASE_URL = "https://api.prod.usesimple.ai/api/v1";
1349
- function envVar(name) {
1350
- if (typeof process === "undefined" || process.env === void 0) {
1351
- return void 0;
1352
- }
1353
- const value = process.env[name];
1354
- return value === void 0 || value === "" ? void 0 : value;
1355
- }
1356
- var SimpleAI = class {
1357
- /** Custom data tables — query, read, and write records. */
1358
- data;
1359
- constructor(options = {}) {
1360
- const apiKey = options.apiKey ?? envVar("SIMPLE_API_KEY");
1361
- if (apiKey === void 0) {
1362
- throw new Error(
1363
- "Missing API key. Pass `apiKey` to new SimpleAI(...) or set the SIMPLE_API_KEY environment variable. Inside Simple AI code actions the key is injected automatically."
1364
- );
1365
- }
1366
- const baseUrl = options.baseUrl ?? envVar("SIMPLE_BASE_URL") ?? DEFAULT_BASE_URL;
1367
- const fetchImplementation = options.fetch ?? ((url, init) => fetch(url, init));
1368
- const http = createHttpClient({ baseUrl, apiKey, fetchImplementation });
1369
- this.data = new DataClient(http);
1370
- }
1371
- };
1372
-
1373
- // src/define-action.ts
1374
- var SIMPLE_ACTION_BRAND = /* @__PURE__ */ Symbol.for("simple-ai.action");
1375
- function defineAction(handler) {
1376
- const wrapped = async ({ inputs, config }) => {
1377
- const client = new SimpleAI();
1378
- return handler({ inputs, config, client });
1379
- };
1380
- return Object.assign(wrapped, { [SIMPLE_ACTION_BRAND]: true });
1381
- }
1382
-
1383
1154
  // src/projects.ts
1384
1155
  function defineAgentSnapshot(definition) {
1385
1156
  return { kind: "agent-snapshot", ...definition };