@softr/sdk 0.0.89-alpha.4 → 0.0.90-ai.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/action.d.ts +34 -1
- package/dist/action.js +12 -1
- package/dist/auth/platform.js +1 -1
- package/dist/core/ai.d.ts +79 -0
- package/dist/core/ai.js +64 -0
- package/dist/core/file-upload.js +3 -2
- package/dist/core/workflow.js +5 -4
- package/dist/datasource/record.js +1 -1
- package/dist/fetch.js +63 -1
- package/dist/formatting.d.ts +3 -3
- package/dist/index.d.ts +3 -4
- package/dist/index.js +2 -4
- package/dist/locale-settings.js +1 -1
- package/dist/mcp.js +4 -8
- package/dist/package.js +1 -1
- package/dist/pwa.d.ts +2 -2
- package/dist/pwa.js +2 -2
- package/dist/server.d.ts +2 -1
- package/dist/server.js +2 -1
- package/package.json +1 -1
- package/skills/softr-sdk/SKILL.md +13 -8
- package/skills/softr-sdk/ai/SKILL.md +168 -0
- package/skills/softr-sdk/auth/SKILL.md +1 -1
- package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
- package/skills/softr-sdk/current-user/SKILL.md +1 -1
- package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
- package/skills/softr-sdk/formatting/SKILL.md +1 -1
- package/skills/softr-sdk/integrations/SKILL.md +8 -4
- package/skills/softr-sdk/mcp/SKILL.md +1 -1
- package/skills/softr-sdk/pwa/SKILL.md +1 -1
- package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
- package/skills/softr-sdk/record-queries/SKILL.md +1 -1
- package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/routes-and-visibility/SKILL.md +1 -1
- package/skills/softr-sdk/workflows/SKILL.md +1 -1
- package/dist/agent/agent-fns.d.ts +0 -30
- package/dist/agent/agent-fns.js +0 -215
- package/dist/agent/use-agent-chat.d.ts +0 -106
- package/dist/agent/use-agent-chat.js +0 -486
- package/skills/softr-sdk/agent-chat/SKILL.md +0 -124
package/dist/action.d.ts
CHANGED
|
@@ -234,5 +234,38 @@ type IntegrationDefinition<TId extends string> = {
|
|
|
234
234
|
* const res = await listEvents({ query: { timeMin: now, singleEvents: "true" } })
|
|
235
235
|
*/
|
|
236
236
|
declare function defineIntegration<const TId extends string>(definition: IntegrationDefinition<TId>): IntegrationAction<TId>;
|
|
237
|
+
type AiResource = {
|
|
238
|
+
type: "SOFTR_AI";
|
|
239
|
+
model: string;
|
|
240
|
+
};
|
|
241
|
+
type AiAction<TId extends string = string> = Action<AiResource> & {
|
|
242
|
+
id: TId;
|
|
243
|
+
};
|
|
244
|
+
type AiDefinition<TId extends string> = {
|
|
245
|
+
id: TId;
|
|
246
|
+
model: string;
|
|
247
|
+
permissions: ActionPermissions;
|
|
248
|
+
};
|
|
249
|
+
/**
|
|
250
|
+
* Declares an AI action: a model call run by Softr on its own provider keys and billed to the
|
|
251
|
+
* workspace's AI credits, so nothing has to be connected. `model` is the id of a model from
|
|
252
|
+
* Softr's AI catalog, chosen when the app is built: read the catalog with the `ai_list_models`
|
|
253
|
+
* tool and copy the id exactly. An id outside the catalog is refused when the action is saved.
|
|
254
|
+
*
|
|
255
|
+
* Every call spends the workspace's credits, so keep the audience to signed-in users unless a
|
|
256
|
+
* public page really needs the call.
|
|
257
|
+
*
|
|
258
|
+
* Pass the returned object to `ai.generate()` or `ai.stream()` at runtime.
|
|
259
|
+
*
|
|
260
|
+
* @example
|
|
261
|
+
* const summarizeDeal = defineAiAction({
|
|
262
|
+
* id: "summarizeDeal",
|
|
263
|
+
* model: "anthropic-claude-sonnet-5-5",
|
|
264
|
+
* permissions: { userGroupTypes: ["LOGGED_IN_USERS"] },
|
|
265
|
+
* })
|
|
266
|
+
*
|
|
267
|
+
* const answer = await ai.generate(summarizeDeal, { system: "...", prompt: facts })
|
|
268
|
+
*/
|
|
269
|
+
declare function defineAiAction<const TId extends string>(definition: AiDefinition<TId>): AiAction<TId>;
|
|
237
270
|
//#endregion
|
|
238
|
-
export { ActionData, ActionPermissions, ActionRecord, ActionShape, DatasourceAction, FieldTypeOf, IntegrationAction, ReadOf, ReadShape, SoftrDatasources, WorkflowAction, defineIntegration, defineMutation, defineQuery, defineWorkflow };
|
|
271
|
+
export { ActionData, ActionPermissions, ActionRecord, ActionShape, AiAction, DatasourceAction, FieldTypeOf, IntegrationAction, ReadOf, ReadShape, SoftrDatasources, WorkflowAction, defineAiAction, defineIntegration, defineMutation, defineQuery, defineWorkflow };
|
package/dist/action.js
CHANGED
|
@@ -56,6 +56,17 @@ function isDatasourceAction(value) {
|
|
|
56
56
|
const resource = candidate.resource;
|
|
57
57
|
return typeof candidate.id === "string" && typeof resource === "object" && resource !== null && resource.type === "DATASOURCE";
|
|
58
58
|
}
|
|
59
|
+
function defineAiAction(definition) {
|
|
60
|
+
const { id, model, permissions } = definition;
|
|
61
|
+
return {
|
|
62
|
+
id,
|
|
63
|
+
resource: {
|
|
64
|
+
type: "SOFTR_AI",
|
|
65
|
+
model
|
|
66
|
+
},
|
|
67
|
+
permissions
|
|
68
|
+
};
|
|
69
|
+
}
|
|
59
70
|
|
|
60
71
|
//#endregion
|
|
61
|
-
export { defineIntegration, defineMutation, defineQuery, defineWorkflow, isDatasourceAction };
|
|
72
|
+
export { defineAiAction, defineIntegration, defineMutation, defineQuery, defineWorkflow, isDatasourceAction };
|
package/dist/auth/platform.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../assertions.js";
|
|
2
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
2
3
|
import { fetch } from "../fetch.js";
|
|
3
4
|
import { softrConfig } from "../softr-config.js";
|
|
4
5
|
import { permissionsSchema } from "./permissions.js";
|
|
5
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
6
6
|
import { z } from "zod";
|
|
7
7
|
|
|
8
8
|
//#region src/auth/platform.ts
|
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { AiAction } from "../action.js";
|
|
2
|
+
|
|
3
|
+
//#region src/core/ai.d.ts
|
|
4
|
+
/** A document or image the model reads, by the URL the app holds it under: one of its own uploads, as a rule. */
|
|
5
|
+
interface AiFile {
|
|
6
|
+
/** An https URL Softr may fetch. */
|
|
7
|
+
url: string;
|
|
8
|
+
/** The file's type when the URL does not say, such as `application/pdf`. */
|
|
9
|
+
mimeType?: string;
|
|
10
|
+
}
|
|
11
|
+
/** One earlier turn of a conversation. */
|
|
12
|
+
interface AiMessage {
|
|
13
|
+
role: 'user' | 'assistant';
|
|
14
|
+
content: string;
|
|
15
|
+
}
|
|
16
|
+
interface AiGenerateInit {
|
|
17
|
+
/** What the model is and the rules it answers under. */
|
|
18
|
+
system?: string;
|
|
19
|
+
/** The earlier turns of a conversation, oldest first, before the prompt. Leave out for a one-shot call. */
|
|
20
|
+
messages?: ReadonlyArray<AiMessage>;
|
|
21
|
+
/** What it is asked, with the facts it is given. */
|
|
22
|
+
prompt: string;
|
|
23
|
+
/**
|
|
24
|
+
* A JSON schema the answer has to match. With it, the model is asked for JSON only and the
|
|
25
|
+
* answer comes back parsed in `json` as well as written in `text`.
|
|
26
|
+
*/
|
|
27
|
+
schema?: Record<string, unknown>;
|
|
28
|
+
/** Documents and images the model reads alongside the prompt. */
|
|
29
|
+
files?: ReadonlyArray<AiFile>;
|
|
30
|
+
/** A cap on the answer's length, in tokens; Softr caps it further. */
|
|
31
|
+
maxOutputTokens?: number;
|
|
32
|
+
/**
|
|
33
|
+
* How hard a reasoning model thinks before it answers. A model that does not reason ignores it;
|
|
34
|
+
* the catalog says which do. Left out, the provider's default applies.
|
|
35
|
+
*/
|
|
36
|
+
reasoning?: 'low' | 'medium' | 'high';
|
|
37
|
+
/**
|
|
38
|
+
* How varied the answer is, 0 to 1: 0 for an extraction, higher for a draft. Left out, the provider's default
|
|
39
|
+
* applies. A model whose provider no longer takes one ignores it.
|
|
40
|
+
*/
|
|
41
|
+
temperature?: number;
|
|
42
|
+
signal?: AbortSignal;
|
|
43
|
+
}
|
|
44
|
+
interface AiUsage {
|
|
45
|
+
inputTokens: number;
|
|
46
|
+
outputTokens: number;
|
|
47
|
+
}
|
|
48
|
+
interface AiAnswer {
|
|
49
|
+
/** The answer as the model wrote it. */
|
|
50
|
+
text: string;
|
|
51
|
+
/** The answer parsed as JSON when `schema` was given and the model kept to it; `null` otherwise. */
|
|
52
|
+
json: unknown;
|
|
53
|
+
usage: AiUsage;
|
|
54
|
+
/** The model that answered. */
|
|
55
|
+
model: string;
|
|
56
|
+
}
|
|
57
|
+
/**
|
|
58
|
+
* Thrown when the model call was refused or failed. `status` is the HTTP status Softr answered
|
|
59
|
+
* with; 402 means the workspace has no AI credits left.
|
|
60
|
+
*/
|
|
61
|
+
declare class AiError extends Error {
|
|
62
|
+
readonly status: number;
|
|
63
|
+
constructor(status: number, message: string);
|
|
64
|
+
}
|
|
65
|
+
/** Runs the action once and answers when the model is done. */
|
|
66
|
+
declare function aiGenerate(action: AiAction, init: AiGenerateInit): Promise<AiAnswer>;
|
|
67
|
+
/**
|
|
68
|
+
* Runs the action and answers while the model writes. The returned `Response` body is a stream of
|
|
69
|
+
* Server-Sent Events, one JSON object per `data:` line: `{ "text": "..." }` for each piece of the
|
|
70
|
+
* answer, then `{ "done": true, "usage": {...}, "model": "..." }`, or `{ "error": "..." }` in its
|
|
71
|
+
* place. Hand it to the browser as a `Response` with `Content-Type: text/event-stream`.
|
|
72
|
+
*/
|
|
73
|
+
declare function aiStream(action: AiAction, init: AiGenerateInit): Promise<Response>;
|
|
74
|
+
declare const ai: {
|
|
75
|
+
generate: typeof aiGenerate;
|
|
76
|
+
stream: typeof aiStream;
|
|
77
|
+
};
|
|
78
|
+
//#endregion
|
|
79
|
+
export { AiAnswer, AiError, AiFile, AiGenerateInit, AiMessage, AiUsage, ai };
|
package/dist/core/ai.js
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
1
|
+
import { fetch } from "../fetch.js";
|
|
2
|
+
import { readSessionToken } from "../auth/session.js";
|
|
3
|
+
import { describeFailure, dsUrl, refererHeader } from "../datasource/record.js";
|
|
4
|
+
|
|
5
|
+
//#region src/core/ai.ts
|
|
6
|
+
/**
|
|
7
|
+
* Thrown when the model call was refused or failed. `status` is the HTTP status Softr answered
|
|
8
|
+
* with; 402 means the workspace has no AI credits left.
|
|
9
|
+
*/
|
|
10
|
+
var AiError = class extends Error {
|
|
11
|
+
status;
|
|
12
|
+
constructor(status, message) {
|
|
13
|
+
super(message);
|
|
14
|
+
this.name = "AiError";
|
|
15
|
+
this.status = status;
|
|
16
|
+
}
|
|
17
|
+
};
|
|
18
|
+
function body(init) {
|
|
19
|
+
return JSON.stringify({
|
|
20
|
+
system: init.system,
|
|
21
|
+
messages: init.messages,
|
|
22
|
+
prompt: init.prompt,
|
|
23
|
+
schema: init.schema,
|
|
24
|
+
files: init.files,
|
|
25
|
+
maxOutputTokens: init.maxOutputTokens,
|
|
26
|
+
reasoning: init.reasoning,
|
|
27
|
+
temperature: init.temperature
|
|
28
|
+
});
|
|
29
|
+
}
|
|
30
|
+
async function post(action, path, init) {
|
|
31
|
+
if (init.signal?.aborted) throw init.signal.reason ?? new DOMException("The operation was aborted.", "AbortError");
|
|
32
|
+
const res = await fetch(`${dsUrl(action.id)}/${path}`, {
|
|
33
|
+
method: "POST",
|
|
34
|
+
headers: {
|
|
35
|
+
"Content-Type": "application/json",
|
|
36
|
+
"Authorization": `Bearer ${readSessionToken()}`,
|
|
37
|
+
...refererHeader()
|
|
38
|
+
},
|
|
39
|
+
body: body(init),
|
|
40
|
+
signal: init.signal
|
|
41
|
+
});
|
|
42
|
+
if (!res.ok) throw new AiError(res.status, `AI call "${action.id}" failed: ${await describeFailure(res)}`);
|
|
43
|
+
return res;
|
|
44
|
+
}
|
|
45
|
+
/** Runs the action once and answers when the model is done. */
|
|
46
|
+
async function aiGenerate(action, init) {
|
|
47
|
+
return await (await post(action, "softr-ai/generate", init)).json();
|
|
48
|
+
}
|
|
49
|
+
/**
|
|
50
|
+
* Runs the action and answers while the model writes. The returned `Response` body is a stream of
|
|
51
|
+
* Server-Sent Events, one JSON object per `data:` line: `{ "text": "..." }` for each piece of the
|
|
52
|
+
* answer, then `{ "done": true, "usage": {...}, "model": "..." }`, or `{ "error": "..." }` in its
|
|
53
|
+
* place. Hand it to the browser as a `Response` with `Content-Type: text/event-stream`.
|
|
54
|
+
*/
|
|
55
|
+
async function aiStream(action, init) {
|
|
56
|
+
return post(action, "softr-ai/generate/stream", init);
|
|
57
|
+
}
|
|
58
|
+
const ai = {
|
|
59
|
+
generate: aiGenerate,
|
|
60
|
+
stream: aiStream
|
|
61
|
+
};
|
|
62
|
+
|
|
63
|
+
//#endregion
|
|
64
|
+
export { AiError, ai };
|
package/dist/core/file-upload.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
1
2
|
import { fetch } from "../fetch.js";
|
|
2
3
|
import { sessionConfig } from "../auth/config.js";
|
|
3
4
|
import { readSessionToken } from "../auth/session.js";
|
|
4
|
-
import {
|
|
5
|
+
import { describeFailure } from "../datasource/record.js";
|
|
5
6
|
import { randomUUID } from "node:crypto";
|
|
6
7
|
|
|
7
8
|
//#region src/core/file-upload.ts
|
|
@@ -18,7 +19,7 @@ async function upload(action, file) {
|
|
|
18
19
|
headers: token ? { Authorization: `Bearer ${token}` } : {},
|
|
19
20
|
body: formData
|
|
20
21
|
});
|
|
21
|
-
if (!res.ok) throw new Error(`File upload failed: ${res
|
|
22
|
+
if (!res.ok) throw new Error(`File upload failed: ${await describeFailure(res)}`);
|
|
22
23
|
const resultJSON = await res.json();
|
|
23
24
|
return {
|
|
24
25
|
url: resultJSON.url,
|
package/dist/core/workflow.js
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
1
2
|
import { fetch } from "../fetch.js";
|
|
2
3
|
import { sessionConfig } from "../auth/config.js";
|
|
3
4
|
import { readSessionToken } from "../auth/session.js";
|
|
4
|
-
import {
|
|
5
|
+
import { describeFailure } from "../datasource/record.js";
|
|
5
6
|
|
|
6
7
|
//#region src/core/workflow.ts
|
|
7
8
|
const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms));
|
|
@@ -14,7 +15,7 @@ async function triggerWorkflow(action, payload) {
|
|
|
14
15
|
},
|
|
15
16
|
body: JSON.stringify({ input: payload ?? {} })
|
|
16
17
|
});
|
|
17
|
-
if (!triggerRes.ok) throw new Error(`Workflow trigger failed: ${triggerRes
|
|
18
|
+
if (!triggerRes.ok) throw new Error(`Workflow trigger failed: ${await describeFailure(triggerRes)}`);
|
|
18
19
|
let details = await triggerRes.json();
|
|
19
20
|
while (details.status !== "FINISHED") {
|
|
20
21
|
if (details.status === "PENDING_INTERACTION") for (const interaction of details.nextInteractions) {
|
|
@@ -23,11 +24,11 @@ async function triggerWorkflow(action, payload) {
|
|
|
23
24
|
headers: { "Content-Type": "application/json" },
|
|
24
25
|
body: "{}"
|
|
25
26
|
});
|
|
26
|
-
if (!interactionRes.ok) throw new Error(`Workflow interaction failed: ${interactionRes
|
|
27
|
+
if (!interactionRes.ok) throw new Error(`Workflow interaction failed: ${await describeFailure(interactionRes)}`);
|
|
27
28
|
}
|
|
28
29
|
await sleep(1e3);
|
|
29
30
|
const detailsRes = await fetch(`${softrApiUrl("SOFTR_WORKFLOWS_API_URL")}/v1/workflows/${action.resource.workflowId}/executions/${details.id}/details`);
|
|
30
|
-
if (!detailsRes.ok) throw new Error(`Workflow status check failed: ${detailsRes
|
|
31
|
+
if (!detailsRes.ok) throw new Error(`Workflow status check failed: ${await describeFailure(detailsRes)}`);
|
|
31
32
|
details = await detailsRes.json();
|
|
32
33
|
}
|
|
33
34
|
}
|
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { assert, panic } from "../assertions.js";
|
|
2
|
+
import { softrApiUrl } from "../softr-api.js";
|
|
2
3
|
import { fetch } from "../fetch.js";
|
|
3
4
|
import { readUserTimezone } from "../cookies.js";
|
|
4
5
|
import { readSessionToken } from "../auth/session.js";
|
|
5
|
-
import { softrApiUrl } from "../softr-api.js";
|
|
6
6
|
import { isDatasourceAction } from "../action.js";
|
|
7
7
|
import { buildFilterCriteria, buildOrderBy, dealiasFilterCriteria, dealiasOrderBy } from "./filter.js";
|
|
8
8
|
import { andAll, makeFieldSet, makeSortSet } from "./fields.js";
|
package/dist/fetch.js
CHANGED
|
@@ -1,9 +1,29 @@
|
|
|
1
|
+
import { version } from "./package.js";
|
|
2
|
+
import { assert, requireDefined } from "./assertions.js";
|
|
1
3
|
import { logger } from "./logger.js";
|
|
4
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
5
|
|
|
3
6
|
//#region src/fetch.ts
|
|
4
7
|
const fetch = async (input, init) => {
|
|
5
|
-
if (process.env.NODE_ENV === "production") return globalThis.fetch(input, init);
|
|
6
8
|
const url = input instanceof Request ? input.url : String(input);
|
|
9
|
+
if ([
|
|
10
|
+
softrApiUrl("SOFTR_PLATFORM_API_URL"),
|
|
11
|
+
softrApiUrl("SOFTR_DATASOURCE_API_URL"),
|
|
12
|
+
softrApiUrl("SOFTR_WORKFLOWS_API_URL")
|
|
13
|
+
].some((base) => url.startsWith(`${base}/`))) {
|
|
14
|
+
const headers = new Headers(init?.headers ?? (input instanceof Request ? input.headers : void 0));
|
|
15
|
+
headers.set("user-agent", `softr-sdk/${version}`);
|
|
16
|
+
init = {
|
|
17
|
+
...init,
|
|
18
|
+
headers
|
|
19
|
+
};
|
|
20
|
+
const signed = await sign(input, init);
|
|
21
|
+
if (signed) {
|
|
22
|
+
input = signed;
|
|
23
|
+
init = void 0;
|
|
24
|
+
}
|
|
25
|
+
}
|
|
26
|
+
if (process.env.NODE_ENV === "production") return globalThis.fetch(input, init);
|
|
7
27
|
const method = init?.method ?? (input instanceof Request ? input.method : "GET");
|
|
8
28
|
const started = Date.now();
|
|
9
29
|
try {
|
|
@@ -16,6 +36,48 @@ const fetch = async (input, init) => {
|
|
|
16
36
|
throw error;
|
|
17
37
|
}
|
|
18
38
|
};
|
|
39
|
+
/**
|
|
40
|
+
* RFC 9421 signature over the request, with the key Studio handed the app at publish or session start. The SDK
|
|
41
|
+
* never derives, rotates or inspects the key: Softr derives it from a master key and the app's nonce, and the key
|
|
42
|
+
* id (`<environment>/<applicationId>/<master number>`) is copied into the signature as is so the verifier can
|
|
43
|
+
* derive the same key.
|
|
44
|
+
*
|
|
45
|
+
* The signature covers the method, authority, path, query and, when sent, the Authorization header. The body is
|
|
46
|
+
* not covered: TLS protects it in transit, and signing is there to tell the app's own server from anyone holding a
|
|
47
|
+
* user token, which needs no body coverage. So nothing is buffered here and the body streams through as given.
|
|
48
|
+
*/
|
|
49
|
+
async function sign(input, init) {
|
|
50
|
+
const key = process.env.SOFTR_REQUEST_SIGNING_KEY;
|
|
51
|
+
const keyId = process.env.SOFTR_REQUEST_SIGNING_KEY_ID;
|
|
52
|
+
if (!key || !keyId) return void 0;
|
|
53
|
+
assert(/^[0-9a-f]{64}$/i.test(key), "SOFTR_REQUEST_SIGNING_KEY must be 64 hex characters");
|
|
54
|
+
assert(!/["\\]/.test(keyId), "SOFTR_REQUEST_SIGNING_KEY_ID must not contain quotes or backslashes");
|
|
55
|
+
const request = new Request(input, init);
|
|
56
|
+
const headers = new Headers(request.headers);
|
|
57
|
+
const { host, pathname, search } = new URL(request.url);
|
|
58
|
+
const derived = {
|
|
59
|
+
"@method": request.method,
|
|
60
|
+
"@authority": host,
|
|
61
|
+
"@path": pathname,
|
|
62
|
+
"@query": search || "?"
|
|
63
|
+
};
|
|
64
|
+
const fields = Object.keys(derived);
|
|
65
|
+
if (headers.has("authorization")) fields.push("authorization");
|
|
66
|
+
const created = Math.floor(Date.now() / 1e3);
|
|
67
|
+
const params = `(${fields.map((field) => `"${field}"`).join(" ")});created=${created};keyid="${keyId}";tag="softr-code-app"`;
|
|
68
|
+
const base = [...fields.map((field) => `"${field}": ${derived[field] ?? requireDefined(headers.get(field), field)}`), `"@signature-params": ${params}`].join("\n");
|
|
69
|
+
const hmacKey = await crypto.subtle.importKey("raw", Uint8Array.from(key.match(/../g) ?? [], (byte) => parseInt(byte, 16)), {
|
|
70
|
+
name: "HMAC",
|
|
71
|
+
hash: "SHA-256"
|
|
72
|
+
}, false, ["sign"]);
|
|
73
|
+
const signature = base64(await crypto.subtle.sign("HMAC", hmacKey, new TextEncoder().encode(base)));
|
|
74
|
+
headers.set("signature-input", `softr=${params}`);
|
|
75
|
+
headers.set("signature", `softr=:${signature}:`);
|
|
76
|
+
return new Request(request, { headers });
|
|
77
|
+
}
|
|
78
|
+
function base64(bytes) {
|
|
79
|
+
return btoa(String.fromCharCode(...new Uint8Array(bytes)));
|
|
80
|
+
}
|
|
19
81
|
|
|
20
82
|
//#endregion
|
|
21
83
|
export { fetch };
|
package/dist/formatting.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { z } from "zod";
|
|
2
|
-
import * as
|
|
2
|
+
import * as react0 from "react";
|
|
3
3
|
import { ReactNode } from "react";
|
|
4
4
|
|
|
5
5
|
//#region src/formatting.d.ts
|
|
@@ -94,7 +94,7 @@ declare function FormattingScope({
|
|
|
94
94
|
/** A BCP 47 locale, such as `de-DE`. It drops the app's fixed date format inside the scope. */
|
|
95
95
|
locale?: string;
|
|
96
96
|
children?: ReactNode;
|
|
97
|
-
}):
|
|
97
|
+
}): react0.FunctionComponentElement<react0.ProviderProps<Scope>>;
|
|
98
98
|
/**
|
|
99
99
|
* A date in the app's format, safe to render on the server. A timestamp whose
|
|
100
100
|
* zone is not known yet renders `fallback` until the browser supplies it, so
|
|
@@ -115,6 +115,6 @@ declare function FormattedDate({
|
|
|
115
115
|
time?: boolean;
|
|
116
116
|
/** What renders while the visitor's zone is unknown. */
|
|
117
117
|
fallback?: ReactNode;
|
|
118
|
-
}):
|
|
118
|
+
}): react0.FunctionComponentElement<react0.FragmentProps>;
|
|
119
119
|
//#endregion
|
|
120
120
|
export { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting };
|
package/dist/index.d.ts
CHANGED
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import { SoftrUserGroupId, SoftrUserGroups, SoftrUserProperties, User } from "./auth/user.js";
|
|
2
|
-
import { ActionPermissions, SoftrDatasources, defineIntegration, defineMutation, defineQuery, defineWorkflow } from "./action.js";
|
|
2
|
+
import { ActionPermissions, SoftrDatasources, defineAiAction, defineIntegration, defineMutation, defineQuery, defineWorkflow } from "./action.js";
|
|
3
3
|
import { FileAttachment } from "./core/file-upload.js";
|
|
4
4
|
import { FileItem, useFileUpload } from "./core/use-file-upload.js";
|
|
5
|
+
import { AiAnswer, AiFile, AiGenerateInit, AiMessage, AiUsage } from "./core/ai.js";
|
|
5
6
|
import { DateOptions, DateParts, DateSeparator, DateValue, FixedDateFormat, FormattedDate, Formatting, FormattingScope, WeekDay, formatDate, formatDateTime, formatNumber, useFormatting } from "./formatting.js";
|
|
6
7
|
import { SoftrContext } from "./auth/context.js";
|
|
7
8
|
import { AuthSettings } from "./auth/platform.js";
|
|
@@ -16,7 +17,5 @@ import { useOverrides } from "./core/use-overrides.js";
|
|
|
16
17
|
import { useUserTimezone } from "./timezone.js";
|
|
17
18
|
import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
|
|
18
19
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
19
|
-
import { Agent, AgentChatSummary, listAgents } from "./agent/agent-fns.js";
|
|
20
|
-
import { AgentBlock, AgentChat, AgentChatOptions, AgentMessage, AgentQuestion, AgentTodo, AgentToolCall, useAgentChat } from "./agent/use-agent-chat.js";
|
|
21
20
|
import { Audience } from "./route/audience.js";
|
|
22
|
-
export { type ActionPermissions, type
|
|
21
|
+
export { type ActionPermissions, type AiAnswer, type AiFile, type AiGenerateInit, type AiMessage, type AiUsage, Audience, type AuthOptions, type AuthSettings, AuthSettingsProvider, type DateOptions, type DateParts, type DateSeparator, type DateValue, DefaultErrorOverlay, type FieldShape, type FileAttachment, type FileItem, type FixedDateFormat, FormattedDate, type Formatting, FormattingScope, type Page, type PageSettings, type PwaInstall, type PwaPlatform, type SoftrContext, type SoftrDatasources, type SoftrFieldRegistry, SoftrPwaHead, type SoftrUserGroupId, type SoftrUserGroups, type SoftrUserProperties, type User, type WeekDay, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
|
+
import { defineAiAction, defineIntegration, defineMutation, defineQuery, defineWorkflow } from "./action.js";
|
|
1
2
|
import { useFileUpload } from "./core/use-file-upload.js";
|
|
2
|
-
import { defineIntegration, defineMutation, defineQuery, defineWorkflow } from "./action.js";
|
|
3
3
|
import { checkAccess, defineVisibility, isAuthorized } from "./route/visibility.js";
|
|
4
4
|
import { assertRouteAccess, guardRoute, isAccessError, isAlreadyAuthenticatedError, isForbiddenError, isUnauthenticatedError } from "./route/route.js";
|
|
5
5
|
import { definePage, pageHead } from "./route/page.js";
|
|
@@ -12,8 +12,6 @@ import { fieldShape, formatDuration, formatField, formatValue, registerSoftrFiel
|
|
|
12
12
|
import { useOverrides } from "./core/use-overrides.js";
|
|
13
13
|
import { useUserTimezone } from "./timezone.js";
|
|
14
14
|
import { DefaultErrorOverlay } from "./default-error-overlay.js";
|
|
15
|
-
import { listAgents } from "./agent/agent-fns.js";
|
|
16
|
-
import { useAgentChat } from "./agent/use-agent-chat.js";
|
|
17
15
|
import { Audience } from "./route/audience.js";
|
|
18
16
|
|
|
19
|
-
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError,
|
|
17
|
+
export { Audience, AuthSettingsProvider, DefaultErrorOverlay, FormattedDate, FormattingScope, SoftrPwaHead, assertRouteAccess, checkAccess, defineAiAction, defineIntegration, defineMutation, definePage, defineQuery, defineVisibility, defineWorkflow, fieldShape, formatDate, formatDateTime, formatDuration, formatField, formatNumber, formatValue, getAuthSettings, getSoftrContext, guardRoute, initialSoftrContext, isAccessError, isAlreadyAuthenticatedError, isAuthorized, isForbiddenError, isUnauthenticatedError, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
|
package/dist/locale-settings.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
import { logger } from "./logger.js";
|
|
2
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
3
|
import { fetch } from "./fetch.js";
|
|
3
4
|
import { readRequestCookies, serializeCookie, writeCookies } from "./cookies.js";
|
|
4
5
|
import { sessionConfig } from "./auth/config.js";
|
|
5
|
-
import { softrApiUrl } from "./softr-api.js";
|
|
6
6
|
import { localeSettingsSchema } from "./formatting.js";
|
|
7
7
|
import { getRequestProtocol } from "@tanstack/react-start/server";
|
|
8
8
|
|
package/dist/mcp.js
CHANGED
|
@@ -1,9 +1,9 @@
|
|
|
1
1
|
import { assert } from "./assertions.js";
|
|
2
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
3
|
import { fetch } from "./fetch.js";
|
|
3
4
|
import { softrConfig } from "./softr-config.js";
|
|
4
5
|
import { sessionConfig } from "./auth/config.js";
|
|
5
6
|
import { readSessionToken, withSessionToken } from "./auth/session.js";
|
|
6
|
-
import { softrApiUrl } from "./softr-api.js";
|
|
7
7
|
import { isDatasourceAction } from "./action.js";
|
|
8
8
|
import { makePlatform } from "./auth/platform.js";
|
|
9
9
|
import { ds } from "./datasource/datasource.js";
|
|
@@ -244,8 +244,7 @@ const WHOAMI = {
|
|
|
244
244
|
type: "object",
|
|
245
245
|
properties: {},
|
|
246
246
|
additionalProperties: false
|
|
247
|
-
}
|
|
248
|
-
annotations: { readOnlyHint: true }
|
|
247
|
+
}
|
|
249
248
|
};
|
|
250
249
|
/** How many records a read returns when the caller does not say. */
|
|
251
250
|
const DEFAULT_LIMIT = 20;
|
|
@@ -266,7 +265,6 @@ function describeTool(action) {
|
|
|
266
265
|
case "read": return {
|
|
267
266
|
name: action.id,
|
|
268
267
|
description: `Read records from "${action.id}". Returns the fields ${names.join(", ")}. Only records the signed-in user may see come back.`,
|
|
269
|
-
annotations: { readOnlyHint: true },
|
|
270
268
|
inputSchema: {
|
|
271
269
|
type: "object",
|
|
272
270
|
properties: {
|
|
@@ -387,10 +385,8 @@ async function rpc(request, origin, actions) {
|
|
|
387
385
|
const token = bearerToken(request);
|
|
388
386
|
if (token === null) return unauthorized(origin);
|
|
389
387
|
const session = await platformSession(token);
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
else if (session.refused && await resolveUser(token) !== null) sessionToken = token;
|
|
393
|
-
else return session.refused ? unauthorized(origin) : unavailable();
|
|
388
|
+
if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
|
|
389
|
+
const { sessionToken } = session;
|
|
394
390
|
const body = await readJson(request);
|
|
395
391
|
const message = z.object({
|
|
396
392
|
id: z.union([z.string(), z.number()]).optional(),
|
package/dist/package.js
CHANGED
package/dist/pwa.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import * as
|
|
1
|
+
import * as react4 from "react";
|
|
2
2
|
import "@tanstack/react-start";
|
|
3
3
|
|
|
4
4
|
//#region src/pwa.d.ts
|
|
@@ -23,7 +23,7 @@ import "@tanstack/react-start";
|
|
|
23
23
|
* )
|
|
24
24
|
* }
|
|
25
25
|
*/
|
|
26
|
-
declare function SoftrPwaHead():
|
|
26
|
+
declare function SoftrPwaHead(): react4.FunctionComponentElement<react4.FragmentProps>;
|
|
27
27
|
type PwaPlatform = "ios" | "android" | "desktop";
|
|
28
28
|
type PwaInstall = {
|
|
29
29
|
available: false;
|
package/dist/pwa.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { logger } from "./logger.js";
|
|
2
|
+
import { softrApiUrl } from "./softr-api.js";
|
|
2
3
|
import { fetch } from "./fetch.js";
|
|
3
4
|
import { sessionConfig } from "./auth/config.js";
|
|
4
|
-
import { softrApiUrl } from "./softr-api.js";
|
|
5
5
|
import { z } from "zod";
|
|
6
6
|
import { Fragment, createElement, useEffect, useState } from "react";
|
|
7
7
|
import { createMiddleware } from "@tanstack/react-start";
|
|
@@ -125,7 +125,7 @@ function usePwaInstall() {
|
|
|
125
125
|
useEffect(() => {
|
|
126
126
|
if (window.matchMedia("(display-mode: standalone)").matches || "standalone" in navigator && navigator.standalone === true) return;
|
|
127
127
|
let cancelled = false;
|
|
128
|
-
fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
|
|
128
|
+
globalThis.fetch(INSTALL_PATH, { headers: { accept: "application/json" } }).then(async (response) => {
|
|
129
129
|
if (!response.ok) return;
|
|
130
130
|
const parsed = installSchema.safeParse(await response.json());
|
|
131
131
|
if (!parsed.success || cancelled) return;
|
package/dist/server.d.ts
CHANGED
|
@@ -1,8 +1,9 @@
|
|
|
1
1
|
import { upload } from "./core/file-upload.js";
|
|
2
|
+
import { AiError, ai } from "./core/ai.js";
|
|
2
3
|
import { auth } from "./auth/server.js";
|
|
3
4
|
import { FieldChoice, RecordOption, RecordOptions } from "./core/options.js";
|
|
4
5
|
import { ds } from "./datasource/datasource.js";
|
|
5
6
|
import { workflow } from "./core/workflow.js";
|
|
6
7
|
import { integration } from "./core/integration.js";
|
|
7
8
|
import "@tanstack/react-start/server-only";
|
|
8
|
-
export { type FieldChoice, type RecordOption, type RecordOptions, auth, ds, integration, upload, workflow };
|
|
9
|
+
export { AiError, type FieldChoice, type RecordOption, type RecordOptions, ai, auth, ds, integration, upload, workflow };
|
package/dist/server.js
CHANGED
|
@@ -3,6 +3,7 @@ import { ds } from "./datasource/datasource.js";
|
|
|
3
3
|
import { auth } from "./auth/server.js";
|
|
4
4
|
import { workflow } from "./core/workflow.js";
|
|
5
5
|
import { integration } from "./core/integration.js";
|
|
6
|
+
import { AiError, ai } from "./core/ai.js";
|
|
6
7
|
import "@tanstack/react-start/server-only";
|
|
7
8
|
|
|
8
|
-
export { auth, ds, integration, upload, workflow };
|
|
9
|
+
export { AiError, ai, auth, ds, integration, upload, workflow };
|
package/package.json
CHANGED
|
@@ -9,7 +9,7 @@ description: >-
|
|
|
9
9
|
metadata:
|
|
10
10
|
type: core
|
|
11
11
|
library: softr-sdk
|
|
12
|
-
library_version: 0.0.89
|
|
12
|
+
library_version: 0.0.89
|
|
13
13
|
---
|
|
14
14
|
|
|
15
15
|
# Softr SDK core
|
|
@@ -22,6 +22,8 @@ metadata:
|
|
|
22
22
|
>
|
|
23
23
|
> **CRITICAL**: The app is already wired. `src/start.ts`, `src/router.tsx` and `src/routes/__root.tsx` register `softrAuthMiddleware` and resolve the session. Do not add a second registration of it. `softrMcpMiddleware` is the one thing an app adds to `src/start.ts` itself — load the `softr-sdk/mcp` sub-skill before doing so.
|
|
24
24
|
>
|
|
25
|
+
> **CRITICAL**: `ai.generate` and `ai.stream` live on `@softr/sdk/server` and only run inside a `createServerFn` handler. Use `defineAiAction` from `@softr/sdk` to declare the action with the model it runs on, an id copied from the `ai_list_models` tool. Softr runs the model on its own keys; never ask the user for an API key for the app's own AI feature. Load the `softr-sdk/ai` sub-skill for the full pattern.
|
|
26
|
+
>
|
|
25
27
|
> **CRITICAL**: `workflow.trigger` lives on `@softr/sdk/server` and only runs inside a `createServerFn` handler. Use `defineWorkflow` from `@softr/sdk` to declare the action, then pass it to `workflow.trigger`. Load the `softr-sdk/workflows` sub-skill for the full pattern.
|
|
26
28
|
|
|
27
29
|
Each sub-skill stands alone for its task and repeats the boundary above, so most work needs **one** sub-skill and not this file. Load this one when you are unsure which sub-skill applies, or when the wiring below is what you are touching. Add a second sub-skill only when the work genuinely crosses that boundary: a page that lists records behind a group restriction needs `record-queries` plus `routes-and-visibility`.
|
|
@@ -30,8 +32,8 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
30
32
|
|
|
31
33
|
| Import | Runs | Holds |
|
|
32
34
|
| --- | --- | --- |
|
|
33
|
-
| `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
|
|
34
|
-
| `@softr/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration` |
|
|
35
|
+
| `@softr/sdk` | Both | `defineQuery`, `defineMutation`, `defineAiAction`, `definePage`, `pageHead`, `defineVisibility`, `guardRoute`, `assertRouteAccess`, `isAuthorized`, `checkAccess`, `Audience`, `useCurrentUser`, `useUserTimezone`, `FormattedDate`, `FormattingScope`, `useFormatting`, `formatDate`, `formatDateTime`, `formatNumber`, `formatValue`, `formatField`, `fieldShape`, `registerSoftrFields`, `useOverrides`, `SoftrPwaHead`, `usePwaInstall`, `getSoftrContext`, `initialSoftrContext`, `softrAuthMiddleware`, the error predicates, and every type |
|
|
36
|
+
| `@softr/sdk/server` | Server only | `ds`, `auth`, `workflow`, `integration`, `ai` |
|
|
35
37
|
| `@softr/sdk/client` | Browser only | `useFileUpload` |
|
|
36
38
|
| `@softr/sdk/vite` | Build | `softr()`, already in `vite.config.ts` |
|
|
37
39
|
|
|
@@ -47,9 +49,9 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
|
|
|
47
49
|
| Create, update or delete a record | [record-mutations/SKILL.md](./record-mutations/SKILL.md) |
|
|
48
50
|
| Trigger a Softr workflow | [workflows/SKILL.md](./workflows/SKILL.md) |
|
|
49
51
|
| Sign a visitor in, out, or up | [auth/SKILL.md](./auth/SKILL.md) |
|
|
50
|
-
|
|
|
52
|
+
| Ask an AI model: a summary, an extraction from a document, a classification, a draft, a chat | [ai/SKILL.md](./ai/SKILL.md) |
|
|
53
|
+
| Call a connected third-party API (Slack, Stripe, Gmail, …), or an AI model on the user's own provider account | [integrations/SKILL.md](./integrations/SKILL.md) |
|
|
51
54
|
| Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
|
|
52
|
-
| Let visitors chat with a Softr agent | [agent-chat/SKILL.md](./agent-chat/SKILL.md) |
|
|
53
55
|
| Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
|
|
54
56
|
| Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
|
|
55
57
|
|
|
@@ -80,15 +82,18 @@ Triggering a Softr workflow from a button or form?
|
|
|
80
82
|
Wiring a login, signup, or sign-out?
|
|
81
83
|
load softr-sdk/auth
|
|
82
84
|
|
|
85
|
+
Asking an AI model for anything: a summary, fields out of a document, a classification, a draft, a chat?
|
|
86
|
+
load softr-sdk/ai — Softr runs the model on its own keys, nothing to connect; pick the model from ai_list_models
|
|
87
|
+
|
|
83
88
|
Calling a connected third-party API (Slack, Stripe, Gmail, Google Calendar, …)?
|
|
84
89
|
load softr-sdk/integrations
|
|
85
90
|
|
|
91
|
+
Running a model on the user's OWN provider account, because they chose that for the feature?
|
|
92
|
+
load softr-sdk/integrations: its "Calling an AI model" section
|
|
93
|
+
|
|
86
94
|
Opening the app to an AI assistant over MCP?
|
|
87
95
|
load softr-sdk/mcp
|
|
88
96
|
|
|
89
|
-
Adding a chat with one of the app's Softr agents, or a Connect button for the visitor's account it needs?
|
|
90
|
-
load softr-sdk/agent-chat
|
|
91
|
-
|
|
92
97
|
Adding an install button, or making the app installable?
|
|
93
98
|
load softr-sdk/pwa
|
|
94
99
|
|