@segmentstream/ontology 0.134.0 → 0.136.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 CHANGED
@@ -1,5 +1,59 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.136.0
4
+
5
+ Workspace secrets named in code give way to values of the connections that use them.
6
+
7
+ - A workspace channel names a verification value of its connection with
8
+ `channels.<name>.input`, such as `"input": "webhook_signing_secret"`, and its code's
9
+ `signedWith` and `matches` check deliveries against it.
10
+ - `check` warns `named-secret-deprecated` for a webhook's `signature.secret` or
11
+ `verification.verifyToken` and for the guests' `botCheck.secret`.
12
+ - `secret_ref(...)` is documented as the older form of a connection's own `Secret(...)`.
13
+ - Deploying a connection field changed from `secret_ref(name)` to its own `Secret(...)` makes the
14
+ workspace secret that field's value, without reading it, when nothing else the deployment
15
+ declares names it: nobody enters the value again, and a Telegram bot keeps its token and chats.
16
+
17
+ Action required: `secret_ref(name)` in `connections/connections.py`, including
18
+ `TelegramBotConnection(key="telegram", token=secret_ref("agent-telegram-token"))` from earlier
19
+ `segmentstream agent init` runs, stops working after 2027-01-19. Replace each with the field's own
20
+ `Secret(...)`, or `TelegramBotConnection(key="telegram")`, and deploy: the deploy takes the
21
+ workspace secret over as the field's value.
22
+
23
+ Action required: a webhook's `signature: { scheme, secret }` and
24
+ `verification: { scheme: "meta", verifyToken }` stop working after 2027-01-19. Declare the secret
25
+ as a verification value of the webhook's connection, `verification={"webhook_signing_secret":
26
+ Secret(...)}`, name the connection with `connection`, write `input: "webhook_signing_secret"`, and
27
+ paste the value on the connection's page; a WhatsApp number on the workspace's own Meta app
28
+ uses `WhatsAppConnection(key=..., application="own")`, which checks Meta's deliveries itself.
29
+
30
+ Action required: a workspace channel's `channels.<name>.secret` in `agent/segmentstream.json`
31
+ stops working after 2027-01-19. Declare the value on the channel's connection with
32
+ `verification={...}`, write `"input": "<field>"` instead, and paste it on the connection's page.
33
+
34
+ ## 0.135.0
35
+
36
+ `agent_chat.send` writes to a chat as the agent, without the sender attribution a post carries,
37
+ for a workflow or a member that writes first, such as a follow-up the workspace decides on. It
38
+ takes the chat, text and idempotency key as `postMessage` does, under its own grant,
39
+ `agent_chat:send`. The archive keeps the message as the agent's, with who asked for it, so the
40
+ person's next session reads it as the agent's. The agent's own sessions and its tasks cannot call
41
+ it: a task's workflow sends what the task wrote.
42
+
43
+ A message a chat's provider refuses says why in `refusal`: `outside_reply_window` (on WhatsApp the
44
+ person last wrote more than 24 hours ago), `recipient_unreachable` or `recipient_opted_out`. The
45
+ ontology's `ActionRejected` carries it, the action's 422 answers it as `refusal`, and the app SDK's
46
+ `SegmentStreamApiError` as `refusal`.
47
+
48
+ A post to a person's private chat named by channel and member is archived under the chat their
49
+ channel keys, the chat the inbox registered for them or the one they last wrote in, so their
50
+ chat's history and their session read it; on WhatsApp and Slack it was kept under their account.
51
+
52
+ A grant of `agent_chat:post_message` or `agent_chat:send` within a scope covers the registered
53
+ chats the scope holds, named by their record id. A person named by channel, or a group by its
54
+ title, is refused with it, since the scope could not be checked for them; posts by a group's title
55
+ were sent outside the scope before.
56
+
3
57
  ## 0.134.0
4
58
 
5
59
  The feedback guidance is one text in the ontology SDK. The MCP server's instructions carry it for a
@@ -57,6 +57,18 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
57
57
  readonly skipped: number;
58
58
  readonly expired: number;
59
59
  }>;
60
+ readonly send: import("./action.js").Action<Schema.Struct<{
61
+ readonly chat: Schema.String;
62
+ readonly text: Schema.String;
63
+ readonly replyTo: Schema.optionalKey<Schema.String>;
64
+ readonly idempotencyKey: Schema.String;
65
+ }>, {
66
+ readonly status: "sent" | "uncertain";
67
+ readonly message_id: string | null;
68
+ readonly url: string | null;
69
+ readonly duplicate: boolean;
70
+ readonly history_recorded: boolean;
71
+ }>;
60
72
  readonly postMessage: import("./action.js").Action<Schema.Struct<{
61
73
  readonly chat: Schema.String;
62
74
  readonly text: Schema.String;
@@ -200,6 +200,29 @@ export const AgentChat = entity("agent_chat", {
200
200
  return yield* delivery.value.importHistory(input);
201
201
  }),
202
202
  }),
203
+ send: action({
204
+ description: "Send a message to a chat as the agent, without the sender attribution a post carries: the " +
205
+ "person reads it as the agent's, and the archive keeps who asked for it. For a workflow or " +
206
+ "a member that writes first, such as a follow-up the workspace decides on. Same chat, text " +
207
+ "and idempotency key as postMessage; text is Markdown each channel renders natively. " +
208
+ "Refused for the agent's own sessions and its tasks: a task's workflow sends what the task " +
209
+ "wrote. Reuse the same idempotency key on replay; an uncertain operation is never resent. A " +
210
+ "message the provider refuses spends its key and says why in refusal: outside_reply_window " +
211
+ "(on WhatsApp the person last wrote more than 24 hours ago), recipient_unreachable or " +
212
+ "recipient_opted_out.",
213
+ input: ChatPostInput,
214
+ hints: { destructive: false, irreversible: true, idempotent: true },
215
+ connections: [],
216
+ prepare: ({ input }) => Effect.gen(function* () {
217
+ const delivery = yield* Effect.serviceOption(ChatDelivery);
218
+ if (Option.isNone(delivery) || delivery.value.send === undefined) {
219
+ return yield* new ActionRejected({
220
+ message: "Sending as the agent requires the authenticated ontology service.",
221
+ });
222
+ }
223
+ return yield* delivery.value.send(input);
224
+ }),
225
+ }),
203
226
  postMessage: action({
204
227
  description: "Post to an eligible chat ID or exact title. text is Markdown (bold, italic, code, lists, " +
205
228
  "[text](url)); each channel renders it natively and degrades constructs it can't show. " +
package/dist/analyze.js CHANGED
@@ -758,6 +758,10 @@ function resolveWorkflows(input) {
758
758
  }
759
759
  return resolved;
760
760
  }
761
+ /** @legacy ontology.webhook-named-secrets: the last day a webhook reads a workspace secret. */
762
+ const WEBHOOK_NAMED_SECRETS_END = "2027-01-19";
763
+ /** @legacy ontology.guest-bot-check-secret: the last day the bot check reads a workspace secret. */
764
+ const GUEST_BOT_CHECK_SECRET_ENDS = "2026-12-21";
761
765
  let deliveryJsonSchema;
762
766
  /**
763
767
  * The JSON Schema of `webhookDelivery`, the input every webhook-started workflow declares, as the
@@ -811,6 +815,26 @@ function resolveWebhookTrigger(trigger, at, scope) {
811
815
  valid = false;
812
816
  }
813
817
  }
818
+ // @legacy ontology.webhook-named-secrets
819
+ const named = [
820
+ ...(typeof signature === "object" &&
821
+ signature !== null &&
822
+ typeof signature.secret === "string"
823
+ ? [`${at}.signature.secret`]
824
+ : []),
825
+ ...(typeof verification === "object" &&
826
+ verification !== null &&
827
+ typeof verification.verifyToken === "string"
828
+ ? [`${at}.verification.verifyToken`]
829
+ : []),
830
+ ];
831
+ if (valid) {
832
+ for (const path of named) {
833
+ report("named-secret-deprecated", path, `a workspace secret works for a webhook only until ${WEBHOOK_NAMED_SECRETS_END}: declare ` +
834
+ "it as a verification value of the webhook's connection, " +
835
+ 'verification={"webhook_signing_secret": Secret(...)}, and name it with input.', "warning");
836
+ }
837
+ }
814
838
  const headers = trigger.headers;
815
839
  if (!Array.isArray(headers) || headers.length > MAX_WEBHOOK_HEADERS) {
816
840
  report("workflow_webhook_headers_invalid", `${at}.headers`, `headers is a list of at most ${MAX_WEBHOOK_HEADERS} lowercase header names.`);
@@ -1859,6 +1883,9 @@ function guestBotCheck(value, report, connections) {
1859
1883
  report("invalid-sign-in", "guest.botCheck.secret", `${JSON.stringify(secret) ?? "undefined"} is not a workspace secret name. ${shape}`);
1860
1884
  valid = false;
1861
1885
  }
1886
+ if (valid) {
1887
+ report("named-secret-deprecated", "guest.botCheck.secret", `a workspace secret works as the bot check's secret key only until ${GUEST_BOT_CHECK_SECRET_ENDS}. ${shape}`, "warning");
1888
+ }
1862
1889
  return valid && typeof secret === "string"
1863
1890
  ? { scheme: scheme, secret }
1864
1891
  : undefined;
package/dist/chat.d.ts CHANGED
@@ -115,6 +115,8 @@ declare const ChatDelivery_base: Context.ServiceClass<ChatDelivery, "@segmentstr
115
115
  readonly preview: (input: ChatPostInput) => Effect.Effect<ChatPreview, ActionError>;
116
116
  readonly validate: (input: ChatPostInput) => Effect.Effect<void, ActionError>;
117
117
  readonly post: (input: ChatPostInput) => Effect.Effect<ChatPostResult, ActionError>;
118
+ /** Sends as the agent, without the requester's attribution, which the archive still keeps. */
119
+ readonly send?: (input: ChatPostInput) => Effect.Effect<ChatPostResult, ActionError>;
118
120
  /** Sends a reply a member approved, as the agent and without attribution, at most once. */
119
121
  readonly sendReview?: (input: ReviewSendInput) => Effect.Effect<ReviewSendResult, ActionError>;
120
122
  /** Asks the agent to redraft a reply it held for review, in a session of its own. */
@@ -1,10 +1,10 @@
1
1
  import { Schema } from "effect";
2
- export declare const DIAGNOSTIC_CODES: readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "feedback-unreportable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "trigger_runs_invalid", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"];
2
+ export declare const DIAGNOSTIC_CODES: readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "feedback-unreportable", "agent-tools-implicit", "named-secret-deprecated", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "trigger_runs_invalid", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"];
3
3
  export type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number];
4
4
  /** A problem `check` found in an ontology definition. */
5
5
  export declare const Diagnostic: Schema.Struct<{
6
6
  readonly severity: Schema.Literals<readonly ["error", "warning", "info"]>;
7
- readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "feedback-unreportable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "trigger_runs_invalid", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
7
+ readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "feedback-unreportable", "agent-tools-implicit", "named-secret-deprecated", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "trigger_runs_invalid", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
8
8
  /** Where the problem is, for example `lead.properties.status.options[1]`. */
9
9
  readonly path: Schema.String;
10
10
  readonly message: Schema.String;
@@ -14,7 +14,7 @@ declare const InvalidOntology_base: Schema.Class<InvalidOntology, Schema.TaggedS
14
14
  readonly message: Schema.String;
15
15
  readonly diagnostics: Schema.$Array<Schema.Struct<{
16
16
  readonly severity: Schema.Literals<readonly ["error", "warning", "info"]>;
17
- readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "feedback-unreportable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "trigger_runs_invalid", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
17
+ readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "feedback-unreportable", "agent-tools-implicit", "named-secret-deprecated", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "trigger_runs_invalid", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
18
18
  /** Where the problem is, for example `lead.properties.status.options[1]`. */
19
19
  readonly path: Schema.String;
20
20
  readonly message: Schema.String;
@@ -60,6 +60,7 @@ export const DIAGNOSTIC_CODES = [
60
60
  "feedback-unanswerable",
61
61
  "feedback-unreportable",
62
62
  "agent-tools-implicit",
63
+ "named-secret-deprecated",
63
64
  "unknown-connection",
64
65
  "unused-connection",
65
66
  "invalid-prepare",
package/dist/errors.d.ts CHANGED
@@ -64,6 +64,13 @@ declare const ActionRejected_base: Schema.Class<ActionRejected, Schema.TaggedStr
64
64
  * a client that is unsure whether its request took effect retries with the same key.
65
65
  */
66
66
  readonly keyConsumed: Schema.optionalKey<Schema.Literal<true>>;
67
+ /**
68
+ * Why a chat's provider refused a message, for code to act on: `outside_reply_window` (the person
69
+ * last wrote longer ago than the channel lets a free-form message reach them; WhatsApp takes a
70
+ * template), `recipient_unreachable` (the person blocked the sender or cannot receive it) or
71
+ * `recipient_opted_out` (the person stopped such messages).
72
+ */
73
+ readonly refusal: Schema.optionalKey<Schema.String>;
67
74
  }>, import("effect/Cause").YieldableError>;
68
75
  /**
69
76
  * An action refused the request for a business reason. The message is written for the caller and is
package/dist/errors.js CHANGED
@@ -41,6 +41,13 @@ export class ActionRejected extends Schema.TaggedError()("ActionRejected", {
41
41
  * a client that is unsure whether its request took effect retries with the same key.
42
42
  */
43
43
  keyConsumed: Schema.optionalKey(Schema.Literal(true)),
44
+ /**
45
+ * Why a chat's provider refused a message, for code to act on: `outside_reply_window` (the person
46
+ * last wrote longer ago than the channel lets a free-form message reach them; WhatsApp takes a
47
+ * template), `recipient_unreachable` (the person blocked the sender or cannot receive it) or
48
+ * `recipient_opted_out` (the person stopped such messages).
49
+ */
50
+ refusal: Schema.optionalKey(Schema.String),
44
51
  }) {
45
52
  }
46
53
  /**
@@ -7,6 +7,7 @@ import type { ConnectionTransportFactory } from "../connections.js";
7
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
+ import type { ChatArchiveTransport } from "../agent/chat-archive.js";
10
11
  import { type Destination } from "./resolve.js";
11
12
  import type { AgentChannelTransport } from "./providers/provider.js";
12
13
  import { type HistoryArchive } from "./history-import.js";
@@ -34,4 +35,6 @@ agent?: {
34
35
  readonly fetch?: AgentChannelTransport["fetch"];
35
36
  },
36
37
  /** The archive a chat's earlier history is imported to; without it nothing is. */
37
- history?: HistoryArchive): ChatDeliveryFactory;
38
+ history?: HistoryArchive,
39
+ /** The chat archive's reads, which find the chat a person writes from on a channel. */
40
+ chats?: ChatArchiveTransport): ChatDeliveryFactory;
@@ -42,7 +42,9 @@ export function makeChatDelivery(ontology, connections, archive, previews = {},
42
42
  */
43
43
  agent = {},
44
44
  /** The archive a chat's earlier history is imported to; without it nothing is. */
45
- history) {
45
+ history,
46
+ /** The chat archive's reads, which find the chat a person writes from on a channel. */
47
+ chats) {
46
48
  if (previews.settings) {
47
49
  validateTelegramPreviews(previews.settings);
48
50
  }
@@ -53,21 +55,33 @@ history) {
53
55
  const destination = ontology.manifest.chat?.telegram?.connection;
54
56
  const destinationPreviews = previews.settings?.connection === destination ? previews : { ownOrigins: previews.ownOrigins };
55
57
  return (context) => {
56
- const check = (input, approved = true) => Effect.gen(function* () {
57
- if (!isAllowed("agent_chat:post_message", context.principal)) {
58
+ /**
59
+ * A post's destination, requester and exact text. `asAgent` sends it as the agent, without the
60
+ * sender attribution, under `agent_chat:send`; the requester is still recorded with it.
61
+ */
62
+ const check = (input, approved = true, asAgent = false) => Effect.gen(function* () {
63
+ const permission = asAgent ? "agent_chat:send" : "agent_chat:post_message";
64
+ if (!isAllowed(permission, context.principal)) {
58
65
  return yield* new PermissionDenied({
59
- message: "agent_chat:post_message is required.",
60
- permission: "agent_chat:post_message",
66
+ message: `${permission} is required.`,
67
+ permission,
68
+ });
69
+ }
70
+ // The agent's own sessions answer through their channels, and its tasks have nobody to
71
+ // confirm what they send: a task's workflow sends what the task wrote.
72
+ if (asAgent && context.caller.kind === "runtime") {
73
+ return yield* new ActionRejected({
74
+ message: "The agent's sessions do not send as the agent: they answer in their chats.",
61
75
  });
62
76
  }
63
77
  const user = yield* context.backend.get({ entity: "user", id: context.principal.id });
64
78
  if (user.active !== true || user.kind !== context.principal.kind) {
65
79
  return yield* new PermissionDenied({ message: "The requester is inactive." });
66
80
  }
67
- const inbox = yield* inboxChat(input.chat);
81
+ const inbox = yield* inboxChat(input.chat, permission);
68
82
  // A member answers a person in the inbox from their own session in the app, signed with
69
83
  // their name as the workspace's attribution lays it out.
70
- const requester = inbox !== undefined &&
84
+ const requester = (inbox !== undefined || asAgent) &&
71
85
  context.caller.kind === "member" &&
72
86
  context.caller.subjectId === context.principal.id &&
73
87
  context.principal.kind === "member"
@@ -91,7 +105,33 @@ history) {
91
105
  const target = inbox?.target ??
92
106
  (yield* chatResolver(context.backend, context.principal, providers, {
93
107
  kindOf: (channel) => chatKind(ontology.manifest.chat, channel),
108
+ sending: permission,
94
109
  }).resolve(input.chat));
110
+ // A grant within a scope covers the registered chats it holds, named by their record:
111
+ // a person named by channel, or a group by its title, is outside what it can check.
112
+ const scope = effectiveScope(permission, context.principal);
113
+ if (scope !== undefined && inbox === undefined) {
114
+ if (!UUID.test(input.chat) || target.id !== input.chat) {
115
+ return yield* new PermissionDenied({
116
+ message: `A scoped ${permission} names the chat by its agent_chat record.`,
117
+ permission,
118
+ });
119
+ }
120
+ yield* context.backend
121
+ .get({
122
+ entity: "agent_chat",
123
+ id: input.chat,
124
+ reader: {
125
+ ...context.principal,
126
+ permissions: ["agent_chat:read"],
127
+ scopes: [{ permission: "agent_chat:read", where: scope }],
128
+ },
129
+ })
130
+ .pipe(Effect.mapError(() => new PermissionDenied({
131
+ message: `The chat is outside the chats ${permission} covers.`,
132
+ permission,
133
+ })));
134
+ }
95
135
  // A chat is a destination only on a channel the ontology declares a connection for; the
96
136
  // channel's kind sends it.
97
137
  const provider = channelProvider(ontology.manifest.chat, target.provider);
@@ -105,8 +145,10 @@ history) {
105
145
  message: "Chat posting requires a configured connection for the chat's provider.",
106
146
  });
107
147
  }
148
+ // The agent's own message carries no attribution, as a reply a member approved does not.
149
+ const signature = asAgent ? "" : requester.attribution;
108
150
  const { finalText, plainText } = yield* Effect.try({
109
- try: () => provider.render(input.text, requester.attribution, separator),
151
+ try: () => provider.render(input.text, signature, asAgent ? "" : separator),
110
152
  catch: (cause) => new ActionRejected({ message: "The Markdown could not be rendered.", cause }),
111
153
  });
112
154
  if (!input.text.trim() ||
@@ -125,7 +167,7 @@ history) {
125
167
  provider: target.provider,
126
168
  externalId: target.external_id,
127
169
  title: target.title,
128
- attribution: requester.attribution,
170
+ attribution: signature,
129
171
  text: input.text,
130
172
  finalText,
131
173
  replyTo,
@@ -157,7 +199,7 @@ history) {
157
199
  * a role may hold the post within a scope, which must hold the record. `undefined` for any
158
200
  * other chat, which the destinations resolve as before.
159
201
  */
160
- const inboxChat = (chat) => Effect.gen(function* () {
202
+ const inboxChat = (chat, permission = "agent_chat:post_message") => Effect.gen(function* () {
161
203
  if (!UUID.test(chat)) {
162
204
  return undefined;
163
205
  }
@@ -173,7 +215,7 @@ history) {
173
215
  if (record === undefined || record.kind !== "private") {
174
216
  return undefined;
175
217
  }
176
- const postable = effectiveScope("agent_chat:post_message", context.principal);
218
+ const postable = effectiveScope(permission, context.principal);
177
219
  if (postable !== undefined) {
178
220
  yield* context.backend
179
221
  .get({
@@ -186,8 +228,8 @@ history) {
186
228
  },
187
229
  })
188
230
  .pipe(Effect.mapError(() => new PermissionDenied({
189
- message: "The chat is outside the chats agent_chat:post_message covers.",
190
- permission: "agent_chat:post_message",
231
+ message: `The chat is outside the chats ${permission} covers.`,
232
+ permission,
191
233
  })));
192
234
  }
193
235
  // Its person, the chat's one member, takes part in what is posted there: without them the
@@ -222,6 +264,66 @@ history) {
222
264
  : null,
223
265
  };
224
266
  });
267
+ /**
268
+ * The chat a person's private destination is on, as its channel keys it, which differs from
269
+ * the account a post is sent to on WhatsApp and Slack: the chat the inbox registered for them
270
+ * on the channel, else the one they last wrote in, else none, and the post is kept under their
271
+ * account. A post kept there would be missing from their chat's history and their session.
272
+ */
273
+ const personalChat = (target) => Effect.gen(function* () {
274
+ const person = target.participantIds[0];
275
+ if (target.kind !== "private" || person === undefined) {
276
+ return undefined;
277
+ }
278
+ const registered = yield* context.backend
279
+ .find({
280
+ entity: "agent_chat",
281
+ query: {
282
+ where: {
283
+ and: [
284
+ { provider: { eq: target.provider } },
285
+ { kind: { eq: "private" } },
286
+ { members: { some: { id: { eq: person } } } },
287
+ ],
288
+ },
289
+ limit: 1,
290
+ },
291
+ })
292
+ .pipe(Effect.option);
293
+ const record = registered._tag === "Some"
294
+ ? registered.value.items.find((item) => item.kind === "private" && item.provider === target.provider)
295
+ : undefined;
296
+ if (record !== undefined) {
297
+ return {
298
+ chatId: String(record.external_id),
299
+ threadId: typeof record.thread_id === "string" && record.thread_id !== ""
300
+ ? record.thread_id
301
+ : null,
302
+ };
303
+ }
304
+ if (chats === undefined) {
305
+ return undefined;
306
+ }
307
+ // The person's private chats on the channel, newest first: the chat they last wrote in,
308
+ // by a message of theirs, which the channel keeps under its chat. A post kept under their
309
+ // account by a release before this one is no chat of theirs.
310
+ const page = yield* chats({
311
+ search: { provider: target.provider, limit: 50 },
312
+ principal: { id: person, kind: "member", roles: [], permissions: [] },
313
+ identityToken: context.identityToken,
314
+ }).pipe(Effect.option);
315
+ const latest = page._tag === "Some"
316
+ ? page.value.events.find((event) => event.kind === "inbound")
317
+ : undefined;
318
+ return typeof latest?.chatId === "string" && latest.chatId !== ""
319
+ ? {
320
+ chatId: latest.chatId,
321
+ threadId: typeof latest.threadId === "string" && latest.threadId !== ""
322
+ ? latest.threadId
323
+ : null,
324
+ }
325
+ : undefined;
326
+ });
225
327
  const report = (phase, cause) => Effect.logWarning("ontology.chat.delivery_diagnostic").pipe(Effect.annotateLogs({
226
328
  phase,
227
329
  requestId: context.requestId,
@@ -265,10 +367,16 @@ history) {
265
367
  }),
266
368
  preview: (input) => check(input, false).pipe(Effect.map(({ preview }) => preview)),
267
369
  validate: (input) => check(input).pipe(Effect.asVoid),
268
- post: (input) => Effect.gen(function* () {
269
- const { target, requester, connection, provider, preview, inbox } = yield* check(input);
370
+ post: (input) => deliver(input, false),
371
+ send: (input) => deliver(input, true),
372
+ };
373
+ /** One delivery: posted with its requester's attribution, or sent as the agent without it. */
374
+ function deliver(input, asAgent) {
375
+ return Effect.gen(function* () {
376
+ const { target, requester, connection, provider, preview, inbox } = yield* check(input, true, asAgent);
270
377
  // A member who answers in the inbox writes as themselves, not as the agent.
271
- const staff = inbox !== undefined && context.caller.kind === "member";
378
+ const staff = inbox !== undefined && context.caller.kind === "member" && !asAgent;
379
+ const place = inbox ?? (yield* personalChat(target));
272
380
  const operationId = context.envelope?.operation_id ?? randomUUID();
273
381
  const scope = deliveryScopeDigest({
274
382
  via: requester.via,
@@ -281,9 +389,9 @@ history) {
281
389
  eventId: `chat-delivery:${operationId}:reserve`,
282
390
  operationId,
283
391
  provider: target.provider,
284
- chatId: inbox?.chatId ?? target.external_id,
392
+ chatId: place?.chatId ?? target.external_id,
285
393
  chatType: target.kind,
286
- threadId: inbox?.threadId ?? null,
394
+ threadId: place?.threadId ?? null,
287
395
  participantIds: target.participantIds,
288
396
  senderId: staff ? requester.id : "agent",
289
397
  senderName: staff ? requester.name : "agent",
@@ -295,7 +403,7 @@ history) {
295
403
  turnId: null,
296
404
  // The claim binds text immutably. Keep the source here and the actual wire payload
297
405
  // in argsSummary, which can record the plain retry without changing that binding.
298
- text: `${input.text}${separator}${requester.attribution}`,
406
+ text: asAgent ? input.text : `${input.text}${separator}${requester.attribution}`,
299
407
  decision: null,
300
408
  reason: null,
301
409
  toolCallId: null,
@@ -366,7 +474,7 @@ history) {
366
474
  transport: connections({
367
475
  identityToken: context.identityToken,
368
476
  audit: {
369
- action: "agent_chat.post_message",
477
+ action: asAgent ? "agent_chat.send" : "agent_chat.post_message",
370
478
  principalId: context.principal.id,
371
479
  requestId: context.requestId,
372
480
  },
@@ -408,6 +516,7 @@ history) {
408
516
  return yield* new ActionRejected({
409
517
  message: "The provider refused the message. This operation key is consumed.",
410
518
  keyConsumed: true,
519
+ ...(outcome.refusal === undefined ? {} : { refusal: outcome.refusal }),
411
520
  });
412
521
  }
413
522
  return {
@@ -417,7 +526,7 @@ history) {
417
526
  duplicate: false,
418
527
  history_recorded: historyRecorded,
419
528
  };
420
- }),
421
- };
529
+ });
530
+ }
422
531
  };
423
532
  }
@@ -10,7 +10,11 @@ export interface ProviderOutcome {
10
10
  readonly messageId: string | null;
11
11
  readonly url: string | null;
12
12
  readonly cause?: unknown;
13
+ /** Why the provider refused a `failed` message, when it says: see `ActionRejected.refusal`. */
14
+ readonly refusal?: ChatRefusal;
13
15
  }
16
+ /** Why a chat's provider refused a message, for code to act on. */
17
+ export type ChatRefusal = "outside_reply_window" | "recipient_unreachable" | "recipient_opted_out";
14
18
  /**
15
19
  * How the service reaches the app's agent, which sends through a workspace channel: the
16
20
  * deployment's production origin and the service's Vercel OIDC token, each undefined outside
@@ -88,6 +88,8 @@ function attemptTelegram(input, payload) {
88
88
  messageId: null,
89
89
  url: null,
90
90
  cause: new Error(typeof body.description === "string" ? body.description : "Telegram refused the message."),
91
+ // A person who blocked the bot, or never started it, cannot be written to.
92
+ ...(result.value.status === 403 ? { refusal: "recipient_unreachable" } : {}),
91
93
  };
92
94
  }
93
95
  const message = record(body.result);
@@ -3,6 +3,16 @@ import { renderWhatsApp, WHATSAPP_MESSAGE_LIMIT } from "../../../whatsapp.js";
3
3
  import { record, transportFailure, } from "./provider.js";
4
4
  /** A WhatsApp id: the member's number, digits only. */
5
5
  const WA_ID = /^[1-9][0-9]{5,19}$/;
6
+ /**
7
+ * Meta's refusals that code acts on: 131047, the person last wrote more than 24 hours ago, so only a
8
+ * template reaches them; 131026, the message cannot be delivered to the number; 131050, the person
9
+ * stopped marketing messages.
10
+ */
11
+ const REFUSALS = {
12
+ 131047: "outside_reply_window",
13
+ 131026: "recipient_unreachable",
14
+ 131050: "recipient_opted_out",
15
+ };
6
16
  /** The id Meta gives an accepted message. */
7
17
  const WAMID = /^wamid\.[A-Za-z0-9+/=_-]{1,512}$/;
8
18
  /**
@@ -57,6 +67,7 @@ export function sendWhatsApp(input) {
57
67
  const explanation = [error.message, record(error.error_data).details]
58
68
  .filter((text) => typeof text === "string" && text !== "")
59
69
  .join(" ");
70
+ const refusal = REFUSALS[Number(error.code)];
60
71
  return {
61
72
  payload,
62
73
  status: "failed",
@@ -64,6 +75,7 @@ export function sendWhatsApp(input) {
64
75
  url: null,
65
76
  cause: new Error(`WhatsApp refused the message with code ${code}.` +
66
77
  (explanation === "" ? "" : ` ${explanation}`)),
78
+ ...(refusal === undefined ? {} : { refusal }),
67
79
  };
68
80
  }
69
81
  const id = record(Array.isArray(body.messages) ? body.messages[0] : undefined).id;
@@ -37,6 +37,8 @@ export declare function chatResolver(backend: OntologyBackend["Service"], princi
37
37
  readonly memberGroups?: boolean;
38
38
  /** The kind of each channel, whose identities reach its private chats; the name by default. */
39
39
  readonly kindOf?: (channel: string) => string | undefined;
40
+ /** The permission that sends to the destinations: posting by default, or sending as the agent. */
41
+ readonly sending?: "agent_chat:post_message" | "agent_chat:send";
40
42
  }): {
41
43
  list: (chat?: string) => Effect.Effect<Destination[], ActionRejected | PermissionDenied, never>;
42
44
  resolve: (chat: string) => Effect.Effect<Destination, ActionRejected | PermissionDenied, never>;
@@ -78,9 +78,10 @@ export function withChatMembership(transport, backend) {
78
78
  */
79
79
  export function chatResolver(backend, principal, providers, options = {}) {
80
80
  const kindOf = options.kindOf ?? ((channel) => channel);
81
- const canGroup = isAllowed("agent_chat:read", principal) || isAllowed("agent_chat:post_message", principal);
81
+ const sending = options.sending ?? "agent_chat:post_message";
82
+ const canGroup = isAllowed("agent_chat:read", principal) || isAllowed(sending, principal);
82
83
  const memberGroups = options.memberGroups === true && principal.kind === "member";
83
- const canDirectory = isAllowed("user:read", principal) || isAllowed("agent_chat:post_message", principal);
84
+ const canDirectory = isAllowed("user:read", principal) || isAllowed(sending, principal);
84
85
  const destinations = (chat) => Effect.gen(function* () {
85
86
  if (!canGroup && principal.kind !== "member") {
86
87
  return yield* denied();
@@ -490,7 +490,7 @@ export function expectedFailure(error, requestId) {
490
490
  };
491
491
  }
492
492
  if (Predicate.isTagged(error, "ActionRejected")) {
493
- const { message, keyConsumed } = error;
493
+ const { message, keyConsumed, refusal } = error;
494
494
  return {
495
495
  status: 422,
496
496
  body: {
@@ -501,6 +501,7 @@ export function expectedFailure(error, requestId) {
501
501
  ...batchDetails(error),
502
502
  ...limitDetails(error),
503
503
  ...(keyConsumed === true ? { key_consumed: true } : {}),
504
+ ...(typeof refusal === "string" ? { refusal } : {}),
504
505
  },
505
506
  };
506
507
  }
@@ -223,11 +223,11 @@ function runActionOf(backend, plan, hooks, connections, replicate, chatDelivery)
223
223
  : call.input;
224
224
  // A chat post needs its requester's confirmation, and a task has none (spec decision 7).
225
225
  if (planned.name === "agent_chat" &&
226
- name === "post_message" &&
226
+ (name === "post_message" || name === "send") &&
227
227
  principal.authenticatedVia === AGENT_TASK_AUTHENTICATION) {
228
228
  return yield* new ActionRejected({
229
- message: "Agent tasks cannot post to chat in this release: agent_chat.post_message is refused " +
230
- "for a task whatever its workflow's role grants.",
229
+ message: `Agent tasks cannot post to chat in this release: agent_chat.${name} is refused ` +
230
+ "for a task whatever its workflow's role grants; the workflow sends what the task wrote.",
231
231
  });
232
232
  }
233
233
  if (planned.name === "agent_chat" && name === "post_message" && caller.kind === "runtime") {
@@ -614,6 +614,8 @@ export const ErrorSchemas = {
614
614
  limit: Schema.optionalKey(LimitErrorWire),
615
615
  // The idempotency key is spent on an operation that did not happen: retry with a new one.
616
616
  key_consumed: Schema.optionalKey(Schema.Literal(true)),
617
+ // Why a chat's provider refused a message, such as outside_reply_window.
618
+ refusal: Schema.optionalKey(Schema.String),
617
619
  }),
618
620
  rateLimited: errorBody("RateLimited", 429, ["rate_limited"]),
619
621
  internal: errorBody("InternalError", 500, ["internal_error"]),
@@ -344,13 +344,13 @@ export function createOntologyService(ontology, config) {
344
344
  ? deployedConnections(config)
345
345
  : localConnections(config.localConnections)));
346
346
  const replicate = deployedReplication(config);
347
+ const chatHistory = config.runtimeIdentity === undefined ? undefined : platformChatArchive(config);
347
348
  const chatDelivery = makeChatDelivery(ontology, connections, config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
348
349
  // The app's agent sends through a workspace channel, at the origin it takes its tasks at.
349
350
  {
350
351
  origin: config.agentOrigin,
351
352
  ...(config.agentTaskTransport === undefined ? {} : { fetch: config.agentTaskTransport }),
352
- }, config.chatHistoryArchive ?? platformHistoryArchive(config));
353
- const chatHistory = config.runtimeIdentity === undefined ? undefined : platformChatArchive(config);
353
+ }, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
354
354
  const metricQueries = makeMetricQueries({
355
355
  ontology,
356
356
  transport: platformMetricQueries({ ...config, manifestHash: ontology.manifest.hash }),
@@ -43,6 +43,7 @@ export function deployedWebhookTokenVerifier(environment, fetchImpl = fetch) {
43
43
  export function deployedSecretVerifier(environment, operation, fetchImpl) {
44
44
  const base = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
45
45
  `${encodeURIComponent(environment.workspaceId)}/`;
46
+ // @legacy ontology.webhook-named-secrets: a workspace secret is checked at secrets/{name}.
46
47
  const target = (request) => request.input === undefined
47
48
  ? `secrets/${encodeURIComponent(request.secret)}`
48
49
  : `connections/${encodeURIComponent(request.input.connection)}/inputs/` +
@@ -149,7 +149,11 @@ export type WebhookSignatureSecret = {
149
149
  readonly secret?: undefined;
150
150
  readonly input?: undefined;
151
151
  } | {
152
- /** A workspace secret's name, such as `stripe-webhook-signing-secret`. */
152
+ /**
153
+ * A workspace secret's name, such as `stripe-webhook-signing-secret`.
154
+ *
155
+ * @deprecated Name a verification value of the webhook's `connection` with `input`.
156
+ */
153
157
  readonly secret: string;
154
158
  readonly generated?: undefined;
155
159
  readonly input?: undefined;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.134.0",
3
+ "version": "0.136.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",