@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,23 +1,45 @@
1
1
  import { Effect } from "effect";
2
- import { type ChatMessageStore } from "../../runtime/chat-messages.js";
2
+ import { type ChatMessageStore, type ChatSend } from "../../runtime/chat-messages.js";
3
3
  import type { OntologyBackend } from "../runtime-contract.js";
4
- import { type DeliveryArchive } from "./archive.js";
4
+ import { type DeliveryArchive, type DeliveryReceipt } from "./archive.js";
5
5
  /**
6
6
  * A delivery's key on the store: one per caller scope and idempotency key, an opaque digest of
7
7
  * both, so neither digest is shown to the chat's readers. No channel's queue of sends due holds it.
8
8
  */
9
9
  export declare function deliveryOperation(scope: string, key: string): string;
10
+ /** The whole reply a proposal's first message belongs to, as its row keeps it; none otherwise. */
11
+ export declare function sendBinding(row: ChatSend): string | undefined;
12
+ /**
13
+ * What a key's delivery answers, from its row. Reported, a `sent` receipt whose message the
14
+ * provider later reported failed reads `failed` with its refusal; the receipt phase reads the
15
+ * receipt as recorded, which its caller compares with its own outcome. `operation` names the
16
+ * attempt that reserved it where the row no longer does, its `meta` gone with a deletion or
17
+ * retention. A row past `retentionDays` or scrubbed to its tombstone answers its outcome without
18
+ * its message.
19
+ */
20
+ export declare function storedReceipt(row: ChatSend, input: {
21
+ readonly operation: string;
22
+ readonly retentionDays: number;
23
+ readonly reported: boolean;
24
+ readonly inserted?: boolean;
25
+ }): DeliveryReceipt;
10
26
  /**
11
27
  * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
12
28
  * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
13
29
  * request claims nothing and answers the row's receipt, and another request is a conflict. Only
14
30
  * the claim records the receipt, once; another outcome for it is a conflict. A row past
15
- * `retentionDays` or scrubbed to its tombstone answers its outcome without its message.
31
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message. A `sent`
32
+ * receipt names the provider's id of the message, unless `unnamedSends`: the channel's provider may
33
+ * take a message without naming it, as a workspace channel's code may.
16
34
  */
17
- export declare function storeDeliveryArchive(store: ChatMessageStore, retentionDays: number): DeliveryArchive;
35
+ export declare function storeDeliveryArchive(store: ChatMessageStore, retentionDays: number, options?: {
36
+ readonly unnamedSends?: boolean;
37
+ }): DeliveryArchive;
18
38
  /**
19
39
  * Where a delivery reserves and receipts its key: the workspace chat store once it holds a message,
20
40
  * the evidence that the agent records there, as a chat's history is imported there from then on.
21
41
  * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
22
42
  */
23
- export declare function deliveryArchiveOf(backend: OntologyBackend["Service"], cloud: DeliveryArchive, retentionDays: number): Effect.Effect<DeliveryArchive>;
43
+ export declare function deliveryArchiveOf(backend: OntologyBackend["Service"], cloud: DeliveryArchive, retentionDays: number, options?: {
44
+ readonly unnamedSends?: boolean;
45
+ }): Effect.Effect<DeliveryArchive>;
@@ -61,6 +61,11 @@ function object(value) {
61
61
  ? value
62
62
  : undefined;
63
63
  }
64
+ /** The whole reply a proposal's first message belongs to, as its row keeps it; none otherwise. */
65
+ export function sendBinding(row) {
66
+ const binding = object(object(row.meta)?.delivery)?.binding;
67
+ return typeof binding === "string" ? binding : undefined;
68
+ }
64
69
  function claimOf(row) {
65
70
  const claim = object(object(row.meta)?.delivery);
66
71
  return {
@@ -101,43 +106,47 @@ const conflict = (reason, cause) => new DeliveryArchiveError({
101
106
  });
102
107
  /** The store could not be read or written: nothing was reserved, or the receipt is not recorded. */
103
108
  const storeFailure = (diagnostic, cause) => Effect.fail(new DeliveryArchiveError({ diagnostic, cause }));
109
+ /**
110
+ * What a key's delivery answers, from its row. Reported, a `sent` receipt whose message the
111
+ * provider later reported failed reads `failed` with its refusal; the receipt phase reads the
112
+ * receipt as recorded, which its caller compares with its own outcome. `operation` names the
113
+ * attempt that reserved it where the row no longer does, its `meta` gone with a deletion or
114
+ * retention. A row past `retentionDays` or scrubbed to its tombstone answers its outcome without
115
+ * its message.
116
+ */
117
+ export function storedReceipt(row, input) {
118
+ const claim = claimOf(row);
119
+ const recorded = recordedOf(row);
120
+ const expired = row.purged || Date.parse(row.at) < Date.now() - input.retentionDays * DAY_MS;
121
+ const retained = !expired && recorded !== undefined;
122
+ const failedLater = input.reported && recorded === "sent" && row.status === "failed";
123
+ const status = failedLater ? "failed" : (recorded ?? "uncertain");
124
+ // Retention scrubs a refusal with the message, as the archive in Cloud did.
125
+ const reason = status === "failed" && !row.purged ? row.failure : null;
126
+ return {
127
+ version: 1,
128
+ claimed: false,
129
+ duplicate: input.inserted !== true,
130
+ operationId: claim.operation ?? input.operation,
131
+ status,
132
+ messageId: retained ? row.messageId : null,
133
+ url: retained ? (claim.url ?? null) : null,
134
+ historyRecorded: retained,
135
+ ...(status === "failed" && reason !== null && REFUSAL.test(reason) ? { refusal: reason } : {}),
136
+ };
137
+ }
104
138
  /**
105
139
  * The delivery archive on the workspace chat store, by the chat archive in Cloud's protocol: the
106
140
  * first reservation of a key is `claimed` with the row's id as its claim; a replay with the same
107
141
  * request claims nothing and answers the row's receipt, and another request is a conflict. Only
108
142
  * the claim records the receipt, once; another outcome for it is a conflict. A row past
109
- * `retentionDays` or scrubbed to its tombstone answers its outcome without its message.
143
+ * `retentionDays` or scrubbed to its tombstone answers its outcome without its message. A `sent`
144
+ * receipt names the provider's id of the message, unless `unnamedSends`: the channel's provider may
145
+ * take a message without naming it, as a workspace channel's code may.
110
146
  */
111
- export function storeDeliveryArchive(store, retentionDays) {
147
+ export function storeDeliveryArchive(store, retentionDays, options = {}) {
112
148
  const expired = (row) => row.purged || Date.parse(row.at) < Date.now() - retentionDays * DAY_MS;
113
- /**
114
- * What a key's delivery answers. Reported, a `sent` receipt whose message the provider later
115
- * reported failed reads `failed` with its refusal; the receipt phase reads the receipt as
116
- * recorded, which its caller compares with its own outcome. `operation` names the attempt that
117
- * reserved it where the row no longer does, its `meta` gone with a deletion or retention.
118
- */
119
- const answer = (row, operation, reported, inserted = false) => {
120
- const claim = claimOf(row);
121
- const recorded = recordedOf(row);
122
- const retained = !expired(row) && recorded !== undefined;
123
- const failedLater = reported && recorded === "sent" && row.status === "failed";
124
- const status = failedLater ? "failed" : (recorded ?? "uncertain");
125
- // Retention scrubs a refusal with the message, as the archive in Cloud did.
126
- const reason = status === "failed" && !row.purged ? row.failure : null;
127
- return {
128
- version: 1,
129
- claimed: false,
130
- duplicate: !inserted,
131
- operationId: claim.operation ?? operation,
132
- status,
133
- messageId: retained ? row.messageId : null,
134
- url: retained ? (claim.url ?? null) : null,
135
- historyRecorded: retained,
136
- ...(status === "failed" && reason !== null && REFUSAL.test(reason)
137
- ? { refusal: reason }
138
- : {}),
139
- };
140
- };
149
+ const answer = (row, operation, reported, inserted = false) => storedReceipt(row, { operation, retentionDays, reported, inserted });
141
150
  /** The key's row, which a reservation that found it must have. */
142
151
  const sendOf = (operation) => store
143
152
  .findSend(operation)
@@ -191,6 +200,7 @@ export function storeDeliveryArchive(store, retentionDays) {
191
200
  // while the request alone still finds the key's receipt.
192
201
  fingerprint: `${delivery.fingerprint}:${payloadFingerprint(event)}`,
193
202
  ...(event.sessionId === null ? {} : { sessionId: event.sessionId }),
203
+ ...(event.turnId === null ? {} : { turnId: event.turnId }),
194
204
  meta: {
195
205
  ...payloadOf(event),
196
206
  delivery: {
@@ -201,6 +211,7 @@ export function storeDeliveryArchive(store, retentionDays) {
201
211
  via: requester.via,
202
212
  clientId: requester.clientId,
203
213
  },
214
+ ...(event.binding === undefined ? {} : { binding: event.binding }),
204
215
  },
205
216
  },
206
217
  };
@@ -224,7 +235,8 @@ export function storeDeliveryArchive(store, retentionDays) {
224
235
  });
225
236
  const receipt = (event, delivery) => Effect.gen(function* () {
226
237
  const status = event.status;
227
- if (status === "requested" || (status === "sent" && event.messageId === null)) {
238
+ if (status === "requested" ||
239
+ (status === "sent" && event.messageId === null && options.unnamedSends !== true)) {
228
240
  return yield* new DeliveryArchiveError({ diagnostic: "chat_store_invalid_receipt" });
229
241
  }
230
242
  const operation = deliveryOperation(delivery.scope, delivery.key);
@@ -301,7 +313,7 @@ export function storeDeliveryArchive(store, retentionDays) {
301
313
  * the evidence that the agent records there, as a chat's history is imported there from then on.
302
314
  * `cloud` is the chat archive in Cloud, which takes the deliveries until then.
303
315
  */
304
- export function deliveryArchiveOf(backend, cloud, retentionDays) {
316
+ export function deliveryArchiveOf(backend, cloud, retentionDays, options = {}) {
305
317
  const store = backend.agents?.chatMessages;
306
318
  // @legacy agent.cloud-chat-archive Until the agent records into the store, the archive in Cloud
307
319
  // reserves and receipts the delivery, as it keeps the agent's messages.
@@ -310,5 +322,5 @@ export function deliveryArchiveOf(backend, cloud, retentionDays) {
310
322
  }
311
323
  return store
312
324
  .holds()
313
- .pipe(Effect.map((held) => (held ? storeDeliveryArchive(store, retentionDays) : cloud)));
325
+ .pipe(Effect.map((held) => (held ? storeDeliveryArchive(store, retentionDays, options) : cloud)));
314
326
  }
@@ -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: {
@@ -728,6 +730,31 @@ export interface AgentStore {
728
730
  * not an active member of the app. Absent on stores that predate reviews.
729
731
  */
730
732
  readonly holdReply?: (input: HeldReplyInput) => Effect.Effect<HeldReview | undefined>;
733
+ /**
734
+ * A reply the agent proposed, held under the lock `holdReply` takes on its key, once per key and
735
+ * only while `delivered`, read under that lock, finds no delivery of it: `delivered` when one
736
+ * began, and nothing is held. With {@link AgentStore.reserveProposal}, which takes the same lock,
737
+ * one proposal of a key decides it, however proposals of it overlap: a reply once held is never
738
+ * sent, nor one sent held. `undefined` when its person is no active member. Absent on stores
739
+ * that predate proposals.
740
+ */
741
+ readonly holdProposal?: (input: HeldReplyInput, delivered: Effect.Effect<boolean>) => Effect.Effect<HeldReview | "delivered" | undefined>;
742
+ /**
743
+ * Reserves a proposed reply's delivery under the lock its hold takes, in one transaction with
744
+ * `reserve`, the reservation on the chat store, only while no draft holds its key: `held` with
745
+ * that draft otherwise, and nothing is reserved. The lock is released with the transaction,
746
+ * before the provider is called. Absent on stores that predate proposals.
747
+ */
748
+ readonly reserveProposal?: <A, E>(input: {
749
+ readonly key: string;
750
+ readonly reserve: Effect.Effect<A, E>;
751
+ }) => Effect.Effect<{
752
+ readonly kind: "reserved";
753
+ readonly value: A;
754
+ } | {
755
+ readonly kind: "held";
756
+ readonly review: HeldReview;
757
+ }, E>;
731
758
  /**
732
759
  * Holds a reply the agent redrafted at a member's request: a pending review that replaces the one
733
760
  * it redrafts, which becomes `superseded`. `discarded` when that review was decided, or another
@@ -858,6 +885,11 @@ export interface HeldReplyInput {
858
885
  };
859
886
  /** The agent's turn that wrote the reply; absent from agents that predate it. */
860
887
  readonly turnId?: string;
888
+ /**
889
+ * Where the chat stood when the turn read it, `<time>~<id>`, as a proposed reply names it: the
890
+ * draft's basis. Without it, the newest message the turn took in the chat store.
891
+ */
892
+ readonly basis?: string;
861
893
  }
862
894
  /** A reply the agent redrafted, as `POST /api/ontology/agent/drafts/revision` reports it. */
863
895
  export interface RevisedReplyInput {
@@ -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<{
@@ -23,6 +23,7 @@ import { workspaceSourceLayer } from "./agent/source.js";
23
23
  import { platformChatArchive } from "./agent/chat-archive.js";
24
24
  import { archiveRoutes } from "./agent/archive-routes.js";
25
25
  import { makeChatDelivery } from "./chat/delivery.js";
26
+ import { replyProposals } from "./chat/reply-proposal.js";
26
27
  import { platformDeliveryArchive } from "./chat/archive.js";
27
28
  import { platformHistoryArchive } from "./chat/history-import.js";
28
29
  import { chatRoutes } from "./chat/routes.js";
@@ -383,14 +384,14 @@ export function createOntologyService(ontology, config) {
383
384
  const replicate = deployedReplication(config);
384
385
  // The platform keeps chat history for production agents only.
385
386
  const chatHistory = config.runtimeIdentity === undefined || preview ? undefined : platformChatArchive(config);
386
- const chatDelivery = makeChatDelivery(ontology, connections,
387
387
  // @legacy agent.cloud-chat-archive Deliveries reserve here while the store holds no message.
388
- config.chatArchive ?? platformDeliveryArchive(config), { settings: config.channels?.telegram, ownOrigins: config.appOrigins },
388
+ const deliveries = config.chatArchive ?? platformDeliveryArchive(config);
389
389
  // The app's agent sends through a workspace channel, at the origin it takes its tasks at.
390
- {
390
+ const agentChannels = {
391
391
  origin: config.agentOrigin,
392
392
  ...(config.agentTaskTransport === undefined ? {} : { fetch: config.agentTaskTransport }),
393
- }, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
393
+ };
394
+ const chatDelivery = makeChatDelivery(ontology, connections, deliveries, { settings: config.channels?.telegram, ownOrigins: config.appOrigins }, agentChannels, config.chatHistoryArchive ?? platformHistoryArchive(config), chatHistory);
394
395
  const metricQueries = makeMetricQueries({
395
396
  ontology,
396
397
  transport: platformMetricQueries({ ...config, manifestHash: ontology.manifest.hash }),
@@ -456,16 +457,6 @@ export function createOntologyService(ontology, config) {
456
457
  verifyToken,
457
458
  verifyRuntime,
458
459
  exchangeSession,
459
- ...(!preview &&
460
- ontology.config.publicGroupAction && {
461
- publicGroupAction: {
462
- binding: ontology.config.publicGroupAction,
463
- plan,
464
- hooks,
465
- connections,
466
- replicate,
467
- },
468
- }),
469
460
  visitorWebsites: preview ? { guests: [], signUp: [] } : visitorWebsites,
470
461
  agentTools,
471
462
  guest: preview ? undefined : guest,
@@ -478,6 +469,13 @@ export function createOntologyService(ontology, config) {
478
469
  }),
479
470
  emailSignUp: signUpRolesOf(ontology.manifest, "email") !== undefined,
480
471
  manifest: ontology.manifest,
472
+ // The turn replies the agent proposes go as approved drafts do, through its channels.
473
+ replies: replyProposals({
474
+ ontology,
475
+ connections,
476
+ cloud: deliveries,
477
+ agent: agentChannels,
478
+ }),
481
479
  emailCodes,
482
480
  cronSecret: config.cronSecret,
483
481
  chatRetentionDays: chatRetentionDaysOf(ontology.manifest),
@@ -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>;
@@ -260,7 +260,7 @@ export function resultText(result) {
260
260
  * fixed values replace whatever the caller sent for them; the call goes through the toolset's
261
261
  * connection, audited as `<toolset>.<tool>`.
262
262
  */
263
- export function runToolsetToolOf(connections) {
263
+ export function runToolsetToolOf(connections, reportCost) {
264
264
  return (toolset, tool, call) => Effect.gen(function* () {
265
265
  const principal = yield* CurrentPrincipal;
266
266
  const caller = yield* currentCaller;
@@ -278,10 +278,44 @@ export function runToolsetToolOf(connections) {
278
278
  });
279
279
  }
280
280
  const requestId = yield* RequestId;
281
- const transport = connections({
281
+ const invoke = (target, input) => callTool(connections({
282
282
  identityToken: call.identityToken,
283
- audit: { action: `${toolset.name}.${tool.name}`, principalId: principal.id, requestId },
283
+ audit: {
284
+ action: `${toolset.name}.${target.name}`,
285
+ principalId: principal.id,
286
+ requestId,
287
+ },
288
+ }), toolset, target, { ...input, ...target.fixed });
289
+ const handle = tool.handle;
290
+ if (!handle) {
291
+ return yield* invoke(tool, call.input);
292
+ }
293
+ let costIndex = 0;
294
+ return yield* Effect.tryPromise({
295
+ try: (signal) => handle({
296
+ name: tool.name,
297
+ input: call.input,
298
+ principal,
299
+ signal,
300
+ recordCost: async (costUsd) => {
301
+ if (reportCost &&
302
+ principal.kind === "guest" &&
303
+ Number.isFinite(costUsd) &&
304
+ costUsd > 0) {
305
+ await Effect.runPromise(reportCost(principal.id, costUsd, `tool:${requestId}:${++costIndex}`), { signal });
306
+ }
307
+ },
308
+ call: async (name, input) => {
309
+ const target = toolset.tools.find((item) => item.name === name);
310
+ if (!target ||
311
+ (target !== tool && target.access !== "read") ||
312
+ !isAllowed(target.permission, principal)) {
313
+ throw new Error("The tool is unavailable to this caller.");
314
+ }
315
+ return Effect.runPromise(invoke(target, input), { signal });
316
+ },
317
+ }),
318
+ catch: () => new ActionRejected({ message: "The workspace could not complete the tool request." }),
284
319
  });
285
- return yield* callTool(transport, toolset, tool, { ...call.input, ...tool.fixed });
286
320
  });
287
321
  }
package/dist/sign-in.d.ts CHANGED
@@ -51,24 +51,28 @@ export interface ResolvedSignUp {
51
51
  /** The websites whose visitors may sign up on `web`, by origin. */
52
52
  readonly origins?: ReadonlyArray<string>;
53
53
  }
54
- /** The channels a guest talks to the agent through: only `web`, a website's chat, so far. */
55
- export declare const GUEST_CHANNELS: readonly ["web"];
56
- export type GuestChannel = (typeof GUEST_CHANNELS)[number];
54
+ /** Channel kinds with a guest admission path. Named connections select their own policy. */
55
+ export declare const GUEST_CHANNELS: readonly ["web", "telegram", "slack", "whatsapp"];
56
+ export type GuestChannel = (typeof GUEST_CHANNELS)[number] | WorkspaceSignUpChannel;
57
57
  export declare function isGuestChannel(value: unknown): value is GuestChannel;
58
58
  /**
59
59
  * Who may talk to the agent without signing in or signing up: a guest, the counterpart of the
60
60
  * built-in `member`. A guest is a session, not a user: nobody proved who they are, so no user or
61
- * identity record is created for them, and they hold the built-in role `guest` alone. Without
61
+ * identity record is created for them. The channel selects their roles, defaulting to `guest`. Without
62
62
  * `guest`, nobody chats without signing in or signing up.
63
63
  */
64
- export interface GuestOptions<P = unknown> {
65
- /** Where guests talk to the agent: `["web"]`, a declared website's chat. */
64
+ export interface GuestOptions<P = unknown, R = unknown> {
65
+ /** Named connections on which an authorized invitation opens guest questions in a new group. */
66
+ readonly openOnInvite?: ReadonlyArray<string>;
67
+ /** Roles replacing the default guest permissions on a listed channel. */
68
+ readonly byChannel?: Readonly<Partial<Record<GuestChannel, ReadonlyArray<R>>>>;
69
+ /** Websites, admitted Telegram or Slack groups, or a WhatsApp number receiving private messages. */
66
70
  readonly channels: ReadonlyArray<GuestChannel>;
67
71
  /**
68
72
  * The websites whose visitors are guests, as {@link websiteOrigin} accepts them, such as
69
73
  * `https://www.example.com` or `https://*.example.com`.
70
74
  */
71
- readonly origins: ReadonlyArray<string>;
75
+ readonly origins?: ReadonlyArray<string>;
72
76
  /**
73
77
  * What every guest may do, as role permissions: the permissions of the built-in role `guest`.
74
78
  * `check` holds them to the rules of sign-up roles, and a guest has no user record, so a scope
@@ -125,6 +129,9 @@ export type ResolvedGuestBotCheck = {
125
129
  };
126
130
  /** Guests as the manifest carries them; the built-in role `guest` holds their permissions. */
127
131
  export interface ResolvedGuest {
132
+ /** Named connections on which an authorized invitation opens guest questions in a new group. */
133
+ readonly openOnInvite?: ReadonlyArray<string>;
134
+ readonly byChannel?: Readonly<Partial<Record<GuestChannel, ReadonlyArray<string>>>>;
128
135
  readonly channels: ReadonlyArray<GuestChannel>;
129
136
  readonly origins: ReadonlyArray<string>;
130
137
  /** The challenge a new guest passes, when declared. */
package/dist/sign-in.js CHANGED
@@ -23,10 +23,11 @@ export function isSignUpChannel(value) {
23
23
  return (SIGN_UP_CHANNELS.includes(value) ||
24
24
  (typeof value === "string" && WORKSPACE_IDENTITY_PROVIDER.test(value)));
25
25
  }
26
- /** The channels a guest talks to the agent through: only `web`, a website's chat, so far. */
27
- export const GUEST_CHANNELS = ["web"];
26
+ /** Channel kinds with a guest admission path. Named connections select their own policy. */
27
+ export const GUEST_CHANNELS = ["web", "telegram", "slack", "whatsapp"];
28
28
  export function isGuestChannel(value) {
29
- return GUEST_CHANNELS.includes(value);
29
+ return (GUEST_CHANNELS.includes(value) ||
30
+ (typeof value === "string" && WORKSPACE_IDENTITY_PROVIDER.test(value)));
30
31
  }
31
32
  /**
32
33
  * The challenge providers a guest's bot check can verify. `turnstile` is Cloudflare Turnstile: the
package/dist/toolset.d.ts CHANGED
@@ -1,4 +1,6 @@
1
1
  import { Schema } from "effect";
2
+ import type { Principal } from "./runtime.js";
3
+ import type { ToolResult } from "./service/toolsets.js";
2
4
  import type { AnyConnectionHandle } from "./connection.js";
3
5
  export declare const ToolsetTypeId: unique symbol;
4
6
  /** The lock format `segmentstream connection mcp lock` writes. */
@@ -50,8 +52,21 @@ export declare const ToolsetLock: Schema.Struct<{
50
52
  }>>;
51
53
  }>;
52
54
  export type ToolsetLock = typeof ToolsetLock.Type;
53
- /** The workspace's own words for one tool, replacing the provider's. */
55
+ /** Trusted workspace code runs after caller authorization, for every MCP entry point.
56
+ * call() may invoke this tool or another permitted read in the same locked toolset.
57
+ * Fixed arguments are applied by the transport. Raw provider results remain inside the hook. */
58
+ export interface ToolInvocation {
59
+ readonly principal: Principal;
60
+ readonly name: string;
61
+ readonly input: Readonly<Record<string, unknown>>;
62
+ readonly signal: AbortSignal;
63
+ readonly call: (name: string, input: Readonly<Record<string, unknown>>) => Promise<ToolResult>;
64
+ readonly recordCost: (costUsd: number) => Promise<void>;
65
+ }
66
+ export type ToolHandler = (invocation: ToolInvocation) => Promise<ToolResult>;
67
+ /** Workspace presentation and handling of an existing provider tool. */
54
68
  export interface ToolsetToolOptions {
69
+ readonly handle?: ToolHandler;
55
70
  readonly description?: string;
56
71
  }
57
72
  export interface ToolsetDefinition {
@@ -99,6 +114,7 @@ export interface ResolvedToolHints {
99
114
  }
100
115
  /** One tool of a checked toolset, as the service serves it. */
101
116
  export interface ResolvedTool {
117
+ readonly handle?: ToolHandler;
102
118
  /** The provider's tool name. */
103
119
  readonly name: string;
104
120
  /** `<toolset>_<tool>`. */
@@ -28,6 +28,12 @@ export declare const WORKSPACE_CHANNEL_ID: RegExp;
28
28
  export declare const WORKSPACE_CHANNEL_TEXT_LIMIT = 20000;
29
29
  /** The text a workspace channel sends: the text as written, then the separator and attribution. */
30
30
  export declare function renderWorkspaceChannelText(text: string, attribution: string, separator: string): string;
31
+ /**
32
+ * A reply in parts of at most `maxLength` characters, as a workspace channel whose code sets
33
+ * `limits.maxLength` sends a longer one: at a paragraph, else a line, else a space, else where the
34
+ * length ends. The agent splits its own replies so, and the ontology the turn replies it sends.
35
+ */
36
+ export declare function splitReply(text: string, maxLength: number | undefined): ReadonlyArray<string>;
31
37
  /** `POST` {@link workspaceChannelSendRoute}: one message to one person's chat. */
32
38
  export interface WorkspaceChannelSend {
33
39
  /** Names the message, so a send the ontology tries again is the same message. */
@@ -34,6 +34,33 @@ export const WORKSPACE_CHANNEL_TEXT_LIMIT = 20_000;
34
34
  export function renderWorkspaceChannelText(text, attribution, separator) {
35
35
  return attribution === "" ? text : `${text}${separator}${attribution}`;
36
36
  }
37
+ /**
38
+ * A reply in parts of at most `maxLength` characters, as a workspace channel whose code sets
39
+ * `limits.maxLength` sends a longer one: at a paragraph, else a line, else a space, else where the
40
+ * length ends. The agent splits its own replies so, and the ontology the turn replies it sends.
41
+ */
42
+ export function splitReply(text, maxLength) {
43
+ if (maxLength === undefined || text.length <= maxLength) {
44
+ return [text];
45
+ }
46
+ const parts = [];
47
+ let rest = text;
48
+ while (rest.length > maxLength) {
49
+ const window = rest.slice(0, maxLength);
50
+ const cut = [
51
+ window.lastIndexOf("\n\n"),
52
+ window.lastIndexOf("\n"),
53
+ window.lastIndexOf(" "),
54
+ ].find((index) => index > 0);
55
+ const end = cut ?? maxLength;
56
+ parts.push(rest.slice(0, end).trimEnd());
57
+ rest = rest.slice(end).trimStart();
58
+ }
59
+ if (rest !== "") {
60
+ parts.push(rest);
61
+ }
62
+ return parts;
63
+ }
37
64
  /**
38
65
  * The most bytes of files one message through a workspace channel carries unless the channel's
39
66
  * code takes more (`limits.fileBytes`).
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.180.0",
3
+ "version": "0.182.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",
@@ -45,6 +45,10 @@
45
45
  "types": "./dist/workspace-channel.d.ts",
46
46
  "import": "./dist/workspace-channel.js"
47
47
  },
48
+ "./review": {
49
+ "types": "./dist/review.d.ts",
50
+ "import": "./dist/review.js"
51
+ },
48
52
  "./chat-personas": {
49
53
  "types": "./dist/chat-personas.d.ts",
50
54
  "import": "./dist/chat-personas.js"
@@ -1,23 +0,0 @@
1
- import { Effect } from "effect";
2
- import type { HttpServerRequest } from "effect/unstable/http";
3
- import { makeOperations } from "../operations.js";
4
- type Resources = Parameters<typeof makeOperations>;
5
- export interface PublicActionOptions {
6
- readonly binding: {
7
- role: string;
8
- entity: string;
9
- action: string;
10
- };
11
- readonly plan: Resources[1];
12
- readonly hooks: Resources[2];
13
- readonly connections: Resources[3];
14
- readonly replicate: Resources[4];
15
- }
16
- /** Stable UUID in the given namespace. A group action's sender is scoped to that chat. */
17
- export declare function groupSubject(parts: readonly string[]): string;
18
- export declare function publicActionForGroup(backend: Resources[0], options: PublicActionOptions): (request: HttpServerRequest.HttpServerRequest, source: {
19
- channel: string;
20
- chat: string;
21
- sender: string;
22
- }, input: Readonly<Record<string, unknown>>) => Effect.Effect<{} | null, import("../../errors.js").ActionError | import("../../connection.js").ConnectionError | import("../../runtime/errors.js").WorkflowRecoveryUnavailable | import("../../runtime/errors.js").TriggerInputInvalid | import("../errors.js").InvalidActionInput, import("../errors.js").RequestId>;
23
- export {};