@segmentstream/ontology 0.108.0 → 0.110.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 (61) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +21 -0
  3. package/dist/analyze.js +55 -3
  4. package/dist/email.d.ts +18 -2
  5. package/dist/email.js +57 -7
  6. package/dist/index.d.ts +5 -5
  7. package/dist/index.js +2 -2
  8. package/dist/manifest.d.ts +94 -5
  9. package/dist/manifest.js +41 -6
  10. package/dist/migrate/apply.d.ts +4 -3
  11. package/dist/migrate/apply.js +8 -3
  12. package/dist/migrate/model.d.ts +46 -2
  13. package/dist/migrate/plan.js +1 -1
  14. package/dist/migrate/preview.js +2 -1
  15. package/dist/migrate/storage.d.ts +13 -1
  16. package/dist/migrate/storage.js +33 -1
  17. package/dist/runtime/agent-counters.d.ts +36 -0
  18. package/dist/runtime/agent-counters.js +84 -0
  19. package/dist/runtime/agent-web.d.ts +1 -1
  20. package/dist/runtime/agent-web.js +175 -3
  21. package/dist/runtime/batch.js +4 -6
  22. package/dist/runtime/history.d.ts +24 -0
  23. package/dist/runtime/history.js +35 -1
  24. package/dist/runtime/pipeline.js +3 -0
  25. package/dist/runtime/principals.d.ts +6 -0
  26. package/dist/runtime/principals.js +25 -6
  27. package/dist/runtime/reads.js +9 -2
  28. package/dist/runtime/sign-in-links.d.ts +10 -0
  29. package/dist/runtime/sign-in-links.js +26 -25
  30. package/dist/runtime/sql-runtime.d.ts +1 -1
  31. package/dist/runtime/sql-runtime.js +3 -2
  32. package/dist/runtime/writes.js +4 -6
  33. package/dist/runtime.d.ts +18 -0
  34. package/dist/service/agent/authentication.d.ts +3 -2
  35. package/dist/service/agent/authentication.js +2 -7
  36. package/dist/service/agent/bot-check.d.ts +42 -0
  37. package/dist/service/agent/bot-check.js +32 -0
  38. package/dist/service/agent/guest-sign-up.d.ts +140 -0
  39. package/dist/service/agent/guest-sign-up.js +545 -0
  40. package/dist/service/agent/protocol.d.ts +33 -1
  41. package/dist/service/agent/protocol.js +41 -1
  42. package/dist/service/agent/server.d.ts +17 -0
  43. package/dist/service/agent/server.js +42 -3
  44. package/dist/service/agent/web-tokens.d.ts +21 -3
  45. package/dist/service/agent/web-tokens.js +79 -6
  46. package/dist/service/authentication.d.ts +8 -1
  47. package/dist/service/authentication.js +26 -5
  48. package/dist/service/chat/providers/email.d.ts +3 -1
  49. package/dist/service/chat/providers/email.js +8 -1
  50. package/dist/service/config.d.ts +10 -0
  51. package/dist/service/operations.d.ts +5 -0
  52. package/dist/service/runtime-contract.d.ts +124 -1
  53. package/dist/service/runtime-identity.d.ts +23 -0
  54. package/dist/service/runtime-identity.js +31 -0
  55. package/dist/service/schemas.d.ts +46 -2
  56. package/dist/service/service.js +27 -1
  57. package/dist/service/webhooks.d.ts +15 -0
  58. package/dist/service/webhooks.js +15 -4
  59. package/dist/sign-in.d.ts +29 -0
  60. package/dist/sign-in.js +8 -0
  61. package/package.json +1 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,77 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.110.0
4
+
5
+ History keeps the chat an action came from. The app's agent names the chat it acts in and its
6
+ session there (`X-SegmentStream-Agent-Chat`, `X-SegmentStream-Agent-Session`, as on its attachment
7
+ routes) on every ontology request it makes for a member or a website's guest. With the
8
+ deployment's runtime token, the ontology keeps that chat as the principal's: an action's handler
9
+ sees it as `principal.chat` (`{ provider, chatId, sessionId? }`, as the chat archive names them,
10
+ such as `web` and `guest:<id>`), and every history entry the action writes carries it as `chat`,
11
+ in the runtime's action attribution table beside a pipeline's verified execution. A web chat counts
12
+ only as the acting member's or guest's own, a messenger's only on the provider the member wrote
13
+ from; any other chat is left out, never refused, and nothing else carries one. So a lead a guest
14
+ left, created by nobody, leads back to the guest's chat; an action can keep `principal.chat` on
15
+ the record for metrics by chat.
16
+
17
+ The next deploy's migration adds the nullable `chat` column to `_ontology_action_attribution` and
18
+ lets `execution` be empty, keeping every row. An agent built before this sends no chat, and an
19
+ ontology built before this ignores the headers. The app SDK's `HistoryEntry` type names `chat`.
20
+
21
+ Guests can be held to a bot check, a money cap, confirmations of their own, and can become users.
22
+
23
+ - `guest.botCheck: { scheme: "turnstile", secret: "turnstile-secret-key" }` makes every new guest
24
+ pass the website's challenge: `POST /api/ontology/agent/visitors` then needs the challenge's
25
+ token as `{ "bot_check": "<token>" }`, and answers `403 bot_check_required` without one,
26
+ `403 bot_check_failed` for one the provider refuses or that was solved on a page whose hostname
27
+ is not the requesting website's, and `503 bot_check_unavailable` when it cannot be checked. `secret` names a workspace secret holding the provider's secret key
28
+ (`segmentstream secret create`); SegmentStream's backend checks each token for the deployed
29
+ ontology, which never holds the key. Renewals need no check.
30
+ - `guest.confirmations: true` answers a guest's agent token introspection with
31
+ `confirmations: true`, so that the app's agent puts actions that need a confirmation to the
32
+ guest in the website's chat, as to a member. Without it nothing changes.
33
+ - The agent's limits may cap guests' daily model cost: `limits.guest.usdPerDay` for each guest
34
+ (at most 100) and `workspaceUsdPerDay` for every guest together (at most 10000), in US dollars.
35
+ The agent reports a guest's spend at `POST /api/ontology/agent/guests/usage` (runtime only,
36
+ `{ guest_id, cost_usd, key }`, once per key), and a guest's turn past a cap is answered
37
+ `limited` with the scope `guestUsdPerDay` or `guestWorkspaceUsdPerDay`. No cap applies unless set.
38
+ - Where `signUp` lists `email`, a guest becomes a user by proving an address with the app's own
39
+ sign-in email, with the guest's agent token, from a guest website.
40
+ `POST /api/ontology/agent/guests/email-code` (`{ email, return_to? }`) answers `{ sent: true }`
41
+ either way: an address whose Neon Auth account receives codes gets the six-digit code, which
42
+ `POST /api/ontology/agent/guests/sign-up` takes as `{ email, code }`; any other gets the app's
43
+ sign-in link, which creates its account. Opened, the link lands on
44
+ `GET /api/ontology/agent/guests/link`, which admits the user and redirects to `return_to` with
45
+ `#segmentstream_guest=<handoff>`; `/sign-up` takes `{ handoff }` only from the guest who asked
46
+ for the link, and refuses another browser's guest `handoff_other_browser`. The guest becomes the
47
+ user sign-up created with the address, or a new one with the roles `signUp` gives `email` (and
48
+ `onSignUp`); the address of a member is refused `member_address`. The guest's grant becomes
49
+ the user's, with new tokens in the answer
50
+ `{ token, expires_at, refresh_token, chat, user_id, created }`. Other refusals are
51
+ `email_sign_up_closed`, `code_invalid`, `link_invalid`, `handoff_invalid`, `rate_limited` and
52
+ `email_unavailable`. Pending links live in the new agent
53
+ table `_agent_guest_links`, which the next deploy creates; nonces and handoffs are stored as
54
+ hashes.
55
+
56
+ The manifest carries `sign_in.guest.bot_check` and `confirmations` only when declared, so other
57
+ manifests keep their hashes. Declare `guest.botCheck` only once SegmentStream verifies challenge
58
+ tokens for it; a deployment without that support answers new guests `503 bot_check_unavailable`.
59
+
60
+ ## 0.109.0
61
+
62
+ `emailReplyMessage` from `@segmentstream/ontology/email` takes `attachments` (file name, MIME type
63
+ and bytes): the reply becomes `multipart/mixed`, its text and HTML first, with every threading
64
+ header, `Auto-Submitted` and reply key it had, and refuses more than `EMAIL_ATTACHMENTS_LIMIT`
65
+ (25 MB, Gmail's limit) of files together.
66
+
67
+ A reviewed reply approved for an email chat is now marked `Auto-Submitted: auto-replied` and
68
+ named `X-SegmentStream-Reply: review-<review id>`, as the email channel's own replies are, so no
69
+ autoresponder answers it and the channel does not take it for staff's mail.
70
+
71
+ The agent routes now admit an email chat (`email:<thread>:<address>`), whose address holds `@`,
72
+ `.` and `+`: storing the attachments of an email, reading them and sending stored files in an email
73
+ chat were refused before.
74
+
3
75
  ## 0.108.0
4
76
 
5
77
  A workspace can send its own invitation. `signIn.invitationEmail` names one of the ontology's
package/README.md CHANGED
@@ -427,6 +427,27 @@ export default defineOntology({
427
427
  whose `*` is one whole leftmost label over a domain of at least two labels (`websiteOrigin`,
428
428
  `matchesWebsite`). The manifest carries `sign_in.guest` and the built-in role only when
429
429
  declared; `guestOf(manifest)` reads them.
430
+ - `guest.botCheck: { scheme: "turnstile", secret }` makes a new guest's request carry the
431
+ website challenge's token as `bot_check`; the ontology has SegmentStream's backend check it with
432
+ the challenge's provider under the workspace secret `secret` names, at
433
+ `…/secrets/{name}/verify-challenge`, and refuses `bot_check_required`, `bot_check_failed` or
434
+ `503 bot_check_unavailable`; each check carries an idempotency key, and a challenge solved on a
435
+ page whose hostname is not the requesting website's fails. `guest.confirmations: true` answers a
436
+ guest's introspection with `confirmations: true`, for the agent to put actions that need a
437
+ confirmation to the guest. Agent limits may cap guests' daily model cost with
438
+ `limits.guest.usdPerDay` (each guest, at most $100) and `workspaceUsdPerDay` (every guest
439
+ together, at most $10,000); the agent reports each answer's cost at
440
+ `POST /api/ontology/agent/guests/usage`, once per `key`, and a guest's turn past a cap is
441
+ answered `limited` with the scope `guestUsdPerDay` or `guestWorkspaceUsdPerDay`. With `signUp`
442
+ listing `email`, a guest becomes a user with the app's own sign-in email:
443
+ `POST /api/ontology/agent/guests/email-code` sends a code to an address whose Neon Auth account
444
+ receives codes and a sign-in link to any other, answering the same either way. A code goes back
445
+ to `…/guests/sign-up` as `{ email, code }`; a link lands on `GET …/guests/link`, which admits the
446
+ user and returns to the website with a single-use handoff, which `…/guests/sign-up` takes as
447
+ `{ handoff }` only from the guest who asked (`handoff_other_browser` otherwise). The user is the
448
+ one sign-up created with the address, or a new one, and the guest's grant moves to them with new
449
+ tokens; a member's address is refused `member_address`. Pending links and handoffs live in
450
+ `_agent_guest_links`, as hashes. See the guests' section of the ontology docs.
430
451
  - `signUp: { channels, roles, byChannel?, origins? }` opens sign-up to strangers on each listed
431
452
  channel: `email` (signing in to the app by email code), `telegram` (a first private message to
432
453
  the bot, or opening the Mini App), `whatsapp` (a first message to the number) and `web` (a
package/dist/analyze.js CHANGED
@@ -11,7 +11,7 @@ import { REFERENCE_ANNOTATION, propertyDefinition, propertyOptionNames, unknownP
11
11
  import { AGENT_TOOL, AGENT_TOOL_VERBS, EXPLICIT_GRANT_ENTITIES, generatedActionPermissions, grants, isAllowed, namesAgentTools, normalizePermission, parsePermission, parseWorkflowPermission, permissionOf, READ_VERB, rolesGranting, USER_IDENTITY_VERBS, USER_MEMBER_VERBS, WILDCARD, wildcardEntityCovers, WORKSPACE_SOURCE, WORKSPACE_SOURCE_PERMISSION, } from "./permissions.js";
12
12
  import { ON_DELETE, isRelationship } from "./relationship.js";
13
13
  import { isRole, member, role } from "./role.js";
14
- import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, GUEST_CHANNELS, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isGuestChannel, isSignInPolicy, isSignUpChannel, websiteOrigin, } from "./sign-in.js";
14
+ import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, GUEST_BOT_CHECK_SCHEMES, GUEST_CHANNELS, SIGN_UP_CHANNELS, SIGN_UP_CHAT_CHANNELS, isGuestBotCheckScheme, isGuestChannel, isSignInPolicy, isSignUpChannel, websiteOrigin, } from "./sign-in.js";
15
15
  import { BUILT_IN_EMAIL_VALUES, emailOptions, emailValueNames, } from "./emails.js";
16
16
  import { AgentChat } from "./agent-chat.js";
17
17
  import { AgentReview } from "./agent-review.js";
@@ -1484,7 +1484,13 @@ const WEBSITE_ORIGIN_HINT = "Use an origin alone, such as https://www.example.co
1484
1484
  /** The built-in `guest` roles `defineOntology({ guest })` made, as opposed to a declared one. */
1485
1485
  const BUILT_IN_GUESTS = new WeakSet();
1486
1486
  /** The guest keys `defineOntology({ guest })` takes. */
1487
- const GUEST_KEYS = ["channels", "origins", "permissions"];
1487
+ const GUEST_KEYS = [
1488
+ "channels",
1489
+ "origins",
1490
+ "permissions",
1491
+ "botCheck",
1492
+ "confirmations",
1493
+ ];
1488
1494
  /**
1489
1495
  * Where guests talk to the agent, and the built-in role `guest` with their permissions, when the
1490
1496
  * definition declares `guest`. Every problem is reported; the role is made from the permissions
@@ -1545,6 +1551,10 @@ function guestOptions(config, report) {
1545
1551
  if (!Array.isArray(options.permissions)) {
1546
1552
  report("missing-permissions", "guest.permissions", 'List what every guest may do, such as permissions: ["lead:submit"]; [] grants nothing.');
1547
1553
  }
1554
+ const botCheck = guestBotCheck(options.botCheck, report);
1555
+ if (options.confirmations !== undefined && typeof options.confirmations !== "boolean") {
1556
+ report("invalid-sign-in", "guest.confirmations", "confirmations is true to let guests confirm actions in the website's chat, or false.");
1557
+ }
1548
1558
  const guest = role(GUEST_ROLE, {
1549
1559
  description: "Every guest: a visitor of a declared website, who is no user.",
1550
1560
  permissions: Array.isArray(options.permissions)
@@ -1552,7 +1562,49 @@ function guestOptions(config, report) {
1552
1562
  : [],
1553
1563
  });
1554
1564
  BUILT_IN_GUESTS.add(guest);
1555
- return { resolved: { channels, origins }, role: guest };
1565
+ return {
1566
+ resolved: {
1567
+ channels,
1568
+ origins,
1569
+ ...(botCheck === undefined ? {} : { botCheck }),
1570
+ ...(options.confirmations === true ? { confirmations: true } : {}),
1571
+ },
1572
+ role: guest,
1573
+ };
1574
+ }
1575
+ /**
1576
+ * The challenge a new guest passes, as `guest.botCheck` declares it: the provider's scheme and the
1577
+ * workspace secret holding its secret key. Every problem is reported.
1578
+ */
1579
+ function guestBotCheck(value, report) {
1580
+ if (value === undefined) {
1581
+ return undefined;
1582
+ }
1583
+ const shape = `guest.botCheck takes { scheme: "${GUEST_BOT_CHECK_SCHEMES[0]}", secret: "<workspace secret>" }: ` +
1584
+ "the challenge's provider and the workspace secret holding its secret key.";
1585
+ if (!isPlainObject(value)) {
1586
+ report("invalid-sign-in", "guest.botCheck", shape);
1587
+ return undefined;
1588
+ }
1589
+ for (const key of Object.keys(value)) {
1590
+ if (key !== "scheme" && key !== "secret") {
1591
+ report("invalid-sign-in", `guest.botCheck.${key}`, `Unknown botCheck key: ${key}. ${shape}`);
1592
+ }
1593
+ }
1594
+ const { scheme, secret } = value;
1595
+ if (!isGuestBotCheckScheme(scheme)) {
1596
+ report("invalid-sign-in", "guest.botCheck.scheme", `${JSON.stringify(scheme) ?? "undefined"} is not a bot check; use one of ` +
1597
+ `${GUEST_BOT_CHECK_SCHEMES.join(", ")}.`);
1598
+ }
1599
+ if (typeof secret !== "string" || !WORKSPACE_SECRET_NAME.test(secret)) {
1600
+ report("invalid-sign-in", "guest.botCheck.secret", `${JSON.stringify(secret) ?? "undefined"} is not a workspace secret name; name the secret ` +
1601
+ "that holds the challenge's secret key, such as turnstile-secret-key.");
1602
+ }
1603
+ return isGuestBotCheckScheme(scheme) &&
1604
+ typeof secret === "string" &&
1605
+ WORKSPACE_SECRET_NAME.test(secret)
1606
+ ? { scheme, secret }
1607
+ : undefined;
1556
1608
  }
1557
1609
  /** Whether a scope's `where` names `me` or a path from it anywhere. */
1558
1610
  function usesMe(value) {
package/dist/email.d.ts CHANGED
@@ -1,5 +1,10 @@
1
1
  /** The most characters of a reply the mail channel sends in one message. */
2
2
  export declare const EMAIL_MESSAGE_LIMIT = 100000;
3
+ /**
4
+ * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
5
+ * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
6
+ */
7
+ export declare const EMAIL_ATTACHMENTS_LIMIT = 25000000;
3
8
  /**
4
9
  * A reply's Markdown as the HTML part of an email. HTML the text holds is escaped, so a reply can
5
10
  * carry no markup, image or script the platform did not render from Markdown itself.
@@ -7,6 +12,12 @@ export declare const EMAIL_MESSAGE_LIMIT = 100000;
7
12
  export declare function renderEmailHtml(text: string): string;
8
13
  /** The subject a reply in a thread carries: the thread's own, prefixed `Re:` once. */
9
14
  export declare function replySubject(subject: string | null | undefined): string;
15
+ /** A file a reply carries. */
16
+ export interface EmailAttachment {
17
+ readonly filename: string;
18
+ readonly contentType: string;
19
+ readonly bytes: Uint8Array;
20
+ }
10
21
  /** What a reply in an email thread needs from the message it answers. */
11
22
  export interface EmailReply {
12
23
  /** The address the reply goes to: a lower-case address without a name. */
@@ -31,12 +42,17 @@ export interface EmailReply {
31
42
  * failure can find it in the thread instead of sending it twice. Letters, digits, `-` and `_`.
32
43
  */
33
44
  readonly replyKey?: string;
45
+ /**
46
+ * Files the reply carries after its text, at most {@link EMAIL_ATTACHMENTS_LIMIT} bytes
47
+ * together. With files the message is `multipart/mixed`, its text first.
48
+ */
49
+ readonly attachments?: ReadonlyArray<EmailAttachment>;
34
50
  }
35
51
  /** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
36
52
  export declare const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
37
53
  /**
38
- * The reply as an RFC 5322 message with a plain-text and an HTML part, for a mailbox to send in
39
- * the same thread. It names no sender: the mailbox sends from its own address.
54
+ * The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
55
+ * a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
40
56
  */
41
57
  export declare function emailReplyMessage(reply: EmailReply): string;
42
58
  /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
package/dist/email.js CHANGED
@@ -1,6 +1,11 @@
1
1
  import { Marked } from "marked";
2
2
  /** The most characters of a reply the mail channel sends in one message. */
3
3
  export const EMAIL_MESSAGE_LIMIT = 100_000;
4
+ /**
5
+ * The most bytes of files one reply carries, together: Gmail takes 25 MB of attachments in a
6
+ * message. A sender whose own transport takes less, such as a connection proxy, bounds them lower.
7
+ */
8
+ export const EMAIL_ATTACHMENTS_LIMIT = 25_000_000;
4
9
  const HTML_ESCAPES = {
5
10
  "&": "&amp;",
6
11
  "<": "&lt;",
@@ -42,17 +47,37 @@ function messageId(value) {
42
47
  return flat !== undefined && /^<[^<>\s]+>$/.test(flat) ? flat : undefined;
43
48
  }
44
49
  /** Base64 in lines of 76 characters, as MIME bodies carry it. */
45
- function base64Lines(text) {
46
- return (Buffer.from(text, "utf8")
50
+ function base64Lines(content) {
51
+ return ((typeof content === "string" ? Buffer.from(content, "utf8") : Buffer.from(content))
47
52
  .toString("base64")
48
53
  .match(/.{1,76}/g)
49
54
  ?.join("\r\n") ?? "");
50
55
  }
56
+ /** A MIME type as a header carries it, or `application/octet-stream` for anything else. */
57
+ function mediaType(value) {
58
+ const type = value.trim().toLowerCase();
59
+ return /^[a-z0-9][a-z0-9!#$&^_.+-]{0,126}\/[a-z0-9][a-z0-9!#$&^_.+-]{0,126}$/.test(type)
60
+ ? type
61
+ : "application/octet-stream";
62
+ }
63
+ /**
64
+ * A file name as a MIME parameter: printable ASCII in quotes, followed by the same name in UTF-8
65
+ * (RFC 2231) when it holds anything else, so mail programs show it as it was named.
66
+ */
67
+ function fileNameParameter(parameter, filename) {
68
+ const flat = filename.replace(/[\r\n\t"\\]+/g, " ").trim() || "attachment";
69
+ const ascii = flat.replace(/[^\x20-\x7e]/g, "_");
70
+ if (ascii === flat) {
71
+ return `${parameter}="${flat}"`;
72
+ }
73
+ const encoded = encodeURIComponent(flat).replace(/['()*]/g, (character) => `%${character.charCodeAt(0).toString(16).toUpperCase()}`);
74
+ return `${parameter}="${ascii}"; ${parameter}*=UTF-8''${encoded}`;
75
+ }
51
76
  /** The header that names a reply, as {@link EmailReply.replyKey} sets it. */
52
77
  export const REPLY_KEY_HEADER = "X-SegmentStream-Reply";
53
78
  /**
54
- * The reply as an RFC 5322 message with a plain-text and an HTML part, for a mailbox to send in
55
- * the same thread. It names no sender: the mailbox sends from its own address.
79
+ * The reply as an RFC 5322 message with a plain-text and an HTML part, followed by its files, for
80
+ * a mailbox to send in the same thread. It names no sender: the mailbox sends from its own address.
56
81
  */
57
82
  export function emailReplyMessage(reply) {
58
83
  if (!/^[^\s<>@,;:"]+@[^\s<>@,;:"]+$/.test(reply.to)) {
@@ -61,6 +86,11 @@ export function emailReplyMessage(reply) {
61
86
  if (reply.replyKey !== undefined && !/^[A-Za-z0-9_-]{1,128}$/.test(reply.replyKey)) {
62
87
  throw new Error("The reply's key holds characters a header cannot carry.");
63
88
  }
89
+ const attachments = reply.attachments ?? [];
90
+ const size = attachments.reduce((total, file) => total + file.bytes.byteLength, 0);
91
+ if (size > EMAIL_ATTACHMENTS_LIMIT) {
92
+ throw new Error(`A reply carries at most ${EMAIL_ATTACHMENTS_LIMIT} bytes of files.`);
93
+ }
64
94
  const boundary = `segmentstream-${crypto.randomUUID()}`;
65
95
  const parent = messageId(reply.inReplyTo);
66
96
  const references = [
@@ -79,10 +109,10 @@ export function emailReplyMessage(reply) {
79
109
  ...(reply.autoSubmitted === true ? ["Auto-Submitted: auto-replied"] : []),
80
110
  ...(reply.replyKey === undefined ? [] : [`${REPLY_KEY_HEADER}: ${reply.replyKey}`]),
81
111
  "MIME-Version: 1.0",
82
- `Content-Type: multipart/alternative; boundary="${boundary}"`,
83
112
  ];
84
- return [
85
- ...headers,
113
+ // The text and the same text as HTML: the whole message without files, its first part with them.
114
+ const text = [
115
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
86
116
  "",
87
117
  `--${boundary}`,
88
118
  "Content-Type: text/plain; charset=UTF-8",
@@ -95,6 +125,26 @@ export function emailReplyMessage(reply) {
95
125
  "",
96
126
  base64Lines(reply.html),
97
127
  `--${boundary}--`,
128
+ ];
129
+ if (attachments.length === 0) {
130
+ return [...headers, ...text, ""].join("\r\n");
131
+ }
132
+ const mixed = `segmentstream-${crypto.randomUUID()}`;
133
+ return [
134
+ ...headers,
135
+ `Content-Type: multipart/mixed; boundary="${mixed}"`,
136
+ "",
137
+ `--${mixed}`,
138
+ ...text,
139
+ ...attachments.flatMap((file) => [
140
+ `--${mixed}`,
141
+ `Content-Type: ${mediaType(file.contentType)}; ${fileNameParameter("name", file.filename)}`,
142
+ `Content-Disposition: attachment; ${fileNameParameter("filename", file.filename)}`,
143
+ "Content-Transfer-Encoding: base64",
144
+ "",
145
+ base64Lines(file.bytes),
146
+ ]),
147
+ `--${mixed}--`,
98
148
  "",
99
149
  ].join("\r\n");
100
150
  }
package/dist/index.d.ts CHANGED
@@ -48,12 +48,12 @@ export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkfl
48
48
  export { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_HEADERS, MAX_WEBHOOKS, WEBHOOK_BASE_PATH, WEBHOOK_SIGNATURE_SCHEMES, webhookDelivery, webhookHeaderProblem, webhookPath, } from "./webhooks.js";
49
49
  export type { WebhookDelivery, WebhookSignatureScheme } from "./webhooks.js";
50
50
  export type { ActionEvent, ActionTrigger, AfterOptions, AnyActionHandle, AnyWorkflow, ChangedBounds, CronOptions, CronProblem, CronTrigger, TriggerFunction, TriggerRecord, WebhookOptions, WebhookSignature, WebhookVerification, WebhookTrigger, Workflow, WorkflowFunction, WorkflowOptions, WorkflowRunContext, WorkflowTrigger, } from "./workflow.js";
51
- export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, GUEST_CHANNELS, matchesWebsite, signUpOrigin, websiteOrigin, } from "./sign-in.js";
52
- export type { ChannelProvider, GuestChannel, GuestOptions, ResolvedGuest, ResolvedSignInOptions, ResolvedSignUp, SignInCheck, SignInMethod, SignInOptions, SignInPolicy, SignUpChannel, SignUpOptions, } from "./sign-in.js";
51
+ export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, GUEST_BOT_CHECK_SCHEMES, GUEST_CHANNELS, matchesWebsite, signUpOrigin, websiteOrigin, } from "./sign-in.js";
52
+ export type { ChannelProvider, GuestBotCheck, GuestBotCheckScheme, GuestChannel, GuestOptions, ResolvedGuest, ResolvedSignInOptions, ResolvedSignUp, SignInCheck, SignInMethod, SignInOptions, SignInPolicy, SignUpChannel, SignUpOptions, } from "./sign-in.js";
53
53
  export type { EmailSection, EmailSectionItem, EmailTemplate } from "./emails.js";
54
54
  export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
55
55
  export type { ActionRunOptions } from "./runtime.js";
56
- export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, BatchSummaryResult, CreateManyInput, FieldCondition, OntologyRuntimeService, FindOptions, FreshMetricQueryOptions, GetOptions, Principal, RecordWhere, StoredRecord, StoredValues, UpsertResult, UpdateManyInput, UpsertManyInput, } from "./runtime.js";
56
+ export type { BatchOptions, BatchRecordResult, BatchResult, BatchReturning, BatchSummaryResult, ChatProvenance, CreateManyInput, FieldCondition, OntologyRuntimeService, FindOptions, FreshMetricQueryOptions, GetOptions, Principal, RecordWhere, StoredRecord, StoredValues, UpsertResult, UpdateManyInput, UpsertManyInput, } from "./runtime.js";
57
57
  export { User } from "./user.js";
58
58
  export type { UserHandle, UserMemberWrites } from "./user.js";
59
59
  export { AgentChat } from "./agent-chat.js";
@@ -86,9 +86,9 @@ export { configFromEnv, ENVIRONMENT_VARIABLES, NEON_AUTH_ENVIRONMENT_VARIABLES,
86
86
  export type { ActionCommitted, AfterCommitHook, NeonAuthEnvironment, OntologyEnvironment, OntologyServiceConfig, } from "./service/config.js";
87
87
  export type { Decide, DecisionRequest } from "./service/decisions.js";
88
88
  export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-contract.js";
89
- export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, GuestIssue, VisitorSignUp, WebTurnLimit, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
89
+ export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, GuestIssue, GuestUpgrade, VisitorSignUp, WebTurnLimit, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
90
90
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
91
- export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, } from "./service/agent/server.js";
91
+ export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, GUEST_EMAIL_CODE_PATH, GUEST_SIGN_UP_PATH, GUEST_USAGE_PATH, GUEST_LINK_PATH, } from "./service/agent/server.js";
92
92
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
93
93
  export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
94
94
  export { AGENT_WEB_CLIENT_ID, agentResource } from "./service/agent/web-tokens.js";
package/dist/index.js CHANGED
@@ -26,7 +26,7 @@ export { renderCatalog } from "./render.js";
26
26
  export { member, role, roleEntries, rolePermissions } from "./role.js";
27
27
  export { after, changed, cron, cronNeverFires, cronProblem, isWorkflow, isWorkflowTrigger, MAX_ACTION_TRIGGERS, MAX_WORKFLOWS, nextCronTime, webhook, workflow, } from "./workflow.js";
28
28
  export { MAX_WEBHOOK_BODY_BYTES, MAX_META_WEBHOOK_BODY_BYTES, MAX_WEBHOOK_HEADERS, MAX_WEBHOOKS, WEBHOOK_BASE_PATH, WEBHOOK_SIGNATURE_SCHEMES, webhookDelivery, webhookHeaderProblem, webhookPath, } from "./webhooks.js";
29
- export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, GUEST_CHANNELS, matchesWebsite,
29
+ export { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, SIGN_IN_METHODS, SIGN_IN_POLICIES, SIGN_UP_CHANNELS, GUEST_BOT_CHECK_SCHEMES, GUEST_CHANNELS, matchesWebsite,
30
30
  // @legacy ontology.sign-up-origin-name
31
31
  signUpOrigin, websiteOrigin, } from "./sign-in.js";
32
32
  export { OntologyActions, OntologyReads, OntologyRuntime, OntologyWrites } from "./runtime.js";
@@ -56,7 +56,7 @@ export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-co
56
56
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
57
57
  // The app's own agent: pairing channel accounts with members, and acting as them, or as a
58
58
  // workflow's user in the tasks workflows hand it.
59
- export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, } from "./service/agent/server.js";
59
+ export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, AGENT_VISITORS_PATH, GUEST_EMAIL_CODE_PATH, GUEST_SIGN_UP_PATH, GUEST_USAGE_PATH, GUEST_LINK_PATH, } from "./service/agent/server.js";
60
60
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
61
61
  export { WORKSPACE_SOURCE_PATH } from "./service/agent/source.js";
62
62
  // Agent tokens: access tokens of a member's grant to the agent, which a browser shows the agent.
@@ -73,6 +73,10 @@ import { type ResolvedGuest, type ResolvedSignInOptions, type SignInPolicy } fro
73
73
  * declared: the wire name of the email the platform sends instead of its own invitation. Older
74
74
  * readers ignore `sections` and `invitationEmail`, leave the two values empty and send the
75
75
  * platform's invitation.
76
+ * Within version 15, `guest` may carry `bot_check`, `{ scheme, secret }`, the challenge a new
77
+ * guest passes and the workspace secret its verification reads, and `confirmations: true`, written
78
+ * only when declared. Older readers ignore both: they ask new guests for no challenge, and keep
79
+ * refusing guests the actions that need a confirmation.
76
80
  */
77
81
  export declare const MANIFEST_VERSION = 15;
78
82
  /** The phrase used for a direction the author did not phrase. */
@@ -634,9 +638,18 @@ export declare const SignUpManifest: Schema.Struct<{
634
638
  * permissions are the built-in `guest` role's. Read as text: channels and origins a reader does not
635
639
  * know admit nobody.
636
640
  */
637
- export declare const GuestManifest: Schema.Struct<{
641
+ export declare const GuestManifest: Schema.encodeKeys<Schema.Struct<{
638
642
  readonly channels: Schema.$Array<Schema.String>;
639
643
  readonly origins: Schema.$Array<Schema.String>;
644
+ /** The challenge a new guest passes, and the workspace secret holding its secret key. */
645
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
646
+ readonly scheme: Schema.String;
647
+ readonly secret: Schema.String;
648
+ }>>;
649
+ /** Guests may confirm actions that need a confirmation. */
650
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
651
+ }>, {
652
+ readonly botCheck: "bot_check";
640
653
  }>;
641
654
  export declare const SignInManifest: Schema.encodeKeys<Schema.Struct<{
642
655
  readonly browser: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
@@ -658,9 +671,18 @@ export declare const SignInManifest: Schema.encodeKeys<Schema.Struct<{
658
671
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
659
672
  }>>;
660
673
  readonly onSignUp: Schema.optionalKey<Schema.String>;
661
- readonly guest: Schema.optionalKey<Schema.Struct<{
674
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
662
675
  readonly channels: Schema.$Array<Schema.String>;
663
676
  readonly origins: Schema.$Array<Schema.String>;
677
+ /** The challenge a new guest passes, and the workspace secret holding its secret key. */
678
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
679
+ readonly scheme: Schema.String;
680
+ readonly secret: Schema.String;
681
+ }>>;
682
+ /** Guests may confirm actions that need a confirmation. */
683
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
684
+ }>, {
685
+ readonly botCheck: "bot_check";
664
686
  }>>;
665
687
  /** The wire name of the email the platform sends instead of its own invitation. */
666
688
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
@@ -960,9 +982,18 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
960
982
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
961
983
  }>>;
962
984
  readonly onSignUp: Schema.optionalKey<Schema.String>;
963
- readonly guest: Schema.optionalKey<Schema.Struct<{
985
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
964
986
  readonly channels: Schema.$Array<Schema.String>;
965
987
  readonly origins: Schema.$Array<Schema.String>;
988
+ /** The challenge a new guest passes, and the workspace secret holding its secret key. */
989
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
990
+ readonly scheme: Schema.String;
991
+ readonly secret: Schema.String;
992
+ }>>;
993
+ /** Guests may confirm actions that need a confirmation. */
994
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
995
+ }>, {
996
+ readonly botCheck: "bot_check";
966
997
  }>>;
967
998
  /** The wire name of the email the platform sends instead of its own invitation. */
968
999
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
@@ -1356,6 +1387,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1356
1387
  readonly guest?: {
1357
1388
  readonly channels: readonly string[];
1358
1389
  readonly origins: readonly string[];
1390
+ readonly botCheck?: {
1391
+ readonly scheme: string;
1392
+ readonly secret: string;
1393
+ } | undefined;
1394
+ readonly confirmations?: boolean | undefined;
1359
1395
  } | undefined;
1360
1396
  readonly browser?: {
1361
1397
  readonly methods: readonly string[];
@@ -1647,6 +1683,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1647
1683
  readonly guest?: {
1648
1684
  readonly channels: readonly string[];
1649
1685
  readonly origins: readonly string[];
1686
+ readonly botCheck?: {
1687
+ readonly scheme: string;
1688
+ readonly secret: string;
1689
+ } | undefined;
1690
+ readonly confirmations?: boolean | undefined;
1650
1691
  } | undefined;
1651
1692
  readonly browser?: {
1652
1693
  readonly methods: readonly string[];
@@ -2003,6 +2044,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2003
2044
  readonly guest?: {
2004
2045
  readonly channels: readonly string[];
2005
2046
  readonly origins: readonly string[];
2047
+ readonly confirmations?: boolean | undefined;
2048
+ readonly bot_check?: {
2049
+ readonly scheme: string;
2050
+ readonly secret: string;
2051
+ } | undefined;
2006
2052
  } | undefined;
2007
2053
  readonly browser?: {
2008
2054
  readonly methods: readonly string[];
@@ -2229,6 +2275,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2229
2275
  readonly guest?: {
2230
2276
  readonly channels: readonly string[];
2231
2277
  readonly origins: readonly string[];
2278
+ readonly confirmations?: boolean | undefined;
2279
+ readonly bot_check?: {
2280
+ readonly scheme: string;
2281
+ readonly secret: string;
2282
+ } | undefined;
2232
2283
  } | undefined;
2233
2284
  readonly browser?: {
2234
2285
  readonly methods: readonly string[];
@@ -2518,9 +2569,18 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2518
2569
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
2519
2570
  }>>;
2520
2571
  readonly onSignUp: Schema.optionalKey<Schema.String>;
2521
- readonly guest: Schema.optionalKey<Schema.Struct<{
2572
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
2522
2573
  readonly channels: Schema.$Array<Schema.String>;
2523
2574
  readonly origins: Schema.$Array<Schema.String>;
2575
+ /** The challenge a new guest passes, and the workspace secret holding its secret key. */
2576
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
2577
+ readonly scheme: Schema.String;
2578
+ readonly secret: Schema.String;
2579
+ }>>;
2580
+ /** Guests may confirm actions that need a confirmation. */
2581
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
2582
+ }>, {
2583
+ readonly botCheck: "bot_check";
2524
2584
  }>>;
2525
2585
  /** The wire name of the email the platform sends instead of its own invitation. */
2526
2586
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
@@ -2899,9 +2959,18 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2899
2959
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
2900
2960
  }>>;
2901
2961
  readonly onSignUp: Schema.optionalKey<Schema.String>;
2902
- readonly guest: Schema.optionalKey<Schema.Struct<{
2962
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
2903
2963
  readonly channels: Schema.$Array<Schema.String>;
2904
2964
  readonly origins: Schema.$Array<Schema.String>;
2965
+ /** The challenge a new guest passes, and the workspace secret holding its secret key. */
2966
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
2967
+ readonly scheme: Schema.String;
2968
+ readonly secret: Schema.String;
2969
+ }>>;
2970
+ /** Guests may confirm actions that need a confirmation. */
2971
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
2972
+ }>, {
2973
+ readonly botCheck: "bot_check";
2905
2974
  }>>;
2906
2975
  /** The wire name of the email the platform sends instead of its own invitation. */
2907
2976
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
@@ -3287,6 +3356,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3287
3356
  readonly guest?: {
3288
3357
  readonly channels: readonly string[];
3289
3358
  readonly origins: readonly string[];
3359
+ readonly botCheck?: {
3360
+ readonly scheme: string;
3361
+ readonly secret: string;
3362
+ } | undefined;
3363
+ readonly confirmations?: boolean | undefined;
3290
3364
  } | undefined;
3291
3365
  readonly browser?: {
3292
3366
  readonly methods: readonly string[];
@@ -3578,6 +3652,11 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3578
3652
  readonly guest?: {
3579
3653
  readonly channels: readonly string[];
3580
3654
  readonly origins: readonly string[];
3655
+ readonly botCheck?: {
3656
+ readonly scheme: string;
3657
+ readonly secret: string;
3658
+ } | undefined;
3659
+ readonly confirmations?: boolean | undefined;
3581
3660
  } | undefined;
3582
3661
  readonly browser?: {
3583
3662
  readonly methods: readonly string[];
@@ -3875,6 +3954,11 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
3875
3954
  readonly guest?: {
3876
3955
  readonly channels: readonly string[];
3877
3956
  readonly origins: readonly string[];
3957
+ readonly botCheck?: {
3958
+ readonly scheme: string;
3959
+ readonly secret: string;
3960
+ } | undefined;
3961
+ readonly confirmations?: boolean | undefined;
3878
3962
  } | undefined;
3879
3963
  readonly browser?: {
3880
3964
  readonly methods: readonly string[];
@@ -4166,6 +4250,11 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
4166
4250
  readonly guest?: {
4167
4251
  readonly channels: readonly string[];
4168
4252
  readonly origins: readonly string[];
4253
+ readonly botCheck?: {
4254
+ readonly scheme: string;
4255
+ readonly secret: string;
4256
+ } | undefined;
4257
+ readonly confirmations?: boolean | undefined;
4169
4258
  } | undefined;
4170
4259
  readonly browser?: {
4171
4260
  readonly methods: readonly string[];