@softr/sdk 0.0.92-emailotc.0 → 0.0.93-alpha.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.
Files changed (40) hide show
  1. package/dist/agent/agent-fns.d.ts +30 -0
  2. package/dist/agent/agent-fns.js +215 -0
  3. package/dist/agent/use-agent-chat.d.ts +106 -0
  4. package/dist/agent/use-agent-chat.js +486 -0
  5. package/dist/app-identity.js +25 -0
  6. package/dist/auth/isomorphic.d.ts +1 -1
  7. package/dist/auth/isomorphic.js +2 -0
  8. package/dist/auth/methods/password.d.ts +1 -4
  9. package/dist/auth/methods/password.js +1 -6
  10. package/dist/auth/platform.js +0 -25
  11. package/dist/auth/server.d.ts +0 -3
  12. package/dist/auth/server.js +1 -4
  13. package/dist/datasource/record.js +12 -3
  14. package/dist/default-error-overlay.d.ts +2 -2
  15. package/dist/formatting.d.ts +3 -3
  16. package/dist/index.d.ts +3 -1
  17. package/dist/index.js +3 -1
  18. package/dist/mcp.d.ts +17 -4
  19. package/dist/mcp.js +61 -18
  20. package/dist/package.js +1 -1
  21. package/dist/pwa.d.ts +2 -2
  22. package/package.json +10 -33
  23. package/skills/softr-sdk/SKILL.md +5 -1
  24. package/skills/softr-sdk/agent-chat/SKILL.md +110 -0
  25. package/skills/softr-sdk/ai/SKILL.md +1 -1
  26. package/skills/softr-sdk/auth/SKILL.md +3 -31
  27. package/skills/softr-sdk/charts-and-metrics/SKILL.md +1 -1
  28. package/skills/softr-sdk/current-user/SKILL.md +1 -1
  29. package/skills/softr-sdk/file-uploads/SKILL.md +1 -1
  30. package/skills/softr-sdk/formatting/SKILL.md +1 -1
  31. package/skills/softr-sdk/integrations/SKILL.md +1 -1
  32. package/skills/softr-sdk/mcp/SKILL.md +16 -1
  33. package/skills/softr-sdk/pwa/SKILL.md +1 -1
  34. package/skills/softr-sdk/record-mutations/SKILL.md +1 -1
  35. package/skills/softr-sdk/record-queries/SKILL.md +1 -1
  36. package/skills/softr-sdk/region-visibility/SKILL.md +1 -1
  37. package/skills/softr-sdk/routes-and-visibility/SKILL.md +4 -4
  38. package/skills/softr-sdk/workflows/SKILL.md +1 -1
  39. package/dist/auth/methods/emailCode2fa.d.ts +0 -34
  40. package/dist/auth/methods/emailCode2fa.js +0 -71
@@ -30,6 +30,15 @@ function refererHeader() {
30
30
  const referer = getRequestHeader("referer");
31
31
  return { Referer: referer !== void 0 && URL.parse(referer)?.origin === page.origin ? referer : page.href };
32
32
  }
33
+ /** A datasource call the service refused. `status` is its HTTP status. */
34
+ var DatasourceError = class extends Error {
35
+ status;
36
+ constructor(message, status) {
37
+ super(message);
38
+ this.name = "DatasourceError";
39
+ this.status = status;
40
+ }
41
+ };
33
42
  async function describeFailure(res) {
34
43
  const body = await res.json().catch(() => null);
35
44
  const message = typeof body === "object" && body !== null && "message" in body ? body.message : null;
@@ -235,7 +244,7 @@ async function updateRecord(action, options) {
235
244
  },
236
245
  body: JSON.stringify({ fields: rawFields })
237
246
  });
238
- if (!res.ok) throw new Error(`datasource update failed for action "${actionId}": ${await describeFailure(res)}`);
247
+ if (!res.ok) throw new DatasourceError(`datasource update failed for action "${actionId}": ${await describeFailure(res)}`, res.status);
239
248
  const record = await res.json();
240
249
  return {
241
250
  id: record.id,
@@ -257,7 +266,7 @@ async function deleteRecord(action, options) {
257
266
  ...refererHeader()
258
267
  }
259
268
  });
260
- if (!res.ok) throw new Error(`datasource delete failed for action "${actionId}": ${await describeFailure(res)}`);
269
+ if (!res.ok) throw new DatasourceError(`datasource delete failed for action "${actionId}": ${await describeFailure(res)}`, res.status);
261
270
  }
262
271
  function resolveTarget(subject, operation) {
263
272
  const declaredBy = operation === "read" ? "defineQuery" : "defineMutation";
@@ -281,4 +290,4 @@ function dealiasData(data, select) {
281
290
  }
282
291
 
283
292
  //#endregion
284
- export { createRecord, deleteRecord, describeFailure, dsUrl, getRecord, listRecords, refererHeader, resolveTarget, updateRecord };
293
+ export { DatasourceError, createRecord, deleteRecord, describeFailure, dsUrl, getRecord, listRecords, refererHeader, resolveTarget, updateRecord };
@@ -1,4 +1,4 @@
1
- import * as react2 from "react";
1
+ import * as react4 from "react";
2
2
 
3
3
  //#region src/default-error-overlay.d.ts
4
4
  type Props = {
@@ -8,6 +8,6 @@ type Props = {
8
8
  declare function DefaultErrorOverlay({
9
9
  error,
10
10
  reset
11
- }: Props): react2.JSX.Element;
11
+ }: Props): react4.JSX.Element;
12
12
  //#endregion
13
13
  export { DefaultErrorOverlay };
@@ -1,5 +1,5 @@
1
1
  import { z } from "zod";
2
- import * as react3 from "react";
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
- }): react3.FunctionComponentElement<react3.ProviderProps<Scope>>;
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
- }): react3.FunctionComponentElement<react3.FragmentProps>;
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
@@ -17,5 +17,7 @@ import { useOverrides } from "./core/use-overrides.js";
17
17
  import { useUserTimezone } from "./timezone.js";
18
18
  import { PwaInstall, PwaPlatform, SoftrPwaHead, usePwaInstall } from "./pwa.js";
19
19
  import { DefaultErrorOverlay } from "./default-error-overlay.js";
20
+ import { Agent, AgentChatSummary, listAgents } from "./agent/agent-fns.js";
21
+ import { AgentBlock, AgentChat, AgentChatOptions, AgentMessage, AgentQuestion, AgentTodo, AgentToolCall, useAgentChat } from "./agent/use-agent-chat.js";
20
22
  import { Audience } from "./route/audience.js";
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 };
23
+ export { type ActionPermissions, type Agent, type AgentBlock, type AgentChat, type AgentChatOptions, type AgentChatSummary, type AgentMessage, type AgentQuestion, type AgentTodo, type AgentToolCall, 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, listAgents, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/index.js CHANGED
@@ -12,6 +12,8 @@ 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";
15
17
  import { Audience } from "./route/audience.js";
16
18
 
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 };
19
+ 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, listAgents, pageHead, registerSoftrFields, softrAuthMiddleware, softrMcpMiddleware, toReturnPath, useAgentChat, useAuthSettings, useCurrentUser, useFileUpload, useFormatting, useOverrides, usePwaInstall, useUserTimezone };
package/dist/mcp.d.ts CHANGED
@@ -1,9 +1,9 @@
1
- import { DatasourceAction } from "./action.js";
2
- import * as _tanstack_react_start6 from "@tanstack/react-start";
1
+ import { DatasourceAction, ReadShape } from "./action.js";
2
+ import * as _tanstack_react_start7 from "@tanstack/react-start";
3
3
 
4
4
  //#region src/mcp.d.ts
5
5
 
6
- type SoftrMcpOptions = {
6
+ type SoftrMcpOptions<TUsers extends ReadShape = ReadShape> = {
7
7
  /**
8
8
  * The actions to expose as tools, from `defineQuery` and `defineMutation`.
9
9
  *
@@ -12,6 +12,19 @@ type SoftrMcpOptions = {
12
12
  * decide who may run the ones that are listed.
13
13
  */
14
14
  actions?: Array<DatasourceAction>;
15
+ /**
16
+ * Fills the owner of a person's record from who is calling, the way the app's
17
+ * pages do with `auth.currentUserRow`. The field is left out of the tool, so
18
+ * the assistant can't leave it wrong or name someone else.
19
+ */
20
+ owner?: SoftrMcpOwner<TUsers>;
21
+ };
22
+ type SoftrMcpOwner<TUsers extends ReadShape = ReadShape> = {
23
+ /** The people table, and its email field, to find the caller's row in. */
24
+ users: DatasourceAction<TUsers>;
25
+ email: keyof TUsers["fields"] & string;
26
+ /** Listed create or update action id to the field that links to the caller's row. */
27
+ fields: Record<string, string>;
15
28
  };
16
29
  /**
17
30
  * Serves the MCP endpoint and its OAuth flow from the app's own origin.
@@ -31,6 +44,6 @@ type SoftrMcpOptions = {
31
44
  * ],
32
45
  * }))
33
46
  */
34
- declare function softrMcpMiddleware(options?: SoftrMcpOptions): _tanstack_react_start6.RequestMiddlewareAfterServer<{}, undefined, undefined>;
47
+ declare function softrMcpMiddleware<TUsers extends ReadShape>(options?: SoftrMcpOptions<TUsers>): _tanstack_react_start7.RequestMiddlewareAfterServer<{}, undefined, undefined>;
35
48
  //#endregion
36
49
  export { softrMcpMiddleware };
package/dist/mcp.js CHANGED
@@ -5,8 +5,10 @@ import { softrConfig } from "./softr-config.js";
5
5
  import { sessionConfig } from "./auth/config.js";
6
6
  import { readSessionToken, withSessionToken } from "./auth/session.js";
7
7
  import { isDatasourceAction } from "./action.js";
8
+ import { DatasourceError } from "./datasource/record.js";
8
9
  import { makePlatform } from "./auth/platform.js";
9
10
  import { ds } from "./datasource/datasource.js";
11
+ import { currentUserRow } from "./auth/current-user-row.js";
10
12
  import { z } from "zod";
11
13
  import { createMiddleware } from "@tanstack/react-start";
12
14
 
@@ -48,6 +50,14 @@ function softrMcpMiddleware(options = {}) {
48
50
  assert(!actions.has(value.id), `two actions share the id "${value.id}"`);
49
51
  actions.set(value.id, value);
50
52
  }
53
+ const owner = options.owner;
54
+ for (const [actionId, field] of Object.entries(owner?.fields ?? {})) {
55
+ const action = actions.get(actionId);
56
+ assert(action, `owner names "${actionId}", which is not a listed action`);
57
+ const { operation, fields } = action.resource;
58
+ assert(operation === "create" || operation === "update", `owner fills "${actionId}", which is a ${operation}`);
59
+ assert(field in (fields ?? {}), `"${actionId}" has no field "${field}" for the owner`);
60
+ }
51
61
  return createMiddleware({ type: "request" }).server(async ({ next, request }) => {
52
62
  const url = new URL(request.url);
53
63
  const origin = url.origin;
@@ -71,7 +81,7 @@ function softrMcpMiddleware(options = {}) {
71
81
  });
72
82
  case AUTHORIZE_PATH: return await authorize(request, login);
73
83
  case TOKEN_PATH: return await issueToken(request);
74
- case MCP_PATH: return await rpc(request, origin, actions);
84
+ case MCP_PATH: return await rpc(request, origin, actions, owner);
75
85
  default: return await next();
76
86
  }
77
87
  });
@@ -244,7 +254,8 @@ const WHOAMI = {
244
254
  type: "object",
245
255
  properties: {},
246
256
  additionalProperties: false
247
- }
257
+ },
258
+ annotations: { readOnlyHint: true }
248
259
  };
249
260
  /** How many records a read returns when the caller does not say. */
250
261
  const DEFAULT_LIMIT = 20;
@@ -257,14 +268,16 @@ const MAX_LIMIT = 100;
257
268
  * that only ever reads one datasource exposes one read, even though its
258
269
  * credentials would allow more.
259
270
  */
260
- function describeTool(action) {
271
+ function describeTool(action, ownerField) {
261
272
  const { operation, fields } = action.resource;
262
273
  const names = Object.keys(fields ?? {});
263
- const fieldProps = Object.fromEntries(names.map((name) => [name, { description: `The "${name}" field.` }]));
274
+ const writable = names.filter((name) => name !== ownerField);
275
+ const fieldProps = Object.fromEntries(writable.map((name) => [name, { description: `The "${name}" field.` }]));
264
276
  switch (operation) {
265
277
  case "read": return {
266
278
  name: action.id,
267
279
  description: `Read records from "${action.id}". Returns the fields ${names.join(", ")}. Only records the signed-in user may see come back.`,
280
+ annotations: { readOnlyHint: true },
268
281
  inputSchema: {
269
282
  type: "object",
270
283
  properties: {
@@ -285,7 +298,7 @@ function describeTool(action) {
285
298
  };
286
299
  case "create": return {
287
300
  name: action.id,
288
- description: `Create a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
301
+ description: `Create a record with "${action.id}". Writable fields: ${writable.join(", ")}.`,
289
302
  inputSchema: {
290
303
  type: "object",
291
304
  properties: fieldProps,
@@ -294,7 +307,7 @@ function describeTool(action) {
294
307
  };
295
308
  case "update": return {
296
309
  name: action.id,
297
- description: `Update a record with "${action.id}". Writable fields: ${names.join(", ")}.`,
310
+ description: `Update a record with "${action.id}". Writable fields: ${writable.join(", ")}.`,
298
311
  inputSchema: {
299
312
  type: "object",
300
313
  properties: {
@@ -330,7 +343,7 @@ function describeTool(action) {
330
343
  * visitor's user groups exactly as it would a click in the app. Nothing here
331
344
  * decides what is allowed.
332
345
  */
333
- async function runTool(action, args) {
346
+ async function runTool(action, args, owner) {
334
347
  const typed = action;
335
348
  switch (action.resource.operation) {
336
349
  case "read": {
@@ -342,13 +355,21 @@ async function runTool(action, args) {
342
355
  nextOffset: result$1.nextOffset
343
356
  };
344
357
  }
345
- case "create": return await ds.create(typed, { data: writableFields(action, args) });
358
+ case "create": {
359
+ const data = writableFields(action, args, owner?.field);
360
+ if (owner !== null) {
361
+ const row = await owner.row();
362
+ if (row === null) throw new Error("The visitor has no row in the people table, so this record can't be created for them.");
363
+ data[owner.field] = { id: row.id };
364
+ }
365
+ return await ds.create(typed, { data });
366
+ }
346
367
  case "update": {
347
368
  const { id,...data } = args;
348
369
  assert(typeof id === "string" && id !== "", "update needs a record id");
349
370
  return await ds.update(typed, {
350
371
  id,
351
- data: writableFields(action, data)
372
+ data: writableFields(action, data, owner?.field)
352
373
  });
353
374
  }
354
375
  case "delete": {
@@ -359,8 +380,19 @@ async function runTool(action, args) {
359
380
  }
360
381
  }
361
382
  }
383
+ function ownerFieldOf(owner, actionId) {
384
+ return owner !== void 0 && Object.hasOwn(owner.fields, actionId) ? owner.fields[actionId] : void 0;
385
+ }
386
+ function ownerFill(owner, actionId, sessionToken) {
387
+ const field = ownerFieldOf(owner, actionId);
388
+ if (owner === void 0 || field === void 0) return null;
389
+ return {
390
+ field,
391
+ row: async () => currentUserRow(await resolveUser(sessionToken), owner.users, owner.email)
392
+ };
393
+ }
362
394
  /**
363
- * Only the fields the action declared.
395
+ * Only the fields the action declared, less the owner it fills itself.
364
396
  *
365
397
  * `additionalProperties: false` in the tool schema is a hint to the model, not
366
398
  * a check — a client can send whatever it likes. An unlisted key reaches the
@@ -368,9 +400,18 @@ async function runTool(action, args) {
368
400
  * straight through. So the action's field list gets enforced here, or it isn't
369
401
  * a boundary at all.
370
402
  */
371
- function writableFields(action, args) {
403
+ function writableFields(action, args, ownerField) {
372
404
  const allowed = action.resource.fields ?? {};
373
- return Object.fromEntries(Object.entries(args).filter(([name]) => name in allowed));
405
+ return Object.fromEntries(Object.entries(args).filter(([name]) => name in allowed && name !== ownerField));
406
+ }
407
+ /**
408
+ * The error as the assistant should read it. A row rule that keeps the caller
409
+ * from changing a record answers 404, the same as a deleted record, so a bare
410
+ * "not found" would leave the assistant guessing.
411
+ */
412
+ function describeError(error) {
413
+ if (error instanceof DatasourceError && error.status === 404) return "Refused: this record doesn't exist, or the visitor's user group may not change it. If it still shows in a read, it is a permission. Tell the visitor they don't have access to this action, and that the app's builder can grant it.";
414
+ return error instanceof Error ? error.message : String(error);
374
415
  }
375
416
  function clampLimit(raw) {
376
417
  if (typeof raw !== "number" || !Number.isInteger(raw)) return DEFAULT_LIMIT;
@@ -380,13 +421,15 @@ function clampOffset(raw) {
380
421
  if (typeof raw !== "number" || !Number.isInteger(raw) || raw < 0) return null;
381
422
  return raw;
382
423
  }
383
- async function rpc(request, origin, actions) {
424
+ async function rpc(request, origin, actions, owner) {
384
425
  if (request.method !== "POST") return methodNotAllowed("POST");
385
426
  const token = bearerToken(request);
386
427
  if (token === null) return unauthorized(origin);
387
428
  const session = await platformSession(token);
388
- if (!session.ok) return session.refused ? unauthorized(origin) : unavailable();
389
- const { sessionToken } = session;
429
+ let sessionToken;
430
+ if (session.ok) sessionToken = session.sessionToken;
431
+ else if (session.refused && await resolveUser(token) !== null) sessionToken = token;
432
+ else return session.refused ? unauthorized(origin) : unavailable();
390
433
  const body = await readJson(request);
391
434
  const message = z.object({
392
435
  id: z.union([z.string(), z.number()]).optional(),
@@ -415,7 +458,7 @@ async function rpc(request, origin, actions) {
415
458
  }
416
459
  });
417
460
  }
418
- case "tools/list": return result(id, { tools: [WHOAMI, ...[...actions.values()].map(describeTool)] });
461
+ case "tools/list": return result(id, { tools: [WHOAMI, ...[...actions.values()].map((action) => describeTool(action, ownerFieldOf(owner, action.id)))] });
419
462
  case "tools/call": {
420
463
  const name = params?.name;
421
464
  const args = typeof params?.arguments === "object" && params.arguments !== null ? params.arguments : {};
@@ -427,13 +470,13 @@ async function rpc(request, origin, actions) {
427
470
  const action = typeof name === "string" ? actions.get(name) : void 0;
428
471
  if (action === void 0) return failure(id, -32602, `Unknown tool: ${String(name)}`);
429
472
  try {
430
- return result(id, toolResult(await withSessionToken(sessionToken, () => runTool(action, args))));
473
+ return result(id, toolResult(await withSessionToken(sessionToken, () => runTool(action, args, ownerFill(owner, action.id, sessionToken)))));
431
474
  } catch (error) {
432
475
  return result(id, {
433
476
  isError: true,
434
477
  content: [{
435
478
  type: "text",
436
- text: error instanceof Error ? error.message : String(error)
479
+ text: describeError(error)
437
480
  }]
438
481
  });
439
482
  }
package/dist/package.js CHANGED
@@ -1,5 +1,5 @@
1
1
  //#region package.json
2
- var version = "0.0.92-emailotc.0";
2
+ var version = "0.0.93-alpha.0";
3
3
 
4
4
  //#endregion
5
5
  export { version };
package/dist/pwa.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import * as react0 from "react";
1
+ import * as react5 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(): react0.FunctionComponentElement<react0.FragmentProps>;
26
+ declare function SoftrPwaHead(): react5.FunctionComponentElement<react5.FragmentProps>;
27
27
  type PwaPlatform = "ios" | "android" | "desktop";
28
28
  type PwaInstall = {
29
29
  available: false;
package/package.json CHANGED
@@ -1,37 +1,16 @@
1
1
  {
2
2
  "name": "@softr/sdk",
3
- "version": "0.0.92-emailotc.0",
3
+ "version": "0.0.93-alpha.0",
4
4
  "type": "module",
5
5
  "exports": {
6
- ".": {
7
- "types": "./dist/index.d.ts",
8
- "import": "./dist/index.js"
9
- },
10
- "./client": {
11
- "types": "./dist/client.d.ts",
12
- "import": "./dist/client.js"
13
- },
14
- "./server": {
15
- "types": "./dist/server.d.ts",
16
- "import": "./dist/server.js"
17
- },
18
- "./vite": {
19
- "types": "./dist/vite.d.ts",
20
- "import": "./dist/vite.js"
21
- }
22
- },
23
- "bin": {
24
- "softr-sdk": "./dist/cli.js"
25
- },
26
- "files": [
27
- "dist",
28
- "schema",
29
- "skills",
30
- "!skills/_artifacts"
31
- ],
32
- "publishConfig": {
33
- "access": "public"
34
- },
6
+ ".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
7
+ "./client": { "types": "./dist/client.d.ts", "import": "./dist/client.js" },
8
+ "./server": { "types": "./dist/server.d.ts", "import": "./dist/server.js" },
9
+ "./vite": { "types": "./dist/vite.d.ts", "import": "./dist/vite.js" }
10
+ },
11
+ "bin": { "softr-sdk": "./dist/cli.js" },
12
+ "files": ["dist", "schema", "skills", "!skills/_artifacts"],
13
+ "publishConfig": { "access": "public" },
35
14
  "scripts": {
36
15
  "build": "tsdown",
37
16
  "test": "node --import ./src/test-utils/setup.ts --test",
@@ -63,9 +42,7 @@
63
42
  "optional": true
64
43
  }
65
44
  },
66
- "keywords": [
67
- "tanstack-intent"
68
- ],
45
+ "keywords": ["tanstack-intent"],
69
46
  "intent": {
70
47
  "version": 1,
71
48
  "repo": "@softr/sdk",
@@ -9,7 +9,7 @@ description: >-
9
9
  metadata:
10
10
  type: core
11
11
  library: softr-sdk
12
- library_version: 0.0.91
12
+ library_version: 0.0.93-alpha.0
13
13
  ---
14
14
 
15
15
  # Softr SDK core
@@ -52,6 +52,7 @@ Each sub-skill stands alone for its task and repeats the boundary above, so most
52
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
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) |
54
54
  | Open the app to AI assistants over MCP | [mcp/SKILL.md](./mcp/SKILL.md) |
55
+ | Let visitors chat with a Softr agent | [agent-chat/SKILL.md](./agent-chat/SKILL.md) |
55
56
  | Let visitors install the app on their home screen | [pwa/SKILL.md](./pwa/SKILL.md) |
56
57
  | Show a date, a time or a number | [formatting/SKILL.md](./formatting/SKILL.md) |
57
58
 
@@ -94,6 +95,9 @@ Running a model on the user's OWN provider account, because they chose that for
94
95
  Opening the app to an AI assistant over MCP?
95
96
  load softr-sdk/mcp
96
97
 
98
+ Adding a chat with one of the app's Softr agents, or a Connect button for the visitor's account it needs?
99
+ load softr-sdk/agent-chat
100
+
97
101
  Adding an install button, or making the app installable?
98
102
  load softr-sdk/pwa
99
103
 
@@ -0,0 +1,110 @@
1
+ ---
2
+ name: agent-chat
3
+ description: >-
4
+ Chat with one of the app's Softr agents: listAgents() and
5
+ useAgentChat(agentId, { record }) from @softr/sdk give the chat state with no
6
+ UI — messages, the streaming reply, past chats, approve, reject, connect. Load
7
+ it for an agent chat, approving its actions, which records the agent may
8
+ change for each visitor, or connecting the visitor's account a tool needs.
9
+ metadata:
10
+ type: sub-skill
11
+ library: softr-sdk
12
+ library_version: 0.0.93-alpha.0
13
+ ---
14
+
15
+ **Boundary.** `listAgents` and `useAgentChat` live on `@softr/sdk`. `listAgents` runs in a route loader, `useAgentChat` in a component. Neither needs a route, server function or registration of its own. It chats as the signed-in visitor, or anonymously when no one is signed in.
16
+
17
+ # Agent chat
18
+
19
+ A Softr agent is set up in Studio's Agents tab and attached to the app there. There is no chat widget: the hook gives the state, and the app draws it with its own components.
20
+
21
+ ## Setup
22
+
23
+ ```ts
24
+ import { listAgents, useAgentChat } from '@softr/sdk'
25
+ ```
26
+
27
+ `listAgents()` resolves to the agents this visitor may chat with, `{ id, title, avatar, thumbnail }[]`. Call it in the route's `loader`. An agent hidden from this visitor isn't in the list, so show no chat when it's empty. When there are several, let the visitor pick one, or pick the one the builder named by its `title`. Take the id from the list. A hand-written id fails on the first message, and shows an agent the visitor may not see.
28
+
29
+ ## Core pattern
30
+
31
+ ```tsx
32
+ // agentId comes from listAgents() in the route's loader.
33
+ function AgentPanel({ agentId, ticket }: { agentId: string; ticket: Ticket | null }) {
34
+ const chat = useAgentChat(agentId, {
35
+ record: ticket && { id: ticket.id, fields: { Title: ticket.title, Status: ticket.status } },
36
+ })
37
+ const [draft, setDraft] = useState('')
38
+
39
+ return (
40
+ <>
41
+ {chat.messages.map((message) => (
42
+ <Message key={message.id} message={message} onApprove={chat.approve} onReject={chat.reject} />
43
+ ))}
44
+ {chat.error && <p role="alert">{chat.error.message}</p>}
45
+ <form onSubmit={(e) => { e.preventDefault(); chat.send(draft); setDraft('') }}>
46
+ <Textarea value={draft} onChange={(e) => setDraft(e.target.value)} />
47
+ {chat.status === 'idle'
48
+ ? <Button type="submit">Send</Button>
49
+ : <Button type="button" onClick={chat.stop}>Stop</Button>}
50
+ </form>
51
+ </>
52
+ )
53
+ }
54
+ ```
55
+
56
+ ## What the hook returns
57
+
58
+ - `messages`: the whole chat, oldest first. While the agent answers, its reply is the last message and grows as it streams.
59
+ - `status`: `thinking` until the first part of the reply arrives, `replying` until it ends, then `idle`. Show a typing hint while it's `thinking`.
60
+ - `loading`: `true` while a past chat loads. Show a spinner, not the empty-chat greeting.
61
+ - `error`: why the last request failed, or `null`.
62
+ - `send(text)`, `stop()`, `newChat()`.
63
+ - `listChats()` resolves to the visitor's past chats, `{ id, title }[]`, with `title` `null` until the agent names the chat. `openChat(id)` loads one. `chatId` is the open one, `null` for a new chat. The open chat is kept in the browser for each signed-in user, so the hook reopens it after a remount or a reload. A signed-out visitor keeps it only until the tab closes.
64
+ - `approve(toolCallId, scope?)` and `reject(toolCallId)` answer a tool waiting for approval. `scope` is `ONCE` (default), `SESSION` for the rest of this chat, or `USER` for this agent from now on.
65
+ - `connect(toolCallId)` signs the visitor in to a tool's `integration` in a popup. Call it straight from the click, or the browser blocks the popup.
66
+
67
+ ## Rendering a message
68
+
69
+ Each message has `role` (`user` or `assistant`) and `blocks`. Render every block type, in the order given. Show only `text` and a tool waiting for approval never appears, so the agent waits forever. A tool waiting for Approve or Connect comes last in its message, below the text asking for it.
70
+
71
+ | Block | Show it as |
72
+ | --- | --- |
73
+ | `text` | Markdown, tables included |
74
+ | `tool` | One line: the tool `name` and its `status`. Collapse finished ones. Expanded, show `thought`, `input` as `Label: value` lines (never raw JSON), `error` and `durationMs`, leaving out empty ones. |
75
+ | `todo` | A checklist of the agent's plan. It updates in place. |
76
+ | `question` | The questions with their options. One question with a single choice sends its label with `send` on click. Several questions, or `multiSelect`, collect the picks and show a Send button, enabled once each question has one. It sends one line per question, picked labels joined by ", ". An answered question stays locked. |
77
+ | `error` | An error line inside the reply |
78
+
79
+ A `tool` with status `awaiting-approval` blocks the agent until the visitor answers. Give it a split Approve button and a Reject button. The button says "Approve once" (`approve(id)`), and its menu offers "Approve for this session" (`approve(id, 'SESSION')`) and "Approve for this agent" (`approve(id, 'USER')`). With only one Approve, the visitor approves the same action again on every call. The agent continues on its own after an approval.
80
+
81
+ A `tool` with status `awaiting-connection` needs the visitor's own `integration` account, such as their Gmail. Say "You need to connect to {integration} for this request. You'll only need to connect once.", with the name in readable case, and show a Connect button that calls `connect`. While it's `connecting`, show "Connecting…" and disable the button. The agent continues on its own once they're signed in. Every integration works the same way, so build one button, not one per integration.
82
+
83
+ ## Context
84
+
85
+ `record` is the one record the visitor is looking at, so they can say "close this one". Pass it where a page shows one record, and `null` elsewhere. Use readable field names as keys. The agent reads them as they are.
86
+
87
+ The page title and URL go along on their own. Nothing else about the page does, so don't try to send whole lists.
88
+
89
+ ## Letting the agent act on the app
90
+
91
+ The agent reads and changes data through the app's own MCP, as the visitor who is chatting, using the actions `softrMcpMiddleware` lists. With no MCP wired, the agent can only talk. Load [mcp/SKILL.md](../mcp/SKILL.md) to wire it and choose the actions.
92
+
93
+ **The agent calls a listed action directly, with any input.** It skips pages and server functions. Two things guard it: the action's `permissions` say who may run it, and the app's data restrictions say which rows each user group reaches. A read returns every row the visitor may see, and an update or delete takes any id that passes both.
94
+
95
+ - **The owner comes from the app, never from the agent.** Name each create's owner link in `owner` on `softrMcpMiddleware`, as [mcp/SKILL.md](../mcp/SKILL.md) shows. The agent knows the visitor's login, not their row, and could name anyone.
96
+ - **By default, each visitor changes only their own records.** On a table whose rows belong to a person, such as requests or bookings, open its create, update and delete to every signed-in visitor, and let the table's data restriction narrow edit and delete to the visitor's own rows. The groups that manage everyone's records get no restriction.
97
+ - Split an action by role only for fields one role sets. A request's status goes on its own update with `customGroups` for the managers, and the visitor's update doesn't list it. One update open to every signed-in visitor that writes the status lets an employee have the agent approve their own vacation request.
98
+ - Don't list an update or delete on a table whose rows belong to people until its restriction is in place. Without it, the agent edits anyone's row.
99
+ - Where the app's pages show people only their own rows, the restriction needs a view rule too. The pages' filter lives in server functions, and without the rule the agent reads everyone's rows.
100
+
101
+ ## Failure modes
102
+
103
+ **Building a chat without the hook.** Calling the agents service from the browser fails: only the app's server can sign the request in as the visitor. Use `useAgentChat`.
104
+
105
+ **The hook inside a component that unmounts when the panel closes.** Closing it stops a reply that is still coming. Call `useAgentChat` in the component that owns the panel's open state and pass `chat` down. Keep the selected agent there too, or closing the panel resets it.
106
+
107
+ ## References
108
+
109
+ - [mcp/SKILL.md](../mcp/SKILL.md): the actions the agent may call
110
+ - [current-user/SKILL.md](../current-user/SKILL.md): showing the chat to signed-in visitors only
@@ -13,7 +13,7 @@ description: >-
13
13
  metadata:
14
14
  type: sub-skill
15
15
  library: softr-sdk
16
- library_version: 0.0.91
16
+ library_version: 0.0.93-alpha.0
17
17
  ---
18
18
 
19
19
  **Boundary.** `ai` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build. `defineAiAction` and every type come from `@softr/sdk` and can be imported anywhere.
@@ -3,13 +3,13 @@ name: auth
3
3
  description: >-
4
4
  Sign a visitor in, out or up from a server function with auth from
5
5
  @softr/sdk/server: password, code, Google and magic link, sign-up and its
6
- confirmation, the emailed-code and authenticator-app steps, password reset links,
6
+ confirmation, the authenticator-app steps, password reset links,
7
7
  updateProfile, and getAuthSettings and useAuthSettings for the methods the app
8
8
  enables. Covers the Result shape, its error codes, and toReturnPath.
9
9
  metadata:
10
10
  type: sub-skill
11
11
  library: softr-sdk
12
- library_version: 0.0.91
12
+ library_version: 0.0.93-alpha.0
13
13
  ---
14
14
 
15
15
  **Boundary.** `auth` lives on `@softr/sdk/server` and runs only inside a `createServerFn` handler — importing it into a component fails the build.
@@ -55,13 +55,6 @@ Signing out:
55
55
  | --- | --- |
56
56
  | `auth.signOut()` | Ends every session that visitor has in this app, on every device |
57
57
 
58
- Finishing a sign-in that wants a code from the visitor's inbox:
59
-
60
- | Call | Does |
61
- | --- | --- |
62
- | `auth.verifyEmailCode({ code })` | Answers it with the code that was emailed |
63
- | `auth.resendEmailCode()` | Emails that code again |
64
-
65
58
  Finishing a sign-in that wants an authenticator app:
66
59
 
67
60
  | Call | Does |
@@ -204,8 +197,6 @@ Those calls take only what the visitor typed. The sign-in they finish is the one
204
197
 
205
198
  An app with no authenticator app configured never answers `authenticatorRequired`. The type still has both arms either way, so `result.data.user` does not exist until you have narrowed on `status`.
206
199
 
207
- `signIn` has a third answer, `{ status: 'emailCodeRequired' }`, for an app that asks a password sign-in for a code from the visitor's inbox as well. The code is already on its way. Show a code field as the next step and finish with `auth.verifyEmailCode({ code })`, see [Finishing a sign-in that needs an emailed code](#finishing-a-sign-in-that-needs-an-emailed-code). That call answers like `signIn` does, so an app that also wants an authenticator app goes on to that step after it.
208
-
209
200
  ## Landing after sign-in
210
201
 
211
202
  A guard that turns a signed-out visitor away sends them to the page `softr.json` names for that, usually the login page. The page they wanted rides along in the search param named for the login page. `toReturnPath` from `@softr/sdk` reads it back:
@@ -264,13 +255,10 @@ if (answer.message !== null) return setMessage(answer.message)
264
255
  if (answer.outcome.status === 'authenticatorRequired') {
265
256
  return setStep({ name: 'secondFactor', opensOn: answer.outcome.step })
266
257
  }
267
- if (answer.outcome.status === 'emailCodeRequired') {
268
- return setStep({ name: 'emailCode' })
269
- }
270
258
  await navigate({ href: target })
271
259
  ```
272
260
 
273
- Four exits: a message for the form to render, the emailed-code step, the authenticator step, the return target.
261
+ Three exits: a message for the form to render, the second-factor step, the return target.
274
262
 
275
263
  A server function that throws `redirect` needs the hook. Call the imported function directly and the throw never reaches the router, so a successful sign-in leaves the visitor on the form.
276
264
 
@@ -397,22 +385,6 @@ The UI has to carry email into step two, plus the name if step one collected one
397
385
 
398
386
  `password` is what the account is created with. Leave it out only for an app that signs people in with an emailed code. An app that expects a password rejects a sign-up without one, and an app that does not expect one rejects a sign-up that sends it.
399
387
 
400
- ### Finishing a sign-in that needs an emailed code
401
-
402
- After `signIn` answers `emailCodeRequired`, the visitor owes the code that was just emailed to them:
403
-
404
- ```ts
405
- // invalidCode for a wrong or expired code, otherwise the same two-armed result as signIn.
406
- const result = await auth.verifyEmailCode({ code })
407
-
408
- // For a "Resend code" link.
409
- const sent = await auth.resendEmailCode()
410
- ```
411
-
412
- Send `authenticatorRequired` on to the authenticator step, never into the app.
413
-
414
- Asking for a resend too soon sends nothing and still succeeds. It answers `notAuthenticated` once the sign-in has run out of time, and the visitor then signs in again from the start.
415
-
416
388
  ### Finishing a sign-in that needs an authenticator app
417
389
 
418
390
  On `step: 'verify'` the visitor already has an app, and owes a code from it: