@segmentstream/ontology 0.180.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.
Files changed (50) hide show
  1. package/CHANGELOG.md +31 -0
  2. package/dist/agent-chat.d.ts +2 -2
  3. package/dist/agent-chat.js +2 -1
  4. package/dist/agent-draft.d.ts +8 -8
  5. package/dist/analyze.d.ts +1 -8
  6. package/dist/analyze.js +108 -52
  7. package/dist/index.d.ts +1 -1
  8. package/dist/manifest.d.ts +110 -68
  9. package/dist/manifest.js +24 -2
  10. package/dist/migrate/model.d.ts +78 -50
  11. package/dist/review.d.ts +46 -0
  12. package/dist/review.js +47 -0
  13. package/dist/runtime/agent-web.js +47 -26
  14. package/dist/runtime/agents.js +53 -4
  15. package/dist/runtime/guests.d.ts +4 -1
  16. package/dist/runtime/guests.js +24 -5
  17. package/dist/service/agent/protocol.d.ts +51 -0
  18. package/dist/service/agent/protocol.js +66 -1
  19. package/dist/service/agent/server.d.ts +8 -2
  20. package/dist/service/agent/server.js +208 -48
  21. package/dist/service/authentication.js +14 -3
  22. package/dist/service/chat/archive.d.ts +8 -1
  23. package/dist/service/chat/delivery.js +3 -1
  24. package/dist/service/chat/envelope.d.ts +8 -8
  25. package/dist/service/chat/local-reads.d.ts +5 -5
  26. package/dist/service/chat/providers/custom.js +2 -0
  27. package/dist/service/chat/providers/provider.d.ts +5 -0
  28. package/dist/service/chat/reply-proposal.d.ts +122 -0
  29. package/dist/service/chat/reply-proposal.js +385 -0
  30. package/dist/service/chat/review-delivery.d.ts +131 -24
  31. package/dist/service/chat/review-delivery.js +393 -296
  32. package/dist/service/chat/store-delivery.d.ts +27 -5
  33. package/dist/service/chat/store-delivery.js +45 -33
  34. package/dist/service/discovery-search.d.ts +1 -1
  35. package/dist/service/operations.js +2 -1
  36. package/dist/service/runtime-contract.d.ts +33 -1
  37. package/dist/service/runtime-identity.d.ts +1 -0
  38. package/dist/service/runtime-identity.js +2 -0
  39. package/dist/service/schemas.d.ts +4 -0
  40. package/dist/service/service.js +12 -14
  41. package/dist/service/toolsets.d.ts +1 -1
  42. package/dist/service/toolsets.js +38 -4
  43. package/dist/sign-in.d.ts +14 -7
  44. package/dist/sign-in.js +4 -3
  45. package/dist/toolset.d.ts +17 -1
  46. package/dist/workspace-channel.d.ts +6 -0
  47. package/dist/workspace-channel.js +27 -0
  48. package/package.json +5 -1
  49. package/dist/service/agent/public-group-action.d.ts +0 -23
  50. package/dist/service/agent/public-group-action.js +0 -53
@@ -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,17 +10,18 @@ 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";
18
17
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
19
- import { AgentLimitsRequest, ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
18
+ import { AgentLimitsRequest, ChatHandoffRequest, ChatSeenRequest, DraftFilesRequest, ReplyProposalRequest, ReviewRequest, RevisionRequest, SessionReviewsRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
20
19
  import { AGENT_TOKEN_LIMIT, BOT_CHECK_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
21
20
  import { issueEvalToken } from "./eval-tokens.js";
22
21
  import { CHAT_MESSAGE_PATHS, changeChatMessage, purgeChatMessages, readChatMessages, recordChatMessage, } from "./chat-message-routes.js";
23
22
  import { CHAT_RETENTION_DAYS } from "../../manifest.js";
24
23
  import { snapshotDraftFiles } from "../chat/draft-files.js";
24
+ import { chatKind } from "../chat/providers/index.js";
25
25
  import { parseChatCursor } from "../../runtime/chat-messages.js";
26
26
  import { GUEST_LINK_PATH, guestRoutesPreflight, guestSignUpRoutes, recordGuestUsage, } from "./guest-sign-up.js";
27
27
  import { identityToken } from "../operations.js";
@@ -35,6 +35,8 @@ const DRAFTS_PATH = `${AGENT_PATH}/drafts`;
35
35
  // @legacy agent.review-runtime-paths
36
36
  // The drafts' routes under their earlier name, which agent SDKs released before them call.
37
37
  const REVIEWS_PATH = `${AGENT_PATH}/reviews`;
38
+ /** Where the agent proposes a turn's reply, which the ontology sends or holds by its review. */
39
+ export const AGENT_REPLIES_PATH = `${AGENT_PATH}/replies`;
38
40
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
39
41
  export const AGENT_TOKENS_PATH = `${AGENT_PATH}/tokens`;
40
42
  export const AGENT_TOKEN_INTROSPECTION_PATH = `${AGENT_TOKENS_PATH}/introspect`;
@@ -195,7 +197,7 @@ function resolveIdentity(store, agentTools) {
195
197
  });
196
198
  }
197
199
  /** Runtime-only admission; expected refusals and limits are 200 discriminated results. */
198
- function resolveChannelIdentity(store, agentTools) {
200
+ function resolveChannelIdentity(store, agentTools, guest) {
199
201
  return (request) => Effect.gen(function* () {
200
202
  const requestId = yield* RequestId;
201
203
  const decoded = Schema.decodeUnknownResult(ResolveIdentityRequest)(yield* jsonBody(request), {
@@ -220,6 +222,12 @@ function resolveChannelIdentity(store, agentTools) {
220
222
  status: resolution.status,
221
223
  ...memberForWire(resolution.member, agentTools),
222
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
+ : {}),
223
231
  counted: resolution.counted,
224
232
  notice_due: resolution.noticeDue,
225
233
  on_new_user_pending: resolution.onNewUserPending,
@@ -495,6 +503,167 @@ function holdReply(store, backend, manifest) {
495
503
  return json({ id: review.id, status: review.status, created: review.created });
496
504
  });
497
505
  }
506
+ /**
507
+ * `POST /api/ontology/agent/replies` (runtime): the reply a turn wrote, which the agent proposes
508
+ * rather than sends. The ontology applies the agent's `review` with the roles the person holds now
509
+ * (`replies`): a reply it lets go is sent through the chat's channel as an approved draft is, and
510
+ * any other is held as the drafts route holds it. Each outcome is answered with the review applied;
511
+ * a delivery that failed, or may have, is an outcome like a sent one, and so is a reply its review
512
+ * holds that is longer than a draft holds (`failed`, `draft_too_long`). 404 when this service sends
513
+ * no proposed replies, or its chat store, where they are decided, holds no message yet, which the
514
+ * agent takes for an ontology that predates them; 409 `proposal_conflict` for another reply under
515
+ * a key that decided one; 422 when the person is no longer an active member, or a file is
516
+ * refused. A refused proposal sends and holds nothing.
517
+ */
518
+ function proposeReply(store, backend, manifest, replies) {
519
+ return (request) => Effect.gen(function* () {
520
+ const requestId = yield* RequestId;
521
+ const decoded = Schema.decodeUnknownResult(ReplyProposalRequest)(yield* jsonBody(request), {
522
+ errors: "all",
523
+ onExcessProperty: "error",
524
+ });
525
+ if (Result.isFailure(decoded)) {
526
+ return invalidBody(requestId, schemaIssues(decoded.failure));
527
+ }
528
+ const messages = store.chatMessages;
529
+ if (replies === undefined ||
530
+ messages === undefined ||
531
+ store.holdProposal === undefined ||
532
+ store.reserveProposal === undefined) {
533
+ return toServerResponse(notFound(requestId, "This ontology service sends no proposed replies."));
534
+ }
535
+ const body = decoded.success;
536
+ const channel = body.channel ?? body.provider;
537
+ const refuse = (error, extra = {}, status = 422) => HttpServerResponse.jsonUnsafe({ error, ...extra, request_id: requestId }, { status, headers: NO_STORE });
538
+ // A channel named after a kind is that kind, and a workspace channel has a name of its own,
539
+ // of the kind the ontology declares it with, when it declares it.
540
+ if (body.channel !== undefined &&
541
+ isChatChannelKind(body.channel) &&
542
+ channel !== body.provider) {
543
+ return invalidBody(requestId, [
544
+ { path: ["channel"], message: "A channel named after a kind is that kind." },
545
+ ]);
546
+ }
547
+ if (body.provider === WORKSPACE_CHANNEL_KIND && channel === WORKSPACE_CHANNEL_KIND) {
548
+ return invalidBody(requestId, [
549
+ { path: ["channel"], message: "A workspace channel's reply names its channel." },
550
+ ]);
551
+ }
552
+ const declared = chatKind(manifest?.chat, channel);
553
+ if (declared !== undefined && declared !== body.provider) {
554
+ return invalidBody(requestId, [
555
+ { path: ["provider"], message: `The ontology declares ${channel} as ${declared}.` },
556
+ ]);
557
+ }
558
+ // Only a reply to mail names whom it goes to beside its recipient.
559
+ if (body.provider !== "email" && (body.to !== undefined || body.cc !== undefined)) {
560
+ return invalidBody(requestId, [
561
+ { path: [body.to === undefined ? "cc" : "to"], message: "Only a reply to mail has it." },
562
+ ]);
563
+ }
564
+ // Only a workspace channel's code sets the length its provider takes.
565
+ if (body.provider !== WORKSPACE_CHANNEL_KIND && body.max_length !== undefined) {
566
+ return invalidBody(requestId, [
567
+ { path: ["max_length"], message: "Only a workspace channel's reply has it." },
568
+ ]);
569
+ }
570
+ const text = body.text ?? "";
571
+ // A reply is its text, its files, or both; its files' captions go with its files.
572
+ if (text.trim() === "" && body.files === undefined) {
573
+ return invalidBody(requestId, [
574
+ { path: ["text"], message: "A reply without files has text." },
575
+ ]);
576
+ }
577
+ if (body.caption !== undefined && body.files === undefined) {
578
+ return invalidBody(requestId, [
579
+ { path: ["caption"], message: "Only a reply with files has captions." },
580
+ ]);
581
+ }
582
+ if (body.basis !== null && parseChatCursor(body.basis) === undefined) {
583
+ return invalidBody(requestId, [
584
+ { path: ["basis"], message: "The chat's place is <time>~<id>." },
585
+ ]);
586
+ }
587
+ // The review applies to the person as they are now: one no longer active is no one's.
588
+ const member = yield* store.member(body.member_id);
589
+ if (member === undefined) {
590
+ return refuse("member_inactive");
591
+ }
592
+ // @legacy agent.cloud-chat-archive A proposal is decided, and found again, on the workspace
593
+ // chat store: until it holds a message, the agent reviews the reply itself, as before.
594
+ if (!(yield* messages.holds())) {
595
+ return toServerResponse(notFound(requestId, "This ontology service decides replies once its chat store holds one."));
596
+ }
597
+ const answered = yield* replies({
598
+ backend,
599
+ identityToken: identityToken(request),
600
+ requestId,
601
+ })({
602
+ key: body.key,
603
+ provider: body.provider,
604
+ channel,
605
+ chatId: body.chat_id,
606
+ recipient: body.recipient,
607
+ ...(body.to === undefined ? {} : { to: body.to.map((address) => address.toLowerCase()) }),
608
+ ...(body.cc === undefined ? {} : { cc: body.cc.map((address) => address.toLowerCase()) }),
609
+ ...(body.participants === undefined
610
+ ? {}
611
+ : { participants: [...new Set(body.participants.map((id) => id.toLowerCase()))] }),
612
+ threadId: body.thread_id,
613
+ replyTo: body.reply_to,
614
+ memberId: body.member_id,
615
+ sessionId: body.session_id,
616
+ turnId: body.turn_id,
617
+ text,
618
+ ...(body.caption === undefined ? {} : { caption: body.caption }),
619
+ files: body.files ?? [],
620
+ review: body.review,
621
+ confidence: body.confidence,
622
+ basis: body.basis,
623
+ ...(body.max_length === undefined ? {} : { maxLength: body.max_length }),
624
+ }, member).pipe(Effect.result);
625
+ if (Result.isFailure(answered)) {
626
+ const failure = answered.failure;
627
+ yield* Effect.logWarning("ontology.agent.reply_refused").pipe(Effect.annotateLogs({ requestId, channel, reason: failure.message }));
628
+ // Another reply under a key that decided one is a conflict, as a changed approval is.
629
+ return failure._tag === "ActionRejected"
630
+ ? refuse(failure.refusal ?? "reply_refused", { message: failure.message }, failure.refusal === "proposal_conflict" ? 409 : 422)
631
+ : toServerResponse(forbidden(requestId, failure.message));
632
+ }
633
+ const answer = answered.success;
634
+ if (answer === undefined) {
635
+ return refuse("member_inactive");
636
+ }
637
+ if ("refused" in answer) {
638
+ yield* Effect.logInfo("ontology.agent.reply_files_refused").pipe(Effect.annotateLogs({ requestId, channel, refusal: answer.refused }));
639
+ return refuse(answer.refused, answer.index === undefined ? {} : { index: answer.index });
640
+ }
641
+ const review = {
642
+ mode: answer.review.mode,
643
+ ...(answer.review.mode === "whenUnsure"
644
+ ? { min_confidence: answer.review.minConfidence }
645
+ : {}),
646
+ };
647
+ yield* Effect.logInfo("ontology.agent.reply_proposed").pipe(Effect.annotateLogs({
648
+ requestId,
649
+ provider: body.provider,
650
+ channel,
651
+ outcome: answer.outcome,
652
+ mode: answer.review.mode,
653
+ duplicate: answer.duplicate,
654
+ }));
655
+ return answer.outcome === "held"
656
+ ? json({ outcome: "held", draft: answer.draft, duplicate: answer.duplicate, review })
657
+ : json({
658
+ outcome: answer.outcome,
659
+ message_id: answer.messageId,
660
+ duplicate: answer.duplicate,
661
+ ...(answer.refusal === undefined ? {} : { refusal: answer.refusal }),
662
+ ...(answer.files === undefined ? {} : { files: answer.files }),
663
+ review,
664
+ });
665
+ });
666
+ }
498
667
  /**
499
668
  * `POST /api/ontology/agent/drafts/files` (runtime): the files a reply would carry, read as the
500
669
  * member it is for and checked against its channel as holding the reply checks them, without
@@ -718,7 +887,7 @@ export function agentLayer(options) {
718
887
  yield* router.add("POST", `${PAIRINGS_PATH}/:code/approve`, asMember((_, member) => approvePairing(store, member)));
719
888
  yield* router.add("GET", IDENTITIES_PATH, asMember((_, member) => listIdentities(store, member)));
720
889
  yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store, options.agentTools), { delegated: true }));
721
- 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)));
722
891
  yield* router.add("POST", `${IDENTITIES_PATH}/notice`, asRuntime(recordNotice(store)));
723
892
  yield* router.add("POST", `${IDENTITIES_PATH}/limit-notice`, asRuntime(completeLimitNotice(store)));
724
893
  for (const blocked of [true, false]) {
@@ -853,7 +1022,7 @@ export function agentLayer(options) {
853
1022
  })));
854
1023
  }
855
1024
  if (store.readGroupAccess) {
856
- 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* () {
857
1026
  const requestId = yield* RequestId;
858
1027
  const decoded = Schema.decodeUnknownResult(Schema.Struct({
859
1028
  key: Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(1024)),
@@ -864,6 +1033,11 @@ export function agentLayer(options) {
864
1033
  return invalidBody(requestId, schemaIssues(decoded.failure));
865
1034
  }
866
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
+ }
867
1041
  const identity = yield* store.findIdentity({ provider, externalId: inviter });
868
1042
  const principal = identity && identity.revokedAt === null
869
1043
  ? yield* store.actingMember(identity.userId, provider)
@@ -885,57 +1059,42 @@ export function agentLayer(options) {
885
1059
  return json({ opened: Exit.isSuccess(result) });
886
1060
  })));
887
1061
  }
888
- const readAccess = store.readGroupAccess;
889
- const countPublicTurn = store.web?.countGuestTurn;
890
- if (readAccess && options.publicGroupAction) {
891
- const run = publicActionForGroup(backend, options.publicGroupAction);
892
- 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* () {
893
1066
  const requestId = yield* RequestId;
894
1067
  const part = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
895
- const decoded = Schema.decodeUnknownResult(Schema.Struct({
1068
+ const parsed = Schema.decodeUnknownResult(Schema.Struct({
896
1069
  channel: part,
897
1070
  chat: part,
898
1071
  sender: part,
899
- input: Schema.Record(Schema.String, Schema.Unknown),
900
- }))(yield* jsonBody(request), { onExcessProperty: "error" });
901
- if (Result.isFailure(decoded)) {
902
- return invalidBody(requestId, schemaIssues(decoded.failure));
903
- }
904
- const { channel, chat, sender, input } = decoded.success;
905
- if (JSON.stringify(input).length > 12000 ||
906
- (yield* readAccess(`${channel}:${chat}`)) !== "public") {
907
- return toServerResponse(forbidden(requestId, "Public action unavailable."));
908
- }
909
- return yield* run(request, { channel, chat, sender }, input).pipe(Effect.map((result) => json({ result })), Effect.catchCause((cause) => failureResponse(cause, requestId)));
910
- })));
911
- }
912
- if (readAccess && countPublicTurn) {
913
- yield* router.add("POST", `${AGENT_PATH}/chats/public-turn`, asRuntime((request) => Effect.gen(function* () {
914
- const requestId = yield* RequestId;
915
- const keyPart = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(256));
916
- const decoded = Schema.decodeUnknownResult(Schema.Struct({
917
- channel: keyPart,
918
- chat: keyPart,
919
- sender: keyPart,
920
- check: Schema.optionalKey(Schema.Boolean),
1072
+ message: Schema.optionalKey(part),
1073
+ purpose: Schema.optionalKey(Schema.Literal("identify")),
921
1074
  limits: Schema.optionalKey(AgentLimitsRequest),
922
1075
  }))(yield* jsonBody(request), { onExcessProperty: "error" });
923
- if (Result.isFailure(decoded)) {
924
- return invalidBody(requestId, schemaIssues(decoded.failure));
1076
+ if (Result.isFailure(parsed)) {
1077
+ return invalidBody(requestId, schemaIssues(parsed.failure));
925
1078
  }
926
- const { channel, chat, sender, limits } = decoded.success;
927
- const access = yield* readAccess(`${channel}:${chat}`);
928
- if (access !== "public") {
1079
+ const { channel, chat, sender, limits } = parsed.success;
1080
+ const principal = yield* admit(channel, chat, sender);
1081
+ if (!principal) {
929
1082
  return json({ status: "closed" });
930
1083
  }
931
- if (decoded.success.check) {
932
- return json({ status: "public" });
933
- }
934
- // The same sender shares a guest budget across groups on this connection.
935
- // The id is for accounting only and never represents a workspace principal.
936
- const guestId = groupSubject(["group-guest", channel, sender]);
937
- const limited = yield* countPublicTurn(guestId, limits);
938
- 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
+ });
939
1098
  })));
940
1099
  }
941
1100
  yield* router.add("POST", CHATS_SEEN_PATH, asRuntime(seeChat(store)));
@@ -960,6 +1119,7 @@ export function agentLayer(options) {
960
1119
  yield* router.add("POST", `${path}/revision`, asRuntime(revision(store)));
961
1120
  }
962
1121
  yield* router.add("POST", `${DRAFTS_PATH}/files`, asRuntime(checkDraftFiles(store, backend, options.manifest)));
1122
+ yield* router.add("POST", AGENT_REPLIES_PATH, asRuntime(proposeReply(store, backend, options.manifest, options.replies)));
963
1123
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
964
1124
  if (store.web !== undefined && backend.oauth !== undefined) {
965
1125
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
@@ -1006,7 +1166,7 @@ export function agentLayer(options) {
1006
1166
  // Where an emailed link lands, signed in on the app's origin: a top-level navigation.
1007
1167
  yield* router.add("GET", GUEST_LINK_PATH, guests.link);
1008
1168
  }
1009
- if (websites.guests.length > 0 || readAccess !== undefined) {
1169
+ if (websites.guests.length > 0 || store.channelGuest !== undefined) {
1010
1170
  yield* router.add("POST", GUEST_USAGE_PATH, asRuntime(recordGuestUsage(store.web)));
1011
1171
  }
1012
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.
@@ -27,7 +27,8 @@ export interface DeliveryEvent {
27
27
  readonly messageId: string | null;
28
28
  readonly replyToMessageId: string | null;
29
29
  readonly sessionId: string | null;
30
- readonly turnId: null;
30
+ /** The agent's turn that wrote the message: a reply it proposed, which the ontology sent. */
31
+ readonly turnId: string | null;
31
32
  readonly text: string;
32
33
  readonly decision: null;
33
34
  /** A refused delivery's receipt: why the provider refused it, such as outside_reply_window. */
@@ -46,6 +47,12 @@ export interface DeliveryEvent {
46
47
  readonly requestedBy: ChatRequester;
47
48
  readonly url: string | null;
48
49
  readonly at: string;
50
+ /**
51
+ * The whole reply a proposal's first message belongs to, as a digest the workspace chat store
52
+ * keeps with the message's delivery, so another reply proposed under its key is refused. Only
53
+ * the store takes it: a delivery in the archive in Cloud never has one.
54
+ */
55
+ readonly binding?: string;
49
56
  }
50
57
  export interface DeliveryCommand {
51
58
  readonly phase: "reserve" | "receipt";
@@ -592,7 +592,9 @@ chats) {
592
592
  });
593
593
  const key = deliveryKeyDigest(input.idempotencyKey);
594
594
  // The key's claim and receipt live on the workspace chat store once it holds a message.
595
- const archive = yield* deliveryArchiveOf(context.backend, cloud, retentionDays);
595
+ const archive = yield* deliveryArchiveOf(context.backend, cloud, retentionDays, {
596
+ unnamedSends: provider.unnamedSends === true,
597
+ });
596
598
  const unreserved = (cause) => new ActionRejected({
597
599
  cause,
598
600
  message: cause.diagnostic === "chat_archive_conflict"
@@ -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
  /**
@@ -129,4 +129,6 @@ export const customProvider = {
129
129
  // bound; the channel refuses those past its own `limits.fileBytes`, sending nothing.
130
130
  files: { count: AGENT_DRAFT_FILES_LIMIT, bytes: WORKSPACE_CHANNEL_MAXIMUM_FILES_BYTES },
131
131
  send: sendThroughAgent,
132
+ // The channel's `send` may take a message without the provider's id of it.
133
+ unnamedSends: true,
132
134
  };
@@ -187,6 +187,11 @@ export interface ChatProvider {
187
187
  }>) => ChatFilesRefusal | undefined;
188
188
  /** One attempt: `sent` only when the provider's answer proves it. */
189
189
  readonly send: (input: ChatSend) => Effect.Effect<ProviderOutcome>;
190
+ /**
191
+ * Whether a message the provider took may have no id of it, as a workspace channel's `send` may
192
+ * answer none: its `sent` receipt then names none. Omitted, a `sent` message has its id.
193
+ */
194
+ readonly unnamedSends?: true;
190
195
  /**
191
196
  * Whom a reply in a thread several people share goes to, read from the provider before anything
192
197
  * is reserved or sent, for a provider whose chat can be such a thread, such as a mailbox's: the