@segmentstream/ontology 0.181.0 → 0.182.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.
@@ -2,7 +2,7 @@ import { randomUUID } from "node:crypto";
2
2
  import { Effect } from "effect";
3
3
  import { SqlClient } from "effect/unstable/sql";
4
4
  import { signUpRolesOf } from "../manifest.js";
5
- import { AGENT_GUEST_LINKS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
5
+ import { AGENT_GUEST_LINKS_TABLE, AGENT_COUNTERS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
6
6
  import { AGENT_EVAL_CLIENT_ID, AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
7
7
  import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, FULL_SCOPE, REFRESH_TOKEN_PREFIX, REFRESH_TOKEN_TTL_MS, newSecret, secretHash, } from "../service/oauth/protocol.js";
8
8
  import { addGuestSpend, completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, guestSpendLimited, } from "./agent-counters.js";
@@ -216,34 +216,55 @@ export function sqlAgentWebStore(ontology, sql, admission) {
216
216
  .pipe(Effect.orDie);
217
217
  return standing === undefined ? undefined : guestPrincipal(ontology, grantId);
218
218
  }),
219
- countGuestTurn: (guestId, input) => Effect.gen(function* () {
220
- if (!isRecordId(guestId)) {
221
- return undefined;
222
- }
223
- const limits = yield* effectiveChannelLimits(sql, input);
224
- // Money first: a guest past a cap starts no turn, and the turn is not counted.
225
- const spent = yield* guestSpendLimited(sql, { guestId, limits });
226
- if (spent !== undefined) {
227
- return spent;
228
- }
229
- for (const [scope, subject, limit] of [
230
- ["guestTurnsPerDay", guestId, limits.guest.turnsPerDay],
231
- ["guestWorkspaceTurnsPerDay", "workspace", limits.guest.workspaceTurnsPerDay],
232
- ]) {
233
- const limited = yield* countAgentAttempt(sql, { scope, subject, window: "day", limit });
234
- if (limited !== undefined) {
235
- // The refusal the browser gets is this window's notice.
236
- if (limited.notificationId !== undefined) {
237
- yield* completeAgentLimitNotice(sql, {
238
- notificationId: limited.notificationId,
239
- delivered: true,
240
- });
219
+ countGuestTurn: (guestId, input, delivery) => {
220
+ const count = Effect.gen(function* () {
221
+ if (!isRecordId(guestId)) {
222
+ return undefined;
223
+ }
224
+ const limits = yield* effectiveChannelLimits(sql, input);
225
+ // Money first: a guest past a cap starts no turn, and the turn is not counted.
226
+ const spent = yield* guestSpendLimited(sql, { guestId, limits });
227
+ if (spent !== undefined) {
228
+ return spent;
229
+ }
230
+ for (const [scope, subject, limit] of [
231
+ ["guestTurnsPerDay", guestId, limits.guest.turnsPerDay],
232
+ ["guestWorkspaceTurnsPerDay", "workspace", limits.guest.workspaceTurnsPerDay],
233
+ ]) {
234
+ const limited = yield* countAgentAttempt(sql, { scope, subject, window: "day", limit });
235
+ if (limited !== undefined) {
236
+ // The refusal the browser gets is this window's notice.
237
+ if (limited.notificationId !== undefined) {
238
+ yield* completeAgentLimitNotice(sql, {
239
+ notificationId: limited.notificationId,
240
+ delivered: true,
241
+ });
242
+ }
243
+ return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
241
244
  }
242
- return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
243
245
  }
246
+ return undefined;
247
+ });
248
+ if (!delivery || !isRecordId(guestId)) {
249
+ return count.pipe(Effect.orDie);
244
250
  }
245
- return undefined;
246
- }).pipe(Effect.orDie),
251
+ // Provider retries share the accepted turn's charge, including concurrent deliveries.
252
+ const key = `guestDelivery:${guestId}:${secretHash(delivery)}`;
253
+ return sql
254
+ .withTransaction(Effect.gen(function* () {
255
+ const [fresh] = yield* sql.unsafe(`INSERT INTO "${AGENT_COUNTERS_TABLE}" ("key","window_start","count")
256
+ VALUES ($1,date_trunc('day',now()),1) ON CONFLICT ("key","window_start") DO NOTHING RETURNING 1`, [key]);
257
+ if (!fresh) {
258
+ return undefined;
259
+ }
260
+ const limited = yield* count;
261
+ if (limited) {
262
+ yield* sql.unsafe(`DELETE FROM "${AGENT_COUNTERS_TABLE}" WHERE "key"=$1 AND "window_start"=date_trunc('day',now())`, [key]);
263
+ }
264
+ return limited;
265
+ }))
266
+ .pipe(Effect.orDie);
267
+ },
247
268
  recordGuestUsage: ({ guestId, costUsd, key }) => isRecordId(guestId) ? addGuestSpend(sql, { guestId, costUsd, key }) : Effect.void,
248
269
  countGuestAttempt: ({ scope, subject, limit }) => countAgentAttempt(sql, { scope, subject, window: "hour", limit }).pipe(Effect.map((limited) => limited?.retryAfterSeconds)),
249
270
  upgradeGuest: ({ guestId, identity, expiresAt }) => Effect.gen(function* () {
@@ -1,3 +1,4 @@
1
+ import { channelGuestId, guestPrincipal } from "./guests.js";
1
2
  import { sqlConfirmationStore } from "./confirmations.js";
2
3
  import { randomUUID } from "node:crypto";
3
4
  import { Effect, Option, Schema } from "effect";
@@ -619,6 +620,30 @@ export function sqlAgentStore(ontology, sql) {
619
620
  return true;
620
621
  }))
621
622
  .pipe(Effect.orDie),
623
+ channelGuest: (channel, chat, sender) => Effect.gen(function* () {
624
+ const kind = store.channelKind?.(channel);
625
+ if ((kind !== "telegram" && kind !== "slack" && kind !== "whatsapp") ||
626
+ !sender ||
627
+ sender.length > 256 ||
628
+ !chat ||
629
+ chat.length > 256) {
630
+ return undefined;
631
+ }
632
+ const principal = guestPrincipal(ontology, channelGuestId(channel, sender), kind, channel);
633
+ if (!principal) {
634
+ return undefined;
635
+ }
636
+ if (kind === "whatsapp"
637
+ ? !/^whatsapp:[^:]+:[0-9]+$/.test(chat) || chat.split(":")[2] !== sender
638
+ : (yield* store.readGroupAccess(`${channel}:${chat}`)) !== "public") {
639
+ return undefined;
640
+ }
641
+ // Linked, inactive and revoked identities alike must pass through member admission.
642
+ if (yield* store.findIdentity({ provider: kind, externalId: sender })) {
643
+ return undefined;
644
+ }
645
+ return { ...principal, chat: { provider: channel, chatId: chat } };
646
+ }),
622
647
  readGroupAccess: (key) => rows(`SELECT "group_access" FROM ${quoteIdentifier(tableName(AgentChat.name))}
623
648
  WHERE "key" = $1 AND "kind" = 'group' AND "handoff_at" IS NULL AND "handled_by_id" IS NULL`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.group_access))),
624
649
  readChatPersona: (key) => rows(`SELECT "agent_persona" FROM ${quoteIdentifier(tableName(AgentChat.name))} WHERE "key" = $1`, [key]).pipe(Effect.map(([chat]) => nullableText(chat?.agent_persona))),
@@ -1,3 +1,4 @@
1
+ import { type GuestChannel } from "../sign-in.js";
1
2
  import type { Ontology } from "../ontology.js";
2
3
  import { type AgentToolVerb } from "../permissions.js";
3
4
  import type { Principal } from "../runtime.js";
@@ -30,4 +31,6 @@ export declare function actingGuestId(actAs: string): string | undefined;
30
31
  * holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
31
32
  * `undefined` when the ontology admits no guests.
32
33
  */
33
- export declare function guestPrincipal(ontology: Ontology, guestId: string): Principal | undefined;
34
+ export declare function guestPrincipal(ontology: Ontology, guestId: string, channel?: GuestChannel, connection?: string): Principal | undefined;
35
+ /** Budget identity shared across chats on one configured messenger connection. */
36
+ export declare function channelGuestId(channel: string, sender: string): string;
@@ -1,6 +1,6 @@
1
+ import { createHash } from "node:crypto";
1
2
  import { GUEST_ROLE } from "../names.js";
2
3
  import { AGENT_TOOL_VERBS, agentToolPermission, agentToolsOf, isAllowed, MEMBER_AGENT_TOOLS, permissionsOf, principalScopes, } from "../permissions.js";
3
- import { WEB_PROVIDER } from "../service/runtime-identity.js";
4
4
  import { isRecordId } from "./records.js";
5
5
  /**
6
6
  * A guest as the agent names them in `X-SegmentStream-Act-As`: `guest:` and their id, so that no
@@ -49,17 +49,36 @@ export function actingGuestId(actAs) {
49
49
  * holds the built-in role `guest` alone, with the permissions `defineOntology({ guest })` gives it.
50
50
  * `undefined` when the ontology admits no guests.
51
51
  */
52
- export function guestPrincipal(ontology, guestId) {
53
- if (ontology.signIn.guest === undefined || !isRecordId(guestId)) {
52
+ export function guestPrincipal(ontology, guestId, channel = "web", connection) {
53
+ const settings = ontology.signIn.guest;
54
+ const named = `channel:${connection}`;
55
+ const selected = connection && settings?.channels.includes(named) ? named : channel;
56
+ if (!settings?.channels.includes(selected) || !isRecordId(guestId)) {
54
57
  return undefined;
55
58
  }
56
- const roles = [GUEST_ROLE];
59
+ const roles = settings.byChannel?.[selected] ?? [GUEST_ROLE];
57
60
  return {
58
61
  id: guestId,
59
62
  kind: "guest",
60
63
  roles,
61
64
  permissions: permissionsOf(ontology.roles, roles),
62
65
  ...principalScopes(ontology.roles, roles),
63
- authenticatedVia: WEB_PROVIDER,
66
+ authenticatedVia: channel,
64
67
  };
65
68
  }
69
+ /** Budget identity shared across chats on one configured messenger connection. */
70
+ export function channelGuestId(channel, sender) {
71
+ const bytes = createHash("sha256")
72
+ .update(JSON.stringify(["group-guest", channel, sender]))
73
+ .digest();
74
+ bytes[6] = (bytes[6] & 15) | 80;
75
+ bytes[8] = (bytes[8] & 63) | 128;
76
+ const hex = bytes.toString("hex");
77
+ return [
78
+ hex.slice(0, 8),
79
+ hex.slice(8, 12),
80
+ hex.slice(12, 16),
81
+ hex.slice(16, 20),
82
+ hex.slice(20, 32),
83
+ ].join("-");
84
+ }
@@ -1,4 +1,3 @@
1
- import { type PublicActionOptions } from "./public-group-action.js";
2
1
  import { Layer, Redacted } from "effect";
3
2
  import { HttpRouter } from "effect/unstable/http";
4
3
  import { type SessionExchange, type TokenVerifier } from "../authentication.js";
@@ -37,7 +36,6 @@ export { GUEST_LINK_PATH };
37
36
  */
38
37
  export declare const PAIRING_LIMIT: RateLimit;
39
38
  export interface AgentServerOptions {
40
- readonly publicGroupAction?: PublicActionOptions;
41
39
  readonly verifyToken: TokenVerifier;
42
40
  /**
43
41
  * The websites whose visitors get an agent token: as guests, and, while `web` is open to sign-up,
@@ -1,5 +1,4 @@
1
1
  import { chatPersona, chatPersonaNames, deployedChatPersonas } from "../../chat-personas.js";
2
- import { publicActionForGroup, groupSubject, } from "./public-group-action.js";
3
2
  import { isAllowed, effectiveScope } from "../../permissions.js";
4
3
  import { confirmationCommand } from "./confirmations.js";
5
4
  import { randomUUID } from "node:crypto";
@@ -11,7 +10,7 @@ import { API_KEY_PREFIX } from "../../runtime/principals.js";
11
10
  import { schemaIssues } from "../../runtime/validation.js";
12
11
  import { BASE_PATH } from "../api.js";
13
12
  import { CurrentPrincipal, withPrincipal, } from "../authentication.js";
14
- import { RequestId, errorBodyForWire, failureResponse, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
13
+ import { RequestId, errorBodyForWire, forbidden, notFound, rateLimited, toServerResponse, unauthorized, unavailable, } from "../errors.js";
15
14
  import { secretHash } from "../oauth/protocol.js";
16
15
  import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
17
16
  import { OntologyBackend } from "../runtime-contract.js";
@@ -198,7 +197,7 @@ function resolveIdentity(store, agentTools) {
198
197
  });
199
198
  }
200
199
  /** Runtime-only admission; expected refusals and limits are 200 discriminated results. */
201
- function resolveChannelIdentity(store, agentTools) {
200
+ function resolveChannelIdentity(store, agentTools, guest) {
202
201
  return (request) => Effect.gen(function* () {
203
202
  const requestId = yield* RequestId;
204
203
  const decoded = Schema.decodeUnknownResult(ResolveIdentityRequest)(yield* jsonBody(request), {
@@ -223,6 +222,12 @@ function resolveChannelIdentity(store, agentTools) {
223
222
  status: resolution.status,
224
223
  ...memberForWire(resolution.member, agentTools),
225
224
  provisioned: resolution.provisioned,
225
+ ...(input.chat === "group" &&
226
+ guest?.channels.some((channel) => (channel.startsWith("channel:")
227
+ ? store.channelKind?.(channel.slice(8))
228
+ : channel) === input.provider)
229
+ ? { separate_session: true }
230
+ : {}),
226
231
  counted: resolution.counted,
227
232
  notice_due: resolution.noticeDue,
228
233
  on_new_user_pending: resolution.onNewUserPending,
@@ -882,7 +887,7 @@ export function agentLayer(options) {
882
887
  yield* router.add("POST", `${PAIRINGS_PATH}/:code/approve`, asMember((_, member) => approvePairing(store, member)));
883
888
  yield* router.add("GET", IDENTITIES_PATH, asMember((_, member) => listIdentities(store, member)));
884
889
  yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store, options.agentTools), { delegated: true }));
885
- yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store, options.agentTools)));
890
+ yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store, options.agentTools, options.guest)));
886
891
  yield* router.add("POST", `${IDENTITIES_PATH}/notice`, asRuntime(recordNotice(store)));
887
892
  yield* router.add("POST", `${IDENTITIES_PATH}/limit-notice`, asRuntime(completeLimitNotice(store)));
888
893
  for (const blocked of [true, false]) {
@@ -1017,7 +1022,7 @@ export function agentLayer(options) {
1017
1022
  })));
1018
1023
  }
1019
1024
  if (store.readGroupAccess) {
1020
- yield* router.add("POST", `${AGENT_PATH}/chats/public-invite`, asRuntime((request) => Effect.gen(function* () {
1025
+ yield* router.add("POST", `${AGENT_PATH}/chats/invite`, asRuntime((request) => Effect.gen(function* () {
1021
1026
  const requestId = yield* RequestId;
1022
1027
  const decoded = Schema.decodeUnknownResult(Schema.Struct({
1023
1028
  key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)),
@@ -1028,6 +1033,11 @@ export function agentLayer(options) {
1028
1033
  return invalidBody(requestId, schemaIssues(decoded.failure));
1029
1034
  }
1030
1035
  const { key, provider, inviter } = decoded.success;
1036
+ const channel = key.split(":", 1)[0];
1037
+ if (!options.guest?.openOnInvite?.includes(channel) ||
1038
+ store.channelKind?.(channel) !== provider) {
1039
+ return json({ opened: false });
1040
+ }
1031
1041
  const identity = yield* store.findIdentity({ provider, externalId: inviter });
1032
1042
  const principal = identity && identity.revokedAt === null
1033
1043
  ? yield* store.actingMember(identity.userId, provider)
@@ -1049,57 +1059,42 @@ export function agentLayer(options) {
1049
1059
  return json({ opened: Exit.isSuccess(result) });
1050
1060
  })));
1051
1061
  }
1052
- const readAccess = store.readGroupAccess;
1053
- const countPublicTurn = store.web?.countGuestTurn;
1054
- if (readAccess && options.publicGroupAction) {
1055
- const run = publicActionForGroup(backend, options.publicGroupAction);
1056
- yield* router.add("POST", `${AGENT_PATH}/chats/public-action`, asRuntime((request) => Effect.gen(function* () {
1062
+ if (store.channelGuest && store.web?.countGuestTurn) {
1063
+ const admit = store.channelGuest;
1064
+ const count = store.web.countGuestTurn;
1065
+ yield* router.add("POST", `${AGENT_PATH}/chats/admit-guest`, asRuntime((request) => Effect.gen(function* () {
1057
1066
  const requestId = yield* RequestId;
1058
1067
  const part = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
1059
- const decoded = Schema.decodeUnknownResult(Schema.Struct({
1068
+ const parsed = Schema.decodeUnknownResult(Schema.Struct({
1060
1069
  channel: part,
1061
1070
  chat: part,
1062
1071
  sender: part,
1063
- input: Schema.Record(Schema.String, Schema.Unknown),
1064
- }))(yield* jsonBody(request), { onExcessProperty: "error" });
1065
- if (Result.isFailure(decoded)) {
1066
- return invalidBody(requestId, schemaIssues(decoded.failure));
1067
- }
1068
- const { channel, chat, sender, input } = decoded.success;
1069
- if (JSON.stringify(input).length > 12000 ||
1070
- (yield* readAccess(`${channel}:${chat}`)) !== "public") {
1071
- return toServerResponse(forbidden(requestId, "Public action unavailable."));
1072
- }
1073
- return yield* run(request, { channel, chat, sender }, input).pipe(Effect.map((result) => json({ result })), Effect.catchCause((cause) => failureResponse(cause, requestId)));
1074
- })));
1075
- }
1076
- if (readAccess && countPublicTurn) {
1077
- yield* router.add("POST", `${AGENT_PATH}/chats/public-turn`, asRuntime((request) => Effect.gen(function* () {
1078
- const requestId = yield* RequestId;
1079
- const keyPart = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
1080
- const decoded = Schema.decodeUnknownResult(Schema.Struct({
1081
- channel: keyPart,
1082
- chat: keyPart,
1083
- sender: keyPart,
1084
- check: Schema.optionalKey(Schema.Boolean),
1072
+ message: Schema.optionalKey(part),
1073
+ purpose: Schema.optionalKey(Schema.Literal("identify")),
1085
1074
  limits: Schema.optionalKey(AgentLimitsRequest),
1086
1075
  }))(yield* jsonBody(request), { onExcessProperty: "error" });
1087
- if (Result.isFailure(decoded)) {
1088
- return invalidBody(requestId, schemaIssues(decoded.failure));
1076
+ if (Result.isFailure(parsed)) {
1077
+ return invalidBody(requestId, schemaIssues(parsed.failure));
1089
1078
  }
1090
- const { channel, chat, sender, limits } = decoded.success;
1091
- const access = yield* readAccess(`${channel}:${chat}`);
1092
- if (access !== "public") {
1079
+ const { channel, chat, sender, limits } = parsed.success;
1080
+ const principal = yield* admit(channel, chat, sender);
1081
+ if (!principal) {
1093
1082
  return json({ status: "closed" });
1094
1083
  }
1095
- if (decoded.success.check) {
1096
- return json({ status: "public" });
1097
- }
1098
- // The same sender shares a guest budget across groups on this connection.
1099
- // The id is for accounting only and never represents a workspace principal.
1100
- const guestId = groupSubject(["group-guest", channel, sender]);
1101
- const limited = yield* countPublicTurn(guestId, limits);
1102
- return json(limited ? { status: "limited" } : { status: "admitted", guestId });
1084
+ const limited = parsed.success.purpose === "identify"
1085
+ ? undefined
1086
+ : yield* count(principal.id, limits, parsed.success.message
1087
+ ? JSON.stringify([channel, chat, parsed.success.message])
1088
+ : undefined);
1089
+ return json(limited
1090
+ ? { status: "limited" }
1091
+ : {
1092
+ status: "guest",
1093
+ guestId: principal.id,
1094
+ ...(options.guest?.confirmations && { confirmations: true }),
1095
+ roles: principal.roles,
1096
+ agentTools: options.agentTools(principal),
1097
+ });
1103
1098
  })));
1104
1099
  }
1105
1100
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
@@ -1171,7 +1166,7 @@ export function agentLayer(options) {
1171
1166
  // Where an emailed link lands, signed in on the app's origin: a top-level navigation.
1172
1167
  yield* router.add("GET", GUEST_LINK_PATH, guests.link);
1173
1168
  }
1174
- if (websites.guests.length > 0 || readAccess !== undefined) {
1169
+ if (websites.guests.length > 0 || store.channelGuest !== undefined) {
1175
1170
  yield* router.add("POST", GUEST_USAGE_PATH, asRuntime(recordGuestUsage(store.web)));
1176
1171
  }
1177
1172
  }
@@ -488,7 +488,7 @@ export function actingChat(principal, provider, chat, kindOf = (channel) => chan
488
488
  * runtime may call only the agent's own routes, which authenticate it themselves. The chat it names
489
489
  * becomes the principal's, as {@link actingChat} admits it.
490
490
  */
491
- function actingMember(actAs, provider, grant, guests = false, chat) {
491
+ function actingMember(actAs, provider, grant, guests = false, chat, sender) {
492
492
  return Effect.gen(function* () {
493
493
  const backend = yield* OntologyBackend;
494
494
  if (actAs === undefined) {
@@ -507,7 +507,18 @@ function actingMember(actAs, provider, grant, guests = false, chat) {
507
507
  ? undefined
508
508
  : provider === WEB_PROVIDER
509
509
  ? yield* webMember(backend.agents, actAs, grant)
510
- : yield* backend.agents.actingMember(actAs, provider);
510
+ : actAs.startsWith("guest:")
511
+ ? guests &&
512
+ sender &&
513
+ chat &&
514
+ backend.agents.channelGuest &&
515
+ provider === backend.agents.channelKind?.(chat.provider)
516
+ ? yield* backend.agents.channelGuest(chat.provider, chat.chatId, sender)
517
+ : undefined
518
+ : yield* backend.agents.actingMember(actAs, provider);
519
+ if (member?.kind === "guest" && actAs !== `guest:${member.id}`) {
520
+ return { status: "forbidden", detail: "The guest does not match this sender." };
521
+ }
511
522
  const acting = member === undefined
512
523
  ? undefined
513
524
  : actingChat(member, provider, chat, backend.agents?.channelKind);
@@ -707,7 +718,7 @@ export function authenticate(credential, verifyToken, options = {}) {
707
718
  };
708
719
  }
709
720
  const resolved = agentTask === undefined
710
- ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true, options.runtime.chat)
721
+ ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true, options.runtime.chat, options.runtime.sender)
711
722
  : yield* agentTaskPrincipal(agentTask, actAs, options.agentTasks);
712
723
  // Narrowed, the request keeps only the reads of whom it acts for, as an OAuth grant of
713
724
  // that scope does.
@@ -60,6 +60,9 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
60
60
  } | undefined;
61
61
  readonly channel?: string | undefined;
62
62
  readonly message_id?: string | undefined;
63
+ readonly reply_to_message_id?: string | undefined;
64
+ readonly callback_query_id?: string | undefined;
65
+ readonly sender?: string | undefined;
63
66
  readonly attachments?: readonly {
64
67
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
65
68
  readonly file_id: string;
@@ -67,11 +70,8 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
67
70
  readonly file_unique_id?: string | undefined;
68
71
  readonly media_type?: string | undefined;
69
72
  }[] | undefined;
70
- readonly reply_to_message_id?: string | undefined;
71
- readonly callback_query_id?: string | undefined;
72
- readonly sender?: string | undefined;
73
73
  } | {
74
- readonly kind: "private" | "group";
74
+ readonly kind: "group" | "private";
75
75
  readonly provider: "slack" | "whatsapp";
76
76
  readonly chat_id: string;
77
77
  readonly thread_id: string;
@@ -114,6 +114,9 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
114
114
  } | undefined;
115
115
  readonly channel?: string | undefined;
116
116
  readonly message_id?: string | undefined;
117
+ readonly reply_to_message_id?: string | undefined;
118
+ readonly callback_query_id?: string | undefined;
119
+ readonly sender?: string | undefined;
117
120
  readonly attachments?: readonly {
118
121
  readonly kind: "photo" | "document" | "voice" | "audio" | "video" | "video_note" | "sticker" | "animation";
119
122
  readonly file_id: string;
@@ -121,11 +124,8 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
121
124
  readonly file_unique_id?: string | undefined;
122
125
  readonly media_type?: string | undefined;
123
126
  }[] | undefined;
124
- readonly reply_to_message_id?: string | undefined;
125
- readonly callback_query_id?: string | undefined;
126
- readonly sender?: string | undefined;
127
127
  } | {
128
- readonly kind: "private" | "group";
128
+ readonly kind: "group" | "private";
129
129
  readonly provider: "slack" | "whatsapp";
130
130
  readonly chat_id: string;
131
131
  readonly thread_id: string;
@@ -12,13 +12,13 @@ export declare function chatMessageEvent(message: ChatMessage): {
12
12
  eventId: string;
13
13
  provider: string;
14
14
  chatId: string;
15
- chatType: "channel" | "private" | "group";
15
+ chatType: "channel" | "group" | "private";
16
16
  threadId: string | null;
17
17
  participantIds: readonly string[];
18
18
  senderId: string | null;
19
19
  senderName: string | null;
20
20
  senderIsBot: boolean;
21
- kind: "inbound" | "outbound" | "internal";
21
+ kind: "outbound" | "inbound" | "internal";
22
22
  messageId: string | null;
23
23
  replyToMessageId: string | null;
24
24
  sessionId: string | null;
@@ -42,8 +42,8 @@ export declare function chatMessageEvent(message: ChatMessage): {
42
42
  sequence: string;
43
43
  storedAt: string;
44
44
  id: string;
45
- direction: "inbound" | "outbound" | "internal";
46
- author: "agent" | "human" | "bot";
45
+ direction: "outbound" | "inbound" | "internal";
46
+ author: "agent" | "bot" | "human";
47
47
  sender: {
48
48
  id: string | null;
49
49
  name: string | null;
@@ -59,7 +59,7 @@ export declare function chatMessageEvent(message: ChatMessage): {
59
59
  edited: boolean;
60
60
  deleted: boolean;
61
61
  delivery: "pending" | "read" | "sent" | "failed" | "uncertain" | "delivered" | null;
62
- disposition: "skipped" | "claimed" | "turn" | null;
62
+ disposition: "claimed" | "turn" | "skipped" | null;
63
63
  replaced_by: string | null;
64
64
  };
65
65
  /**
@@ -22,8 +22,8 @@ export declare function searchDocuments(documents: ReadonlyArray<SearchDocument>
22
22
  }[];
23
23
  readonly summary_truncated: boolean;
24
24
  readonly entity?: string | undefined;
25
- readonly tools?: readonly string[] | undefined;
26
25
  readonly metrics?: readonly string[] | undefined;
26
+ readonly tools?: readonly string[] | undefined;
27
27
  readonly relevance?: number | undefined;
28
28
  }[];
29
29
  /** Bytewise canonical-name ordering is independent of a function instance's locale. */
@@ -406,7 +406,8 @@ export function makeOperations(backend, plan, hooks, connections, replicate, cha
406
406
  /** Runs an action as the caller, with the action's after-commit hook and connections. */
407
407
  runAction: runActionOf(backend, plan, hooks, connections, replicate, chatDelivery),
408
408
  /** Calls a toolset's provider tool as the caller, through the toolset's connection. */
409
- runToolsetTool: runToolsetToolOf(connections),
409
+ runToolsetTool: runToolsetToolOf(connections, backend.agents?.web?.recordGuestUsage &&
410
+ ((guestId, costUsd, key) => backend.agents.web.recordGuestUsage({ guestId, costUsd, key }))),
410
411
  /** The caller's user, roles and permissions. It needs no permission. */
411
412
  caller: callerOf(backend, plan.ontology),
412
413
  };
@@ -299,7 +299,7 @@ export interface AgentWebStore {
299
299
  * together, apart from the counters of people who signed up. `limits` are kept first, as for
300
300
  * {@link countTurn}. The limit the turn exceeds, or `undefined` when it may run.
301
301
  */
302
- readonly countGuestTurn?: (guestId: string, limits?: ResolveIdentityInput["limits"]) => Effect.Effect<WebTurnLimit | undefined>;
302
+ readonly countGuestTurn?: (guestId: string, limits?: ResolveIdentityInput["limits"], delivery?: string) => Effect.Effect<WebTurnLimit | undefined>;
303
303
  /**
304
304
  * Adds the model cost of a guest's turn, in US dollars, to that day's spend of the guest and of
305
305
  * every guest together, which {@link countGuestTurn} holds against the agent's
@@ -685,6 +685,8 @@ export interface AgentStore {
685
685
  * it has none. Concurrent calls for one chat leave one record.
686
686
  */
687
687
  readonly claimChatPersonaNotice?: (id: string, memberId: string) => Effect.Effect<boolean>;
688
+ /** Recheck the current chat and sender for every runtime guest tool call. */
689
+ readonly channelGuest?: (channel: string, chat: string, sender: string) => Effect.Effect<Principal | undefined>;
688
690
  readonly readGroupAccess?: (key: string) => Effect.Effect<string | null>;
689
691
  readonly readChatPersona?: (key: string) => Effect.Effect<string | null>;
690
692
  readonly seeChat: (input: {
@@ -114,6 +114,7 @@ export interface RuntimeCredential {
114
114
  readonly agentTask?: Redacted.Redacted<string>;
115
115
  /** The grant in `X-SegmentStream-Agent-Grant`; `undefined` without the header. */
116
116
  readonly grant?: string;
117
+ readonly sender?: string;
117
118
  /** The scope in `X-SegmentStream-Agent-Scope`; `undefined` without the header. */
118
119
  readonly scope?: string;
119
120
  /**
@@ -170,6 +170,7 @@ export function runtimeCredential(verify, request) {
170
170
  const provider = request.headers[ACT_AS_PROVIDER_HEADER]?.trim();
171
171
  const agentTask = agentTaskSecret(request);
172
172
  const grant = request.headers[AGENT_GRANT_HEADER]?.trim();
173
+ const sender = request.headers["x-segmentstream-chat-sender"]?.trim();
173
174
  const scope = request.headers[AGENT_SCOPE_HEADER]?.trim();
174
175
  const chat = requestChat(request);
175
176
  return {
@@ -178,6 +179,7 @@ export function runtimeCredential(verify, request) {
178
179
  ...(provider ? { provider } : {}),
179
180
  ...(agentTask === undefined ? {} : { agentTask }),
180
181
  ...(grant ? { grant } : {}),
182
+ ...(sender && sender.length <= 256 ? { sender } : {}),
181
183
  ...(scope ? { scope } : {}),
182
184
  ...(chat === undefined ? {} : { chat }),
183
185
  };
@@ -463,6 +463,8 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
463
463
  }>>;
464
464
  readonly onSignUp: Schema.optionalKey<Schema.String>;
465
465
  readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
466
+ readonly openOnInvite: Schema.optionalKey<Schema.$Array<Schema.String>>;
467
+ readonly byChannel: Schema.optionalKey<Schema.$Record<Schema.String, Schema.$Array<Schema.String>>>;
466
468
  readonly channels: Schema.$Array<Schema.String>;
467
469
  readonly origins: Schema.$Array<Schema.String>;
468
470
  readonly botCheck: Schema.optionalKey<Schema.Struct<{
@@ -854,6 +856,8 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
854
856
  }>>;
855
857
  readonly onSignUp: Schema.optionalKey<Schema.String>;
856
858
  readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
859
+ readonly openOnInvite: Schema.optionalKey<Schema.$Array<Schema.String>>;
860
+ readonly byChannel: Schema.optionalKey<Schema.$Record<Schema.String, Schema.$Array<Schema.String>>>;
857
861
  readonly channels: Schema.$Array<Schema.String>;
858
862
  readonly origins: Schema.$Array<Schema.String>;
859
863
  readonly botCheck: Schema.optionalKey<Schema.Struct<{
@@ -457,16 +457,6 @@ export function createOntologyService(ontology, config) {
457
457
  verifyToken,
458
458
  verifyRuntime,
459
459
  exchangeSession,
460
- ...(!preview &&
461
- ontology.config.publicGroupAction && {
462
- publicGroupAction: {
463
- binding: ontology.config.publicGroupAction,
464
- plan,
465
- hooks,
466
- connections,
467
- replicate,
468
- },
469
- }),
470
460
  visitorWebsites: preview ? { guests: [], signUp: [] } : visitorWebsites,
471
461
  agentTools,
472
462
  guest: preview ? undefined : guest,
@@ -49,4 +49,4 @@ export declare function resultText(result: ToolResult): string;
49
49
  * fixed values replace whatever the caller sent for them; the call goes through the toolset's
50
50
  * connection, audited as `<toolset>.<tool>`.
51
51
  */
52
- export declare function runToolsetToolOf(connections: ConnectionTransportFactory): (toolset: ResolvedToolset, tool: ResolvedTool, call: ToolsetCall) => Effect.Effect<ToolResult, ActionRejected | PermissionDenied | ConnectionError, RequestId | CurrentPrincipal>;
52
+ export declare function runToolsetToolOf(connections: ConnectionTransportFactory, reportCost?: (guestId: string, costUsd: number, key: string) => Effect.Effect<void>): (toolset: ResolvedToolset, tool: ResolvedTool, call: ToolsetCall) => Effect.Effect<ToolResult, ActionRejected | PermissionDenied | ConnectionError, RequestId | CurrentPrincipal>;