@segmentstream/ontology 0.105.0 → 0.106.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,30 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.106.1
4
+
5
+ Workflow maps read more workflows in full. A promise's `.catch(…)` or `.finally(…)` now reads as a
6
+ `try` around the promise's steps, and `.then(…)`'s callback as what runs after them, instead of an
7
+ unread call; a handler's returned call is waited for like any other. A `.then(…)` with both handlers
8
+ keeps the success handler inside the `try` and marks the map as not read in full. A method of a value in a `return`, such as `return lines.join("\n")` in a helper, is
9
+ read as a value rather than an awaited call the map cannot follow; other returned method calls,
10
+ which may return a promise, and a promise handler reached through a value (`handlers.retry`) stay
11
+ unread. A helper's early `return`, a
12
+ `break` or a `continue` marks the map as not read in full only when it skips a step, wait or
13
+ agent task (a `break` also skips a loop's incrementor and `do…while` condition, a `continue` does
14
+ not), so helpers that format text or check a value no longer do.
15
+
16
+ ## 0.106.0
17
+
18
+ The ontology admits people who write to the agent's mailbox. An `email` account is the sender's
19
+ address, admitted only when the agent reports that the receiving server proved it (DMARC with
20
+ alignment): `signUp` with `email` then also signs up a stranger who writes, with the same roles as
21
+ a code sign-in, and sets the new user's `email`. The address of a user sign-up created is linked
22
+ to them; a member's address is attached with `user_identity.attach`, which now takes `email`.
23
+ `chat.email` names the mailbox a reply held for review leaves from: the reply goes in the
24
+ person's thread, threaded under its last message, never as a chat post. Attachments may come from
25
+ `email`. The first-contact notice is recorded for everyone sign-up created, whatever the channel.
26
+ `@segmentstream/ontology/email` renders a reply's Markdown as email HTML and builds the reply.
27
+
3
28
  ## 0.105.0
4
29
 
5
30
  The console can draw each workflow as a map. `ontologyWorkflows()` now reads every workflow's
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;
@@ -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>;
@@ -3,11 +3,13 @@ import { Effect, Option, Schema } from "effect";
3
3
  import { isSqlError } from "effect/unstable/sql/SqlError";
4
4
  import { Conflict } from "../errors.js";
5
5
  import { channelPolicyOf, signUpRolesOf } from "../manifest.js";
6
- import { AGENT_IDENTITIES_TABLE, CHANNEL_USERS_TABLE } from "../migrate/storage.js";
6
+ import { AGENT_IDENTITIES_TABLE, CHANNEL_USERS_TABLE, USER_TABLE } from "../migrate/storage.js";
7
+ import { EMAIL_PATTERN } from "../property.js";
7
8
  import { countAgentAttempt, effectiveChannelLimits } from "./agent-counters.js";
8
9
  import { runNewUserHook } from "./new-user-hook.js";
9
10
  import { makeOntologyRuntime, makePrincipalUserWriter } from "./sql-runtime.js";
10
11
  import { makeIdentityWriter, USER_IDENTITY_TABLE } from "./user-identities.js";
12
+ import { EMAIL_PROVIDER } from "./user-identity-sql.js";
11
13
  class RegistrationCapped extends Schema.TaggedError()("RegistrationCapped", {
12
14
  limit: Schema.Int,
13
15
  }) {
@@ -21,7 +23,16 @@ function uniqueFailure(error) {
21
23
  return sqlError.reason._tag === "UniqueViolation" || cause?.code === "23505";
22
24
  }
23
25
  /** Account admission shares pairing's lock and creates User plus identity in one transaction. */
24
- export function resolveAgentIdentity(ontology, sql, store, input, context = "agent") {
26
+ export function resolveAgentIdentity(ontology, sql, store, requested, context = "agent") {
27
+ const mail = requested.provider === EMAIL_PROVIDER;
28
+ // An address is one account whatever its case. Mail the receiving server could not prove may
29
+ // come from anyone: it admits nobody, and the person's existing account acts on none of it.
30
+ const input = mail
31
+ ? { ...requested, externalId: requested.externalId.trim().toLowerCase() }
32
+ : requested;
33
+ if (mail && (requested.addressVerified !== true || !EMAIL_PATTERN.test(input.externalId))) {
34
+ return Effect.succeed({ status: "pairing_required" });
35
+ }
25
36
  const contact = input.turn || context === "channel_app";
26
37
  // A channel `signUp` opens grants these roles; one an open `signIn.channels` opens grants member.
27
38
  const signUpRoles = signUpRolesOf(ontology.manifest, input.provider);
@@ -35,6 +46,41 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
35
46
  if (identity !== undefined && identity.revokedAt !== null) {
36
47
  return { status: "refused", reason: "blocked" };
37
48
  }
49
+ if (identity === undefined && mail && contact && input.chat === "private") {
50
+ // The address of a user sign-up created is theirs: a code in the app or proved mail shows
51
+ // the same thing. A member's address is not linked: mail proves its domain, not the
52
+ // mailbox, so the member attaches it themselves.
53
+ const [owner] = yield* sql.unsafe(`SELECT "u"."id"::text AS "id",
54
+ COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up",
55
+ EXISTS (SELECT 1 FROM "${USER_IDENTITY_TABLE}" AS "i" WHERE "i"."user_id" = "u"."id"
56
+ AND "i"."provider" = $2 AND "i"."revoked_at" IS NULL) AS "held"
57
+ FROM "${USER_TABLE}" AS "u"
58
+ LEFT JOIN "${CHANNEL_USERS_TABLE}" AS "c" ON "c"."user_id" = "u"."id"
59
+ WHERE "u"."email" = $1 AND "u"."kind" = 'member' LIMIT 1`, [input.externalId, EMAIL_PROVIDER]);
60
+ if (owner !== undefined) {
61
+ if (!owner.signed_up || owner.held) {
62
+ return { status: "pairing_required" };
63
+ }
64
+ const identityId = randomUUID();
65
+ yield* makeIdentityWriter(ontology, sql, {
66
+ action: `${USER_IDENTITY_TABLE}.provision`,
67
+ actionId: randomUUID(),
68
+ }).create({
69
+ id: identityId,
70
+ provider: input.provider,
71
+ issuer: null,
72
+ subject: input.externalId,
73
+ userId: owner.id,
74
+ origin: "channel",
75
+ display: input.display?.trim() || null,
76
+ username: null,
77
+ });
78
+ yield* sql.unsafe(`INSERT INTO "${AGENT_IDENTITIES_TABLE}"
79
+ ("id", "provider", "external_id", "user_id", "display", "origin")
80
+ VALUES ($1::uuid, $2, $3, $4::uuid, $5, 'provisioned')`, [identityId, input.provider, input.externalId, owner.id, input.display?.trim() || null]);
81
+ identity = yield* store.findIdentity(input);
82
+ }
83
+ }
38
84
  if (identity === undefined) {
39
85
  if (!contact ||
40
86
  input.chat !== "private" ||
@@ -63,8 +109,14 @@ export function resolveAgentIdentity(ontology, sql, store, input, context = "age
63
109
  });
64
110
  const user = yield* writer.create({
65
111
  kind: "member",
66
- name: display || (username ? `@${username}` : `${providerName} ${input.externalId}`),
67
- email: null,
112
+ name: display ||
113
+ (username
114
+ ? `@${username}`
115
+ : mail
116
+ ? input.externalId
117
+ : `${providerName} ${input.externalId}`),
118
+ // Proved mail proves the address: a later code sign-in with it is the same person.
119
+ email: mail ? input.externalId : null,
68
120
  identity_provider: null,
69
121
  identity_subject: null,
70
122
  });
@@ -11,6 +11,11 @@ export declare const USER_IDENTITY_TABLE = "user_identity";
11
11
  export declare const USER_IDENTITY_ENTITY_ID = "ent_user_identity";
12
12
  /** The provider of email sign-in: the workspace's Neon Auth. */
13
13
  export declare const NEON_AUTH_PROVIDER = "neon-auth";
14
+ /**
15
+ * The provider of an address that writes to the agent's mailbox. Its subject is the address in
16
+ * lower case; the agent's mail channel admits it only when the receiving server proved it.
17
+ */
18
+ export declare const EMAIL_PROVIDER = "email";
14
19
  /** The provider of SegmentStream (OIDC) sign-in; the issuer tells the issuing deployment apart. */
15
20
  export declare const OIDC_PROVIDER = "oidc";
16
21
  /** The legacy `user.identity_provider` of an OIDC binding: `oidc:<issuer>`. */
@@ -11,6 +11,11 @@ export const USER_IDENTITY_TABLE = "user_identity";
11
11
  export const USER_IDENTITY_ENTITY_ID = "ent_user_identity";
12
12
  /** The provider of email sign-in: the workspace's Neon Auth. */
13
13
  export const NEON_AUTH_PROVIDER = "neon-auth";
14
+ /**
15
+ * The provider of an address that writes to the agent's mailbox. Its subject is the address in
16
+ * lower case; the agent's mail channel admits it only when the receiving server proved it.
17
+ */
18
+ export const EMAIL_PROVIDER = "email";
14
19
  /** The provider of SegmentStream (OIDC) sign-in; the issuer tells the issuing deployment apart. */
15
20
  export const OIDC_PROVIDER = "oidc";
16
21
  /** The legacy `user.identity_provider` of an OIDC binding: `oidc:<issuer>`. */
@@ -31,6 +31,7 @@ export declare const ResolveIdentityRequest: Schema.Struct<{
31
31
  readonly username: Schema.optionalKey<Schema.String>;
32
32
  readonly notice_version: Schema.optionalKey<Schema.String>;
33
33
  readonly notice_sha256: Schema.optionalKey<Schema.String>;
34
+ readonly address_verified: Schema.optionalKey<Schema.Boolean>;
34
35
  readonly limits: Schema.optionalKey<Schema.Struct<{
35
36
  readonly perSender: Schema.optionalKey<Schema.Struct<{
36
37
  readonly turnsPerMinute: Schema.optionalKey<Schema.Int>;