@segmentstream/ontology 0.143.0 → 0.145.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.
- package/CHANGELOG.md +27 -0
- package/dist/agent-chat.d.ts +7 -0
- package/dist/agent-chat.js +6 -1
- package/dist/chat.d.ts +30 -0
- package/dist/chat.js +40 -0
- package/dist/metric-routes.js +3 -2
- package/dist/migrate/apply.js +15 -8
- package/dist/replicated-entities.d.ts +14 -0
- package/dist/replicated-entities.js +20 -0
- package/dist/replication/baseline.js +2 -1
- package/dist/replication/legacy-baseline.js +2 -1
- package/dist/replication/model.d.ts +4 -1
- package/dist/replication/model.js +8 -4
- package/dist/replication/schema.js +2 -3
- package/dist/service/chat/delivery.d.ts +1 -1
- package/dist/service/chat/delivery.js +34 -8
- package/dist/service/chat/idempotency.d.ts +4 -2
- package/dist/service/chat/idempotency.js +4 -2
- package/dist/service/chat/providers/provider.d.ts +16 -2
- package/dist/service/chat/providers/provider.js +10 -0
- package/dist/service/chat/providers/slack.d.ts +7 -0
- package/dist/service/chat/providers/slack.js +29 -2
- package/dist/service/chat/providers/telegram.d.ts +5 -0
- package/dist/service/chat/providers/telegram.js +19 -2
- package/dist/service/chat/providers/whatsapp.d.ts +13 -0
- package/dist/service/chat/providers/whatsapp.js +68 -5
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,32 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.145.0
|
|
4
|
+
|
|
5
|
+
`agent_chat.send` takes `buttons` under a text: rows of links (`{ text, url }`) and workspace
|
|
6
|
+
buttons (`{ text, token }`, a token of at most 60 UTF-8 bytes), whose press calls the workspace's
|
|
7
|
+
button action with `{ token }` as the member who pressed it. Each channel lays them out its own way:
|
|
8
|
+
an inline keyboard in Telegram, rows of buttons under a Markdown block in Slack, and on WhatsApp an
|
|
9
|
+
interactive message with up to three workspace buttons (labels of at most 20 characters, each its
|
|
10
|
+
own) or one link, under at most 1,024 characters.
|
|
11
|
+
|
|
12
|
+
A channel that cannot show the buttons as given refuses the message with
|
|
13
|
+
`refusal: "buttons_unsupported"` before its key is reserved, so the key stays free; nothing is cut.
|
|
14
|
+
The key binds the buttons. The chat's history keeps the text with the buttons after it, so a card a
|
|
15
|
+
workflow sends with buttons is part of the conversation the agent reads, in every channel. A
|
|
16
|
+
template has its own buttons and takes none.
|
|
17
|
+
|
|
18
|
+
## 0.144.0
|
|
19
|
+
|
|
20
|
+
The built-in entities `agent_chat`, `agent_review` and `app_feedback` replicate to the warehouse
|
|
21
|
+
as a workspace's own stored entities do: metric queries reach them as stored entities, such as a
|
|
22
|
+
visit metric grouped by its chat's `provider` through `rel.one(AgentChat, { on: { chat: "key" } })`,
|
|
23
|
+
and warehouse models can join them. The built-in `user` and `user_identity` stay in the ontology.
|
|
24
|
+
|
|
25
|
+
A migration applies what its release replicates even when the ontology did not change: when the
|
|
26
|
+
source's projection lacks an entity the release replicates, the migration installs its capture and
|
|
27
|
+
a scoped repair copies that entity's records alone. Existing workspaces start replicating these
|
|
28
|
+
entities at their next deployment.
|
|
29
|
+
|
|
3
30
|
## 0.143.0
|
|
4
31
|
|
|
5
32
|
Roles can grant the agent's web search: `agent_tool:web_search`. It gives a caller the agent's
|
package/dist/agent-chat.d.ts
CHANGED
|
@@ -85,6 +85,13 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
|
|
|
85
85
|
readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
|
|
86
86
|
}>>;
|
|
87
87
|
readonly replyTo: Schema.optionalKey<Schema.String>;
|
|
88
|
+
readonly buttons: Schema.optionalKey<Schema.$Array<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
|
|
89
|
+
readonly text: Schema.String;
|
|
90
|
+
readonly url: Schema.String;
|
|
91
|
+
}>, Schema.Struct<{
|
|
92
|
+
readonly text: Schema.String;
|
|
93
|
+
readonly token: Schema.String;
|
|
94
|
+
}>]>>>>;
|
|
88
95
|
readonly idempotencyKey: Schema.String;
|
|
89
96
|
}>, {
|
|
90
97
|
readonly status: "sent" | "uncertain";
|
package/dist/agent-chat.js
CHANGED
|
@@ -229,7 +229,12 @@ export const AgentChat = entity("agent_chat", {
|
|
|
229
229
|
"(on WhatsApp the person last wrote more than 24 hours ago), recipient_unreachable or " +
|
|
230
230
|
"recipient_opted_out. On WhatsApp, template sends an approved template in place of text, " +
|
|
231
231
|
"which reaches a person outside the 24 hours, with its body's, header's and buttons' " +
|
|
232
|
-
"values; give exactly one of text and template."
|
|
232
|
+
"values; give exactly one of text and template. buttons puts rows of buttons under a " +
|
|
233
|
+
"text: links ({ text, url }) and workspace buttons ({ text, token }), whose press calls the " +
|
|
234
|
+
"workspace's button action with { token } as the member who pressed it. A channel that " +
|
|
235
|
+
"cannot show them as given refuses the message with refusal buttons_unsupported before " +
|
|
236
|
+
"spending the key: WhatsApp shows one link, or up to three workspace buttons with labels of " +
|
|
237
|
+
"at most 20 characters, under at most 1,024 characters.",
|
|
233
238
|
input: ChatSendInput,
|
|
234
239
|
hints: { destructive: false, irreversible: true, idempotent: true },
|
|
235
240
|
connections: [],
|
package/dist/chat.d.ts
CHANGED
|
@@ -65,6 +65,29 @@ export declare const ChatTemplate: Schema.Struct<{
|
|
|
65
65
|
readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
|
|
66
66
|
}>;
|
|
67
67
|
export type ChatTemplate = typeof ChatTemplate.Type;
|
|
68
|
+
/** The most UTF-8 bytes of a workspace button's token: what fits Telegram's callback data. */
|
|
69
|
+
export declare const CHAT_BUTTON_TOKEN_BYTES = 60;
|
|
70
|
+
/**
|
|
71
|
+
* A button under a message the agent sends: a link it opens, by an https URL, or a workspace button,
|
|
72
|
+
* whose press calls the workspace's button action as the member who pressed it, with this token.
|
|
73
|
+
*/
|
|
74
|
+
export declare const ChatButton: Schema.Union<readonly [Schema.Struct<{
|
|
75
|
+
readonly text: Schema.String;
|
|
76
|
+
readonly url: Schema.String;
|
|
77
|
+
}>, Schema.Struct<{
|
|
78
|
+
readonly text: Schema.String;
|
|
79
|
+
readonly token: Schema.String;
|
|
80
|
+
}>]>;
|
|
81
|
+
export type ChatButton = typeof ChatButton.Type;
|
|
82
|
+
/** A message's buttons by row, as the person sees them; each channel lays them out its own way. */
|
|
83
|
+
export declare const ChatButtonRows: Schema.$Array<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
|
|
84
|
+
readonly text: Schema.String;
|
|
85
|
+
readonly url: Schema.String;
|
|
86
|
+
}>, Schema.Struct<{
|
|
87
|
+
readonly text: Schema.String;
|
|
88
|
+
readonly token: Schema.String;
|
|
89
|
+
}>]>>>;
|
|
90
|
+
export type ChatButtonRows = typeof ChatButtonRows.Type;
|
|
68
91
|
/** What `agent_chat.send` takes: a post's text, or on WhatsApp an approved template instead. */
|
|
69
92
|
export declare const ChatSendInput: Schema.Struct<{
|
|
70
93
|
readonly chat: Schema.String;
|
|
@@ -88,6 +111,13 @@ export declare const ChatSendInput: Schema.Struct<{
|
|
|
88
111
|
readonly buttons: Schema.optionalKey<Schema.$Record<Schema.String, Schema.String>>;
|
|
89
112
|
}>>;
|
|
90
113
|
readonly replyTo: Schema.optionalKey<Schema.String>;
|
|
114
|
+
readonly buttons: Schema.optionalKey<Schema.$Array<Schema.$Array<Schema.Union<readonly [Schema.Struct<{
|
|
115
|
+
readonly text: Schema.String;
|
|
116
|
+
readonly url: Schema.String;
|
|
117
|
+
}>, Schema.Struct<{
|
|
118
|
+
readonly text: Schema.String;
|
|
119
|
+
readonly token: Schema.String;
|
|
120
|
+
}>]>>>>;
|
|
91
121
|
readonly idempotencyKey: Schema.String;
|
|
92
122
|
}>;
|
|
93
123
|
export type ChatSendInput = typeof ChatSendInput.Type;
|
package/dist/chat.js
CHANGED
|
@@ -50,6 +50,42 @@ export const ChatTemplate = Schema.Struct({
|
|
|
50
50
|
"returns when tapped.",
|
|
51
51
|
})),
|
|
52
52
|
});
|
|
53
|
+
/** The most UTF-8 bytes of a workspace button's token: what fits Telegram's callback data. */
|
|
54
|
+
export const CHAT_BUTTON_TOKEN_BYTES = 60;
|
|
55
|
+
/** A button's label: one line, as the person reads it. Each channel bounds it further. */
|
|
56
|
+
const ButtonLabel = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(75), Schema.makeFilter((value) => value === value.trim() && !/[\p{Cc}\p{Zl}\p{Zp}]/u.test(value)
|
|
57
|
+
? undefined
|
|
58
|
+
: "Expected one line of text, without spaces around it"));
|
|
59
|
+
/**
|
|
60
|
+
* A button under a message the agent sends: a link it opens, by an https URL, or a workspace button,
|
|
61
|
+
* whose press calls the workspace's button action as the member who pressed it, with this token.
|
|
62
|
+
*/
|
|
63
|
+
export const ChatButton = Schema.Union([
|
|
64
|
+
Schema.Struct({
|
|
65
|
+
text: ButtonLabel,
|
|
66
|
+
url: Schema.String.check(Schema.isMaxLength(2048), Schema.makeFilter((value) => {
|
|
67
|
+
try {
|
|
68
|
+
return new URL(value).protocol === "https:" ? undefined : "Expected an https URL";
|
|
69
|
+
}
|
|
70
|
+
catch {
|
|
71
|
+
return "Expected an https URL";
|
|
72
|
+
}
|
|
73
|
+
})).annotate({ description: "The https link the button opens." }),
|
|
74
|
+
}),
|
|
75
|
+
Schema.Struct({
|
|
76
|
+
text: ButtonLabel,
|
|
77
|
+
token: Schema.String.check(Schema.makeFilter((value) => value !== "" &&
|
|
78
|
+
new TextEncoder().encode(value).byteLength <= CHAT_BUTTON_TOKEN_BYTES &&
|
|
79
|
+
!/\p{Cc}/u.test(value)
|
|
80
|
+
? undefined
|
|
81
|
+
: `Expected 1 to ${CHAT_BUTTON_TOKEN_BYTES} UTF-8 bytes without control characters`)).annotate({
|
|
82
|
+
description: "What the workspace's button action receives as { token } when the button is pressed, " +
|
|
83
|
+
"such as the record and what to do with it.",
|
|
84
|
+
}),
|
|
85
|
+
}),
|
|
86
|
+
]);
|
|
87
|
+
/** A message's buttons by row, as the person sees them; each channel lays them out its own way. */
|
|
88
|
+
export const ChatButtonRows = Schema.Array(Schema.Array(ChatButton).check(Schema.isMinLength(1), Schema.isMaxLength(8))).check(Schema.isMinLength(1), Schema.isMaxLength(10));
|
|
53
89
|
/** What `agent_chat.send` takes: a post's text, or on WhatsApp an approved template instead. */
|
|
54
90
|
export const ChatSendInput = Schema.Struct({
|
|
55
91
|
chat: Identifier,
|
|
@@ -61,6 +97,10 @@ export const ChatSendInput = Schema.Struct({
|
|
|
61
97
|
"more than 24 hours ago.",
|
|
62
98
|
})),
|
|
63
99
|
replyTo: Schema.optionalKey(Identifier),
|
|
100
|
+
buttons: Schema.optionalKey(ChatButtonRows.annotate({
|
|
101
|
+
description: "Buttons under the text, by row: links, and workspace buttons whose press calls the " +
|
|
102
|
+
"workspace's button action. A channel that cannot show them as given refuses the message.",
|
|
103
|
+
})),
|
|
64
104
|
idempotencyKey: Identifier,
|
|
65
105
|
});
|
|
66
106
|
export const ChatPostResult = Schema.Struct({
|
package/dist/metric-routes.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { replicatesRecords } from "./replicated-entities.js";
|
|
1
2
|
import { User } from "./user.js";
|
|
2
3
|
/** A route follows at most this many to-one relationships. */
|
|
3
4
|
export const MAXIMUM_HOPS = 2;
|
|
@@ -114,9 +115,9 @@ class RouteCatalog {
|
|
|
114
115
|
modelMetric(name) {
|
|
115
116
|
return this.metrics.get(name) ?? refuse(unknownModelMetricMessage(name));
|
|
116
117
|
}
|
|
117
|
-
/** Declared properties, and the `id` of a
|
|
118
|
+
/** Declared properties, and the `id` of a replicated entity, which its replication view carries. */
|
|
118
119
|
hasProperty(entity, property) {
|
|
119
|
-
const stored = entity
|
|
120
|
+
const stored = replicatesRecords(entity);
|
|
120
121
|
return (entity.properties.some((candidate) => candidate.name === property) ||
|
|
121
122
|
(stored && property === "id"));
|
|
122
123
|
}
|
package/dist/migrate/apply.js
CHANGED
|
@@ -9,6 +9,7 @@ import { isNoopMigration, NO_RETAINED_STORAGE, RetainedStorage, retainedStorageJ
|
|
|
9
9
|
import { planMigration } from "./plan.js";
|
|
10
10
|
import { REPLICATION_DDL, REPLICATION_SCHEMA_VERSION, replicationEntityDdl, } from "../replication/schema.js";
|
|
11
11
|
import { lockReplicationLifecycle, lockReplicationSchema } from "../replication/transaction.js";
|
|
12
|
+
import { replicatesRecords } from "../replicated-entities.js";
|
|
12
13
|
import { prepareReplicationBaseline } from "../replication/baseline.js";
|
|
13
14
|
import { randomUUID } from "node:crypto";
|
|
14
15
|
import { recordWorkflowCatalog } from "../runtime/workflow-admission.js";
|
|
@@ -206,6 +207,14 @@ const runStep = (sql, step, stepIndex) => Effect.forEach(step.sql, (statement) =
|
|
|
206
207
|
const reconcileWorkflows = (plan, sql, workspaceId) => workspaceId === undefined
|
|
207
208
|
? Effect.void
|
|
208
209
|
: reconcileWorkflowUsers(principalsOntology(plan.target), { workspaceId }).pipe(Effect.provideService(SqlClient.SqlClient, sql));
|
|
210
|
+
/**
|
|
211
|
+
* Whether a source's recorded projection holds every entity this release replicates. One recorded
|
|
212
|
+
* before the release replicated an entity, such as a built-in entity, is not current: the
|
|
213
|
+
* migration installs its capture and copies it, though the ontology did not change.
|
|
214
|
+
*/
|
|
215
|
+
function replicatesAll(manifest, recorded) {
|
|
216
|
+
return resolveReplicationSelection(manifest).every((item) => recorded !== null && Object.hasOwn(recorded, item.entityId));
|
|
217
|
+
}
|
|
209
218
|
/**
|
|
210
219
|
* Applies a plan. Non-transactional steps run first, each statement on its own; they only add enum
|
|
211
220
|
* values and build indexes concurrently, and are safe to run again after a failure. Every other step
|
|
@@ -246,7 +255,8 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
|
|
|
246
255
|
const targetPresent = presence.targets && isNoopMigration(plan)
|
|
247
256
|
? "EXISTS (SELECT 1 FROM _ontology_replication_targets WHERE generation = active_generation)"
|
|
248
257
|
: "false";
|
|
249
|
-
const [state] = yield* sql.unsafe(`SELECT version, enabled, ${targetPresent} AS target_present
|
|
258
|
+
const [state] = yield* sql.unsafe(`SELECT version, enabled, ${targetPresent} AS target_present, selection
|
|
259
|
+
FROM _ontology_replication WHERE id`);
|
|
250
260
|
if (state?.enabled &&
|
|
251
261
|
state.version >= 6 &&
|
|
252
262
|
(yield* requestShadowSupersession(sql, plan.target.hash))) {
|
|
@@ -263,7 +273,7 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
|
|
|
263
273
|
}
|
|
264
274
|
if (isNoopMigration(plan) &&
|
|
265
275
|
state?.version === REPLICATION_SCHEMA_VERSION &&
|
|
266
|
-
(!state.enabled || state.target_present)) {
|
|
276
|
+
(!state.enabled || (state.target_present && replicatesAll(plan.target, state.selection)))) {
|
|
267
277
|
if (options.workspaceId !== undefined || syncsIdentities(plan)) {
|
|
268
278
|
// Under the migration lock, and only while the catalog still records this target.
|
|
269
279
|
yield* sql.withTransaction(Effect.gen(function* () {
|
|
@@ -340,11 +350,9 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
|
|
|
340
350
|
],
|
|
341
351
|
});
|
|
342
352
|
}
|
|
353
|
+
// A runtime-only upgrade adopts the projection this release replicates as well, such as
|
|
354
|
+
// the built-in entities it replicates; only a projection that changed is scanned again.
|
|
343
355
|
active = target;
|
|
344
|
-
// A runtime-only upgrade retains an existing explicit projection.
|
|
345
|
-
if (target?.manifest.hash === plan.target.hash) {
|
|
346
|
-
refresh = target.selection;
|
|
347
|
-
}
|
|
348
356
|
// Both writer protocols are fenced. Capture and schema changes commit on one stream.
|
|
349
357
|
yield* sql.unsafe("UPDATE _ontology_replication SET enabled = false WHERE id");
|
|
350
358
|
}
|
|
@@ -363,8 +371,7 @@ export const applyMigration = (plan, options) => Effect.gen(function* () {
|
|
|
363
371
|
}
|
|
364
372
|
if (plan.steps.some((step) => step.kind === "dropEntities")) {
|
|
365
373
|
for (const entity of previousManifest?.entities ?? []) {
|
|
366
|
-
if (
|
|
367
|
-
!entity.source &&
|
|
374
|
+
if (replicatesRecords(entity) &&
|
|
368
375
|
!plan.target.entities.some((item) => item.id === entity.id)) {
|
|
369
376
|
yield* retainReplicationHistory(sql, historyTableName(entity.name));
|
|
370
377
|
}
|
|
@@ -0,0 +1,14 @@
|
|
|
1
|
+
import type { EntityManifest } from "./manifest.js";
|
|
2
|
+
/**
|
|
3
|
+
* The built-in entities whose records replicate to the warehouse as the workspace's own stored
|
|
4
|
+
* entities do: the chats the agent is in, the replies held for review and the feedback members send
|
|
5
|
+
* the builders, which metrics and warehouse models join to the workspace's data. The user and their
|
|
6
|
+
* sign-in identities stay in the ontology: no metric route passes through the user
|
|
7
|
+
* (`metric-routes.ts`), and an identity is how a person signs in, nothing a query counts.
|
|
8
|
+
*/
|
|
9
|
+
export declare const REPLICATED_BUILT_IN_ENTITIES: ReadonlySet<string>;
|
|
10
|
+
/**
|
|
11
|
+
* Whether an entity's records replicate: every stored entity the workspace declares, and the
|
|
12
|
+
* built-in entities above. A warehouse-backed entity is the warehouse's already.
|
|
13
|
+
*/
|
|
14
|
+
export declare function replicatesRecords(entity: Pick<EntityManifest, "name" | "builtIn" | "source">): boolean;
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The built-in entities whose records replicate to the warehouse as the workspace's own stored
|
|
3
|
+
* entities do: the chats the agent is in, the replies held for review and the feedback members send
|
|
4
|
+
* the builders, which metrics and warehouse models join to the workspace's data. The user and their
|
|
5
|
+
* sign-in identities stay in the ontology: no metric route passes through the user
|
|
6
|
+
* (`metric-routes.ts`), and an identity is how a person signs in, nothing a query counts.
|
|
7
|
+
*/
|
|
8
|
+
export const REPLICATED_BUILT_IN_ENTITIES = new Set([
|
|
9
|
+
"agent_chat",
|
|
10
|
+
"agent_review",
|
|
11
|
+
"app_feedback",
|
|
12
|
+
]);
|
|
13
|
+
/**
|
|
14
|
+
* Whether an entity's records replicate: every stored entity the workspace declares, and the
|
|
15
|
+
* built-in entities above. A warehouse-backed entity is the warehouse's already.
|
|
16
|
+
*/
|
|
17
|
+
export function replicatesRecords(entity) {
|
|
18
|
+
return (entity.source === undefined &&
|
|
19
|
+
(!entity.builtIn || REPLICATED_BUILT_IN_ENTITIES.has(entity.name)));
|
|
20
|
+
}
|
|
@@ -6,6 +6,7 @@ import { REPLICATION_RECORD_BYTES, validateReplicationSelection, } from "./model
|
|
|
6
6
|
import { REPLICATION_TARGET_FILLS, REPLICATION_TARGET_METADATA, snapshotExpression, } from "./schema.js";
|
|
7
7
|
import { lockReplicationLifecycle, shareReplicationLifecycle } from "./transaction.js";
|
|
8
8
|
import { TARGET_MANIFEST_HASH, storedTargets } from "./stored-manifests.js";
|
|
9
|
+
import { replicatesRecords } from "../replicated-entities.js";
|
|
9
10
|
import { initialReplicationLineage } from "./lineage.js";
|
|
10
11
|
import { scheduleReplicationScans, replicationScanScopes, advanceReplicationScan, } from "./scans.js";
|
|
11
12
|
/** An initial scan cannot be created with the requested state or record projection. */
|
|
@@ -44,7 +45,7 @@ export const prepareReplicationBaseline = (sql, input) => sql.withTransaction(Ef
|
|
|
44
45
|
});
|
|
45
46
|
// Drain raw/pre-upgrade writers only at enablement; online pages never lock business tables.
|
|
46
47
|
const tables = input.manifest.entities
|
|
47
|
-
.filter(
|
|
48
|
+
.filter(replicatesRecords)
|
|
48
49
|
.flatMap((e) => [
|
|
49
50
|
tableName(e.name),
|
|
50
51
|
...e.relationships
|
|
@@ -4,6 +4,7 @@ import { joinColumnNames, joinTableName, quoteIdentifier as qi, quoteLiteral as
|
|
|
4
4
|
import { REPLICATION_RECORD_BYTES, validateReplicationSelection, } from "./model.js";
|
|
5
5
|
import { snapshotExpression } from "./schema.js";
|
|
6
6
|
import { createReplicationBaseline as createCurrentBaseline } from "./baseline.js";
|
|
7
|
+
import { replicatesRecords } from "../replicated-entities.js";
|
|
7
8
|
import { lockReplicationLifecycle } from "./transaction.js";
|
|
8
9
|
/** An initial snapshot cannot be created with the requested state or record projection. */
|
|
9
10
|
export class ReplicationBaselineFailed extends Schema.TaggedError()("ReplicationBaselineFailed", { message: Schema.String, cause: Schema.optionalKey(Schema.Unknown) }) {
|
|
@@ -35,7 +36,7 @@ export const createReplicationBaseline = (sql, input) => sql.withTransaction(Eff
|
|
|
35
36
|
});
|
|
36
37
|
// Drain older SDK transactions that started before the compatibility fence was enabled.
|
|
37
38
|
const tables = manifest.entities
|
|
38
|
-
.filter(
|
|
39
|
+
.filter(replicatesRecords)
|
|
39
40
|
.flatMap((e) => [
|
|
40
41
|
tableName(e.name),
|
|
41
42
|
...e.relationships
|
|
@@ -12,7 +12,10 @@ export interface ReplicationSelection {
|
|
|
12
12
|
export type ReplicationFills = Readonly<Record<string, Readonly<Record<string, unknown>>>>;
|
|
13
13
|
/** System fields and relationship keys always replicate. Only declared properties can opt out. */
|
|
14
14
|
export declare function replicatedFields(entity: EntityManifest): import("../query.js").QueryField[];
|
|
15
|
-
/**
|
|
15
|
+
/**
|
|
16
|
+
* Every stored entity the workspace declares, the built-in entities that replicate, and their
|
|
17
|
+
* relationships to one another replicate.
|
|
18
|
+
*/
|
|
16
19
|
export declare function resolveReplicationSelection(manifest: OntologyManifest): ReadonlyArray<ReplicationSelection>;
|
|
17
20
|
export interface ReplicationEvent {
|
|
18
21
|
readonly event_id: string;
|
|
@@ -1,13 +1,17 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { queryFields } from "../query.js";
|
|
3
|
+
import { replicatesRecords } from "../replicated-entities.js";
|
|
3
4
|
/** System fields and relationship keys always replicate. Only declared properties can opt out. */
|
|
4
5
|
export function replicatedFields(entity) {
|
|
5
6
|
const excluded = new Set(entity.properties.filter((p) => p.excludeFromReplication).map((p) => p.name));
|
|
6
7
|
return queryFields(entity).filter((field) => !excluded.has(field.name));
|
|
7
8
|
}
|
|
8
|
-
/**
|
|
9
|
+
/**
|
|
10
|
+
* Every stored entity the workspace declares, the built-in entities that replicate, and their
|
|
11
|
+
* relationships to one another replicate.
|
|
12
|
+
*/
|
|
9
13
|
export function resolveReplicationSelection(manifest) {
|
|
10
|
-
const entities = manifest.entities.filter(
|
|
14
|
+
const entities = manifest.entities.filter(replicatesRecords);
|
|
11
15
|
const selection = entities.map((entity) => ({
|
|
12
16
|
entityId: entity.id,
|
|
13
17
|
fields: replicatedFields(entity).map((field) => field.name),
|
|
@@ -37,7 +41,7 @@ export function validateReplicationSelection(manifest, selection) {
|
|
|
37
41
|
};
|
|
38
42
|
for (const item of selection) {
|
|
39
43
|
const entity = manifest.entities.find((e) => e.id === item.entityId);
|
|
40
|
-
if (!entity || entity
|
|
44
|
+
if (!entity || !replicatesRecords(entity)) {
|
|
41
45
|
throw new Error(`Only stored business entities can be replicated: ${item.entityId}.`);
|
|
42
46
|
}
|
|
43
47
|
addView(entity.name);
|
|
@@ -50,7 +54,7 @@ export function validateReplicationSelection(manifest, selection) {
|
|
|
50
54
|
const target = manifest.entities.find((e) => e.name === relationship?.to);
|
|
51
55
|
if (relationship?.cardinality !== "many" ||
|
|
52
56
|
!target ||
|
|
53
|
-
target
|
|
57
|
+
!replicatesRecords(target) ||
|
|
54
58
|
!selection.some((s) => s.entityId === target.id)) {
|
|
55
59
|
throw new Error(`Replication of ${entity.name}.${name} requires both business entities.`);
|
|
56
60
|
}
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import { columnName, historyTableName, quoteIdentifier as qi, quoteLiteral as ql, relationshipColumnName, SYSTEM_COLUMNS, tableName, joinTableName, } from "../migrate/storage.js";
|
|
3
|
+
import { replicatesRecords } from "../replicated-entities.js";
|
|
3
4
|
import { replicatedFields, REPLICATION_RECORD_BYTES } from "./model.js";
|
|
4
5
|
import { SHADOW_REPLICATION_DDL, SHADOW_CONTROL_JOBS_DDL, SHADOW_SOURCE_REPLACEMENTS_DDL, } from "./shadow-schema.js";
|
|
5
6
|
export const REPLICATION_SCHEMA_VERSION = 6;
|
|
@@ -138,9 +139,7 @@ export function snapshotExpression(entity, alias) {
|
|
|
138
139
|
}
|
|
139
140
|
/** History is the durable source. Triggers also reject old writers while capture is enabled. */
|
|
140
141
|
export function replicationEntityDdl(manifest, previous) {
|
|
141
|
-
return manifest.entities
|
|
142
|
-
.filter((e) => e.source === undefined && !e.builtIn)
|
|
143
|
-
.flatMap((entity) => {
|
|
142
|
+
return manifest.entities.filter(replicatesRecords).flatMap((entity) => {
|
|
144
143
|
const old = previous?.entities.find((item) => item.id === entity.id);
|
|
145
144
|
const compatible = {
|
|
146
145
|
...entity,
|
|
@@ -9,7 +9,7 @@ import type { DeliveryArchive } from "./archive.js";
|
|
|
9
9
|
import type { RuntimeChatEnvelope } from "./envelope.js";
|
|
10
10
|
import type { ChatArchiveTransport } from "../agent/chat-archive.js";
|
|
11
11
|
import { type Destination } from "./resolve.js";
|
|
12
|
-
import type
|
|
12
|
+
import { type AgentChannelTransport } from "./providers/provider.js";
|
|
13
13
|
import { type HistoryArchive } from "./history-import.js";
|
|
14
14
|
export type ChatDeliveryFactory = (input: {
|
|
15
15
|
readonly backend: OntologyBackend["Service"];
|
|
@@ -10,6 +10,7 @@ import { deliveryRequester } from "./attribution.js";
|
|
|
10
10
|
import { deliveryFingerprint, deliveryKeyDigest, deliveryScopeDigest } from "./idempotency.js";
|
|
11
11
|
import { channelProvider, chatConnection, chatKind, listedChatProviders, } from "./providers/index.js";
|
|
12
12
|
import { chatResolver } from "./resolve.js";
|
|
13
|
+
import { buttonLines } from "./providers/provider.js";
|
|
13
14
|
import { reviewSender } from "./review-delivery.js";
|
|
14
15
|
import { chatPeopleQuery, historyImporter } from "./history-import.js";
|
|
15
16
|
import { reviewReviser } from "./review-revision.js";
|
|
@@ -62,12 +63,19 @@ chats) {
|
|
|
62
63
|
*/
|
|
63
64
|
const check = (input, approved = true, asAgent = false) => Effect.gen(function* () {
|
|
64
65
|
const template = "template" in input ? input.template : undefined;
|
|
66
|
+
const buttons = "buttons" in input ? input.buttons : undefined;
|
|
65
67
|
// A message is text, or on WhatsApp a template the agent sends; a post is always text.
|
|
66
68
|
if ((input.text === undefined) === (template === undefined) || (template && !asAgent)) {
|
|
67
69
|
return yield* new ActionRejected({
|
|
68
70
|
message: "Give exactly one of text and template.",
|
|
69
71
|
});
|
|
70
72
|
}
|
|
73
|
+
// An approved template has its own buttons, given by their values.
|
|
74
|
+
if (buttons !== undefined && (template !== undefined || !asAgent)) {
|
|
75
|
+
return yield* new ActionRejected({
|
|
76
|
+
message: "Buttons go under a text the agent sends; a template's are its own.",
|
|
77
|
+
});
|
|
78
|
+
}
|
|
71
79
|
const permission = asAgent ? "agent_chat:send" : "agent_chat:post_message";
|
|
72
80
|
if (!isAllowed(permission, context.principal)) {
|
|
73
81
|
return yield* new PermissionDenied({
|
|
@@ -256,6 +264,18 @@ chats) {
|
|
|
256
264
|
plainText.length > provider.limit) {
|
|
257
265
|
return yield* invalid();
|
|
258
266
|
}
|
|
267
|
+
// Buttons the channel cannot show as given are refused before the key is reserved.
|
|
268
|
+
if (buttons !== undefined) {
|
|
269
|
+
const refused = provider.refuseButtons === undefined
|
|
270
|
+
? "This chat's channel shows no buttons."
|
|
271
|
+
: provider.refuseButtons(buttons, finalText);
|
|
272
|
+
if (refused !== undefined) {
|
|
273
|
+
return yield* new ActionRejected({
|
|
274
|
+
message: `${refused} Nothing was sent.`,
|
|
275
|
+
refusal: "buttons_unsupported",
|
|
276
|
+
});
|
|
277
|
+
}
|
|
278
|
+
}
|
|
259
279
|
const preview = { ...destination, text, finalText };
|
|
260
280
|
if (context.caller.kind === "runtime" && approved) {
|
|
261
281
|
const envelope = context.envelope;
|
|
@@ -284,7 +304,8 @@ chats) {
|
|
|
284
304
|
provider,
|
|
285
305
|
inbox,
|
|
286
306
|
preview,
|
|
287
|
-
|
|
307
|
+
buttons,
|
|
308
|
+
fingerprint: deliveryFingerprint(preview, requester, undefined, buttons),
|
|
288
309
|
compose: Effect.succeed({
|
|
289
310
|
preview,
|
|
290
311
|
payload: undefined,
|
|
@@ -471,7 +492,9 @@ chats) {
|
|
|
471
492
|
/** One delivery: posted with its requester's attribution, or sent as the agent without it. */
|
|
472
493
|
function deliver(input, asAgent) {
|
|
473
494
|
return Effect.gen(function* () {
|
|
474
|
-
const
|
|
495
|
+
const checked = yield* check(input, true, asAgent);
|
|
496
|
+
const { target, requester, connection, provider, inbox, fingerprint, compose } = checked;
|
|
497
|
+
const buttons = "buttons" in checked ? checked.buttons : undefined;
|
|
475
498
|
const scope = deliveryScopeDigest({
|
|
476
499
|
via: requester.via,
|
|
477
500
|
subjectId: requester.id,
|
|
@@ -518,6 +541,10 @@ chats) {
|
|
|
518
541
|
}
|
|
519
542
|
}
|
|
520
543
|
const { preview, payload, summary } = yield* compose;
|
|
544
|
+
// The message as sent without formatting: the text, then any attribution.
|
|
545
|
+
const plainText = preview.attribution === ""
|
|
546
|
+
? preview.text
|
|
547
|
+
: `${preview.text}${separator}${preview.attribution}`;
|
|
521
548
|
// A member who answers in the inbox writes as themselves, not as the agent.
|
|
522
549
|
const staff = inbox !== undefined && context.caller.kind === "member" && !asAgent;
|
|
523
550
|
const place = inbox ?? (yield* personalChat(target));
|
|
@@ -540,15 +567,13 @@ chats) {
|
|
|
540
567
|
turnId: null,
|
|
541
568
|
// The claim binds text immutably. Keep the source here and the actual wire payload
|
|
542
569
|
// in argsSummary, which can record the plain retry without changing that binding. A
|
|
543
|
-
// message without attribution is kept as written.
|
|
544
|
-
text:
|
|
545
|
-
? preview.text
|
|
546
|
-
: `${preview.text}${separator}${preview.attribution}`,
|
|
570
|
+
// message without attribution is kept as written, its buttons after it as they read.
|
|
571
|
+
text: buttons === undefined ? plainText : `${plainText}\n\n${buttonLines(buttons)}`,
|
|
547
572
|
decision: null,
|
|
548
573
|
reason: null,
|
|
549
574
|
toolCallId: null,
|
|
550
575
|
toolName: null,
|
|
551
|
-
argsSummary: JSON.stringify(summary ?? payload ?? provider.payload(preview.finalText)),
|
|
576
|
+
argsSummary: JSON.stringify(summary ?? payload ?? provider.payload(preview.finalText, buttons)),
|
|
552
577
|
status: "requested",
|
|
553
578
|
attachments: [],
|
|
554
579
|
requestedBy: requester,
|
|
@@ -583,11 +608,12 @@ chats) {
|
|
|
583
608
|
attribution: preview.attribution,
|
|
584
609
|
finalText: preview.finalText,
|
|
585
610
|
previews: destinationPreviews,
|
|
586
|
-
plainText
|
|
611
|
+
plainText,
|
|
587
612
|
replyTo: preview.replyTo,
|
|
588
613
|
agent: agentTransport,
|
|
589
614
|
operationId,
|
|
590
615
|
...(payload === undefined ? {} : { payload }),
|
|
616
|
+
...(buttons === undefined ? {} : { buttons }),
|
|
591
617
|
...(inbox === undefined ? {} : { threadId: inbox.threadId, chatId: inbox.chatId }),
|
|
592
618
|
transport: connections({
|
|
593
619
|
identityToken: context.identityToken,
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import type { ChatPreview } from "../../chat.js";
|
|
1
|
+
import type { ChatButtonRows, ChatPreview } from "../../chat.js";
|
|
2
2
|
import type { ChatRequester } from "./attribution.js";
|
|
3
3
|
interface DeliveryScopeIdentifiers {
|
|
4
4
|
readonly via: ChatRequester["via"];
|
|
@@ -36,5 +36,7 @@ export declare function deliveryFingerprint(preview: Pick<ChatPreview, "chatId"
|
|
|
36
36
|
};
|
|
37
37
|
};
|
|
38
38
|
readonly buttons?: Readonly<Record<string, string>>;
|
|
39
|
-
}
|
|
39
|
+
},
|
|
40
|
+
/** Buttons under a text, bound when given so a key without them keeps its binding. */
|
|
41
|
+
buttons?: ChatButtonRows): string;
|
|
40
42
|
export {};
|
|
@@ -20,7 +20,9 @@ export const deliveryKeyDigest = (idempotencyKey) => digest(JSON.stringify(idemp
|
|
|
20
20
|
* message binds the template it names and its values in place of the text, which is read from
|
|
21
21
|
* WhatsApp when it is sent: a replay finds its receipt however the template has changed since.
|
|
22
22
|
*/
|
|
23
|
-
export function deliveryFingerprint(preview, requester, template
|
|
23
|
+
export function deliveryFingerprint(preview, requester, template,
|
|
24
|
+
/** Buttons under a text, bound when given so a key without them keeps its binding. */
|
|
25
|
+
buttons) {
|
|
24
26
|
const sorted = (values) => Object.entries(values).sort(([one], [other]) => (one < other ? -1 : one > other ? 1 : 0));
|
|
25
27
|
const media = template?.header?.media;
|
|
26
28
|
return digest(JSON.stringify([
|
|
@@ -28,7 +30,7 @@ export function deliveryFingerprint(preview, requester, template) {
|
|
|
28
30
|
preview.provider,
|
|
29
31
|
preview.externalId,
|
|
30
32
|
...(template === undefined
|
|
31
|
-
? [preview.finalText, preview.text]
|
|
33
|
+
? [preview.finalText, preview.text, ...(buttons === undefined ? [] : [{ buttons }])]
|
|
32
34
|
: [
|
|
33
35
|
{
|
|
34
36
|
template: template.name,
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { type Effect, type Exit } from "effect";
|
|
2
|
+
import type { ChatButtonRows } from "../../../chat.js";
|
|
2
3
|
import type { TelegramPreviewContext } from "../../../telegram.js";
|
|
3
4
|
import { ConnectionError, type ConnectionReply, type ConnectionTransport } from "../../../connection.js";
|
|
4
5
|
import type { ActionRejected } from "../../../errors.js";
|
|
@@ -52,6 +53,8 @@ export interface ChatSend {
|
|
|
52
53
|
readonly operationId?: string;
|
|
53
54
|
/** What the provider sends in place of the text, such as a WhatsApp template; others ignore it. */
|
|
54
55
|
readonly payload?: Readonly<Record<string, unknown>>;
|
|
56
|
+
/** Buttons under the text, which a provider that shows them lays out its own way. */
|
|
57
|
+
readonly buttons?: ChatButtonRows;
|
|
55
58
|
/**
|
|
56
59
|
* The chat's own id where it differs from the destination's, as a reviewed reply's chat does;
|
|
57
60
|
* a workspace channel's send receives it, others ignore it.
|
|
@@ -92,8 +95,14 @@ export interface ChatProvider {
|
|
|
92
95
|
readonly finalText: string;
|
|
93
96
|
readonly plainText: string;
|
|
94
97
|
};
|
|
95
|
-
/** The payload a delivery records before the provider answers. */
|
|
96
|
-
readonly payload: (finalText: string) => Readonly<Record<string, unknown>>;
|
|
98
|
+
/** The payload a delivery records before the provider answers, its buttons laid out. */
|
|
99
|
+
readonly payload: (finalText: string, buttons?: ChatButtonRows) => Readonly<Record<string, unknown>>;
|
|
100
|
+
/**
|
|
101
|
+
* Why the provider cannot show these buttons under the message as given, or undefined when it
|
|
102
|
+
* can. It is checked before the message is reserved, so a refusal spends no key. Absent for a
|
|
103
|
+
* provider that shows no buttons, which refuses them all.
|
|
104
|
+
*/
|
|
105
|
+
readonly refuseButtons?: (rows: ChatButtonRows, finalText: string) => string | undefined;
|
|
97
106
|
/** One attempt: `sent` only when the provider's answer proves it. */
|
|
98
107
|
readonly send: (input: ChatSend) => Effect.Effect<ProviderOutcome>;
|
|
99
108
|
/**
|
|
@@ -114,3 +123,8 @@ export interface ChatProvider {
|
|
|
114
123
|
*/
|
|
115
124
|
export declare function transportFailure(payload: ProviderOutcome["payload"], result: Exit.Failure<ConnectionReply, ConnectionError>): ProviderOutcome;
|
|
116
125
|
export declare const record: (value: unknown) => Record<string, unknown>;
|
|
126
|
+
/**
|
|
127
|
+
* A message's buttons as its history keeps them, one a line, as the person reads them: a link where
|
|
128
|
+
* it leads, a workspace button by its label. The tokens stay in the delivery's payload.
|
|
129
|
+
*/
|
|
130
|
+
export declare function buttonLines(rows: ChatButtonRows): string;
|
|
@@ -26,3 +26,13 @@ export function transportFailure(payload, result) {
|
|
|
26
26
|
export const record = (value) => value !== null && typeof value === "object" && !Array.isArray(value)
|
|
27
27
|
? value
|
|
28
28
|
: {};
|
|
29
|
+
/**
|
|
30
|
+
* A message's buttons as its history keeps them, one a line, as the person reads them: a link where
|
|
31
|
+
* it leads, a workspace button by its label. The tokens stay in the delivery's payload.
|
|
32
|
+
*/
|
|
33
|
+
export function buttonLines(rows) {
|
|
34
|
+
return rows
|
|
35
|
+
.flat()
|
|
36
|
+
.map((button) => ("url" in button ? `[${button.text}](${button.url})` : button.text))
|
|
37
|
+
.join("\n");
|
|
38
|
+
}
|
|
@@ -1,5 +1,12 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
+
import type { ChatButtonRows } from "../../../chat.js";
|
|
2
3
|
import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
|
|
4
|
+
/**
|
|
5
|
+
* A message with buttons as Slack shows it: the Markdown in a `markdown` block, then a row of
|
|
6
|
+
* buttons in an `actions` block each, a workspace button's value `ws:<token>`, with the plain text
|
|
7
|
+
* for notifications. Without buttons, the Markdown as `markdown_text`, which takes no blocks.
|
|
8
|
+
*/
|
|
9
|
+
export declare function slackPayload(finalText: string, plainText: string, buttons?: ChatButtonRows): Readonly<Record<string, unknown>>;
|
|
3
10
|
/**
|
|
4
11
|
* One `chat.postMessage` through the connection's `web` API, never retried, in the thread of the
|
|
5
12
|
* message it replies to, else in the chat's thread, such as the one a reviewed reply answers.
|
|
@@ -12,6 +12,31 @@ const POSSIBLY_POSTED = new Set([
|
|
|
12
12
|
"fatal_error",
|
|
13
13
|
"service_unavailable",
|
|
14
14
|
]);
|
|
15
|
+
/**
|
|
16
|
+
* A message with buttons as Slack shows it: the Markdown in a `markdown` block, then a row of
|
|
17
|
+
* buttons in an `actions` block each, a workspace button's value `ws:<token>`, with the plain text
|
|
18
|
+
* for notifications. Without buttons, the Markdown as `markdown_text`, which takes no blocks.
|
|
19
|
+
*/
|
|
20
|
+
export function slackPayload(finalText, plainText, buttons) {
|
|
21
|
+
return buttons === undefined
|
|
22
|
+
? { markdown_text: finalText }
|
|
23
|
+
: {
|
|
24
|
+
text: plainText,
|
|
25
|
+
blocks: [
|
|
26
|
+
{ type: "markdown", text: finalText },
|
|
27
|
+
...buttons.map((row, rowIndex) => ({
|
|
28
|
+
type: "actions",
|
|
29
|
+
elements: row.map((button, index) => ({
|
|
30
|
+
type: "button",
|
|
31
|
+
text: { type: "plain_text", text: button.text },
|
|
32
|
+
...("url" in button
|
|
33
|
+
? { action_id: `link:${rowIndex}:${index}`, url: button.url }
|
|
34
|
+
: { action_id: `ws:${rowIndex}:${index}`, value: `ws:${button.token}` }),
|
|
35
|
+
})),
|
|
36
|
+
})),
|
|
37
|
+
],
|
|
38
|
+
};
|
|
39
|
+
}
|
|
15
40
|
/**
|
|
16
41
|
* One `chat.postMessage` through the connection's `web` API, never retried, in the thread of the
|
|
17
42
|
* message it replies to, else in the chat's thread, such as the one a reviewed reply answers.
|
|
@@ -20,7 +45,7 @@ const POSSIBLY_POSTED = new Set([
|
|
|
20
45
|
*/
|
|
21
46
|
export function sendSlack(input) {
|
|
22
47
|
return Effect.gen(function* () {
|
|
23
|
-
const payload =
|
|
48
|
+
const payload = slackPayload(input.finalText, input.plainText, input.buttons);
|
|
24
49
|
const thread = input.replyTo ??
|
|
25
50
|
(typeof input.threadId === "string" && SLACK_TS.test(input.threadId) ? input.threadId : null);
|
|
26
51
|
const result = yield* input.transport
|
|
@@ -92,6 +117,8 @@ export const slackProvider = {
|
|
|
92
117
|
finalText: renderSlack(markdown, attribution, separator),
|
|
93
118
|
plainText: attribution === "" ? markdown : `${markdown}${separator}${attribution}`,
|
|
94
119
|
}),
|
|
95
|
-
payload: (finalText) => (
|
|
120
|
+
payload: (finalText, buttons) => slackPayload(finalText, finalText, buttons),
|
|
121
|
+
// Each row is an actions block; labels and rows fit within what the schema allows.
|
|
122
|
+
refuseButtons: () => undefined,
|
|
96
123
|
send: sendSlack,
|
|
97
124
|
};
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { type TelegramPreviewContext } from "../../../telegram.js";
|
|
2
2
|
import { Effect } from "effect";
|
|
3
|
+
import type { ChatButtonRows } from "../../../chat.js";
|
|
3
4
|
import type { ConnectionTransport } from "../../../connection.js";
|
|
4
5
|
import type { Destination } from "../resolve.js";
|
|
5
6
|
import { type ChatProvider, type ProviderOutcome } from "./provider.js";
|
|
@@ -9,6 +10,8 @@ export declare const TELEGRAM_MESSAGE_LIMIT = 4096;
|
|
|
9
10
|
* attribution, as for a reply the agent sends after a member approved it, there is no footer.
|
|
10
11
|
*/
|
|
11
12
|
export declare function renderTelegram(markdown: string, attribution: string, separator?: string): string;
|
|
13
|
+
/** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
|
|
14
|
+
export declare function telegramKeyboard(rows: ChatButtonRows): Readonly<Record<string, unknown>>;
|
|
12
15
|
interface TelegramSend {
|
|
13
16
|
readonly transport: ConnectionTransport["Service"];
|
|
14
17
|
readonly connection: string;
|
|
@@ -23,6 +26,8 @@ interface TelegramSend {
|
|
|
23
26
|
readonly threadId?: string | null;
|
|
24
27
|
readonly link_preview_options?: Readonly<Record<string, unknown>>;
|
|
25
28
|
readonly disable_web_page_preview?: boolean;
|
|
29
|
+
/** The message's buttons, kept on the plain retry. */
|
|
30
|
+
readonly replyMarkup?: Readonly<Record<string, unknown>>;
|
|
26
31
|
}
|
|
27
32
|
/** One proxy POST, except one plain retry after a definite 400 entity parse refusal.
|
|
28
33
|
* Never retry an unknown outcome; never chunk, truncate or invoke an agent.
|
|
@@ -13,19 +13,29 @@ export function renderTelegram(markdown, attribution, separator = "\n\n") {
|
|
|
13
13
|
? converter.fromMarkdown(markdown)
|
|
14
14
|
: `${converter.fromMarkdown(markdown)}${escapeMarkdownV2(separator)}_${escapeMarkdownV2(attribution)}_`;
|
|
15
15
|
}
|
|
16
|
+
/** Buttons as Telegram shows them: an inline keyboard, a workspace button's data `ws:<token>`. */
|
|
17
|
+
export function telegramKeyboard(rows) {
|
|
18
|
+
return {
|
|
19
|
+
inline_keyboard: rows.map((row) => row.map((button) => "url" in button
|
|
20
|
+
? { text: button.text, url: button.url }
|
|
21
|
+
: { text: button.text, callback_data: `ws:${button.token}` })),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
16
24
|
/** One proxy POST, except one plain retry after a definite 400 entity parse refusal.
|
|
17
25
|
* Never retry an unknown outcome; never chunk, truncate or invoke an agent.
|
|
18
26
|
*/
|
|
19
27
|
export function sendTelegram(input) {
|
|
20
28
|
return Effect.gen(function* () {
|
|
29
|
+
const markup = input.replyMarkup === undefined ? {} : { reply_markup: input.replyMarkup };
|
|
21
30
|
const formatted = yield* attemptTelegram(input, {
|
|
22
31
|
text: input.finalText,
|
|
23
32
|
parse_mode: "MarkdownV2",
|
|
33
|
+
...markup,
|
|
24
34
|
});
|
|
25
35
|
if (!formatted.formattingRefused) {
|
|
26
36
|
return formatted;
|
|
27
37
|
}
|
|
28
|
-
const plain = yield* attemptTelegram(input, { text: input.plainText });
|
|
38
|
+
const plain = yield* attemptTelegram(input, { text: input.plainText, ...markup });
|
|
29
39
|
return {
|
|
30
40
|
...plain,
|
|
31
41
|
cause: plain.cause === undefined
|
|
@@ -135,7 +145,13 @@ export const telegramProvider = {
|
|
|
135
145
|
finalText: renderTelegram(markdown, attribution, separator),
|
|
136
146
|
plainText: attribution === "" ? markdown : `${markdown}${separator}${attribution}`,
|
|
137
147
|
}),
|
|
138
|
-
payload: (finalText) => ({
|
|
148
|
+
payload: (finalText, buttons) => ({
|
|
149
|
+
text: finalText,
|
|
150
|
+
parse_mode: "MarkdownV2",
|
|
151
|
+
...(buttons === undefined ? {} : { reply_markup: telegramKeyboard(buttons) }),
|
|
152
|
+
}),
|
|
153
|
+
// An inline keyboard takes every row the schema allows; a token fits its callback data.
|
|
154
|
+
refuseButtons: () => undefined,
|
|
139
155
|
send: (input) => sendTelegram({
|
|
140
156
|
transport: input.transport,
|
|
141
157
|
connection: input.connection,
|
|
@@ -150,5 +166,6 @@ export const telegramProvider = {
|
|
|
150
166
|
plainText: input.plainText,
|
|
151
167
|
replyTo: input.replyTo,
|
|
152
168
|
...(input.threadId === undefined ? {} : { threadId: input.threadId }),
|
|
169
|
+
...(input.buttons === undefined ? {} : { replyMarkup: telegramKeyboard(input.buttons) }),
|
|
153
170
|
}),
|
|
154
171
|
};
|
|
@@ -1,5 +1,18 @@
|
|
|
1
1
|
import { Effect } from "effect";
|
|
2
|
+
import type { ChatButtonRows } from "../../../chat.js";
|
|
2
3
|
import { type ChatProvider, type ChatSend, type ProviderOutcome } from "./provider.js";
|
|
4
|
+
/** The most characters of an interactive message's body, under which WhatsApp shows buttons. */
|
|
5
|
+
export declare const WHATSAPP_INTERACTIVE_BODY_LIMIT = 1024;
|
|
6
|
+
/**
|
|
7
|
+
* Why WhatsApp cannot show these buttons under the text, or undefined when it can: up to three
|
|
8
|
+
* workspace buttons with distinct labels, or one link, under a body of at most 1,024 characters.
|
|
9
|
+
*/
|
|
10
|
+
export declare function refuseWhatsAppButtons(rows: ChatButtonRows, finalText: string): string | undefined;
|
|
11
|
+
/**
|
|
12
|
+
* A message with buttons as WhatsApp shows it: an interactive message, its body the text, with one
|
|
13
|
+
* call-to-action link or up to three reply buttons, each workspace button's id `ws:<token>`.
|
|
14
|
+
*/
|
|
15
|
+
export declare function whatsappInteractive(finalText: string, rows: ChatButtonRows): Readonly<Record<string, unknown>>;
|
|
3
16
|
/**
|
|
4
17
|
* One text message from the workspace's number, `POST /phone/messages` on the connection's
|
|
5
18
|
* `graph` API, never retried. A Graph refusal with an error code, such as 131047 outside the
|
|
@@ -5,6 +5,66 @@ import { REFUSALS, WAMID } from "./whatsapp-refusals.js";
|
|
|
5
5
|
import { record, transportFailure, } from "./provider.js";
|
|
6
6
|
/** A WhatsApp id: the member's number, digits only. */
|
|
7
7
|
const WA_ID = /^[1-9][0-9]{5,19}$/;
|
|
8
|
+
/** The most characters of an interactive message's body, under which WhatsApp shows buttons. */
|
|
9
|
+
export const WHATSAPP_INTERACTIVE_BODY_LIMIT = 1024;
|
|
10
|
+
/** The most reply buttons one WhatsApp message shows, and the most characters of each label. */
|
|
11
|
+
const WHATSAPP_REPLY_BUTTONS = 3;
|
|
12
|
+
const WHATSAPP_BUTTON_LABEL = 20;
|
|
13
|
+
/**
|
|
14
|
+
* Why WhatsApp cannot show these buttons under the text, or undefined when it can: up to three
|
|
15
|
+
* workspace buttons with distinct labels, or one link, under a body of at most 1,024 characters.
|
|
16
|
+
*/
|
|
17
|
+
export function refuseWhatsAppButtons(rows, finalText) {
|
|
18
|
+
const buttons = rows.flat();
|
|
19
|
+
const links = buttons.filter((button) => "url" in button);
|
|
20
|
+
const labels = buttons.map((button) => button.text);
|
|
21
|
+
if (finalText.length > WHATSAPP_INTERACTIVE_BODY_LIMIT) {
|
|
22
|
+
return `WhatsApp shows buttons under at most ${WHATSAPP_INTERACTIVE_BODY_LIMIT} characters.`;
|
|
23
|
+
}
|
|
24
|
+
if (links.length > 0 && links.length !== buttons.length) {
|
|
25
|
+
return "WhatsApp shows one link or workspace buttons under a message, not both.";
|
|
26
|
+
}
|
|
27
|
+
if (links.length > 1) {
|
|
28
|
+
return "WhatsApp shows one link under a message.";
|
|
29
|
+
}
|
|
30
|
+
if (buttons.length > WHATSAPP_REPLY_BUTTONS) {
|
|
31
|
+
return `WhatsApp shows at most ${WHATSAPP_REPLY_BUTTONS} buttons under a message.`;
|
|
32
|
+
}
|
|
33
|
+
if (labels.some((label) => [...label].length > WHATSAPP_BUTTON_LABEL)) {
|
|
34
|
+
return `WhatsApp shows at most ${WHATSAPP_BUTTON_LABEL} characters of a button's label.`;
|
|
35
|
+
}
|
|
36
|
+
if (new Set(labels).size !== labels.length) {
|
|
37
|
+
return "WhatsApp needs every button under a message to have its own label.";
|
|
38
|
+
}
|
|
39
|
+
return undefined;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* A message with buttons as WhatsApp shows it: an interactive message, its body the text, with one
|
|
43
|
+
* call-to-action link or up to three reply buttons, each workspace button's id `ws:<token>`.
|
|
44
|
+
*/
|
|
45
|
+
export function whatsappInteractive(finalText, rows) {
|
|
46
|
+
const buttons = rows.flat();
|
|
47
|
+
const [link] = buttons.filter((button) => "url" in button);
|
|
48
|
+
return {
|
|
49
|
+
type: "interactive",
|
|
50
|
+
interactive: link !== undefined && "url" in link
|
|
51
|
+
? {
|
|
52
|
+
type: "cta_url",
|
|
53
|
+
body: { text: finalText },
|
|
54
|
+
action: { name: "cta_url", parameters: { display_text: link.text, url: link.url } },
|
|
55
|
+
}
|
|
56
|
+
: {
|
|
57
|
+
type: "button",
|
|
58
|
+
body: { text: finalText },
|
|
59
|
+
action: {
|
|
60
|
+
buttons: buttons.map((button) => ({
|
|
61
|
+
type: "reply",
|
|
62
|
+
reply: { id: "token" in button ? `ws:${button.token}` : "", title: button.text },
|
|
63
|
+
})),
|
|
64
|
+
},
|
|
65
|
+
},
|
|
66
|
+
};
|
|
67
|
+
}
|
|
8
68
|
/**
|
|
9
69
|
* One text message from the workspace's number, `POST /phone/messages` on the connection's
|
|
10
70
|
* `graph` API, never retried. A Graph refusal with an error code, such as 131047 outside the
|
|
@@ -13,10 +73,10 @@ const WA_ID = /^[1-9][0-9]{5,19}$/;
|
|
|
13
73
|
*/
|
|
14
74
|
export function sendWhatsApp(input) {
|
|
15
75
|
return Effect.gen(function* () {
|
|
16
|
-
const payload = input.payload ??
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
76
|
+
const payload = input.payload ??
|
|
77
|
+
(input.buttons === undefined
|
|
78
|
+
? { type: "text", text: { body: input.finalText, preview_url: false } }
|
|
79
|
+
: whatsappInteractive(input.finalText, input.buttons));
|
|
20
80
|
const result = yield* input.transport
|
|
21
81
|
.request({
|
|
22
82
|
connection: input.connection,
|
|
@@ -91,7 +151,10 @@ export const whatsappProvider = {
|
|
|
91
151
|
finalText: renderWhatsApp(text, attribution, separator),
|
|
92
152
|
plainText: attribution === "" ? text : `${text}${separator}${attribution}`,
|
|
93
153
|
}),
|
|
94
|
-
payload: (finalText) =>
|
|
154
|
+
payload: (finalText, buttons) => buttons === undefined
|
|
155
|
+
? { type: "text", text: { body: finalText, preview_url: false } }
|
|
156
|
+
: whatsappInteractive(finalText, buttons),
|
|
157
|
+
refuseButtons: refuseWhatsAppButtons,
|
|
95
158
|
send: sendWhatsApp,
|
|
96
159
|
template: whatsappTemplate,
|
|
97
160
|
};
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@segmentstream/ontology",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.145.0",
|
|
4
4
|
"description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "SegmentStream",
|