@segmentstream/ontology 0.110.0 → 0.113.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 (56) hide show
  1. package/CHANGELOG.md +54 -0
  2. package/README.md +15 -3
  3. package/dist/agent-review.d.ts +2 -0
  4. package/dist/agent-review.js +11 -1
  5. package/dist/analyze.d.ts +38 -34
  6. package/dist/analyze.js +109 -41
  7. package/dist/chat-channel.d.ts +47 -0
  8. package/dist/chat-channel.js +69 -0
  9. package/dist/email-html.d.ts +23 -0
  10. package/dist/email-html.js +249 -0
  11. package/dist/emails.d.ts +38 -6
  12. package/dist/emails.js +71 -2
  13. package/dist/index.d.ts +6 -2
  14. package/dist/index.js +3 -0
  15. package/dist/manifest.d.ts +282 -50
  16. package/dist/manifest.js +41 -6
  17. package/dist/migrate/model.d.ts +126 -18
  18. package/dist/runtime/agents.js +3 -0
  19. package/dist/runtime/resolve-agent-identity.js +4 -1
  20. package/dist/runtime-source.d.ts +4 -0
  21. package/dist/runtime-source.js +5 -0
  22. package/dist/runtime.d.ts +4 -1
  23. package/dist/service/agent/protocol.d.ts +5 -1
  24. package/dist/service/agent/protocol.js +12 -3
  25. package/dist/service/agent/server.js +17 -0
  26. package/dist/service/authentication.d.ts +5 -3
  27. package/dist/service/authentication.js +20 -5
  28. package/dist/service/chat/delivery.d.ts +10 -1
  29. package/dist/service/chat/delivery.js +30 -8
  30. package/dist/service/chat/envelope.d.ts +8 -2
  31. package/dist/service/chat/providers/custom.d.ts +13 -0
  32. package/dist/service/chat/providers/custom.js +103 -0
  33. package/dist/service/chat/providers/index.d.ts +20 -9
  34. package/dist/service/chat/providers/index.js +41 -12
  35. package/dist/service/chat/providers/provider.d.ts +19 -0
  36. package/dist/service/chat/reads.d.ts +6 -3
  37. package/dist/service/chat/reads.js +26 -14
  38. package/dist/service/chat/resolve.d.ts +7 -2
  39. package/dist/service/chat/resolve.js +11 -3
  40. package/dist/service/chat/review-delivery.d.ts +5 -2
  41. package/dist/service/chat/review-delivery.js +23 -9
  42. package/dist/service/chat/routes.js +2 -1
  43. package/dist/service/chat/schemas.d.ts +2 -0
  44. package/dist/service/chat/schemas.js +8 -1
  45. package/dist/service/config.d.ts +6 -2
  46. package/dist/service/mcp/server.js +2 -1
  47. package/dist/service/runtime-contract.d.ts +9 -0
  48. package/dist/service/schemas.d.ts +34 -4
  49. package/dist/service/service.js +6 -1
  50. package/dist/sign-in.d.ts +22 -1
  51. package/dist/sign-in.js +3 -1
  52. package/dist/storage/tables.d.ts +4 -3
  53. package/dist/storage/tables.js +11 -3
  54. package/dist/workspace-channel.d.ts +54 -0
  55. package/dist/workspace-channel.js +36 -0
  56. package/package.json +5 -1
package/CHANGELOG.md CHANGED
@@ -1,5 +1,59 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.113.0
4
+
5
+ A workspace can write every email its people receive, whole. An email in `emails` may be a
6
+ document of its own, `{ subject, html, text, replyTo? }`, instead of fields the platform lays out:
7
+ the platform then only fills its placeholders, escaped in the HTML, and sends it. Its HTML links
8
+ to `{{link}}`, the sign-in link, now a built-in value of every email; it may not run code or post
9
+ forms, and it links only to `https:`, `mailto:` and `tel:` addresses, anchors, or the app's own
10
+ `{{link}}`, `{{app.url}}` and `{{app.mcpUrl}}`. Inside its tags only those three and
11
+ `{{workspace.name}}` may stand; every other value goes in text, so no value an action passes
12
+ becomes an address or an attribute. `check` reports `invalid-email` otherwise.
13
+
14
+ `signIn.linkEmail` and `signIn.codeEmail` name the emails the platform sends instead of its own
15
+ sign-in link and sign-in code, as `signIn.invitationEmail` does for the invitation. The code email
16
+ shows `{{code}}`; its button opens the app's sign-in page, with the code filled in when `codeLink`
17
+ is on. The starter's `ontology/emails.ts` writes all three. Older platform deployments ignore both
18
+ names and documents and send their own emails.
19
+
20
+ ## 0.112.0
21
+
22
+ `chat` declares a channel the workspace defines in its own code by its name with
23
+ `kind: "custom"` and no connection, such as `chat: { zernio: { kind: "custom" } }`. The ontology
24
+ sends nothing through it: an approved reply on it, and a chat post to one of its chats, go to the
25
+ app's agent, at `/eve/segmentstream/v1/custom/<name>/send` on the production origin, with the
26
+ service's Vercel OIDC token, as `agentTask` hands the agent its tasks; the agent's refusal sent
27
+ nothing, and anything else may have. A chat post names only the person, whose chat the agent
28
+ finds. `chat_list` lists its members' private chats with kind
29
+ `custom`, and `@segmentstream/ontology/workspace-channel` holds the route and the text both sides
30
+ compute.
31
+
32
+ Its people's accounts are its own, `channel:<name>`, so it can claim no other channel's account:
33
+ `signUp.channels` may list `channel:<name>` for a channel `chat` declares, a user it creates is
34
+ named after the channel, and history keeps a chat on it only for its own people. Attachments from
35
+ it have the source `channel`; the database's check widens on the next migration.
36
+
37
+ ## 0.111.0
38
+
39
+ `chat` names the agent's channels as its `channels` does: the channel named after its kind
40
+ (`telegram`, `slack`, `whatsapp`, `email`) as before, and any other with its `kind`, such as
41
+ `chat: { sales_whatsapp: { kind: "whatsapp", connection: waSales } }`. Each channel's connection
42
+ is granted to `agent_review.approve`, and those of kinds that take posts to
43
+ `agent_chat.post_message`. A chat of another channel is keyed by the channel's name: its
44
+ `agent_chat` record's `provider`, a member's private chat `<channel>:private:<member>`, and its
45
+ archive and attachments. A member's account reaches them on every channel of its kind.
46
+
47
+ `agent_review` records `channel`, the channel the chat is on, and approval sends the reply
48
+ through that channel's connection, refusing a channel `chat` does not declare or of another kind.
49
+ A review held before has no `channel` and leaves through the channel named after its kind. A
50
+ runtime source may name its `channel`.
51
+
52
+ `chat_list` gives each destination's `kind` beside its `provider`, the channel's name, so an agent
53
+ renders a post to `sales_whatsapp` as WhatsApp does. History keeps the chat an action came from by
54
+ its channel's name, and keeps a messenger's chat only on a channel of the kind the member wrote
55
+ from: the channel named after the kind, or one of another name `chat` declares with that kind.
56
+
3
57
  ## 0.110.0
4
58
 
5
59
  History keeps the chat an action came from. The app's agent names the chat it acts in and its
package/README.md CHANGED
@@ -509,8 +509,11 @@ export default defineOntology({
509
509
  built-in `{{member.name}}`, `{{member.firstName}}`, `{{workspace.name}}`, `{{app.url}}` and
510
510
  `{{app.mcpUrl}}`. `sections` are boxes below the button, each
511
511
  `{ title, text?, copy?: { label?, value }, items?: [{ label, text?, code? }], note? }`.
512
- `signIn.invitationEmail: "memberInvitation"` names the one the platform sends instead of its
513
- own invitation; it may use only built-in values. A handler sends
512
+ An email may instead be a whole document, `{ subject, html, text, replyTo? }`, whose HTML
513
+ links to `{{link}}`; the platform then only fills its values, escaped in the HTML.
514
+ `signIn.invitationEmail`, `linkEmail` and `codeEmail` name the ones the platform sends instead
515
+ of its own invitation, sign-in link and sign-in code; they may use only built-in values, and
516
+ the code email shows `{{code}}`. A handler sends
514
517
  one with `User.sendSignInLink(user, { template: "agreementReview", returnTo: "/shared/1", values })`:
515
518
  after the commit, in production, the platform emails the member a link that signs them in and
516
519
  opens `returnTo`, laid out in its design, from the workspace's name, with replies to `replyTo`
@@ -1552,8 +1555,17 @@ timeout, a 5xx or an answer naming no message is `uncertain`. The receipt's `mes
1552
1555
  `wamid…` Meta accepted; it has no URL, and a failure Meta reports later in delivery statuses does
1553
1556
  not change it.
1554
1557
 
1558
+ `chat` names the agent's channels as its `channels` does. A channel not named after its kind,
1559
+ such as a second number, says its kind: `chat: { sales_whatsapp: { kind: "whatsapp", connection:
1560
+ waSales } }`. Its chats are keyed by its name (`sales_whatsapp:private:<member UUID>`, and the
1561
+ `provider` of its `agent_chat` records), and posts and reviewed replies there leave through its
1562
+ connection. A member's account reaches them on every channel of its kind. A channel the workspace
1563
+ defines in its own code is `chat: { zernio: { kind: "custom" } }`, with no connection: its posts
1564
+ and reviewed replies go to the app's agent, which sends them with the channel's code, and its
1565
+ people's accounts are its own, `channel:zernio`, which `signUp.channels` may list.
1566
+
1555
1567
  `chat_list({ query?, chat?, after?, limit? })` returns eligible routing metadata and server-derived
1556
- attribution. `query` filters titles by a case-insensitive literal substring before pagination.
1568
+ attribution: each item's `provider` is the channel the chat is on, by name, and `kind` its kind. `query` filters titles by a case-insensitive literal substring before pagination.
1557
1569
  `chat` selects an exact ID/title. Choose an ID or exact title; ambiguous titles return candidates and never guess.
1558
1570
  Paired private chats have stable handles `telegram:private:<member UUID>`, and
1559
1571
  `slack:private:<member UUID>` or `whatsapp:private:<member UUID>` when that provider is declared.
@@ -36,6 +36,7 @@ export declare const AGENT_REVIEW_TEXT_LIMIT = 20000;
36
36
  export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
37
37
  readonly key: import("./property.js").Property<string, false, true>;
38
38
  readonly provider: import("./property.js").Property<string, false, false>;
39
+ readonly channel: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
39
40
  readonly chatId: import("./property.js").Property<string, false, false>;
40
41
  readonly recipient: import("./property.js").Property<string, false, false>;
41
42
  readonly chatKind: import("./property.js").Property<"private" | "group", false, false>;
@@ -76,6 +77,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
76
77
  readonly updatedBy: string | null;
77
78
  readonly key: string;
78
79
  readonly provider: string;
80
+ readonly channel: string | null;
79
81
  readonly chatId: string;
80
82
  readonly recipient: string;
81
83
  readonly chatKind: "private" | "group";
@@ -49,7 +49,17 @@ export const AgentReview = entity("agent_review", {
49
49
  unique: true,
50
50
  description: "The agent's key for the reply, so a repeated report holds it once.",
51
51
  }),
52
- provider: p.text({ managed: true, description: "The channel, for example telegram." }),
52
+ provider: p.text({
53
+ managed: true,
54
+ description: "The kind of channel the chat is on, for example telegram.",
55
+ }),
56
+ channel: p.text({
57
+ optional: true,
58
+ managed: true,
59
+ description: "The agent's channel the chat is on, by its name, such as telegram or sales_whatsapp: " +
60
+ "approval sends the reply through that channel's connection. Empty on a reply held " +
61
+ "before channels had names, which is on the channel named after its kind.",
62
+ }),
53
63
  chatId: p.text({ managed: true, description: "The chat's id at the provider." }),
54
64
  recipient: p.text({
55
65
  managed: true,
package/dist/analyze.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import type { ChatAttributionSettings } from "./chat.js";
2
+ import { type ChatKind } from "./chat-channel.js";
3
+ import type { ChatManifestInput } from "./manifest.js";
2
4
  import { Schema } from "effect";
3
5
  import { type Action, type ActionHints } from "./action.js";
4
6
  import { type AnyConnectionHandle } from "./connection.js";
@@ -90,26 +92,15 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
90
92
  */
91
93
  readonly toolsets?: ReadonlyArray<Toolset>;
92
94
  /**
93
- * The providers the built-in exact chat post delivers to, each through its connection, which
94
- * must be listed in `connections`. Only declared providers are destinations. A reply the agent
95
- * held for review is sent through the same connection. `email` names the mailbox the agent's
96
- * mail channel reads: only reviewed replies leave through it, never a chat post.
95
+ * The agent's channels the built-in exact chat post delivers to, by the names the agent's
96
+ * `channels` give them, each through its connection, which must be listed in `connections`. Only
97
+ * declared channels are destinations. A reply the agent held for review is sent through the
98
+ * connection of the channel its chat is on. A channel named after its kind (`telegram`, `slack`,
99
+ * `whatsapp`, `email`) is that kind; any other, such as `sales_whatsapp`, says its `kind`. An
100
+ * `email` channel names the mailbox the agent's mail channel reads: only reviewed replies leave
101
+ * through it, never a chat post.
97
102
  */
98
- readonly chat?: {
99
- readonly telegram?: {
100
- readonly connection: AnyConnectionHandle;
101
- };
102
- readonly slack?: {
103
- readonly connection: AnyConnectionHandle;
104
- };
105
- readonly whatsapp?: {
106
- readonly connection: AnyConnectionHandle;
107
- };
108
- readonly email?: {
109
- readonly connection: AnyConnectionHandle;
110
- };
111
- readonly attribution?: ChatAttributionSettings;
112
- };
103
+ readonly chat?: ChatConfig;
113
104
  /**
114
105
  * Metrics of the model, by camelCase name: each combines metrics of entities, read with
115
106
  * `m.ref("entity.metric")`, or other model metrics, read with `m.ref("name")`, through
@@ -218,21 +209,7 @@ export interface ResolvedEntity {
218
209
  }
219
210
  export interface Analysis {
220
211
  readonly feedback: ResolvedFeedback;
221
- readonly chat?: {
222
- readonly telegram?: {
223
- readonly connection: string;
224
- };
225
- readonly slack?: {
226
- readonly connection: string;
227
- };
228
- readonly whatsapp?: {
229
- readonly connection: string;
230
- };
231
- readonly email?: {
232
- readonly connection: string;
233
- };
234
- readonly attribution?: ChatAttributionSettings;
235
- };
212
+ readonly chat?: ChatManifestInput;
236
213
  readonly entities: ReadonlyArray<ResolvedEntity>;
237
214
  /** The workspace-owned `member` role and declared roles, then the implicit reporter when enabled. */
238
215
  readonly roles: ReadonlyArray<Role>;
@@ -250,6 +227,33 @@ export interface Analysis {
250
227
  readonly toolsets: ReadonlyArray<ResolvedToolset>;
251
228
  readonly diagnostics: ReadonlyArray<Diagnostic>;
252
229
  }
230
+ /**
231
+ * One channel of `chat`, by name: the channel named after its kind, or one that says its kind. A
232
+ * channel the workspace defines in its own code says `kind: "custom"` and takes no connection: the
233
+ * agent sends through it, with the connection `agent/segmentstream.json` gives it.
234
+ */
235
+ export interface ChatChannelConfig {
236
+ readonly kind?: ChatKind;
237
+ readonly connection?: AnyConnectionHandle;
238
+ }
239
+ /** `chat` of {@link OntologyConfig}: the agent's channels by name, and the post attribution. */
240
+ export interface ChatConfig {
241
+ readonly telegram?: {
242
+ readonly connection: AnyConnectionHandle;
243
+ };
244
+ readonly slack?: {
245
+ readonly connection: AnyConnectionHandle;
246
+ };
247
+ readonly whatsapp?: {
248
+ readonly connection: AnyConnectionHandle;
249
+ };
250
+ readonly email?: {
251
+ readonly connection: AnyConnectionHandle;
252
+ };
253
+ readonly attribution?: ChatAttributionSettings;
254
+ /** A channel of another name, such as `sales_whatsapp`, with its `kind`. */
255
+ readonly [name: string]: ChatChannelConfig | ChatAttributionSettings | undefined;
256
+ }
253
257
  /**
254
258
  * Resolves an ontology definition and checks it. It never throws: every problem, including a thunk
255
259
  * that throws, becomes a diagnostic.
package/dist/analyze.js CHANGED
@@ -1,4 +1,5 @@
1
1
  import { validateBrowserSignIn } from "./sign-in.js";
2
+ import { CHAT_CHANNEL_KINDS, CHAT_CHANNEL_NAME, CHAT_KINDS, chatChannelKind, isChatKind, WORKSPACE_CHANNEL_KIND, workspaceChannelOf, } from "./chat-channel.js";
2
3
  import { checkWarehouseSource } from "./warehouse-backed.js";
3
4
  import { Result, Schema } from "effect";
4
5
  import { BLOB_UPLOAD_ANNOTATION } from "./blob.js";
@@ -12,7 +13,7 @@ import { AGENT_TOOL, AGENT_TOOL_VERBS, EXPLICIT_GRANT_ENTITIES, generatedActionP
12
13
  import { ON_DELETE, isRelationship } from "./relationship.js";
13
14
  import { isRole, member, role } from "./role.js";
14
15
  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
- import { BUILT_IN_EMAIL_VALUES, emailOptions, emailValueNames, } from "./emails.js";
16
+ import { BUILT_IN_EMAIL_VALUES, emailOptions, emailValueNames, SIGN_IN_CODE_VALUE, } from "./emails.js";
16
17
  import { AgentChat } from "./agent-chat.js";
17
18
  import { AgentReview } from "./agent-review.js";
18
19
  import { APP_FEEDBACK_ENTITIES } from "./app-feedback.js";
@@ -32,10 +33,22 @@ import { actionInputToWire } from "./authoring-input.js";
32
33
  import { validate } from "./runtime/validation.js";
33
34
  import { fixedArgumentsConflict, isToolset, MAXIMUM_TOOLSET_TOOLS, MCP_TOOL_NAME, toolHints, ToolsetLock, withoutFixedArguments, } from "./toolset.js";
34
35
  const GENERATED_UPSERT = new RegExp(`^${GENERATED_UPSERT_PREFIX}`);
35
- /** The providers `chat` may declare a posting connection for, in the order posting lists them. */
36
- const CHAT_PROVIDER_KEYS = ["telegram", "slack", "whatsapp", "email"];
37
- /** The `chat` providers reviewed replies leave through, but chat posts never reach. */
36
+ /** The kinds of channel `chat` may declare a connection for, in the order posting lists them. */
37
+ const CHAT_PROVIDER_KEYS = CHAT_CHANNEL_KINDS;
38
+ /** The kinds of channel reviewed replies leave through, but chat posts never reach. */
38
39
  const REVIEW_ONLY_CHAT_PROVIDERS = new Set(["email"]);
40
+ /**
41
+ * Names the agent keeps its own chats under, which no channel of `chat` takes, and the kind of a
42
+ * workspace channel, which always has a name of its own.
43
+ */
44
+ const RESERVED_CHAT_NAMES = new Set(["web", "task", WORKSPACE_CHANNEL_KIND]);
45
+ /** Whether `chat` declares a channel of `kind`: the one named after it, or another of the kind. */
46
+ function declaresChatKind(chat, kind) {
47
+ return (isPlainObject(chat) &&
48
+ Object.entries(chat).some(([name, value]) => name !== "attribution" &&
49
+ value !== undefined &&
50
+ chatChannelKind(chat, name) === kind));
51
+ }
39
52
  function errorMessage(error) {
40
53
  return error instanceof Error ? error.message : String(error);
41
54
  }
@@ -78,12 +91,16 @@ export function analyze(config, options = {}) {
78
91
  const emails = emailOptions(config.emails, report, (name, path) => camelCaseName(name, path, "agreementReview", "Email", report));
79
92
  const signInDeclared = signInOptions(config, report);
80
93
  const guest = guestOptions(config, report);
81
- const invitationEmail = invitationEmailOption(config, emails, report);
94
+ const invitationEmail = signInEmailOption(config, emails, report, "invitationEmail");
95
+ const linkEmail = signInEmailOption(config, emails, report, "linkEmail");
96
+ const codeEmail = signInEmailOption(config, emails, report, "codeEmail");
82
97
  const signIn = {
83
98
  ...signInDeclared,
84
99
  ...signUpOptions(config, signInDeclared, declaredRoles, report),
85
100
  ...(guest === undefined ? {} : { guest: guest.resolved }),
86
101
  ...(invitationEmail === undefined ? {} : { invitationEmail }),
102
+ ...(linkEmail === undefined ? {} : { linkEmail }),
103
+ ...(codeEmail === undefined ? {} : { codeEmail }),
87
104
  };
88
105
  const discovery = config.discovery;
89
106
  if (discovery !== undefined &&
@@ -148,39 +165,63 @@ export function analyze(config, options = {}) {
148
165
  ];
149
166
  let chat;
150
167
  if (config.chat !== undefined) {
151
- const declared = isPlainObject(config.chat)
152
- ? CHAT_PROVIDER_KEYS.filter((name) => config.chat?.[name] !== undefined)
168
+ const entries = isPlainObject(config.chat)
169
+ ? Object.entries(config.chat).filter(([name, value]) => name !== "attribution" && value !== undefined)
153
170
  : [];
154
171
  const unknown = isPlainObject(config.chat)
155
- ? Object.keys(config.chat).find((key) => key !== "attribution" && !CHAT_PROVIDER_KEYS.includes(key))
172
+ ? entries.find(([name]) => !CHAT_CHANNEL_NAME.test(name) || RESERVED_CHAT_NAMES.has(name))?.[0]
156
173
  : "chat";
157
- const malformed = declared.find((name) => {
158
- const provider = config.chat?.[name];
159
- return (!isPlainObject(provider) ||
160
- Object.keys(provider).some((key) => key !== "connection") ||
161
- !isConnection(provider.connection));
162
- });
163
- // Read only once every declared provider is well formed.
164
- const handles = malformed === undefined
165
- ? declared.map((name) => [name, config.chat[name].connection])
174
+ const malformed = entries.find(([name, value]) => {
175
+ const named = !CHAT_PROVIDER_KEYS.includes(name);
176
+ return (!isPlainObject(value) ||
177
+ Object.keys(value).some((key) => key !== "connection" && key !== "kind") ||
178
+ // A workspace channel has no connection here: the agent sends through it, with the
179
+ // connection agent/segmentstream.json gives it. Every other channel sends through its own.
180
+ (value.kind === WORKSPACE_CHANNEL_KIND
181
+ ? value.connection !== undefined
182
+ : !isConnection(value.connection)) ||
183
+ (named ? !isChatKind(value.kind) : value.kind !== undefined && value.kind !== name));
184
+ })?.[0];
185
+ // Read only once every declared channel is well formed.
186
+ const channels = malformed === undefined && unknown === undefined
187
+ ? entries.map(([name, value]) => {
188
+ const entry = value;
189
+ return [name, entry.connection, entry.kind ?? name];
190
+ })
166
191
  : [];
192
+ const handles = channels.flatMap(([name, handle, kind]) => handle === undefined ? [] : [[name, handle, kind]]);
167
193
  const unlisted = handles.find(([, handle]) => !(config.connections ?? []).includes(handle));
168
194
  const shared = handles.find(([, handle], index) => handles.findIndex(([, other]) => other === handle) !== index);
169
195
  if (unknown !== undefined) {
170
- report("invalid-connection", "chat", `chat accepts only ${CHAT_PROVIDER_KEYS.join(", ")} and attribution.`);
196
+ report("invalid-connection", "chat", `chat accepts attribution and channels by the agent's names for them: ` +
197
+ `${CHAT_PROVIDER_KEYS.join(", ")}, or another lower-case name with its kind; ` +
198
+ `web and task are the agent's own, and ${WORKSPACE_CHANNEL_KIND} is a kind.`);
171
199
  }
172
200
  else if (malformed !== undefined) {
173
- report("invalid-connection", "chat", `chat.${malformed}.connection must reference a declared connection handle.`);
201
+ report("invalid-connection", "chat", `chat.${malformed}.connection must reference a declared connection handle, and a ` +
202
+ `channel not named after its kind needs kind: ${CHAT_KINDS.join(", ")}; a ` +
203
+ `${WORKSPACE_CHANNEL_KIND} channel takes none, as the agent sends through it.`);
174
204
  }
175
205
  else if (unlisted !== undefined) {
176
- report("invalid-connection", `chat.${unlisted[0]}.connection`, "The chat provider connection must be listed in connections.");
206
+ report("invalid-connection", `chat.${unlisted[0]}.connection`, "The chat channel connection must be listed in connections.");
177
207
  }
178
208
  else if (shared !== undefined) {
179
- report("invalid-connection", `chat.${shared[0]}.connection`, "Each chat provider needs its own connection.");
209
+ report("invalid-connection", `chat.${shared[0]}.connection`, "Each chat channel needs its own connection.");
180
210
  }
181
- else if (handles.length > 0) {
211
+ else if (channels.length > 0) {
212
+ const named = channels.filter(([name]) => !CHAT_PROVIDER_KEYS.includes(name));
182
213
  chat = {
183
- ...Object.fromEntries(handles.map(([name, handle]) => [name, { connection: handle.key }])),
214
+ ...Object.fromEntries(handles
215
+ .filter(([name]) => CHAT_PROVIDER_KEYS.includes(name))
216
+ .map(([name, handle]) => [name, { connection: handle.key }])),
217
+ ...(named.length === 0
218
+ ? {}
219
+ : {
220
+ channels: Object.fromEntries(named.map(([name, handle, kind]) => [
221
+ name,
222
+ { kind, ...(handle === undefined ? {} : { connection: handle.key }) },
223
+ ])),
224
+ }),
184
225
  ...(config.chat.attribution === undefined ? {} : { attribution: config.chat.attribution }),
185
226
  };
186
227
  // Posting to a chat and sending a reviewed reply both send through the chat connections.
@@ -188,8 +229,10 @@ export function analyze(config, options = {}) {
188
229
  agent_chat: "post_message",
189
230
  agent_review: "approve",
190
231
  };
191
- // A chat post never reaches a provider that only sends reviewed replies.
192
- const reaches = (entity) => handles.filter(([name]) => entity === "agent_review" || !REVIEW_ONLY_CHAT_PROVIDERS.has(name));
232
+ // A chat post never reaches a channel whose kind only sends reviewed replies, and the
233
+ // ontology sends nothing through a workspace channel's connection: the agent does.
234
+ const reaches = (entity) => handles.filter(([, , kind]) => kind !== WORKSPACE_CHANNEL_KIND &&
235
+ (entity === "agent_review" || !REVIEW_ONLY_CHAT_PROVIDERS.has(kind)));
193
236
  resolved = resolved.map((entity) => sends[entity.name] === undefined
194
237
  ? entity
195
238
  : {
@@ -1234,7 +1277,16 @@ function signInOptions(config, report) {
1234
1277
  return fallback;
1235
1278
  }
1236
1279
  for (const key of Object.keys(options)) {
1237
- if (!["policy", "channels", "onNewUser", "browser", "codeLink", "invitationEmail"].includes(key)) {
1280
+ if (![
1281
+ "policy",
1282
+ "channels",
1283
+ "onNewUser",
1284
+ "browser",
1285
+ "codeLink",
1286
+ "invitationEmail",
1287
+ "linkEmail",
1288
+ "codeEmail",
1289
+ ].includes(key)) {
1238
1290
  report("invalid-sign-in", `signIn.${key}`, `Unknown signIn key: ${key}.`);
1239
1291
  }
1240
1292
  }
@@ -1261,8 +1313,7 @@ function signInOptions(config, report) {
1261
1313
  report("invalid-sign-in", `signIn.channels.${provider}`, 'Use "open" or "invited".');
1262
1314
  }
1263
1315
  else {
1264
- const adapters = config.chat;
1265
- if (adapters?.[provider] === undefined) {
1316
+ if (!declaresChatKind(config.chat, provider)) {
1266
1317
  report("invalid-sign-in", `signIn.channels.${provider}`, `Configure a matching chat.${provider} adapter.`);
1267
1318
  }
1268
1319
  channels[provider] = policy;
@@ -1293,19 +1344,26 @@ function signInOptions(config, report) {
1293
1344
  ...(typeof codeLink === "boolean" ? { codeLink } : {}),
1294
1345
  };
1295
1346
  }
1347
+ const SIGN_IN_EMAILS = {
1348
+ invitationEmail: { role: "the invitation", values: [] },
1349
+ linkEmail: { role: "the sign-in link email", values: [] },
1350
+ codeEmail: { role: "the sign-in code email", values: [SIGN_IN_CODE_VALUE] },
1351
+ };
1296
1352
  /**
1297
- * `signIn.invitationEmail`: the wire name of the declared email the platform sends instead of its
1298
- * own invitation. Nothing fills an invitation's values, so the email may use only built-in ones.
1353
+ * `signIn.invitationEmail`, `linkEmail` or `codeEmail`: the wire name of the declared email the
1354
+ * platform sends instead of its own. It may use only the built-in values and its own (the code's
1355
+ * `{{code}}`), and the code email must show the code.
1299
1356
  */
1300
- function invitationEmailOption(config, emails, report) {
1357
+ function signInEmailOption(config, emails, report, key) {
1301
1358
  const options = config.signIn;
1302
- const name = isPlainObject(options) ? options.invitationEmail : undefined;
1303
- const path = "signIn.invitationEmail";
1359
+ const name = isPlainObject(options) ? options[key] : undefined;
1360
+ const path = `signIn.${key}`;
1361
+ const { role, values: own } = SIGN_IN_EMAILS[key];
1304
1362
  if (name === undefined) {
1305
1363
  return undefined;
1306
1364
  }
1307
1365
  if (typeof name !== "string" || !/^[a-z][a-zA-Z0-9]*$/.test(name)) {
1308
- report("invalid-sign-in", path, "invitationEmail names one of the ontology's emails, such as memberInvitation.");
1366
+ report("invalid-sign-in", path, `${key} names one of the ontology's emails, such as memberInvitation.`);
1309
1367
  return undefined;
1310
1368
  }
1311
1369
  const wire = nameToWire(name);
@@ -1314,10 +1372,15 @@ function invitationEmailOption(config, emails, report) {
1314
1372
  report("invalid-sign-in", path, `${name} is not one of the ontology's emails.`);
1315
1373
  return undefined;
1316
1374
  }
1317
- const values = emailValueNames(template);
1318
- if (values.length > 0) {
1319
- report("invalid-email", `emails.${name}`, `${name} is the invitation, and nothing fills ${values.map((value) => `{{${value}}}`).join(", ")}: ` +
1320
- `use only ${BUILT_IN_EMAIL_VALUES.map((value) => `{{${value}}}`).join(", ")}.`);
1375
+ const used = emailValueNames(template);
1376
+ const unfilled = used.filter((value) => !own.includes(value));
1377
+ if (unfilled.length > 0) {
1378
+ report("invalid-email", `emails.${name}`, `${name} is ${role}, and nothing fills ${unfilled.map((value) => `{{${value}}}`).join(", ")}: ` +
1379
+ `use only ${[...BUILT_IN_EMAIL_VALUES, ...own].map((value) => `{{${value}}}`).join(", ")}.`);
1380
+ return undefined;
1381
+ }
1382
+ if (key === "codeEmail" && !used.includes(SIGN_IN_CODE_VALUE)) {
1383
+ report("invalid-email", `emails.${name}`, `${name} is ${role}: show the code with {{${SIGN_IN_CODE_VALUE}}}, for instance as a section's value to copy.`);
1321
1384
  return undefined;
1322
1385
  }
1323
1386
  return wire;
@@ -1427,11 +1490,16 @@ function signUpOptions(config, signIn, declaredRoles, report) {
1427
1490
  : `${channel} is opened by signIn.channels too; declare it in signUp only.`);
1428
1491
  }
1429
1492
  if (SIGN_UP_CHAT_CHANNELS.includes(channel)) {
1430
- const adapters = config.chat;
1431
- if (adapters?.[channel] === undefined) {
1493
+ if (!declaresChatKind(config.chat, channel)) {
1432
1494
  report("invalid-sign-in", `signUp.channels`, `Signing up on ${channel} needs a matching chat.${channel} adapter.`);
1433
1495
  }
1434
1496
  }
1497
+ // A workspace channel's people sign up through that channel, which chat declares.
1498
+ const workspace = workspaceChannelOf(channel);
1499
+ if (workspace !== undefined &&
1500
+ chatChannelKind(isPlainObject(config.chat) ? config.chat : undefined, workspace) !== WORKSPACE_CHANNEL_KIND) {
1501
+ report("invalid-sign-in", `signUp.channels`, `Signing up on ${channel} needs chat.${workspace} with kind ${WORKSPACE_CHANNEL_KIND}.`);
1502
+ }
1435
1503
  }
1436
1504
  const origins = [];
1437
1505
  if (options.origins !== undefined) {
@@ -1746,7 +1814,7 @@ function checkSignUpAction(input) {
1746
1814
  }
1747
1815
  for (const [channel, granted] of Object.entries(signIn.signUp?.channels ?? {})) {
1748
1816
  const permissions = roles
1749
- .filter((candidate) => granted.includes(candidate.name))
1817
+ .filter((candidate) => (granted ?? []).includes(candidate.name))
1750
1818
  .flatMap((candidate) => (Array.isArray(candidate.permissions) ? candidate.permissions : []));
1751
1819
  if (!isAllowed(found.permission, { permissions })) {
1752
1820
  fail(`onSignUp must be runnable by the roles ${channel} sign-up grants.`);
@@ -0,0 +1,47 @@
1
+ import { Schema } from "effect";
2
+ /**
3
+ * Channels by name (`docs/agent.md`, "Channels"). The agent answers on channels its
4
+ * `agent/segmentstream.json` names, several of one kind if it likes: two WhatsApp numbers, a few
5
+ * Telegram bots, several mailboxes. The channel named after its kind, such as `telegram`, is that
6
+ * kind and keeps every key it always had; any other name says its `kind`. The ontology's `chat`
7
+ * takes the same names, so a reply a member approves, or a chat post, leaves through the connection
8
+ * of the channel the chat is on. Where the platform keys a chat by its `provider`, such as
9
+ * `agent_chat` and the archive, the value is the channel's name.
10
+ *
11
+ * A workspace may define a channel in its own code (`docs/agent.md`, "Workspace channels"): its
12
+ * kind is {@link WORKSPACE_CHANNEL_KIND}, it always has a name of its own, and the agent sends
13
+ * through it, so a reply a member approves, or a chat post, goes to the agent's channel instead of
14
+ * a connection. Its people's accounts are its own: {@link channelIdentityProvider}.
15
+ */
16
+ /** The kinds of channel the platform provides, each with a channel named after it. */
17
+ export declare const CHAT_CHANNEL_KINDS: readonly ["telegram", "slack", "whatsapp", "email"];
18
+ export type ChatChannelKind = (typeof CHAT_CHANNEL_KINDS)[number];
19
+ export declare function isChatChannelKind(value: unknown): value is ChatChannelKind;
20
+ /**
21
+ * The kind of a channel the workspace defines in its own code. No channel is named after it: each
22
+ * has a name of its own.
23
+ */
24
+ export declare const WORKSPACE_CHANNEL_KIND = "custom";
25
+ /** Every kind a channel of another name may say: the platform's, and the workspace's own. */
26
+ export declare const CHAT_KINDS: readonly ["telegram", "slack", "whatsapp", "email", "custom"];
27
+ export type ChatKind = (typeof CHAT_KINDS)[number];
28
+ export declare function isChatKind(value: unknown): value is ChatKind;
29
+ /** A channel's name: a lower-case letter, then up to 31 lower-case letters, digits or `_`. */
30
+ export declare const CHAT_CHANNEL_NAME: RegExp;
31
+ export declare const ChatChannelName: Schema.String;
32
+ /** A workspace channel's identity provider: `channel:<name>`. */
33
+ export declare const WORKSPACE_IDENTITY_PROVIDER: RegExp;
34
+ /**
35
+ * The provider of the accounts people write from on the channel `name` of `kind`: the kind for
36
+ * the platform's channels, whose accounts are the same on every channel of the kind, and
37
+ * `channel:<name>` for a workspace channel, whose accounts are its own, so it can claim no
38
+ * Telegram, WhatsApp or email account, nor another workspace channel's.
39
+ */
40
+ export declare function channelIdentityProvider(kind: string, name: string): string;
41
+ /** The workspace channel whose accounts `provider` names, or undefined for any other provider. */
42
+ export declare function workspaceChannelOf(provider: string): string | undefined;
43
+ /**
44
+ * The kind of the channel `name`, by `chat`'s entries: the kind an entry names, or the name itself
45
+ * for the channel named after its kind. Undefined for a name that is neither.
46
+ */
47
+ export declare function chatChannelKind(chat: Readonly<Record<string, unknown>> | undefined, name: string): ChatKind | undefined;
@@ -0,0 +1,69 @@
1
+ import { Schema } from "effect";
2
+ /**
3
+ * Channels by name (`docs/agent.md`, "Channels"). The agent answers on channels its
4
+ * `agent/segmentstream.json` names, several of one kind if it likes: two WhatsApp numbers, a few
5
+ * Telegram bots, several mailboxes. The channel named after its kind, such as `telegram`, is that
6
+ * kind and keeps every key it always had; any other name says its `kind`. The ontology's `chat`
7
+ * takes the same names, so a reply a member approves, or a chat post, leaves through the connection
8
+ * of the channel the chat is on. Where the platform keys a chat by its `provider`, such as
9
+ * `agent_chat` and the archive, the value is the channel's name.
10
+ *
11
+ * A workspace may define a channel in its own code (`docs/agent.md`, "Workspace channels"): its
12
+ * kind is {@link WORKSPACE_CHANNEL_KIND}, it always has a name of its own, and the agent sends
13
+ * through it, so a reply a member approves, or a chat post, goes to the agent's channel instead of
14
+ * a connection. Its people's accounts are its own: {@link channelIdentityProvider}.
15
+ */
16
+ /** The kinds of channel the platform provides, each with a channel named after it. */
17
+ export const CHAT_CHANNEL_KINDS = ["telegram", "slack", "whatsapp", "email"];
18
+ export function isChatChannelKind(value) {
19
+ return CHAT_CHANNEL_KINDS.some((kind) => kind === value);
20
+ }
21
+ /**
22
+ * The kind of a channel the workspace defines in its own code. No channel is named after it: each
23
+ * has a name of its own.
24
+ */
25
+ export const WORKSPACE_CHANNEL_KIND = "custom";
26
+ /** Every kind a channel of another name may say: the platform's, and the workspace's own. */
27
+ export const CHAT_KINDS = [...CHAT_CHANNEL_KINDS, WORKSPACE_CHANNEL_KIND];
28
+ export function isChatKind(value) {
29
+ return CHAT_KINDS.some((kind) => kind === value);
30
+ }
31
+ /** A channel's name: a lower-case letter, then up to 31 lower-case letters, digits or `_`. */
32
+ export const CHAT_CHANNEL_NAME = /^[a-z][a-z0-9_]{0,31}$/;
33
+ export const ChatChannelName = Schema.String.check(Schema.isPattern(CHAT_CHANNEL_NAME)).annotate({
34
+ description: "The channel's name, as the agent's channels and the ontology's chat name it: its kind, such " +
35
+ "as telegram, for the channel named after its kind.",
36
+ });
37
+ /** What a workspace channel's people's accounts are named under, before the channel's name. */
38
+ const WORKSPACE_IDENTITY_PREFIX = "channel:";
39
+ /** A workspace channel's identity provider: `channel:<name>`. */
40
+ export const WORKSPACE_IDENTITY_PROVIDER = /^channel:[a-z][a-z0-9_]{0,31}$/;
41
+ /**
42
+ * The provider of the accounts people write from on the channel `name` of `kind`: the kind for
43
+ * the platform's channels, whose accounts are the same on every channel of the kind, and
44
+ * `channel:<name>` for a workspace channel, whose accounts are its own, so it can claim no
45
+ * Telegram, WhatsApp or email account, nor another workspace channel's.
46
+ */
47
+ export function channelIdentityProvider(kind, name) {
48
+ return kind === WORKSPACE_CHANNEL_KIND ? `${WORKSPACE_IDENTITY_PREFIX}${name}` : kind;
49
+ }
50
+ /** The workspace channel whose accounts `provider` names, or undefined for any other provider. */
51
+ export function workspaceChannelOf(provider) {
52
+ return WORKSPACE_IDENTITY_PROVIDER.test(provider)
53
+ ? provider.slice(WORKSPACE_IDENTITY_PREFIX.length)
54
+ : undefined;
55
+ }
56
+ /**
57
+ * The kind of the channel `name`, by `chat`'s entries: the kind an entry names, or the name itself
58
+ * for the channel named after its kind. Undefined for a name that is neither.
59
+ */
60
+ export function chatChannelKind(chat, name) {
61
+ const entry = chat?.[name];
62
+ const kind = entry !== null && typeof entry === "object" && "kind" in entry
63
+ ? entry.kind
64
+ : undefined;
65
+ if (isChatChannelKind(name)) {
66
+ return kind === undefined || kind === name ? name : undefined;
67
+ }
68
+ return isChatKind(kind) && name !== WORKSPACE_CHANNEL_KIND ? kind : undefined;
69
+ }
@@ -0,0 +1,23 @@
1
+ /**
2
+ * The safety rules of an email the workspace lays out itself, applied to its HTML as a browser
3
+ * reads it. A small tokenizer follows the HTML standard's tag, attribute, comment and raw-text
4
+ * states, so markup cannot hide a tag or an attribute from the check (an apostrophe in an unquoted
5
+ * value, a `/` between attributes, a missing space after a quote).
6
+ */
7
+ /**
8
+ * The values that may stand inside a tag, such as in an `href`: the platform's own addresses and
9
+ * the workspace's name. Every other value (the recipient's name, the code, what an action passes)
10
+ * stands only in text, where escaping keeps it text, so it can never become an address or add an
11
+ * attribute.
12
+ */
13
+ export declare const EMAIL_MARKUP_VALUES: readonly ["link", "app.url", "app.mcpUrl", "workspace.name"];
14
+ /**
15
+ * Why an email's HTML is unsafe to send, or undefined: an element that runs code, embeds a page or
16
+ * posts a form; `<svg>`, `<math>` or `<plaintext>`; an event handler; a `<meta http-equiv>`; a
17
+ * value other than {@link EMAIL_MARKUP_VALUES} inside a tag, a comment or a `<style>`, or any value
18
+ * outside a quoted attribute value of a tag or right after `<`; a tag the HTML leaves unclosed; or
19
+ * an address that is not `https:`, `mailto:`, `tel:`, an anchor or the app's own `{{link}}`,
20
+ * `{{app.url}}` or `{{app.mcpUrl}}`. The platform applies the same rules to every deployed email
21
+ * before it sends one.
22
+ */
23
+ export declare function unsafeEmailHtml(html: string): string | undefined;