@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
@@ -208,10 +208,12 @@ export interface CredentialOptions {
208
208
  /**
209
209
  * The chat a verified runtime caller names, kept as the principal's when it can be the chat it acts
210
210
  * in: on the web, the member's or guest's own chat, which their agent token names; on a messenger,
211
- * a chat of the provider the member wrote from. Anything else is left out, never refused: it only
212
- * attributes.
211
+ * a chat on a channel of the kind the member wrote from. The chat names its channel by name, as
212
+ * the archive does; `kindOf` answers the channel's kind, as the ontology's `chat` declares it. A
213
+ * workspace channel's accounts are its own (`channel:<name>`), so they name its chats' channel.
214
+ * Anything else is left out, never refused: it only attributes.
213
215
  */
214
- export declare function actingChat(principal: Principal, provider: string | undefined, chat: ChatProvenance | undefined): ChatProvenance | undefined;
216
+ export declare function actingChat(principal: Principal, provider: string | undefined, chat: ChatProvenance | undefined, kindOf?: (channel: string) => string | undefined): ChatProvenance | undefined;
215
217
  /** Resolves a bearer credential to its current principal and verified credential provenance. */
216
218
  export declare function authenticate(credential: Redacted.Redacted<string>, verifyToken: TokenVerifier, options?: CredentialOptions): Effect.Effect<Authenticated, never, OntologyBackend>;
217
219
  /** A browser's request, which may authenticate with the app's Neon Auth session cookie. */
@@ -2,6 +2,7 @@ import { Cause, Context, Effect, Layer, Redacted } from "effect";
2
2
  import { HttpServerRequest } from "effect/unstable/http";
3
3
  import { HttpApiMiddleware, HttpApiSecurity, OpenApi } from "effect/unstable/httpapi";
4
4
  import { createRemoteJWKSet, decodeJwt, decodeProtectedHeader, errors, jwtVerify, } from "jose";
5
+ import { channelIdentityProvider, WORKSPACE_CHANNEL_KIND, workspaceChannelOf, } from "../chat-channel.js";
5
6
  import { CHANNEL_COOKIE_PATTERN } from "../channel-session.js";
6
7
  import { requireDeploymentCapability } from "../deployment.js";
7
8
  import { API_KEY_PREFIX } from "../runtime/principals.js";
@@ -453,10 +454,12 @@ export function sessionMayAuthenticate(request) {
453
454
  /**
454
455
  * The chat a verified runtime caller names, kept as the principal's when it can be the chat it acts
455
456
  * in: on the web, the member's or guest's own chat, which their agent token names; on a messenger,
456
- * a chat of the provider the member wrote from. Anything else is left out, never refused: it only
457
- * attributes.
457
+ * a chat on a channel of the kind the member wrote from. The chat names its channel by name, as
458
+ * the archive does; `kindOf` answers the channel's kind, as the ontology's `chat` declares it. A
459
+ * workspace channel's accounts are its own (`channel:<name>`), so they name its chats' channel.
460
+ * Anything else is left out, never refused: it only attributes.
458
461
  */
459
- export function actingChat(principal, provider, chat) {
462
+ export function actingChat(principal, provider, chat, kindOf = (channel) => channel) {
460
463
  if (chat === undefined) {
461
464
  return undefined;
462
465
  }
@@ -466,7 +469,17 @@ export function actingChat(principal, provider, chat) {
466
469
  ? chat
467
470
  : undefined;
468
471
  }
469
- return provider === undefined || provider === chat.provider ? chat : undefined;
472
+ // The member's identity is of a kind; a channel of another name, such as `sales_whatsapp`,
473
+ // counts as the kind the ontology's chat declares for it. A workspace channel's accounts are its
474
+ // own: they count only on that channel.
475
+ const kind = kindOf(chat.provider);
476
+ return provider === undefined ||
477
+ workspaceChannelOf(provider) === chat.provider ||
478
+ (kind !== undefined &&
479
+ kind !== WORKSPACE_CHANNEL_KIND &&
480
+ provider === channelIdentityProvider(kind, chat.provider))
481
+ ? chat
482
+ : undefined;
470
483
  }
471
484
  /**
472
485
  * The member a verified runtime caller acts for: the member `X-SegmentStream-Act-As` names, with the
@@ -494,7 +507,9 @@ function actingMember(actAs, provider, grant, guests = false, chat) {
494
507
  : provider === WEB_PROVIDER
495
508
  ? yield* webMember(backend.agents, actAs, grant)
496
509
  : yield* backend.agents.actingMember(actAs, provider);
497
- const acting = member === undefined ? undefined : actingChat(member, provider, chat);
510
+ const acting = member === undefined
511
+ ? undefined
512
+ : actingChat(member, provider, chat, backend.agents?.channelKind);
498
513
  const withChat = acting === undefined ? {} : { chat: acting };
499
514
  if (member?.kind === "guest") {
500
515
  return guests
@@ -8,6 +8,7 @@ import type { OntologyBackend } from "../runtime-contract.js";
8
8
  import type { DeliveryArchive } from "./archive.js";
9
9
  import type { RuntimeChatEnvelope } from "./envelope.js";
10
10
  import { type Destination } from "./resolve.js";
11
+ import type { AgentChannelTransport } from "./providers/provider.js";
11
12
  export type ChatDeliveryFactory = (input: {
12
13
  readonly backend: OntologyBackend["Service"];
13
14
  readonly principal: Principal;
@@ -22,4 +23,12 @@ export type ChatDeliveryFactory = (input: {
22
23
  * private source matches a private destination on the same provider by its `peer`.
23
24
  */
24
25
  export declare function sameChat(source: NonNullable<RuntimeChatEnvelope["source"]>, target: Pick<Destination, "provider" | "external_id" | "kind">): boolean;
25
- export declare function makeChatDelivery(ontology: Ontology, connections: ConnectionTransportFactory, archive: DeliveryArchive, previews?: TelegramPreviewContext): ChatDeliveryFactory;
26
+ export declare function makeChatDelivery(ontology: Ontology, connections: ConnectionTransportFactory, archive: DeliveryArchive, previews?: TelegramPreviewContext,
27
+ /**
28
+ * The app's agent at the deployment's production origin, which sends through a workspace
29
+ * channel; `fetch` by default. Without an origin nothing goes through one.
30
+ */
31
+ agent?: {
32
+ readonly origin?: string | undefined;
33
+ readonly fetch?: AgentChannelTransport["fetch"];
34
+ }): ChatDeliveryFactory;
@@ -7,9 +7,10 @@ import { isAllowed } from "../../permissions.js";
7
7
  import { describeChatError } from "./diagnostics.js";
8
8
  import { deliveryRequester } from "./attribution.js";
9
9
  import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
10
- import { chatConnection, chatProvider, listedChatProviders } from "./providers/index.js";
10
+ import { channelProvider, chatConnection, chatKind, listedChatProviders, } from "./providers/index.js";
11
11
  import { chatResolver } from "./resolve.js";
12
12
  import { reviewSender } from "./review-delivery.js";
13
+ import { WORKSPACE_CHANNEL_KIND } from "../../chat-channel.js";
13
14
  /** The channels a runtime source can name, which a verified pairing's provider is one of. */
14
15
  const CHANNEL_PROVIDERS = new Set(["telegram", "slack", "whatsapp"]);
15
16
  /**
@@ -18,7 +19,8 @@ const CHANNEL_PROVIDERS = new Set(["telegram", "slack", "whatsapp"]);
18
19
  * private source matches a private destination on the same provider by its `peer`.
19
20
  */
20
21
  export function sameChat(source, target) {
21
- if (source.provider !== target.provider) {
22
+ // The target's provider is the channel it is on, by name; the source's is its kind.
23
+ if ((source.channel ?? source.provider) !== target.provider) {
22
24
  return false;
23
25
  }
24
26
  if (source.chat_id === target.external_id) {
@@ -29,7 +31,12 @@ export function sameChat(source, target) {
29
31
  target.kind === "private" &&
30
32
  source.peer === target.external_id);
31
33
  }
32
- export function makeChatDelivery(ontology, connections, archive, previews = {}) {
34
+ export function makeChatDelivery(ontology, connections, archive, previews = {},
35
+ /**
36
+ * The app's agent at the deployment's production origin, which sends through a workspace
37
+ * channel; `fetch` by default. Without an origin nothing goes through one.
38
+ */
39
+ agent = {}) {
33
40
  if (previews.settings) {
34
41
  validateTelegramPreviews(previews.settings);
35
42
  }
@@ -58,12 +65,18 @@ export function makeChatDelivery(ontology, connections, archive, previews = {})
58
65
  message: "The requester must still be paired and active.",
59
66
  });
60
67
  }
61
- const target = yield* chatResolver(context.backend, context.principal, providers).resolve(input.chat);
62
- // A chat is a destination only on a provider the ontology declares a connection for.
63
- const provider = chatProvider(target.provider);
68
+ const target = yield* chatResolver(context.backend, context.principal, providers, {
69
+ kindOf: (channel) => chatKind(ontology.manifest.chat, channel),
70
+ }).resolve(input.chat);
71
+ // A chat is a destination only on a channel the ontology declares a connection for; the
72
+ // channel's kind sends it.
73
+ const provider = channelProvider(ontology.manifest.chat, target.provider);
64
74
  const connection = chatConnection(ontology.manifest.chat, target.provider);
65
75
  const replyTo = input.replyTo ?? null;
66
- if (provider === undefined || !connection) {
76
+ // A workspace channel needs no connection of the ontology's: the agent sends through it.
77
+ if (provider === undefined ||
78
+ (!connection &&
79
+ chatKind(ontology.manifest.chat, target.provider) !== WORKSPACE_CHANNEL_KIND)) {
67
80
  return yield* new ActionRejected({
68
81
  message: "Chat posting requires a configured connection for the chat's provider.",
69
82
  });
@@ -113,17 +126,24 @@ export function makeChatDelivery(ontology, connections, archive, previews = {})
113
126
  });
114
127
  }
115
128
  }
116
- return { target, requester, connection, provider, preview };
129
+ return { target, requester, connection: connection ?? "", provider, preview };
117
130
  });
118
131
  const report = (phase, cause) => Effect.logWarning("ontology.chat.delivery_diagnostic").pipe(Effect.annotateLogs({
119
132
  phase,
120
133
  requestId: context.requestId,
121
134
  error: describeChatError(cause, (text) => context.identityToken ? text.split(context.identityToken).join("[redacted]") : text),
122
135
  }));
136
+ // The agent, which sends through a workspace channel, with this request's identity token.
137
+ const agentTransport = {
138
+ origin: agent.origin,
139
+ identityToken: context.identityToken,
140
+ fetch: agent.fetch ?? ((request) => fetch(request)),
141
+ };
123
142
  return {
124
143
  sendReview: reviewSender({
125
144
  ontology,
126
145
  connections,
146
+ agent: agentTransport,
127
147
  archive,
128
148
  previews: destinationPreviews,
129
149
  backend: context.backend,
@@ -225,6 +245,8 @@ export function makeChatDelivery(ontology, connections, archive, previews = {})
225
245
  previews: destinationPreviews,
226
246
  plainText: event.text,
227
247
  replyTo: preview.replyTo,
248
+ agent: agentTransport,
249
+ operationId,
228
250
  transport: connections({
229
251
  identityToken: context.identityToken,
230
252
  audit: {
@@ -8,6 +8,7 @@ declare const RuntimeEnvelope: Schema.Struct<{
8
8
  readonly operation_id: Schema.optionalKey<Schema.String>;
9
9
  readonly source: Schema.optionalKey<Schema.Union<readonly [Schema.Struct<{
10
10
  readonly provider: Schema.Literal<"telegram">;
11
+ readonly channel: Schema.optionalKey<Schema.String>;
11
12
  readonly chat_id: Schema.String;
12
13
  readonly thread_id: Schema.String;
13
14
  readonly message_id: Schema.optionalKey<Schema.String>;
@@ -29,6 +30,7 @@ declare const RuntimeEnvelope: Schema.Struct<{
29
30
  }>>>;
30
31
  }>, Schema.Struct<{
31
32
  readonly provider: Schema.Literals<readonly ["slack", "whatsapp"]>;
33
+ readonly channel: Schema.optionalKey<Schema.String>;
32
34
  readonly chat_id: Schema.String;
33
35
  readonly thread_id: Schema.String;
34
36
  readonly kind: Schema.Literals<readonly ["private", "group"]>;
@@ -51,6 +53,7 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
51
53
  readonly chat_id: string;
52
54
  readonly thread_id: string;
53
55
  readonly message_id?: string | undefined;
56
+ readonly channel?: string | undefined;
54
57
  readonly attachments?: readonly {
55
58
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
56
59
  readonly file_id: string;
@@ -69,10 +72,11 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
69
72
  } | undefined;
70
73
  } | {
71
74
  readonly kind: "private" | "group";
72
- readonly provider: "whatsapp" | "slack";
75
+ readonly provider: "slack" | "whatsapp";
73
76
  readonly chat_id: string;
74
77
  readonly thread_id: string;
75
78
  readonly message_id?: string | undefined;
79
+ readonly channel?: string | undefined;
76
80
  readonly sender?: string | undefined;
77
81
  readonly peer?: string | undefined;
78
82
  } | undefined;
@@ -103,6 +107,7 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
103
107
  readonly chat_id: string;
104
108
  readonly thread_id: string;
105
109
  readonly message_id?: string | undefined;
110
+ readonly channel?: string | undefined;
106
111
  readonly attachments?: readonly {
107
112
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
108
113
  readonly file_id: string;
@@ -121,10 +126,11 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
121
126
  } | undefined;
122
127
  } | {
123
128
  readonly kind: "private" | "group";
124
- readonly provider: "whatsapp" | "slack";
129
+ readonly provider: "slack" | "whatsapp";
125
130
  readonly chat_id: string;
126
131
  readonly thread_id: string;
127
132
  readonly message_id?: string | undefined;
133
+ readonly channel?: string | undefined;
128
134
  readonly sender?: string | undefined;
129
135
  readonly peer?: string | undefined;
130
136
  } | undefined;
@@ -0,0 +1,13 @@
1
+ import { Effect } from "effect";
2
+ import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
3
+ /**
4
+ * One message through a workspace channel, by the agent's own code: `POST` the channel's send route
5
+ * on the deployment's production origin with the service's Vercel OIDC token, never retried. The
6
+ * agent's `4xx` sent nothing; a timeout, a `5xx` or an answer without its shape may have.
7
+ */
8
+ export declare function sendThroughAgent(input: ChatSend): Effect.Effect<ProviderOutcome>;
9
+ /**
10
+ * A channel the workspace defines in its own code: a person's chat on it, by the id the channel's
11
+ * code keyed it with. Its chats are private, and the text is sent as written; the agent sends it.
12
+ */
13
+ export declare const customProvider: ChatProvider;
@@ -0,0 +1,103 @@
1
+ import { Effect } from "effect";
2
+ import { renderWorkspaceChannelText, WORKSPACE_CHANNEL_ID, WORKSPACE_CHANNEL_TEXT_LIMIT, workspaceChannelSendRoute, } from "../../../workspace-channel.js";
3
+ import { record } from "./provider.js";
4
+ /** How long the agent has to send one message through a workspace channel. */
5
+ const AGENT_SEND_TIMEOUT_MS = 30_000;
6
+ /**
7
+ * A chat, person or message id on a workspace channel, as the agent's channel takes them from the
8
+ * workspace's code: letters, digits and `:_.@+-`, as a chat's provenance carries them.
9
+ */
10
+ const ID = WORKSPACE_CHANNEL_ID;
11
+ /**
12
+ * One message through a workspace channel, by the agent's own code: `POST` the channel's send route
13
+ * on the deployment's production origin with the service's Vercel OIDC token, never retried. The
14
+ * agent's `4xx` sent nothing; a timeout, a `5xx` or an answer without its shape may have.
15
+ */
16
+ export function sendThroughAgent(input) {
17
+ return Effect.gen(function* () {
18
+ const payload = { text: input.finalText };
19
+ const agent = input.agent;
20
+ if (agent?.origin === undefined || agent.identityToken === undefined) {
21
+ return {
22
+ payload,
23
+ status: "failed",
24
+ messageId: null,
25
+ url: null,
26
+ cause: new Error("The agent's workspace channel is reachable only from the production deployment."),
27
+ };
28
+ }
29
+ const body = {
30
+ operation_id: input.operationId ?? input.destination.id,
31
+ // A reviewed reply names its chat. A chat post names only the person: the ontology knows
32
+ // their account, not their chat with the channel, which the agent finds.
33
+ chat_id: input.chatId ?? null,
34
+ recipient: input.destination.external_id,
35
+ thread_id: input.threadId ?? null,
36
+ reply_to: input.replyTo,
37
+ text: input.finalText,
38
+ };
39
+ const answered = yield* Effect.tryPromise(async () => {
40
+ const response = await agent.fetch(new Request(new URL(workspaceChannelSendRoute(input.destination.provider), agent.origin), {
41
+ method: "POST",
42
+ headers: {
43
+ authorization: `Bearer ${agent.identityToken}`,
44
+ "content-type": "application/json",
45
+ },
46
+ body: JSON.stringify(body),
47
+ signal: AbortSignal.timeout(AGENT_SEND_TIMEOUT_MS),
48
+ }));
49
+ const text = await response.text();
50
+ return { status: response.status, text };
51
+ }).pipe(Effect.exit);
52
+ if (answered._tag === "Failure") {
53
+ return { payload, status: "uncertain", messageId: null, url: null, cause: answered.cause };
54
+ }
55
+ const { status, text } = answered.value;
56
+ let answer = {};
57
+ try {
58
+ answer = record(JSON.parse(text));
59
+ }
60
+ catch {
61
+ // The status still says what happened; the body only adds the message's id.
62
+ }
63
+ if (status >= 400 && status < 500) {
64
+ return {
65
+ payload,
66
+ status: "failed",
67
+ messageId: null,
68
+ url: null,
69
+ cause: new Error(`The agent's workspace channel refused the message (${typeof answer.error === "string" ? answer.error : `status ${status}`}).`),
70
+ };
71
+ }
72
+ const id = answer.message_id;
73
+ if (status < 200 ||
74
+ status >= 300 ||
75
+ !("message_id" in answer) ||
76
+ (id !== null && (typeof id !== "string" || !ID.test(id)))) {
77
+ return {
78
+ payload,
79
+ status: "uncertain",
80
+ messageId: null,
81
+ url: null,
82
+ cause: new Error(`The agent's workspace channel answered with status ${status}.`),
83
+ };
84
+ }
85
+ return { payload, status: "sent", messageId: id, url: null };
86
+ });
87
+ }
88
+ /**
89
+ * A channel the workspace defines in its own code: a person's chat on it, by the id the channel's
90
+ * code keyed it with. Its chats are private, and the text is sent as written; the agent sends it.
91
+ */
92
+ export const customProvider = {
93
+ provider: "custom",
94
+ limit: WORKSPACE_CHANNEL_TEXT_LIMIT,
95
+ isTargetId: (externalId, kind) => kind === "private" && ID.test(externalId),
96
+ isReplyId: (replyTo) => ID.test(replyTo),
97
+ render: (text, attribution, separator) => {
98
+ const finalText = renderWorkspaceChannelText(text, attribution, separator);
99
+ return { finalText, plainText: finalText };
100
+ },
101
+ payload: (finalText) => ({ text: finalText }),
102
+ send: sendThroughAgent,
103
+ };
@@ -10,17 +10,28 @@ export declare const CHAT_PROVIDERS: {
10
10
  readonly slack: ChatProvider;
11
11
  readonly whatsapp: ChatProvider;
12
12
  readonly email: ChatProvider;
13
+ readonly custom: ChatProvider;
13
14
  };
14
15
  export type ChatProviderName = keyof typeof CHAT_PROVIDERS;
15
- /** The provider a destination's chat is on, when the platform posts to it. */
16
- export declare function chatProvider(name: string): ChatProvider | undefined;
17
- /** The connection the ontology declares for posting to a provider's chats, if it declares one. */
18
- export declare function chatConnection(chat: OntologyManifest["chat"], provider: string): string | undefined;
19
- /** The providers the ontology declares a posting connection for: the destinations it posts to. */
20
- export declare function declaredChatProviders(chat: OntologyManifest["chat"]): ReadonlyArray<ChatProviderName>;
16
+ /** The provider of a kind of channel, when the platform posts to it. */
17
+ export declare function chatProvider(kind: string): ChatProvider | undefined;
21
18
  /**
22
- * The providers whose chats the chat tools list, read and resolve: Telegram's, whose chats the
23
- * tools always listed, and each declared one. Posting still requires the target's provider to
24
- * be declared.
19
+ * The kind of the agent's channel `name` the ontology's `chat` declares: the name itself for the
20
+ * channel named after its kind, which a chat on it before channels had names also is.
21
+ */
22
+ export declare function chatKind(chat: OntologyManifest["chat"], name: string): string | undefined;
23
+ /** The provider of the agent's channel `name`, by its kind, when the platform posts to it. */
24
+ export declare function channelProvider(chat: OntologyManifest["chat"], name: string): ChatProvider | undefined;
25
+ /** The connection the ontology declares for the agent's channel `name`, if it declares one. */
26
+ export declare function chatConnection(chat: OntologyManifest["chat"], name: string): string | undefined;
27
+ /**
28
+ * The channels the ontology declares a posting connection for, by name: the destinations it posts
29
+ * to. The channel named after each kind comes first, then the others.
30
+ */
31
+ export declare function declaredChatProviders(chat: OntologyManifest["chat"]): ReadonlyArray<string>;
32
+ /**
33
+ * The channels whose chats the chat tools list, read and resolve, by name: Telegram's, whose
34
+ * chats the tools always listed, and each declared one. Posting still requires the target's
35
+ * channel to be declared.
25
36
  */
26
37
  export declare function listedChatProviders(chat: OntologyManifest["chat"]): ReadonlyArray<string>;
@@ -1,3 +1,5 @@
1
+ import { isChatChannelKind, CHAT_CHANNEL_KINDS, WORKSPACE_CHANNEL_KIND, } from "../../../chat-channel.js";
2
+ import { customProvider } from "./custom.js";
1
3
  import { emailProvider } from "./email.js";
2
4
  import { slackProvider } from "./slack.js";
3
5
  import { telegramProvider } from "./telegram.js";
@@ -11,25 +13,52 @@ export const CHAT_PROVIDERS = {
11
13
  slack: slackProvider,
12
14
  whatsapp: whatsappProvider,
13
15
  email: emailProvider,
16
+ // A channel the workspace defines in its own code: the agent sends through it.
17
+ custom: customProvider,
14
18
  };
15
- const NAMES = Object.keys(CHAT_PROVIDERS);
19
+ /** The kinds whose channel is named after them; a workspace channel always has its own name. */
20
+ const NAMES = CHAT_CHANNEL_KINDS;
16
21
  const isChatProvider = (name) => Object.hasOwn(CHAT_PROVIDERS, name);
17
- /** The provider a destination's chat is on, when the platform posts to it. */
18
- export function chatProvider(name) {
19
- return isChatProvider(name) ? CHAT_PROVIDERS[name] : undefined;
22
+ /** The provider of a kind of channel, when the platform posts to it. */
23
+ export function chatProvider(kind) {
24
+ return isChatProvider(kind) ? CHAT_PROVIDERS[kind] : undefined;
20
25
  }
21
- /** The connection the ontology declares for posting to a provider's chats, if it declares one. */
22
- export function chatConnection(chat, provider) {
23
- return isChatProvider(provider) ? chat?.[provider]?.connection : undefined;
26
+ /**
27
+ * The kind of the agent's channel `name` the ontology's `chat` declares: the name itself for the
28
+ * channel named after its kind, which a chat on it before channels had names also is.
29
+ */
30
+ export function chatKind(chat, name) {
31
+ return isChatChannelKind(name)
32
+ ? name
33
+ : name === WORKSPACE_CHANNEL_KIND
34
+ ? undefined
35
+ : chat?.channels?.[name]?.kind;
36
+ }
37
+ /** The provider of the agent's channel `name`, by its kind, when the platform posts to it. */
38
+ export function channelProvider(chat, name) {
39
+ const kind = chatKind(chat, name);
40
+ return kind === undefined ? undefined : chatProvider(kind);
24
41
  }
25
- /** The providers the ontology declares a posting connection for: the destinations it posts to. */
42
+ /** The connection the ontology declares for the agent's channel `name`, if it declares one. */
43
+ export function chatConnection(chat, name) {
44
+ return isChatChannelKind(name) ? chat?.[name]?.connection : chat?.channels?.[name]?.connection;
45
+ }
46
+ /**
47
+ * The channels the ontology declares a posting connection for, by name: the destinations it posts
48
+ * to. The channel named after each kind comes first, then the others.
49
+ */
26
50
  export function declaredChatProviders(chat) {
27
- return NAMES.filter((name) => chat?.[name] !== undefined && CHAT_PROVIDERS[name].posts !== false);
51
+ return [
52
+ ...NAMES.filter((name) => chat?.[name] !== undefined && CHAT_PROVIDERS[name].posts !== false),
53
+ ...Object.entries(chat?.channels ?? {})
54
+ .filter(([, channel]) => chatProvider(channel.kind)?.posts !== false)
55
+ .map(([name]) => name),
56
+ ];
28
57
  }
29
58
  /**
30
- * The providers whose chats the chat tools list, read and resolve: Telegram's, whose chats the
31
- * tools always listed, and each declared one. Posting still requires the target's provider to
32
- * be declared.
59
+ * The channels whose chats the chat tools list, read and resolve, by name: Telegram's, whose
60
+ * chats the tools always listed, and each declared one. Posting still requires the target's
61
+ * channel to be declared.
33
62
  */
34
63
  export function listedChatProviders(chat) {
35
64
  return [...new Set(["telegram", ...declaredChatProviders(chat)])];
@@ -11,6 +11,16 @@ export interface ProviderOutcome {
11
11
  readonly url: string | null;
12
12
  readonly cause?: unknown;
13
13
  }
14
+ /**
15
+ * How the service reaches the app's agent, which sends through a workspace channel: the
16
+ * deployment's production origin and the service's Vercel OIDC token, each undefined outside
17
+ * production, and the transport, `fetch` by default.
18
+ */
19
+ export interface AgentChannelTransport {
20
+ readonly origin: string | undefined;
21
+ readonly identityToken: string | undefined;
22
+ readonly fetch: (request: Request) => Promise<Response>;
23
+ }
14
24
  /** What a provider sends: the exact text its `render` gave, to one resolved destination. */
15
25
  export interface ChatSend {
16
26
  readonly transport: ConnectionTransport["Service"];
@@ -27,6 +37,15 @@ export interface ChatSend {
27
37
  readonly threadId?: string | null;
28
38
  /** Telegram's link preview settings for its destination connection; others ignore them. */
29
39
  readonly previews?: TelegramPreviewContext;
40
+ /** The app's agent, which sends through a workspace channel; others ignore it. */
41
+ readonly agent?: AgentChannelTransport;
42
+ /** The delivery's operation, which a workspace channel's send is named by; others ignore it. */
43
+ readonly operationId?: string;
44
+ /**
45
+ * The chat's own id where it differs from the destination's, as a reviewed reply's chat does;
46
+ * a workspace channel's send receives it, others ignore it.
47
+ */
48
+ readonly chatId?: string;
30
49
  }
31
50
  /**
32
51
  * A channel the platform posts exact chat messages to. Each provider names its own ids, renders
@@ -6,18 +6,21 @@ import type { OntologyBackend } from "../runtime-contract.js";
6
6
  import type { ChatArchiveTransport } from "../agent/chat-archive.js";
7
7
  import type { ChatList, ChatHistory } from "./schemas.js";
8
8
  export declare function chatReads(backend: OntologyBackend["Service"], options: {
9
- /** The providers whose chats are listed, as `listedChatProviders` gives them. */
9
+ /** The channels whose chats are listed, as `listedChatProviders` gives them. */
10
10
  readonly providers: ReadonlyArray<string>;
11
+ /** The kind of each channel, as `chatKind` gives it; the name by default. */
12
+ readonly kindOf?: (channel: string) => string | undefined;
11
13
  readonly chatHistory?: ChatArchiveTransport;
12
14
  readonly attribution?: ChatAttributionSettings;
13
15
  }): {
14
16
  list: (input: typeof ChatList.Type) => Effect.Effect<{
15
17
  items: {
18
+ external_id: string;
19
+ attribution: string | null;
20
+ kind?: "telegram" | "slack" | "whatsapp" | "email" | "custom" | undefined;
16
21
  id: string;
17
22
  title: string;
18
23
  provider: string;
19
- external_id: string;
20
- attribution: string | null;
21
24
  }[];
22
25
  next_cursor: string | null;
23
26
  }, ActionRejected | PermissionDenied | import("../../errors.js").NotFound, CurrentPrincipal>;
@@ -1,3 +1,4 @@
1
+ import { isChatKind } from "../../chat-channel.js";
1
2
  import { Effect } from "effect";
2
3
  import { ActionRejected, PermissionDenied } from "../../errors.js";
3
4
  import { isAllowed } from "../../permissions.js";
@@ -5,16 +6,20 @@ import { CurrentPrincipal } from "../authentication.js";
5
6
  import { currentCaller } from "../caller-context.js";
6
7
  import { chatAttribution } from "./attribution.js";
7
8
  import { chatResolver, groupChatKey, isChatMember } from "./resolve.js";
8
- /** The providers whose archived chats are keyed by the chat a destination names. */
9
- const HISTORY_PROVIDERS = ["telegram"];
9
+ /** The kinds of channel whose archived chats are keyed by the chat a destination names. */
10
+ const HISTORY_KINDS = new Set(["telegram"]);
10
11
  export function chatReads(backend, options) {
11
12
  const { providers, chatHistory, attribution } = options;
13
+ const kindOf = options.kindOf ?? ((channel) => channel);
14
+ const history = [
15
+ ...new Set(["telegram", ...providers.filter((name) => HISTORY_KINDS.has(kindOf(name) ?? ""))]),
16
+ ];
12
17
  return {
13
18
  list: (input) => Effect.gen(function* () {
14
19
  const principal = yield* CurrentPrincipal;
15
20
  const caller = yield* currentCaller;
16
21
  const query = input.query?.toLowerCase();
17
- const items = (yield* chatResolver(backend, principal, providers).list(input.chat))
22
+ const items = (yield* chatResolver(backend, principal, providers, { kindOf }).list(input.chat))
18
23
  .filter((item) => query === undefined || item.title.toLowerCase().includes(query))
19
24
  .sort((a, b) => a.id.localeCompare(b.id));
20
25
  const user = yield* backend.get({ entity: "user", id: principal.id });
@@ -25,13 +30,19 @@ export function chatReads(backend, options) {
25
30
  });
26
31
  }
27
32
  const limit = input.limit ?? 50;
28
- const selected = items.slice(start, start + limit).map((item) => ({
29
- id: item.id,
30
- title: item.title,
31
- provider: item.provider,
32
- external_id: item.external_id,
33
- attribution: chatAttribution(caller, String(user.name), attribution),
34
- }));
33
+ const selected = items.slice(start, start + limit).map((item) => {
34
+ // The kind of the channel the chat is on, so that a reader renders a post to a
35
+ // channel of another name, such as sales_whatsapp, as that kind does.
36
+ const kind = kindOf(item.provider);
37
+ return {
38
+ id: item.id,
39
+ title: item.title,
40
+ provider: item.provider,
41
+ ...(isChatKind(kind) ? { kind } : {}),
42
+ external_id: item.external_id,
43
+ attribution: chatAttribution(caller, String(user.name), attribution),
44
+ };
45
+ });
35
46
  return {
36
47
  items: selected,
37
48
  next_cursor: start + limit < items.length ? selected.at(-1).id : null,
@@ -42,11 +53,12 @@ export function chatReads(backend, options) {
42
53
  if (principal.kind !== "member") {
43
54
  return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
44
55
  }
45
- // History reads Telegram chats only. Other channels archive a chat under their
46
- // session's address with private coordinates, not under the chat a destination names, so
47
- // their history would be incomplete until the archive keys them the same way.
48
- const target = yield* chatResolver(backend, principal, HISTORY_PROVIDERS, {
56
+ // History reads the chats of Telegram channels only. Other channels archive a chat under
57
+ // their session's address with private coordinates, not under the chat a destination
58
+ // names, so their history would be incomplete until the archive keys them the same way.
59
+ const target = yield* chatResolver(backend, principal, history, {
49
60
  memberGroups: true,
61
+ kindOf,
50
62
  }).resolve(input.chat);
51
63
  // A group's members read its history, as they read its attachments; agent_chat:read reads
52
64
  // every group. A private chat is read only by its participant.
@@ -26,12 +26,17 @@ export declare function isChatMember(backend: OntologyBackend["Service"], princi
26
26
  */
27
27
  export declare function withChatMembership(transport: ChatArchiveTransport, backend: OntologyBackend["Service"]): ChatArchiveTransport;
28
28
  /**
29
- * Resolves the chats of `providers`: their group chats in the registry, and each member's private
30
- * chat on each provider they have a live identity on, `<provider>:private:<member id>`.
29
+ * Resolves the chats of `providers`, the agent's channels by name: their group chats in the
30
+ * registry, and each member's private chat on each channel whose kind they have a live identity
31
+ * on, `<channel>:private:<member id>`. People are not per channel: one identity of a kind reaches
32
+ * the member on every channel of that kind. A workspace channel's accounts are its own
33
+ * (`channel:<name>`).
31
34
  */
32
35
  export declare function chatResolver(backend: OntologyBackend["Service"], principal: Principal, providers: ReadonlyArray<string>, options?: {
33
36
  /** Also resolve the group chats a member is in without chat read or post permission. */
34
37
  readonly memberGroups?: boolean;
38
+ /** The kind of each channel, whose identities reach its private chats; the name by default. */
39
+ readonly kindOf?: (channel: string) => string | undefined;
35
40
  }): {
36
41
  list: (chat?: string) => Effect.Effect<Destination[], ActionRejected | PermissionDenied, never>;
37
42
  resolve: (chat: string) => Effect.Effect<Destination, ActionRejected | PermissionDenied, never>;