@segmentstream/ontology 0.104.0 → 0.106.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 (41) hide show
  1. package/CHANGELOG.md +27 -0
  2. package/dist/analyze.d.ts +9 -1
  3. package/dist/analyze.js +7 -3
  4. package/dist/email.d.ts +30 -0
  5. package/dist/email.js +97 -0
  6. package/dist/manifest.d.ts +39 -0
  7. package/dist/manifest.js +3 -0
  8. package/dist/migrate/model.d.ts +24 -0
  9. package/dist/nitro-workflows.d.ts +14 -0
  10. package/dist/nitro-workflows.js +62 -2
  11. package/dist/runtime/agents.js +8 -2
  12. package/dist/runtime/channel-identity-admin.js +6 -2
  13. package/dist/runtime/resolve-agent-identity.d.ts +1 -1
  14. package/dist/runtime/resolve-agent-identity.js +56 -4
  15. package/dist/runtime/user-identity-sql.d.ts +5 -0
  16. package/dist/runtime/user-identity-sql.js +5 -0
  17. package/dist/server.d.ts +7 -0
  18. package/dist/server.js +9 -1
  19. package/dist/service/agent/protocol.d.ts +1 -0
  20. package/dist/service/agent/protocol.js +4 -0
  21. package/dist/service/agent/server.js +2 -1
  22. package/dist/service/chat/providers/email.d.ts +15 -0
  23. package/dist/service/chat/providers/email.js +133 -0
  24. package/dist/service/chat/providers/index.d.ts +5 -1
  25. package/dist/service/chat/providers/index.js +7 -2
  26. package/dist/service/chat/providers/provider.d.ts +5 -0
  27. package/dist/service/runtime-contract.d.ts +5 -0
  28. package/dist/service/schemas.d.ts +6 -0
  29. package/dist/service/workflows.d.ts +2 -0
  30. package/dist/service/workflows.js +14 -1
  31. package/dist/storage/tables.d.ts +1 -1
  32. package/dist/storage/tables.js +1 -1
  33. package/dist/user-identity.d.ts +4 -2
  34. package/dist/user-identity.js +4 -2
  35. package/dist/workflow-runtime.d.ts +5 -0
  36. package/dist/workflow-runtime.js +9 -0
  37. package/dist/workflow-structure-extract.d.ts +52 -0
  38. package/dist/workflow-structure-extract.js +1096 -0
  39. package/dist/workflow-structure.d.ts +141 -0
  40. package/dist/workflow-structure.js +16 -0
  41. package/package.json +6 -2
package/CHANGELOG.md CHANGED
@@ -1,5 +1,32 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.106.0
4
+
5
+ The ontology admits people who write to the agent's mailbox. An `email` account is the sender's
6
+ address, admitted only when the agent reports that the receiving server proved it (DMARC with
7
+ alignment): `signUp` with `email` then also signs up a stranger who writes, with the same roles as
8
+ a code sign-in, and sets the new user's `email`. The address of a user sign-up created is linked
9
+ to them; a member's address is attached with `user_identity.attach`, which now takes `email`.
10
+ `chat.email` names the mailbox a reply held for review leaves from: the reply goes in the
11
+ person's thread, threaded under its last message, never as a chat post. Attachments may come from
12
+ `email`. The first-contact notice is recorded for everyone sign-up created, whatever the channel.
13
+ `@segmentstream/ontology/email` renders a reply's Markdown as email HTML and builds the reply.
14
+
15
+ ## 0.105.0
16
+
17
+ The console can draw each workflow as a map. `ontologyWorkflows()` now reads every workflow's
18
+ code when the ontology builds: the steps its `"use workflow"` function calls in order, its waits
19
+ (`sleep`, hooks, webhooks), `agentTask`, branches (`if`, `switch`, early `return` and `throw`),
20
+ loops (including `do…while`), `Promise.all` groups and `try`/`catch`, following helpers the
21
+ project declares. For each step it keeps the comment above the function as its description and
22
+ the entity actions, record operations and connection requests its code calls. The service serves
23
+ it at `GET /api/ontology/workflows/:workflow/structure` to callers that may read the workflow's
24
+ runs. The reading never runs the code, never fails the build, and marks what it could not follow.
25
+
26
+ Write a comment above each `"use step"` function and above the statements of the workflow body
27
+ that need explaining: the console shows them on the map. The SDK now depends on `typescript` to
28
+ read the code at build time.
29
+
3
30
  ## 0.104.0
4
31
 
5
32
  The agent answers a website's visitors. `signUp` takes the channel `web` with `origins`, the
package/dist/analyze.d.ts CHANGED
@@ -85,7 +85,9 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
85
85
  readonly toolsets?: ReadonlyArray<Toolset>;
86
86
  /**
87
87
  * The providers the built-in exact chat post delivers to, each through its connection, which
88
- * must be listed in `connections`. Only declared providers are destinations.
88
+ * must be listed in `connections`. Only declared providers are destinations. A reply the agent
89
+ * held for review is sent through the same connection. `email` names the mailbox the agent's
90
+ * mail channel reads: only reviewed replies leave through it, never a chat post.
89
91
  */
90
92
  readonly chat?: {
91
93
  readonly telegram?: {
@@ -97,6 +99,9 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
97
99
  readonly whatsapp?: {
98
100
  readonly connection: AnyConnectionHandle;
99
101
  };
102
+ readonly email?: {
103
+ readonly connection: AnyConnectionHandle;
104
+ };
100
105
  readonly attribution?: ChatAttributionSettings;
101
106
  };
102
107
  /**
@@ -217,6 +222,9 @@ export interface Analysis {
217
222
  readonly whatsapp?: {
218
223
  readonly connection: string;
219
224
  };
225
+ readonly email?: {
226
+ readonly connection: string;
227
+ };
220
228
  readonly attribution?: ChatAttributionSettings;
221
229
  };
222
230
  readonly entities: ReadonlyArray<ResolvedEntity>;
package/dist/analyze.js CHANGED
@@ -33,7 +33,9 @@ import { validate } from "./runtime/validation.js";
33
33
  import { fixedArgumentsConflict, isToolset, MAXIMUM_TOOLSET_TOOLS, MCP_TOOL_NAME, toolHints, ToolsetLock, withoutFixedArguments, } from "./toolset.js";
34
34
  const GENERATED_UPSERT = new RegExp(`^${GENERATED_UPSERT_PREFIX}`);
35
35
  /** The providers `chat` may declare a posting connection for, in the order posting lists them. */
36
- const CHAT_PROVIDER_KEYS = ["telegram", "slack", "whatsapp"];
36
+ const CHAT_PROVIDER_KEYS = ["telegram", "slack", "whatsapp", "email"];
37
+ /** The `chat` providers reviewed replies leave through, but chat posts never reach. */
38
+ const REVIEW_ONLY_CHAT_PROVIDERS = new Set(["email"]);
37
39
  function errorMessage(error) {
38
40
  return error instanceof Error ? error.message : String(error);
39
41
  }
@@ -180,6 +182,8 @@ export function analyze(config, options = {}) {
180
182
  agent_chat: "post_message",
181
183
  agent_review: "approve",
182
184
  };
185
+ // A chat post never reaches a provider that only sends reviewed replies.
186
+ const reaches = (entity) => handles.filter(([name]) => entity === "agent_review" || !REVIEW_ONLY_CHAT_PROVIDERS.has(name));
183
187
  resolved = resolved.map((entity) => sends[entity.name] === undefined
184
188
  ? entity
185
189
  : {
@@ -188,10 +192,10 @@ export function analyze(config, options = {}) {
188
192
  ? candidate
189
193
  : {
190
194
  ...candidate,
191
- connections: handles.map(([, handle]) => handle.key),
195
+ connections: reaches(entity.name).map(([, handle]) => handle.key),
192
196
  action: {
193
197
  ...candidate.action,
194
- connections: handles.map(([, handle]) => handle),
198
+ connections: reaches(entity.name).map(([, handle]) => handle),
195
199
  },
196
200
  }),
197
201
  });
@@ -0,0 +1,30 @@
1
+ /** The most characters of a reply the mail channel sends in one message. */
2
+ export declare const EMAIL_MESSAGE_LIMIT = 100000;
3
+ /**
4
+ * A reply's Markdown as the HTML part of an email. HTML the text holds is escaped, so a reply can
5
+ * carry no markup, image or script the platform did not render from Markdown itself.
6
+ */
7
+ export declare function renderEmailHtml(text: string): string;
8
+ /** The subject a reply in a thread carries: the thread's own, prefixed `Re:` once. */
9
+ export declare function replySubject(subject: string | null | undefined): string;
10
+ /** What a reply in an email thread needs from the message it answers. */
11
+ export interface EmailReply {
12
+ /** The address the reply goes to: a lower-case address without a name. */
13
+ readonly to: string;
14
+ /** The thread's subject; the reply carries it with `Re:`. */
15
+ readonly subject: string | null;
16
+ /** The `Message-ID` of the message replied to, which threads the reply under it. */
17
+ readonly inReplyTo?: string | null;
18
+ /** The `References` of the message replied to, which the reply extends with its id. */
19
+ readonly references?: string | null;
20
+ /** The reply as plain text, and the same reply as HTML. */
21
+ readonly text: string;
22
+ readonly html: string;
23
+ }
24
+ /**
25
+ * The reply as an RFC 5322 message with a plain-text and an HTML part, for a mailbox to send in
26
+ * the same thread. It names no sender: the mailbox sends from its own address.
27
+ */
28
+ export declare function emailReplyMessage(reply: EmailReply): string;
29
+ /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
30
+ export declare function base64Url(text: string): string;
package/dist/email.js ADDED
@@ -0,0 +1,97 @@
1
+ import { Marked } from "marked";
2
+ /** The most characters of a reply the mail channel sends in one message. */
3
+ export const EMAIL_MESSAGE_LIMIT = 100_000;
4
+ const HTML_ESCAPES = {
5
+ "&": "&amp;",
6
+ "<": "&lt;",
7
+ ">": "&gt;",
8
+ '"': "&quot;",
9
+ "'": "&#39;",
10
+ };
11
+ function escapeHtml(text) {
12
+ return text.replace(/[&<>"']/g, (character) => HTML_ESCAPES[character] ?? character);
13
+ }
14
+ /** Markdown as HTML, with any HTML written in the text shown as text rather than rendered. */
15
+ const markdown = new Marked({ gfm: true, breaks: true, async: false }).use({
16
+ renderer: {
17
+ html: (token) => escapeHtml(token.text),
18
+ },
19
+ });
20
+ /**
21
+ * A reply's Markdown as the HTML part of an email. HTML the text holds is escaped, so a reply can
22
+ * carry no markup, image or script the platform did not render from Markdown itself.
23
+ */
24
+ export function renderEmailHtml(text) {
25
+ const body = markdown.parse(text);
26
+ return `<!doctype html><html><body>${body}</body></html>`;
27
+ }
28
+ /** The subject a reply in a thread carries: the thread's own, prefixed `Re:` once. */
29
+ export function replySubject(subject) {
30
+ const flat = (subject ?? "").replace(/[\r\n]+/g, " ").trim();
31
+ return /^re:/i.test(flat) ? flat : `Re: ${flat}`.trim();
32
+ }
33
+ /** A header value in RFC 2047 encoded words when it holds anything but printable ASCII. */
34
+ function headerText(value) {
35
+ return /^[\x20-\x7e]*$/.test(value)
36
+ ? value
37
+ : `=?UTF-8?B?${Buffer.from(value, "utf8").toString("base64")}?=`;
38
+ }
39
+ /** A message id (`<…@…>`) with nothing that could end its header. */
40
+ function messageId(value) {
41
+ const flat = value?.replace(/[\r\n]+/g, " ").trim();
42
+ return flat !== undefined && /^<[^<>\s]+>$/.test(flat) ? flat : undefined;
43
+ }
44
+ /** Base64 in lines of 76 characters, as MIME bodies carry it. */
45
+ function base64Lines(text) {
46
+ return (Buffer.from(text, "utf8")
47
+ .toString("base64")
48
+ .match(/.{1,76}/g)
49
+ ?.join("\r\n") ?? "");
50
+ }
51
+ /**
52
+ * The reply as an RFC 5322 message with a plain-text and an HTML part, for a mailbox to send in
53
+ * the same thread. It names no sender: the mailbox sends from its own address.
54
+ */
55
+ export function emailReplyMessage(reply) {
56
+ if (!/^[^\s<>@,;:"]+@[^\s<>@,;:"]+$/.test(reply.to)) {
57
+ throw new Error("The reply's recipient is not a plain address.");
58
+ }
59
+ const boundary = `segmentstream-${crypto.randomUUID()}`;
60
+ const parent = messageId(reply.inReplyTo);
61
+ const references = [
62
+ ...(reply.references ?? "")
63
+ .replace(/[\r\n]+/g, " ")
64
+ .split(/\s+/)
65
+ .map((reference) => messageId(reference))
66
+ .filter((reference) => reference !== undefined),
67
+ ...(parent === undefined ? [] : [parent]),
68
+ ];
69
+ const headers = [
70
+ `To: ${reply.to}`,
71
+ `Subject: ${headerText(replySubject(reply.subject))}`,
72
+ ...(parent === undefined ? [] : [`In-Reply-To: ${parent}`]),
73
+ ...(references.length === 0 ? [] : [`References: ${[...new Set(references)].join(" ")}`]),
74
+ "MIME-Version: 1.0",
75
+ `Content-Type: multipart/alternative; boundary="${boundary}"`,
76
+ ];
77
+ return [
78
+ ...headers,
79
+ "",
80
+ `--${boundary}`,
81
+ "Content-Type: text/plain; charset=UTF-8",
82
+ "Content-Transfer-Encoding: base64",
83
+ "",
84
+ base64Lines(reply.text),
85
+ `--${boundary}`,
86
+ "Content-Type: text/html; charset=UTF-8",
87
+ "Content-Transfer-Encoding: base64",
88
+ "",
89
+ base64Lines(reply.html),
90
+ `--${boundary}--`,
91
+ "",
92
+ ].join("\r\n");
93
+ }
94
+ /** Bytes as URL-safe base64 without padding, as the Gmail API takes a raw message. */
95
+ export function base64Url(text) {
96
+ return Buffer.from(text, "utf8").toString("base64url");
97
+ }
@@ -953,6 +953,8 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
953
953
  /**
954
954
  * The providers whose chats the built-in exact chat post delivers to, each through its declared
955
955
  * connection, and the attribution it adds. Absent, or without a provider, delivers nowhere.
956
+ * `email`, within version 15, is the mailbox reviewed replies to mail leave from; no chat post
957
+ * goes to it.
956
958
  */
957
959
  readonly chat: Schema.optionalKey<Schema.Struct<{
958
960
  readonly telegram: Schema.optionalKey<Schema.Struct<{
@@ -964,6 +966,9 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
964
966
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
965
967
  readonly connection: Schema.String;
966
968
  }>>;
969
+ readonly email: Schema.optionalKey<Schema.Struct<{
970
+ readonly connection: Schema.String;
971
+ }>>;
967
972
  readonly attribution: Schema.optionalKey<Schema.Struct<{
968
973
  readonly template: Schema.optionalKey<Schema.String>;
969
974
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -1206,6 +1211,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1206
1211
  readonly telegram?: {
1207
1212
  readonly connection: string;
1208
1213
  } | undefined;
1214
+ readonly email?: {
1215
+ readonly connection: string;
1216
+ } | undefined;
1209
1217
  readonly whatsapp?: {
1210
1218
  readonly connection: string;
1211
1219
  } | undefined;
@@ -1475,6 +1483,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1475
1483
  readonly telegram?: {
1476
1484
  readonly connection: string;
1477
1485
  } | undefined;
1486
+ readonly email?: {
1487
+ readonly connection: string;
1488
+ } | undefined;
1478
1489
  readonly whatsapp?: {
1479
1490
  readonly connection: string;
1480
1491
  } | undefined;
@@ -1744,6 +1755,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1744
1755
  readonly telegram?: {
1745
1756
  readonly connection: string;
1746
1757
  } | undefined;
1758
+ readonly email?: {
1759
+ readonly connection: string;
1760
+ } | undefined;
1747
1761
  readonly whatsapp?: {
1748
1762
  readonly connection: string;
1749
1763
  } | undefined;
@@ -2013,6 +2027,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2013
2027
  readonly telegram?: {
2014
2028
  readonly connection: string;
2015
2029
  } | undefined;
2030
+ readonly email?: {
2031
+ readonly connection: string;
2032
+ } | undefined;
2016
2033
  readonly whatsapp?: {
2017
2034
  readonly connection: string;
2018
2035
  } | undefined;
@@ -2397,6 +2414,8 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2397
2414
  /**
2398
2415
  * The providers whose chats the built-in exact chat post delivers to, each through its declared
2399
2416
  * connection, and the attribution it adds. Absent, or without a provider, delivers nowhere.
2417
+ * `email`, within version 15, is the mailbox reviewed replies to mail leave from; no chat post
2418
+ * goes to it.
2400
2419
  */
2401
2420
  readonly chat: Schema.optionalKey<Schema.Struct<{
2402
2421
  readonly telegram: Schema.optionalKey<Schema.Struct<{
@@ -2408,6 +2427,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2408
2427
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
2409
2428
  readonly connection: Schema.String;
2410
2429
  }>>;
2430
+ readonly email: Schema.optionalKey<Schema.Struct<{
2431
+ readonly connection: Schema.String;
2432
+ }>>;
2411
2433
  readonly attribution: Schema.optionalKey<Schema.Struct<{
2412
2434
  readonly template: Schema.optionalKey<Schema.String>;
2413
2435
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -2752,6 +2774,8 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2752
2774
  /**
2753
2775
  * The providers whose chats the built-in exact chat post delivers to, each through its declared
2754
2776
  * connection, and the attribution it adds. Absent, or without a provider, delivers nowhere.
2777
+ * `email`, within version 15, is the mailbox reviewed replies to mail leave from; no chat post
2778
+ * goes to it.
2755
2779
  */
2756
2780
  readonly chat: Schema.optionalKey<Schema.Struct<{
2757
2781
  readonly telegram: Schema.optionalKey<Schema.Struct<{
@@ -2763,6 +2787,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2763
2787
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
2764
2788
  readonly connection: Schema.String;
2765
2789
  }>>;
2790
+ readonly email: Schema.optionalKey<Schema.Struct<{
2791
+ readonly connection: Schema.String;
2792
+ }>>;
2766
2793
  readonly attribution: Schema.optionalKey<Schema.Struct<{
2767
2794
  readonly template: Schema.optionalKey<Schema.String>;
2768
2795
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -2997,6 +3024,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2997
3024
  readonly telegram?: {
2998
3025
  readonly connection: string;
2999
3026
  } | undefined;
3027
+ readonly email?: {
3028
+ readonly connection: string;
3029
+ } | undefined;
3000
3030
  readonly whatsapp?: {
3001
3031
  readonly connection: string;
3002
3032
  } | undefined;
@@ -3266,6 +3296,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3266
3296
  readonly telegram?: {
3267
3297
  readonly connection: string;
3268
3298
  } | undefined;
3299
+ readonly email?: {
3300
+ readonly connection: string;
3301
+ } | undefined;
3269
3302
  readonly whatsapp?: {
3270
3303
  readonly connection: string;
3271
3304
  } | undefined;
@@ -3541,6 +3574,9 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
3541
3574
  readonly telegram?: {
3542
3575
  readonly connection: string;
3543
3576
  } | undefined;
3577
+ readonly email?: {
3578
+ readonly connection: string;
3579
+ } | undefined;
3544
3580
  readonly whatsapp?: {
3545
3581
  readonly connection: string;
3546
3582
  } | undefined;
@@ -3810,6 +3846,9 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
3810
3846
  readonly telegram?: {
3811
3847
  readonly connection: string;
3812
3848
  } | undefined;
3849
+ readonly email?: {
3850
+ readonly connection: string;
3851
+ } | undefined;
3813
3852
  readonly whatsapp?: {
3814
3853
  readonly connection: string;
3815
3854
  } | undefined;
package/dist/manifest.js CHANGED
@@ -455,11 +455,14 @@ const OntologyManifestModel = Schema.Struct({
455
455
  /**
456
456
  * The providers whose chats the built-in exact chat post delivers to, each through its declared
457
457
  * connection, and the attribution it adds. Absent, or without a provider, delivers nowhere.
458
+ * `email`, within version 15, is the mailbox reviewed replies to mail leave from; no chat post
459
+ * goes to it.
458
460
  */
459
461
  chat: Schema.optionalKey(Schema.Struct({
460
462
  telegram: Schema.optionalKey(Schema.Struct({ connection: Schema.String })),
461
463
  slack: Schema.optionalKey(Schema.Struct({ connection: Schema.String })),
462
464
  whatsapp: Schema.optionalKey(Schema.Struct({ connection: Schema.String })),
465
+ email: Schema.optionalKey(Schema.Struct({ connection: Schema.String })),
463
466
  attribution: Schema.optionalKey(Schema.Struct({
464
467
  template: Schema.optionalKey(Schema.String),
465
468
  separator: Schema.optionalKey(Schema.String),
@@ -400,6 +400,9 @@ export declare const MigrationPlan: Schema.Struct<{
400
400
  readonly telegram?: {
401
401
  readonly connection: string;
402
402
  } | undefined;
403
+ readonly email?: {
404
+ readonly connection: string;
405
+ } | undefined;
403
406
  readonly whatsapp?: {
404
407
  readonly connection: string;
405
408
  } | undefined;
@@ -669,6 +672,9 @@ export declare const MigrationPlan: Schema.Struct<{
669
672
  readonly telegram?: {
670
673
  readonly connection: string;
671
674
  } | undefined;
675
+ readonly email?: {
676
+ readonly connection: string;
677
+ } | undefined;
672
678
  readonly whatsapp?: {
673
679
  readonly connection: string;
674
680
  } | undefined;
@@ -938,6 +944,9 @@ export declare const MigrationPlan: Schema.Struct<{
938
944
  readonly telegram?: {
939
945
  readonly connection: string;
940
946
  } | undefined;
947
+ readonly email?: {
948
+ readonly connection: string;
949
+ } | undefined;
941
950
  readonly whatsapp?: {
942
951
  readonly connection: string;
943
952
  } | undefined;
@@ -1207,6 +1216,9 @@ export declare const MigrationPlan: Schema.Struct<{
1207
1216
  readonly telegram?: {
1208
1217
  readonly connection: string;
1209
1218
  } | undefined;
1219
+ readonly email?: {
1220
+ readonly connection: string;
1221
+ } | undefined;
1210
1222
  readonly whatsapp?: {
1211
1223
  readonly connection: string;
1212
1224
  } | undefined;
@@ -1551,6 +1563,9 @@ export declare const MigrationPlan: Schema.Struct<{
1551
1563
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
1552
1564
  readonly connection: Schema.String;
1553
1565
  }>>;
1566
+ readonly email: Schema.optionalKey<Schema.Struct<{
1567
+ readonly connection: Schema.String;
1568
+ }>>;
1554
1569
  readonly attribution: Schema.optionalKey<Schema.Struct<{
1555
1570
  readonly template: Schema.optionalKey<Schema.String>;
1556
1571
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -1811,6 +1826,9 @@ export declare const MigrationPlan: Schema.Struct<{
1811
1826
  readonly whatsapp: Schema.optionalKey<Schema.Struct<{
1812
1827
  readonly connection: Schema.String;
1813
1828
  }>>;
1829
+ readonly email: Schema.optionalKey<Schema.Struct<{
1830
+ readonly connection: Schema.String;
1831
+ }>>;
1814
1832
  readonly attribution: Schema.optionalKey<Schema.Struct<{
1815
1833
  readonly template: Schema.optionalKey<Schema.String>;
1816
1834
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -2009,6 +2027,9 @@ export declare const MigrationPlan: Schema.Struct<{
2009
2027
  readonly telegram?: {
2010
2028
  readonly connection: string;
2011
2029
  } | undefined;
2030
+ readonly email?: {
2031
+ readonly connection: string;
2032
+ } | undefined;
2012
2033
  readonly whatsapp?: {
2013
2034
  readonly connection: string;
2014
2035
  } | undefined;
@@ -2278,6 +2299,9 @@ export declare const MigrationPlan: Schema.Struct<{
2278
2299
  readonly telegram?: {
2279
2300
  readonly connection: string;
2280
2301
  } | undefined;
2302
+ readonly email?: {
2303
+ readonly connection: string;
2304
+ } | undefined;
2281
2305
  readonly whatsapp?: {
2282
2306
  readonly connection: string;
2283
2307
  } | undefined;
@@ -1,5 +1,6 @@
1
1
  import { BaseBuilder } from "@workflow/builders";
2
2
  import type { Nitro } from "nitro/types";
3
+ import type { WorkflowStructures } from "./workflow-structure.js";
3
4
  /**
4
5
  * The build side of `ontologyWorkflows()` (see `./nitro.ts`), loaded only while Nitro builds.
5
6
  */
@@ -84,6 +85,19 @@ export declare class OntologyWorkflowBuilder extends BaseBuilder {
84
85
  get platformWorkflowFile(): string | undefined;
85
86
  build(): Promise<void>;
86
87
  }
88
+ /** The module the build writes with the workflows' structures, which the service registers. */
89
+ export declare const STRUCTURES_FILE = "structures.mjs";
90
+ /** The structures module: one default export, the structures by workflow id. */
91
+ export declare function structuresModuleSource(structures: WorkflowStructures): string;
92
+ /**
93
+ * The Nitro plugin that registers the workflows' structures with the service at startup, from the
94
+ * module the build wrote.
95
+ */
96
+ export declare function structuresPluginSource(input: {
97
+ readonly file: string;
98
+ /** The module that exports `registerWorkflowStructures`: the `server` entry. */
99
+ readonly server?: string;
100
+ }): string;
87
101
  /** Where the generated handler takes its runtime from; tests point them elsewhere. */
88
102
  export interface CallbackImports {
89
103
  /** The module that exports `serveWorkflowCallback`. */
@@ -1,5 +1,5 @@
1
1
  import { mkdir, readFile, writeFile } from "node:fs/promises";
2
- import { join } from "node:path";
2
+ import { join, resolve } from "node:path";
3
3
  import { pathToFileURL } from "node:url";
4
4
  import { BaseBuilder, createBaseBuilderConfig } from "@workflow/builders";
5
5
  import { workflowTransformPlugin } from "@workflow/rollup";
@@ -123,12 +123,67 @@ export class OntologyWorkflowBuilder extends BaseBuilder {
123
123
  "the ontology's queue namespace cannot be set.");
124
124
  }
125
125
  await writeFile(flowFile, flow.replace(ENTRYPOINT_CALL, `workflowEntrypoint(workflowCode, { namespace: ${JSON.stringify(this.#namespace)},`));
126
- await this.createManifest({
126
+ const manifest = await this.createManifest({
127
127
  workflowBundlePath: flowFile,
128
128
  manifestDir: this.#outDir,
129
129
  manifest: built.manifest,
130
130
  });
131
+ await writeFile(join(this.#outDir, STRUCTURES_FILE), structuresModuleSource(await this.#structures(manifest === undefined ? undefined : JSON.parse(manifest))));
131
132
  }
133
+ /**
134
+ * What each workspace workflow does, read from its source for the console's map. A reading that
135
+ * fails leaves the workflows without a map and never fails the build.
136
+ */
137
+ async #structures(manifest) {
138
+ if (manifest === undefined) {
139
+ return {};
140
+ }
141
+ try {
142
+ const { readWorkflowStructures } = await import("./workflow-structure-extract.js");
143
+ const imported = (await import("typescript"));
144
+ const platform = this.#platform === undefined ? undefined : this.#platform.dir;
145
+ return readWorkflowStructures({
146
+ ts: imported.default ?? imported,
147
+ root: this.config.workingDir,
148
+ manifest,
149
+ skip: (file) => platform !== undefined && resolve(this.config.workingDir, file).startsWith(platform),
150
+ onError: (workflowId, error) => {
151
+ console.warn(`The ontology could not read the structure of ${workflowId}:`, error);
152
+ },
153
+ });
154
+ }
155
+ catch (error) {
156
+ console.warn("The ontology could not read its workflows' structures:", error);
157
+ return {};
158
+ }
159
+ }
160
+ }
161
+ /** The module the build writes with the workflows' structures, which the service registers. */
162
+ export const STRUCTURES_FILE = "structures.mjs";
163
+ /** The structures module: one default export, the structures by workflow id. */
164
+ export function structuresModuleSource(structures) {
165
+ return [
166
+ "// Written by @segmentstream/ontology's ontologyWorkflows() on every build: what each",
167
+ "// workflow does, read from its code, for the console's map.",
168
+ `export default ${JSON.stringify(structures)};`,
169
+ "",
170
+ ].join("\n");
171
+ }
172
+ /**
173
+ * The Nitro plugin that registers the workflows' structures with the service at startup, from the
174
+ * module the build wrote.
175
+ */
176
+ export function structuresPluginSource(input) {
177
+ const server = input.server ?? "@segmentstream/ontology/server";
178
+ return [
179
+ `import { registerWorkflowStructures } from ${JSON.stringify(server)};`,
180
+ `import structures from ${JSON.stringify(pathToFileURL(input.file).href)};`,
181
+ "",
182
+ "export default function registerOntologyWorkflowStructures() {",
183
+ " registerWorkflowStructures(structures);",
184
+ "}",
185
+ "",
186
+ ].join("\n");
132
187
  }
133
188
  /** See `addNodeRequireBanner` in `workflow/nitro`: undici loads `node:http2` with `require`. */
134
189
  const REQUIRE_BANNER = "import { createRequire as __wkfCreateRequire } from 'node:module'; " +
@@ -256,12 +311,17 @@ export async function setupOntologyWorkflows(nitro, settings) {
256
311
  }
257
312
  const id = "#segmentstream-ontology/workflow-flow";
258
313
  const platformPlugin = "#segmentstream-ontology/platform-workflows";
314
+ const structuresPlugin = "#segmentstream-ontology/workflow-structures";
259
315
  // At startup, before any request: the service refuses an action whose triggers may fire until
260
316
  // the platform's recovery workflow is registered.
261
317
  (nitro.options.plugins ??= []).push(platformPlugin);
262
318
  nitro.options.virtual[platformPlugin] = platformPluginSource({
263
319
  file: join(platformDir, PLATFORM_WORKFLOW_FILE),
264
320
  });
321
+ nitro.options.plugins.push(structuresPlugin);
322
+ nitro.options.virtual[structuresPlugin] = structuresPluginSource({
323
+ file: join(outDir, STRUCTURES_FILE),
324
+ });
265
325
  nitro.options.handlers.push({ route: settings.route, handler: id, lazy: true });
266
326
  nitro.options.virtual[id] = callbackHandlerSource({
267
327
  file: join(outDir, "workflows.mjs"),
@@ -21,6 +21,12 @@ const PAIRINGS = `"${AGENT_PAIRINGS_TABLE}"`;
21
21
  /** The legacy channel accounts, written beside `user_identity` for earlier SDKs. */
22
22
  const LEGACY_IDENTITIES = `"${AGENT_IDENTITIES_TABLE}"`;
23
23
  const USERS = `"${USER_TABLE}"`;
24
+ /**
25
+ * The lifecycle row `c` is of someone who admitted themselves: anyone sign-up created, whatever
26
+ * the channel, or a channel account an open channel created. Their first contact gets the notice.
27
+ */
28
+ const SELF_ADMITTED = `COALESCE(to_jsonb(c) ->> 'signed_up', 'false') = 'true' ` +
29
+ `OR c."created_via" NOT IN ('invite', 'email')`;
24
30
  /** A timestamp as epoch milliseconds, which every driver returns as a plain number. */
25
31
  function epochMs(column) {
26
32
  return `(extract(epoch from ${column}) * 1000)::double precision`;
@@ -219,7 +225,7 @@ export function sqlAgentStore(ontology, sql) {
219
225
  `SELECT "i"."id", now(), $3, $4 FROM ${CHANNEL_IDENTITIES_FROM} ` +
220
226
  `WHERE "i"."provider" = $1 AND "i"."subject" = $2 AND ${LIVE_CHANNEL_IDENTITY} ` +
221
227
  `AND EXISTS (SELECT 1 FROM "${CHANNEL_USERS_TABLE}" c WHERE c."user_id" = "i"."user_id"
222
- AND c."created_via" NOT IN ('invite', 'email')) ` +
228
+ AND (${SELF_ADMITTED})) ` +
223
229
  `ON CONFLICT ("identity_id") DO UPDATE SET "noticed_at" = now(), ` +
224
230
  `"notice_sha256" = EXCLUDED."notice_sha256", ` +
225
231
  `"notice_version" = EXCLUDED."notice_version" ` +
@@ -229,7 +235,7 @@ export function sqlAgentStore(ontology, sql) {
229
235
  yield* rows(`UPDATE ${LEGACY_IDENTITIES} SET "noticed_at" = now(), "notice_sha256" = $3, "notice_version" = $4 ` +
230
236
  `WHERE "provider" = $1 AND "external_id" = $2 AND "revoked_at" IS NULL ` +
231
237
  `AND EXISTS (SELECT 1 FROM "${CHANNEL_USERS_TABLE}" c WHERE c."user_id" = ${LEGACY_IDENTITIES}."user_id"
232
- AND c."created_via" NOT IN ('invite', 'email')) AND ("noticed_at" IS NULL
238
+ AND (${SELF_ADMITTED})) AND ("noticed_at" IS NULL
233
239
  OR "notice_version" IS DISTINCT FROM $4 OR "notice_sha256" IS DISTINCT FROM $3)`, [provider, externalId, sha256, version ?? null]);
234
240
  return noticed.length > 0;
235
241
  }))
@@ -15,12 +15,14 @@ export const ATTACH_IDENTITY_ACTION = `${UserIdentity.name}.attach`;
15
15
  export const REVOKE_IDENTITY_ACTION = `${UserIdentity.name}.revoke`;
16
16
  /**
17
17
  * What an account id looks like on each provider: Telegram's numeric user id, WhatsApp's phone
18
- * number id and Slack's member id. A typo is refused before anything is locked or written.
18
+ * number id, Slack's member id and an email address in lower case, as the agent's mail channel
19
+ * names its senders. A typo is refused before anything is locked or written.
19
20
  */
20
21
  const SUBJECT_PATTERNS = {
21
22
  telegram: /^[1-9][0-9]{0,19}$/,
22
23
  whatsapp: /^[1-9][0-9]{5,19}$/,
23
24
  slack: /^[A-Z0-9]{2,32}$/,
25
+ email: /^(?=.{3,254}$)[^\sA-Z@]+@[^\sA-Z@.]+(?:\.[^\sA-Z@.]+)+$/,
24
26
  };
25
27
  /** At most this many characters of a username or a display name are kept. */
26
28
  const MAX_DESCRIPTION_LENGTH = 256;
@@ -59,7 +61,9 @@ export function attachChannelIdentity(ontology, sql, scope, input) {
59
61
  }
60
62
  if (!SUBJECT_PATTERNS[provider].test(subject)) {
61
63
  return yield* new ActionRejected({
62
- message: `${subject} is not a ${provider} account id.`,
64
+ message: provider === "email"
65
+ ? `${subject} is not an email address in lower case.`
66
+ : `${subject} is not a ${provider} account id.`,
63
67
  });
64
68
  }
65
69
  if (!isRecordId(userId)) {
@@ -3,4 +3,4 @@ import type { SqlClient } from "effect/unstable/sql";
3
3
  import type { Ontology } from "../ontology.js";
4
4
  import type { AgentResolution, AgentStore, ResolveIdentityInput } from "../service/runtime-contract.js";
5
5
  /** Account admission shares pairing's lock and creates User plus identity in one transaction. */
6
- export declare function resolveAgentIdentity(ontology: Ontology, sql: SqlClient.SqlClient, store: AgentStore, input: ResolveIdentityInput, context?: "agent" | "channel_app"): Effect.Effect<AgentResolution>;
6
+ export declare function resolveAgentIdentity(ontology: Ontology, sql: SqlClient.SqlClient, store: AgentStore, requested: ResolveIdentityInput, context?: "agent" | "channel_app"): Effect.Effect<AgentResolution>;