@segmentstream/ontology 0.128.1 → 0.130.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.
@@ -1,7 +1,8 @@
1
1
  import { sqlConfirmationStore } from "./confirmations.js";
2
2
  import { randomUUID } from "node:crypto";
3
- import { Effect } from "effect";
3
+ import { Effect, Option, Schema } from "effect";
4
4
  import { SqlClient } from "effect/unstable/sql";
5
+ import { action } from "../action.js";
5
6
  import { AgentChat } from "../agent-chat.js";
6
7
  import { chatChannelKind } from "../chat-channel.js";
7
8
  import { AgentReview } from "../agent-review.js";
@@ -20,6 +21,10 @@ import { guestChat } from "./guests.js";
20
21
  import { WEB_PROVIDER } from "../service/runtime-identity.js";
21
22
  import { isRecordId } from "./records.js";
22
23
  import { makeOntologyRuntime } from "./sql-runtime.js";
24
+ import { ACTION_TRANSACTION_LIMITS, ActionTransactions } from "./action-transactions.js";
25
+ import { actionTransaction } from "./action-deadlocks.js";
26
+ import { canonicalInstant } from "./records.js";
27
+ import { actionTriggers, evaluateTriggers, insertStarts, startCommitted, WorkflowStarter, } from "./workflow-starts.js";
23
28
  import { CHANNEL_IDENTITIES_FROM, CHANNEL_ORIGIN_SQL, CHANNEL_REVOKED_AT, LIVE_CHANNEL_IDENTITY, makeIdentityWriter, USER_IDENTITY_TABLE, } from "./user-identities.js";
24
29
  const PAIRINGS = `"${AGENT_PAIRINGS_TABLE}"`;
25
30
  /** The legacy channel accounts, written beside `user_identity` for earlier SDKs. */
@@ -98,11 +103,26 @@ function identityOf(row) {
98
103
  noticeVersion: nullableText(row.notice_version),
99
104
  };
100
105
  }
106
+ /**
107
+ * The action a held reply's record is written by, `agent_review.hold`. Only the agent holds replies,
108
+ * through the reviews route, so it is no action of the entity anyone can call: action triggers on
109
+ * `agent_review` itself fire for it, with its input and the review as the result.
110
+ */
111
+ const HOLD_ACTION = "hold";
112
+ /** The most waiting, and the most decided, held replies of one session its next turn learns about. */
113
+ const SESSION_REVIEWS = 50;
114
+ const HOLD_DEFINITION = action({
115
+ description: "The agent held a reply for review.",
116
+ input: Schema.Struct({}),
117
+ handler: () => Effect.void,
118
+ });
101
119
  /**
102
120
  * The agent store on the runtime's agent tables, as `ontology_app`. Expiry is the database's
103
121
  * `now()`; a pairing is consumed with one `UPDATE … WHERE "consumed_at" IS NULL`, so two concurrent
104
122
  * approvals cannot both succeed. Ids that are not UUIDs find nothing rather than fail the cast.
105
- * Chats the agent sees are `agent_chat` records, written as the platform with history.
123
+ * Chats the agent sees are `agent_chat` records, written as the platform with history. Holding a
124
+ * reply is admitted, bounded and starts the workflows whose triggers on `agent_review` fire for it as
125
+ * an action is and does, with the `ActionTransactions` and `WorkflowStarter` it runs with.
106
126
  */
107
127
  export function sqlAgentStore(ontology, sql) {
108
128
  const rows = (statement, values = []) => sql.unsafe(statement, values).pipe(Effect.orDie);
@@ -667,65 +687,170 @@ export function sqlAgentStore(ontology, sql) {
667
687
  };
668
688
  }));
669
689
  }).pipe(Effect.orDie),
670
- holdReply: (input) => sql
671
- .withTransaction(Effect.gen(function* () {
690
+ holdReply: (input) => Effect.gen(function* () {
691
+ // The triggers on `agent_review` itself, which fire for any of its actions: holding is one.
692
+ const triggers = actionTriggers(ontology).filter((trigger) => trigger.entity === AgentReview.name &&
693
+ (trigger.action === undefined || trigger.action === HOLD_ACTION));
694
+ const starter = triggers.length > 0
695
+ ? Option.getOrUndefined(yield* Effect.serviceOption(WorkflowStarter))
696
+ : undefined;
697
+ // Admitted and bounded as an action's transaction is, by the same gate and limits.
698
+ const admission = Option.getOrUndefined(yield* Effect.serviceOption(ActionTransactions));
699
+ const limits = admission?.limits ?? ACTION_TRANSACTION_LIMITS;
700
+ const qualified = `${AgentReview.name}.${HOLD_ACTION}`;
701
+ const actionId = randomUUID();
672
702
  if (!isRecordId(input.memberId)) {
673
703
  return undefined;
674
704
  }
675
- yield* beginReplicationWrite(sql);
676
- // Reports of one reply run one after the other: the first creates it, the rest find it.
677
- yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${input.key}`]);
678
- const runtime = makeOntologyRuntime(ontology, sql, {
679
- action: `${AgentReview.name}.hold`,
680
- actionId: randomUUID(),
681
- principalId: null,
682
- });
683
- const [found] = yield* runtime.find({
684
- entity: AgentReview.name,
685
- options: { where: { key: input.key }, limit: 1 },
686
- });
687
- if (found !== undefined) {
688
- return { id: String(found.id), status: String(found.status), created: false };
705
+ // Before the transaction: whatever it commits must be swept if this request does not start
706
+ // it. The transaction rolls back rather than commit after the deadline the sweep covers.
707
+ if (starter !== undefined) {
708
+ yield* starter.ensureRecovery({ commitBy: Date.now() + limits.handlerTimeoutMs });
689
709
  }
690
- const [member] = yield* rows(`SELECT 1 FROM ${USERS} WHERE "id" = $1::uuid AND "kind"::text = 'member' AND "active"`, [input.memberId]);
691
- if (member === undefined) {
710
+ const transaction = actionTransaction(sql, () => Effect.gen(function* () {
711
+ yield* sql.unsafe(`SELECT set_config('statement_timeout', $1, true), set_config('lock_timeout', $2, true)`, [`${limits.statementTimeoutMs}ms`, `${limits.lockTimeoutMs}ms`]);
712
+ yield* beginReplicationWrite(sql);
713
+ // Reports of one reply run one after the other: the first creates it, the rest find it.
714
+ yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [`review:${input.key}`]);
715
+ const edits = [];
716
+ const snapshots = new Map();
717
+ const runtime = makeOntologyRuntime(ontology, sql, {
718
+ action: qualified,
719
+ actionId,
720
+ principalId: null,
721
+ ...(triggers.length > 0
722
+ ? {
723
+ onEdit: (edit) => edits.push(edit),
724
+ onSnapshot: (snapshot) => {
725
+ if (snapshot.entity === AgentReview.name) {
726
+ snapshots.set(snapshot.id, {
727
+ before: snapshots.get(snapshot.id)?.before ?? snapshot.before,
728
+ after: snapshot.after,
729
+ });
730
+ }
731
+ },
732
+ }
733
+ : {}),
734
+ });
735
+ const [found] = yield* runtime.find({
736
+ entity: AgentReview.name,
737
+ options: { where: { key: input.key }, limit: 1 },
738
+ });
739
+ if (found !== undefined) {
740
+ return {
741
+ review: { id: String(found.id), status: String(found.status), created: false },
742
+ starts: [],
743
+ };
744
+ }
745
+ const [member] = yield* rows(`SELECT 1 FROM ${USERS} WHERE "id" = $1::uuid AND "kind"::text = 'member' AND "active"`, [input.memberId]);
746
+ if (member === undefined) {
747
+ return undefined;
748
+ }
749
+ // The registry keys a chat by its channel's name and its id, as the archive does.
750
+ const [chat] = yield* runtime.find({
751
+ entity: AgentChat.name,
752
+ options: {
753
+ where: { provider: input.channel, external_id: input.chatId },
754
+ limit: 1,
755
+ },
756
+ });
757
+ const review = yield* runtime.create({
758
+ entity: AgentReview.name,
759
+ values: {
760
+ key: input.key,
761
+ provider: input.provider,
762
+ channel: input.channel,
763
+ chat_id: input.chatId,
764
+ recipient: input.recipient,
765
+ chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
766
+ thread_id: input.threadId === "" ? null : input.threadId,
767
+ reply_to: input.replyTo,
768
+ session_id: input.sessionId,
769
+ draft: input.text,
770
+ text: null,
771
+ status: "pending",
772
+ // Select values are stored by their wire names.
773
+ mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
774
+ confidence: input.confidence,
775
+ message_id: null,
776
+ decided_at: null,
777
+ person: input.memberId,
778
+ agent_chat: chat === undefined ? null : String(chat.id),
779
+ },
780
+ });
781
+ const result = { review: String(review.id), status: "pending" };
782
+ let starts = [];
783
+ if (triggers.length > 0) {
784
+ const principal = yield* memberPrincipal(input.memberId);
785
+ const [now] = yield* rows(`SELECT to_char(now() AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "at"`);
786
+ if (principal !== undefined) {
787
+ starts = yield* evaluateTriggers(triggers, {
788
+ ontology,
789
+ entity: AgentReview.name,
790
+ action: HOLD_ACTION,
791
+ definition: HOLD_DEFINITION,
792
+ generated: false,
793
+ actionId,
794
+ at: canonicalInstant(String(now.at)),
795
+ principal,
796
+ input,
797
+ result,
798
+ edits,
799
+ held: snapshots,
800
+ load: (id) => runtime.get({ entity: AgentReview.name, id }).pipe(Effect.map((record) => record), Effect.catchTag("NotFound", () => Effect.succeed(undefined))),
801
+ });
802
+ yield* insertStarts(sql, starts);
803
+ }
804
+ }
805
+ return { review: { id: result.review, status: "pending", created: true }, starts };
806
+ }), {
807
+ qualified,
808
+ actionId,
809
+ retryOnDeadlock: false,
810
+ handlerTimeoutMs: limits.handlerTimeoutMs,
811
+ });
812
+ const held = yield* admission === undefined ? transaction : admission.admit(transaction);
813
+ if (held === undefined) {
692
814
  return undefined;
693
815
  }
694
- // The registry keys a chat by its channel's name and its id, as the archive does.
695
- const [chat] = yield* runtime.find({
696
- entity: AgentChat.name,
697
- options: {
698
- where: { provider: input.channel, external_id: input.chatId },
699
- limit: 1,
700
- },
701
- });
702
- const review = yield* runtime.create({
703
- entity: AgentReview.name,
704
- values: {
705
- key: input.key,
706
- provider: input.provider,
707
- channel: input.channel,
708
- chat_id: input.chatId,
709
- recipient: input.recipient,
710
- chat_kind: chat?.kind === "group" || chat?.kind === "private" ? chat.kind : kindOf(input),
711
- thread_id: input.threadId === "" ? null : input.threadId,
712
- reply_to: input.replyTo,
713
- session_id: input.sessionId,
714
- draft: input.text,
715
- text: null,
716
- status: "pending",
717
- // Select values are stored by their wire names.
718
- mode: input.mode === "whenUnsure" ? "when_unsure" : "always",
719
- confidence: input.confidence,
720
- message_id: null,
721
- decided_at: null,
722
- person: input.memberId,
723
- agent_chat: chat === undefined ? null : String(chat.id),
724
- },
725
- });
726
- return { id: String(review.id), status: "pending", created: true };
727
- }))
728
- .pipe(Effect.orDie),
816
+ // The decided runs start once the review committed; a failure leaves them to the sweep.
817
+ yield* startCommitted(sql, starter, held.starts, actionId);
818
+ return held.review;
819
+ }).pipe(Effect.orDie),
820
+ sessionReviews: (sessionId) => Effect.gen(function* () {
821
+ const runtime = makeOntologyRuntime(ontology, sql);
822
+ // Every reply still waiting, however old, and the latest decisions: a decision on an old
823
+ // reply reaches the session as the newest one.
824
+ const [waiting, decided] = yield* Effect.all([
825
+ runtime.find({
826
+ entity: AgentReview.name,
827
+ options: {
828
+ where: { session_id: sessionId, status: "pending" },
829
+ orderBy: [{ field: "created_at", direction: "desc" }],
830
+ limit: SESSION_REVIEWS,
831
+ },
832
+ }),
833
+ runtime.find({
834
+ entity: AgentReview.name,
835
+ options: {
836
+ where: { session_id: sessionId, status: { ne: "pending" } },
837
+ orderBy: [{ field: "decided_at", direction: "desc" }],
838
+ limit: SESSION_REVIEWS,
839
+ },
840
+ }),
841
+ ]);
842
+ const found = [...waiting, ...decided].sort((first, second) => instant(second.created_at) - instant(first.created_at));
843
+ return found.map((record) => ({
844
+ id: String(record.id),
845
+ status: String(record.status),
846
+ draft: String(record.draft),
847
+ edited: record.text !== null && record.text !== undefined && record.text !== record.draft,
848
+ heldAt: timestampText(record.created_at),
849
+ decidedAt: record.decided_at === null || record.decided_at === undefined
850
+ ? null
851
+ : timestampText(record.decided_at),
852
+ }));
853
+ }).pipe(Effect.orDie),
729
854
  web: sqlAgentWebStore(ontology, sql, {
730
855
  signUp: (visitorId) => resolveChannelSignIn(ontology, sql, { provider: WEB_PROVIDER, externalId: visitorId }),
731
856
  }),
@@ -767,6 +892,10 @@ function inInbox(ontology, input, resolution) {
767
892
  : { ...resolution, inbox: true };
768
893
  }
769
894
  /** A stored timestamp, as the wire carries it. */
895
+ /** A stored timestamp as milliseconds since the epoch. */
896
+ function instant(value) {
897
+ return value instanceof Date ? value.getTime() : Date.parse(String(value));
898
+ }
770
899
  function timestampText(value) {
771
900
  return value instanceof Date ? value.toISOString() : String(value);
772
901
  }
@@ -258,6 +258,12 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
258
258
  resolveIdentity: (input) => agents
259
259
  .resolveIdentity(input)
260
260
  .pipe(withStarter, Effect.provideService(ActionTransactions, actionTransactions)),
261
+ // Holding a reply starts the workflows triggered on `agent_review`, as an action would.
262
+ ...(agents.holdReply === undefined
263
+ ? {}
264
+ : {
265
+ holdReply: (input) => agents.holdReply(input).pipe(withStarter, Effect.provideService(ActionTransactions, actionTransactions)),
266
+ }),
261
267
  },
262
268
  });
263
269
  }));
@@ -156,6 +156,13 @@ export declare const ReviewRequest: Schema.Struct<{
156
156
  readonly confidence: Schema.NullOr<Schema.Number>;
157
157
  }>;
158
158
  export type ReviewRequest = typeof ReviewRequest.Type;
159
+ /**
160
+ * `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
161
+ * next turn learns which the person saw.
162
+ */
163
+ export declare const SessionReviewsRequest: Schema.Struct<{
164
+ readonly session_id: Schema.String;
165
+ }>;
159
166
  /** An identity on the wire, as the member's connect page and settings show it. */
160
167
  export declare function identityForWire(identity: AgentIdentity): {
161
168
  created_at: string;
@@ -209,6 +209,15 @@ export const ReviewRequest = Schema.Struct({
209
209
  description: "The decision model's probability that staff would send it as written.",
210
210
  }),
211
211
  });
212
+ /**
213
+ * `POST /api/ontology/agent/reviews/session`: the replies an agent session held for review, so its
214
+ * next turn learns which the person saw.
215
+ */
216
+ export const SessionReviewsRequest = Schema.Struct({
217
+ session_id: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512)).annotate({
218
+ description: "The agent's session that held the replies.",
219
+ }),
220
+ });
212
221
  /** An identity on the wire, as the member's connect page and settings show it. */
213
222
  export function identityForWire(identity) {
214
223
  return {
@@ -13,7 +13,7 @@ import { secretHash } from "../oauth/protocol.js";
13
13
  import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
14
14
  import { OntologyBackend } from "../runtime-contract.js";
15
15
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
16
- import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
16
+ import { ChatHandoffRequest, ChatSeenRequest, ReviewRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
17
17
  import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
18
18
  import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
19
19
  import { identityToken } from "../operations.js";
@@ -403,6 +403,36 @@ function holdReply(store) {
403
403
  return json({ id: review.id, status: review.status, created: review.created });
404
404
  });
405
405
  }
406
+ /**
407
+ * `POST /api/ontology/agent/reviews/session` (runtime): the replies the session held for review,
408
+ * newest first, with what became of each. Nothing a member wrote about them is in it.
409
+ */
410
+ function sessionReviews(store) {
411
+ return (request) => Effect.gen(function* () {
412
+ const requestId = yield* RequestId;
413
+ const decoded = Schema.decodeUnknownResult(SessionReviewsRequest)(yield* jsonBody(request), {
414
+ errors: "all",
415
+ onExcessProperty: "error",
416
+ });
417
+ if (Result.isFailure(decoded)) {
418
+ return invalidBody(requestId, schemaIssues(decoded.failure));
419
+ }
420
+ if (store.sessionReviews === undefined) {
421
+ return toServerResponse(notFound(requestId, "This ontology service holds no replies."));
422
+ }
423
+ const reviews = yield* store.sessionReviews(decoded.success.session_id);
424
+ return json({
425
+ reviews: reviews.map((review) => ({
426
+ id: review.id,
427
+ status: review.status,
428
+ draft: review.draft,
429
+ edited: review.edited,
430
+ held_at: review.heldAt,
431
+ decided_at: review.decidedAt,
432
+ })),
433
+ });
434
+ });
435
+ }
406
436
  /** `GET /api/ontology/agent/identities` (member): the member's own live identities. */
407
437
  function listIdentities(store, member) {
408
438
  return Effect.gen(function* () {
@@ -515,6 +545,7 @@ export function agentLayer(options) {
515
545
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
516
546
  yield* router.add("POST", CHATS_HANDOFF_PATH, asRuntime(handOffChat(store)));
517
547
  yield* router.add("POST", REVIEWS_PATH, asRuntime(holdReply(store)));
548
+ yield* router.add("POST", `${REVIEWS_PATH}/session`, asRuntime(sessionReviews(store)));
518
549
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
519
550
  if (store.web !== undefined && backend.oauth !== undefined) {
520
551
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
@@ -689,6 +689,11 @@ export interface AgentStore {
689
689
  * not an active member of the app. Absent on stores that predate reviews.
690
690
  */
691
691
  readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
692
+ /**
693
+ * The replies an agent session held for review, newest first: what became of each, for the
694
+ * session's next turn. Absent on stores that predate it.
695
+ */
696
+ readonly sessionReviews?: (sessionId: string) => Effect.Effect<ReadonlyArray<SessionReview>>;
692
697
  /** The grants behind agent tokens for the web. Absent on stores that predate them. */
693
698
  readonly web?: AgentWebStore;
694
699
  }
@@ -732,6 +737,18 @@ export interface HeldReview {
732
737
  /** Whether this report created it, rather than finding the review an earlier one created. */
733
738
  readonly created: boolean;
734
739
  }
740
+ /** A reply an agent session held for review, as the session learns its outcome. */
741
+ export interface SessionReview {
742
+ readonly id: string;
743
+ /** `pending`, `sent`, `uncertain`, `failed` or `rejected`, as the review holds it. */
744
+ readonly status: string;
745
+ /** The reply as the session wrote it. */
746
+ readonly draft: string;
747
+ /** Whether a member sent their edit of the draft instead of the draft. */
748
+ readonly edited: boolean;
749
+ readonly heldAt: string;
750
+ readonly decidedAt: string | null;
751
+ }
735
752
  declare const OntologyBackend_base: Context.ServiceClass<OntologyBackend, "@segmentstream/ontology/OntologyBackend", {
736
753
  readonly workflowAdmissions?: {
737
754
  readonly ensureRecovery: (commitBy: number) => Effect.Effect<number, WorkflowRecoveryUnavailable>;
@@ -587,6 +587,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
587
587
  readonly scheme: Schema.String;
588
588
  readonly secret: Schema.optionalKey<Schema.String>;
589
589
  readonly generated: Schema.optionalKey<Schema.Literal<true>>;
590
+ readonly input: Schema.optionalKey<Schema.String>;
590
591
  readonly algorithm: Schema.optionalKey<Schema.String>;
591
592
  readonly encoding: Schema.optionalKey<Schema.String>;
592
593
  readonly key: Schema.optionalKey<Schema.Struct<{
@@ -618,7 +619,8 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
618
619
  }>>;
619
620
  readonly verification: Schema.optionalKey<Schema.Struct<{
620
621
  readonly scheme: Schema.String;
621
- readonly verifyToken: Schema.String;
622
+ readonly verifyToken: Schema.optionalKey<Schema.String>;
623
+ readonly input: Schema.optionalKey<Schema.String>;
622
624
  }>>;
623
625
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
624
626
  readonly connection: Schema.optionalKey<Schema.String>;
@@ -945,6 +947,7 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
945
947
  readonly scheme: Schema.String;
946
948
  readonly secret: Schema.optionalKey<Schema.String>;
947
949
  readonly generated: Schema.optionalKey<Schema.Literal<true>>;
950
+ readonly input: Schema.optionalKey<Schema.String>;
948
951
  readonly algorithm: Schema.optionalKey<Schema.String>;
949
952
  readonly encoding: Schema.optionalKey<Schema.String>;
950
953
  readonly key: Schema.optionalKey<Schema.Struct<{
@@ -976,7 +979,8 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
976
979
  }>>;
977
980
  readonly verification: Schema.optionalKey<Schema.Struct<{
978
981
  readonly scheme: Schema.String;
979
- readonly verifyToken: Schema.String;
982
+ readonly verifyToken: Schema.optionalKey<Schema.String>;
983
+ readonly input: Schema.optionalKey<Schema.String>;
980
984
  }>>;
981
985
  readonly headers: Schema.optionalKey<Schema.$Array<Schema.String>>;
982
986
  readonly connection: Schema.optionalKey<Schema.String>;
@@ -13,7 +13,7 @@ export type WebhookVerification = {
13
13
  } | {
14
14
  readonly outcome: "invalid";
15
15
  }
16
- /** The workspace secret the webhook names does not exist. */
16
+ /** The secret the webhook names does not exist, or its connection's value is unset. */
17
17
  | {
18
18
  readonly outcome: "secret_missing";
19
19
  }
@@ -25,8 +25,13 @@ export type WebhookVerification = {
25
25
  };
26
26
  /** A signature check the ontology service asks the backend for: the secret never leaves it. */
27
27
  export interface WebhookVerifyRequest {
28
- /** The workspace secret's name. */
28
+ /** The workspace secret's name, when the secret is no connection's verification value. */
29
29
  readonly secret: string;
30
+ /** The verification value of the webhook's connection that holds the secret, when declared. */
31
+ readonly input?: {
32
+ readonly connection: string;
33
+ readonly field: string;
34
+ } | undefined;
30
35
  readonly algorithm: WebhookHmacAlgorithm;
31
36
  readonly encoding: WebhookSignatureEncoding;
32
37
  /** How the secret's value becomes the key, when not as its UTF-8 bytes. */
@@ -50,8 +55,10 @@ export type WebhookTokenVerifier = (request: WebhookTokenVerifyRequest) => Promi
50
55
  export declare const WEBHOOK_VERIFY_TIMEOUT_MS = 3000;
51
56
  /**
52
57
  * The verifier of a deployed ontology service: `POST
53
- * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-hmac` on SegmentStream with the request's
54
- * Vercel OIDC token, admitted only for the secrets the deployed ontology's webhooks name.
58
+ * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-hmac`, or
59
+ * `.../connections/{key}/inputs/{field}/verify-hmac` for a connection's verification value, on
60
+ * SegmentStream with the request's Vercel OIDC token, admitted only for the secrets the deployed
61
+ * ontology's webhooks name.
55
62
  */
56
63
  export declare function deployedWebhookVerifier(environment: {
57
64
  readonly segmentstreamUrl: string;
@@ -80,7 +87,7 @@ export declare function deployedSecretVerifier(environment: {
80
87
  readonly organizationId: string;
81
88
  readonly deploymentId?: string | undefined;
82
89
  readonly previewCredential?: Redacted.Redacted<string> | undefined;
83
- }, operation: "verify-hmac" | "verify-token" | "verify-challenge", fetchImpl: typeof fetch): (request: Pick<WebhookVerifyRequest, "secret" | "identityToken" | "requestId">, payload: unknown) => Promise<WebhookVerification>;
90
+ }, operation: "verify-hmac" | "verify-token" | "verify-challenge", fetchImpl: typeof fetch): (request: Pick<WebhookVerifyRequest, "secret" | "input" | "identityToken" | "requestId">, payload: unknown) => Promise<WebhookVerification>;
84
91
  /** The bytes a scheme's signatures cover and the signatures to compare, or why it refused. */
85
92
  export type SignedContent = {
86
93
  readonly ok: true;
@@ -7,8 +7,10 @@ import { fixedWindowLimiter } from "./rate-limit.js";
7
7
  export const WEBHOOK_VERIFY_TIMEOUT_MS = 3_000;
8
8
  /**
9
9
  * The verifier of a deployed ontology service: `POST
10
- * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-hmac` on SegmentStream with the request's
11
- * Vercel OIDC token, admitted only for the secrets the deployed ontology's webhooks name.
10
+ * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-hmac`, or
11
+ * `.../connections/{key}/inputs/{field}/verify-hmac` for a connection's verification value, on
12
+ * SegmentStream with the request's Vercel OIDC token, admitted only for the secrets the deployed
13
+ * ontology's webhooks name.
12
14
  */
13
15
  export function deployedWebhookVerifier(environment, fetchImpl = fetch) {
14
16
  const verify = deployedSecretVerifier(environment, "verify-hmac", fetchImpl);
@@ -40,7 +42,11 @@ export function deployedWebhookTokenVerifier(environment, fetchImpl = fetch) {
40
42
  */
41
43
  export function deployedSecretVerifier(environment, operation, fetchImpl) {
42
44
  const base = `${environment.segmentstreamUrl}/api/internal/v1/workspaces/` +
43
- `${encodeURIComponent(environment.workspaceId)}/secrets/`;
45
+ `${encodeURIComponent(environment.workspaceId)}/`;
46
+ const target = (request) => request.input === undefined
47
+ ? `secrets/${encodeURIComponent(request.secret)}`
48
+ : `connections/${encodeURIComponent(request.input.connection)}/inputs/` +
49
+ encodeURIComponent(request.input.field);
44
50
  return async (request, payload) => {
45
51
  if (request.identityToken === undefined || request.identityToken === "") {
46
52
  return {
@@ -49,7 +55,7 @@ export function deployedSecretVerifier(environment, operation, fetchImpl) {
49
55
  };
50
56
  }
51
57
  try {
52
- const response = await fetchImpl(`${base}${encodeURIComponent(request.secret)}/${operation}`, {
58
+ const response = await fetchImpl(`${base}${target(request)}/${operation}`, {
53
59
  method: "POST",
54
60
  headers: {
55
61
  "content-type": "application/json",
@@ -1318,7 +1318,10 @@ export function workflowsLayer(options) {
1318
1318
  return yield* refuse("verification_query", 403);
1319
1319
  }
1320
1320
  const verified = yield* Effect.promise(() => verifier({
1321
- secret: verification.verifyToken,
1321
+ secret: verification.verifyToken ?? "",
1322
+ ...(verification.input === undefined || trigger.connection === undefined
1323
+ ? {}
1324
+ : { input: { connection: trigger.connection, field: verification.input } }),
1322
1325
  token,
1323
1326
  identityToken: requestIdentityToken(request),
1324
1327
  requestId,
@@ -1382,6 +1385,9 @@ export function workflowsLayer(options) {
1382
1385
  const verifier = options.webhookVerifier;
1383
1386
  const verified = yield* Effect.promise(() => verifier({
1384
1387
  secret: signature.secret ?? "",
1388
+ ...(signature.input === undefined || trigger.connection === undefined
1389
+ ? {}
1390
+ : { input: { connection: trigger.connection, field: signature.input } }),
1385
1391
  algorithm: format.algorithm,
1386
1392
  encoding: format.encoding,
1387
1393
  ...(format.key === undefined ? {} : { key: format.key }),
@@ -89,25 +89,30 @@ export declare function webhookHmacFormat(signature: {
89
89
  readonly scheme: string;
90
90
  }): WebhookHmacFormat | undefined;
91
91
  /**
92
- * Where a signature's secret comes from: a workspace secret by `secret` name, or with
93
- * `generated: true` the secret the platform derives for the webhook, which workspace code reads
94
- * with `webhookSigningSecret(trigger)` to register it.
92
+ * Where a signature's secret comes from: a verification value of the webhook's connection by
93
+ * `input`, with `generated: true` the secret the platform derives for the webhook, which workspace
94
+ * code reads with `webhookSigningSecret(trigger)` to register it, or a workspace secret by
95
+ * `secret` name.
95
96
  */
96
97
  export interface WebhookSignatureSource {
97
98
  readonly scheme: string;
98
99
  readonly secret?: string | undefined;
99
100
  readonly generated?: true | undefined;
101
+ readonly input?: string | undefined;
100
102
  }
101
103
  /**
102
- * A signature as listings present it: its scheme and the secret's name, which reads `generated`
103
- * with `generated: true` for a secret the platform derives, so readers that know only names still
104
- * show something true.
104
+ * A signature as listings present it: its scheme and where its secret is. `secret` reads
105
+ * `generated` for a secret the platform derives and the value's key for a connection's
106
+ * verification value, so readers that know only names still show something true.
105
107
  */
106
108
  export declare function presentedWebhookSignature(signature: WebhookSignatureSource): {
107
109
  readonly scheme: string;
108
110
  readonly secret: string;
109
111
  readonly generated?: true;
112
+ readonly input?: string;
110
113
  };
114
+ /** A verification value's key on its connection, as connections name fields: `webhook_signing_secret`. */
115
+ export declare const CONNECTION_INPUT_KEY: RegExp;
111
116
  /** A problem with a signature declaration: the key it concerns, under `signature`, and why. */
112
117
  export interface WebhookSignatureProblem {
113
118
  readonly path: string;
@@ -115,8 +120,9 @@ export interface WebhookSignatureProblem {
115
120
  }
116
121
  /**
117
122
  * Every problem of a webhook trigger's `signature`, as `check` and SegmentStream's publication
118
- * check report them: a known scheme and a workspace secret's name, and for `hmac` a complete
119
- * format. Empty when the declaration is valid.
123
+ * check report them: a known scheme, one source of the secret, and for `hmac` a complete format.
124
+ * Empty when the declaration is valid. That an `input` has a connection to read it from is the
125
+ * trigger's check.
120
126
  */
121
127
  export declare function webhookSignatureProblems(signature: unknown): ReadonlyArray<WebhookSignatureProblem>;
122
128
  /**