@segmentstream/ontology 0.114.0 → 0.115.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,27 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.115.0
4
+
5
+ The inbox: `defineOntology({ inbox: { roles: [client] } })` names the roles whose people's private
6
+ chats with the agent the workspace's staff work. Each such chat, on Telegram, WhatsApp, Slack
7
+ direct messages, email threads and workspace channels, becomes an `agent_chat` record of the new
8
+ managed `kind` `private` (group chats are `group`), with its person as its one member and the
9
+ `recipient` and `threadId` its replies use. The agent reports a chat when the answer to its
10
+ admission says the inbox takes the person, so registration needs no workspace code; the service
11
+ checks the person's roles again. Without `inbox`, no private chat is registered.
12
+
13
+ `chat_history`, and its route `POST /api/ontology/chat/history`, read such a chat by its record id.
14
+ A member with `agent_chat:read` whose scope holds the record reads its messages, whoever wrote
15
+ them: the service checks the caller against the record and asks the archive for that exact chat,
16
+ which returns messages, never the agent's tool calls. Its person reads the messages they took part
17
+ in, as in any private chat. Group chats, chat posts, the chat list and attachments behave as
18
+ before.
19
+
20
+ Before declaring `inbox`, check which roles hold `agent_chat:read`, and its
21
+ scopes. Once the inbox takes a role, an unscoped `agent_chat:read` also reads those people's
22
+ private chats and their messages; scope it, for example
23
+ `{ permission: "agent_chat:read", where: { kind: "private" } }`, to give staff only the inbox.
24
+
3
25
  ## 0.114.0
4
26
 
5
27
  `agent_tool:browser` is a built-in permission: roles that name it give their members the agent's
@@ -2,8 +2,11 @@ export declare const TELEGRAM = "telegram";
2
2
  /** Existing chat registry and membership storage; delivery lives in the ontology service. */
3
3
  export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
4
4
  readonly provider: import("./property.js").Property<string, false, false>;
5
+ readonly kind: import("./property.js").Property<"group" | "private", true, false>;
5
6
  readonly externalId: import("./property.js").Property<string, false, false>;
6
7
  readonly title: import("./property.js").Property<string, false, false>;
8
+ readonly recipient: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
9
+ readonly threadId: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
7
10
  readonly lastMessageAt: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
8
11
  readonly purpose: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
9
12
  readonly whenToUse: import("effect/Schema").optionalKey<import("./property.js").Property<string, false, false>>;
@@ -35,8 +38,11 @@ export declare const AgentChat: import("./entity.js").Entity<"agent_chat", {
35
38
  readonly createdBy: string | null;
36
39
  readonly updatedBy: string | null;
37
40
  readonly provider: string;
41
+ readonly kind: "group" | "private";
38
42
  readonly externalId: string;
39
43
  readonly title: string;
44
+ readonly recipient: string | null;
45
+ readonly threadId: string | null;
40
46
  readonly lastMessageAt: string | null;
41
47
  readonly purpose: string | null;
42
48
  readonly whenToUse: string | null;
@@ -12,14 +12,37 @@ export const AgentChat = entity("agent_chat", {
12
12
  label: "Agent chat",
13
13
  plural: "Agent chats",
14
14
  title: "title",
15
- description: "A group chat the workspace's agent is in. The agent records each chat it sees; " +
16
- "members say what the chat is for, so that agents know where to write.",
15
+ description: "A chat of the workspace's agent: a group chat it is in, which the agent records when it sees " +
16
+ "it and members say what it is for, so that agents know where to write; or a person's private " +
17
+ "chat with the agent, which the agent records for the workspace's staff when the ontology's " +
18
+ "inbox takes the person's role.",
17
19
  properties: {
18
20
  provider: p.text({ managed: true, description: "The channel, for example telegram." }),
21
+ kind: p.select([
22
+ { value: "group", description: "A group chat the agent is in." },
23
+ { value: "private", description: "A person's own chat with the agent." },
24
+ ], {
25
+ default: "group",
26
+ managed: true,
27
+ description: "Whether the chat is a group chat or a person's private chat with the agent.",
28
+ }),
19
29
  externalId: p.text({ managed: true, description: "The chat's id at the provider." }),
20
30
  title: p.text({
21
31
  managed: true,
22
- description: "The chat's name at the provider, kept current by the agent.",
32
+ description: "The chat's name at the provider, kept current by the agent: a private chat's is its " +
33
+ "person's name there.",
34
+ }),
35
+ recipient: p.text({
36
+ optional: true,
37
+ managed: true,
38
+ description: "Whom a reply in a private chat is sent to at the provider, where it differs from the " +
39
+ "chat's id.",
40
+ }),
41
+ threadId: p.text({
42
+ optional: true,
43
+ managed: true,
44
+ label: "Thread",
45
+ description: "The thread at the provider a reply in a private chat stays in.",
23
46
  }),
24
47
  lastMessageAt: p.timestamp({
25
48
  optional: true,
@@ -46,7 +69,8 @@ export const AgentChat = entity("agent_chat", {
46
69
  members: rel.many("user", {
47
70
  inverse: "agentChats",
48
71
  phrase: ["includes", "is in"],
49
- description: "Workspace members the agent has seen writing in the chat.",
72
+ description: "Workspace members the agent has seen writing in the chat; a private chat's one member " +
73
+ "is its person.",
50
74
  }),
51
75
  },
52
76
  indexes: [{ properties: ["provider", "externalId"], unique: true }],
@@ -39,7 +39,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
39
39
  readonly channel: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
40
40
  readonly chatId: import("./property.js").Property<string, false, false>;
41
41
  readonly recipient: import("./property.js").Property<string, false, false>;
42
- readonly chatKind: import("./property.js").Property<"private" | "group", false, false>;
42
+ readonly chatKind: import("./property.js").Property<"group" | "private", false, false>;
43
43
  readonly threadId: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
44
44
  readonly replyTo: Schema.optionalKey<import("./property.js").Property<string, false, false>>;
45
45
  readonly sessionId: import("./property.js").Property<string, false, false>;
@@ -80,7 +80,7 @@ export declare const AgentReview: import("./entity.js").Entity<"agent_review", {
80
80
  readonly channel: string | null;
81
81
  readonly chatId: string;
82
82
  readonly recipient: string;
83
- readonly chatKind: "private" | "group";
83
+ readonly chatKind: "group" | "private";
84
84
  readonly threadId: string | null;
85
85
  readonly replyTo: string | null;
86
86
  readonly sessionId: string;
package/dist/analyze.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ChatAttributionSettings } from "./chat.js";
1
+ import type { ChatAttributionSettings, InboxOptions } from "./chat.js";
2
2
  import { type ChatKind } from "./chat-channel.js";
3
3
  import type { ChatManifestInput } from "./manifest.js";
4
4
  import { Schema } from "effect";
@@ -101,6 +101,13 @@ export interface OntologyConfig<Entities extends ReadonlyArray<AnyEntity> = Read
101
101
  * through it, never a chat post.
102
102
  */
103
103
  readonly chat?: ChatConfig;
104
+ /**
105
+ * Whose private chats with the agent the workspace's staff work: `{ roles: [client] }`. The agent
106
+ * registers each private chat of a person holding one of these roles as an `agent_chat` record of
107
+ * kind `private`, which `agent_chat:read` within its scope reads with its messages. Absent, no
108
+ * private chat is registered and `agent_chat` holds group chats only.
109
+ */
110
+ readonly inbox?: InboxOptions<Role | string>;
104
111
  /**
105
112
  * Metrics of the model, by camelCase name: each combines metrics of entities, read with
106
113
  * `m.ref("entity.metric")`, or other model metrics, read with `m.ref("name")`, through
@@ -210,6 +217,10 @@ export interface ResolvedEntity {
210
217
  export interface Analysis {
211
218
  readonly feedback: ResolvedFeedback;
212
219
  readonly chat?: ChatManifestInput;
220
+ /** The wire names of the roles whose private chats join the inbox, when declared. */
221
+ readonly inbox?: {
222
+ readonly roles: ReadonlyArray<string>;
223
+ };
213
224
  readonly entities: ReadonlyArray<ResolvedEntity>;
214
225
  /** The workspace-owned `member` role and declared roles, then the implicit reporter when enabled. */
215
226
  readonly roles: ReadonlyArray<Role>;
package/dist/analyze.js CHANGED
@@ -102,6 +102,7 @@ export function analyze(config, options = {}) {
102
102
  ...(linkEmail === undefined ? {} : { linkEmail }),
103
103
  ...(codeEmail === undefined ? {} : { codeEmail }),
104
104
  };
105
+ const inbox = inboxOptions(config.inbox, declaredRoles, report);
105
106
  const discovery = config.discovery;
106
107
  if (discovery !== undefined &&
107
108
  (!isPlainObject(discovery) ||
@@ -329,8 +330,43 @@ export function analyze(config, options = {}) {
329
330
  toolsets,
330
331
  diagnostics,
331
332
  ...(chat === undefined ? {} : { chat }),
333
+ ...(inbox === undefined ? {} : { inbox }),
332
334
  };
333
335
  }
336
+ /**
337
+ * `inbox`: the wire names of the roles whose private chats join the inbox, each a declared role or
338
+ * `member`; `undefined` when absent or malformed.
339
+ */
340
+ function inboxOptions(value, declaredRoles, report) {
341
+ if (value === undefined) {
342
+ return undefined;
343
+ }
344
+ if (!isPlainObject(value) ||
345
+ Object.keys(value).some((key) => key !== "roles") ||
346
+ !Array.isArray(value.roles) ||
347
+ value.roles.length === 0) {
348
+ report("invalid-inbox", "inbox", "inbox takes { roles: [...] }, at least one role.");
349
+ return undefined;
350
+ }
351
+ const declared = new Set(declaredRoles.map((candidate) => candidate.name));
352
+ const roles = [];
353
+ let valid = true;
354
+ value.roles.forEach((candidate, index) => {
355
+ const name = isRole(candidate)
356
+ ? nameToWire(candidate.name)
357
+ : typeof candidate === "string"
358
+ ? nameToWire(candidate)
359
+ : undefined;
360
+ if (name === undefined || !declared.has(name)) {
361
+ report("invalid-inbox", `inbox.roles[${index}]`, "Use a role the ontology declares, or member.");
362
+ valid = false;
363
+ }
364
+ else if (!roles.includes(name)) {
365
+ roles.push(name);
366
+ }
367
+ });
368
+ return valid ? { roles } : undefined;
369
+ }
334
370
  /**
335
371
  * Warns where workspace code declares a field by the name an earlier SDK gave it, naming the current
336
372
  * one, so that authors move to it while the earlier name is still accepted.
package/dist/chat.d.ts CHANGED
@@ -3,6 +3,13 @@ export interface ChatAttributionSettings {
3
3
  readonly template?: string;
4
4
  readonly separator?: string;
5
5
  }
6
+ /**
7
+ * `inbox` of `defineOntology`: the roles of the people whose private chats with the agent the
8
+ * workspace's staff work, as `agent_chat` records of kind `private`.
9
+ */
10
+ export interface InboxOptions<R = unknown> {
11
+ readonly roles: ReadonlyArray<R>;
12
+ }
6
13
  import { Context, Effect, Schema } from "effect";
7
14
  import type { ActionError } from "./errors.js";
8
15
  export declare const ChatPostInput: Schema.Struct<{
@@ -1,10 +1,10 @@
1
1
  import { Schema } from "effect";
2
- export declare const DIAGNOSTIC_CODES: readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"];
2
+ export declare const DIAGNOSTIC_CODES: readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"];
3
3
  export type DiagnosticCode = (typeof DIAGNOSTIC_CODES)[number];
4
4
  /** A problem `check` found in an ontology definition. */
5
5
  export declare const Diagnostic: Schema.Struct<{
6
6
  readonly severity: Schema.Literals<readonly ["error", "warning", "info"]>;
7
- readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
7
+ readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
8
8
  /** Where the problem is, for example `lead.properties.status.options[1]`. */
9
9
  readonly path: Schema.String;
10
10
  readonly message: Schema.String;
@@ -14,7 +14,7 @@ declare const InvalidOntology_base: Schema.Class<InvalidOntology, Schema.TaggedS
14
14
  readonly message: Schema.String;
15
15
  readonly diagnostics: Schema.$Array<Schema.Struct<{
16
16
  readonly severity: Schema.Literals<readonly ["error", "warning", "info"]>;
17
- readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
17
+ readonly code: Schema.Literals<readonly ["invalid-source", "missing-column", "invalid-column", "invalid-scope", "invalid-scope-path", "scope-reads-all", "scope-unused", "scope-member-overlap", "source-with-actions", "source-with-index", "invalid-metric", "unknown-metric", "circular-metric", "invalid-join", "missing-join", "invalid-entity", "invalid-property", "invalid-relationship", "invalid-actions", "invalid-action", "invalid-action-input", "invalid-role", "invalid-name", "reserved-name", "duplicate-name", "invalid-entity-id", "duplicate-entity-id", "missing-label", "missing-description", "invalid-title", "invalid-options", "invalid-default", "invalid-constraint", "unknown-relationship-target", "inverse-collision", "invalid-on-delete", "invalid-phrase", "invalid-index", "unknown-reference", "invalid-renamed-from", "earlier-name", "invalid-guide", "invalid-writes", "generated-update-empty", "managed-without-effect", "missing-permissions", "invalid-permission", "unknown-permission", "removed-allow", "unreachable-action", "wildcard-permission", "invalid-sign-in", "invalid-inbox", "invalid-connection", "invalid-feedback", "invalid-discovery", "invalid-email", "feedback-unanswerable", "agent-tools-implicit", "unknown-connection", "unused-connection", "invalid-prepare", "invalid-tool-name", "invalid-toolset", "toolset-lock-mismatch", "invalid-alignment", "single-entity-model-metric", "invalid-workflow", "workflow_role_unknown", "workflow_role_is_member", "workflow_role_grants_nothing", "workflow_role_wildcard", "workflow_role_scoped", "workflow_cron_never_fires", "workflow_input_invalid", "workflow_cron_invalid", "workflow_run_missing", "invalid-trigger", "trigger_action_unknown", "trigger_function_async", "workflow_trigger_limit_exceeded", "workflow_webhook_duplicate", "workflow_webhook_input_invalid", "workflow_webhook_mixed_triggers", "workflow_webhook_signature_invalid", "workflow_webhook_verification_invalid", "workflow_webhook_headers_invalid", "workflow_webhook_limit_exceeded"]>;
18
18
  /** Where the problem is, for example `lead.properties.status.options[1]`. */
19
19
  readonly path: Schema.String;
20
20
  readonly message: Schema.String;
@@ -52,6 +52,7 @@ export const DIAGNOSTIC_CODES = [
52
52
  "unreachable-action",
53
53
  "wildcard-permission",
54
54
  "invalid-sign-in",
55
+ "invalid-inbox",
55
56
  "invalid-connection",
56
57
  "invalid-feedback",
57
58
  "invalid-discovery",
package/dist/index.d.ts CHANGED
@@ -24,7 +24,7 @@ export type { ActionsBuilder, AnyEntity, ActionHandle, ActionInvoker, MetricQuer
24
24
  export { ActionRejected, BatchErrorDetails, Conflict, DeploymentInterrupted, DeploymentSwitching, LimitErrorDetails, NotFound, PermissionDenied, ScopeViolated, } from "./errors.js";
25
25
  export type { ActionError } from "./errors.js";
26
26
  export { browserAuthenticationCompatible } from "./manifest-compatibility.js";
27
- export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, GuestManifest, guestOf, signInPolicyOf, channelPolicyOf, signUpOriginsOf, signUpRolesOf, } from "./manifest.js";
27
+ export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, GuestManifest, guestOf, signInPolicyOf, channelPolicyOf, signUpOriginsOf, inboxRolesOf, signUpRolesOf, } from "./manifest.js";
28
28
  export { SYSTEM_PROPERTIES } from "./names.js";
29
29
  export type { SystemProperty } from "./names.js";
30
30
  export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire, MeTypeId, } from "./me.js";
@@ -66,7 +66,7 @@ export { AppFeedback, AppFeedbackFile, APP_FEEDBACK_ENTITIES, APP_FEEDBACK_FILE_
66
66
  export { ChatDelivery, ChatPostInput, ChatPostResult } from "./chat.js";
67
67
  export { CHAT_CHANNEL_KINDS, CHAT_CHANNEL_NAME, CHAT_KINDS, WORKSPACE_CHANNEL_KIND, channelIdentityProvider, } from "./chat-channel.js";
68
68
  export type { ChatChannelKind, ChatKind } from "./chat-channel.js";
69
- export type { ReviewSendInput, ReviewSendResult } from "./chat.js";
69
+ export type { InboxOptions, ReviewSendInput, ReviewSendResult } from "./chat.js";
70
70
  export { DEFAULT_QUERY_LIMIT, entityQueryResultSchema, entityQuerySchema, entityQuerySchemas, entityRecordSchema, FILTER_OPERATORS, LIST_FILTER_OPERATORS, MANY_QUANTIFIERS, MAX_IN_VALUES, MAX_QUERY_LIMIT, OrderBy, Query, queryFields, queryJsonSchema, queryLinks, QueryResult, queryResultJsonSchema, queryResultSchema, SortDirection, WHERE_COMBINATORS, } from "./query.js";
71
71
  export type { EntityQuerySchemas, FieldFilter, FilterOperator, JsonRecord, ListFilterOperator, ManyFilter, QueryField, QueryLink, StorageType, Where, } from "./query.js";
72
72
  export { InvalidQuery, InvalidValues, MemberNotFound, PrincipalRejected, StoredRecordMismatch, UnknownAction, UnknownRole, ValidationIssue, UndeclaredWrite, WriteOutsideAction, } from "./runtime/errors.js";
package/dist/index.js CHANGED
@@ -13,7 +13,7 @@ export { entity, isEntity } from "./entity.js";
13
13
  export { isToolset, MCP_TOOL_NAME, TOOLSET_LOCK_VERSION, toolset, ToolsetLock, ToolsetLockTool, } from "./toolset.js";
14
14
  export { ActionRejected, BatchErrorDetails, Conflict, DeploymentInterrupted, DeploymentSwitching, LimitErrorDetails, NotFound, PermissionDenied, ScopeViolated, } from "./errors.js";
15
15
  export { browserAuthenticationCompatible } from "./manifest-compatibility.js";
16
- export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, GuestManifest, guestOf, signInPolicyOf, channelPolicyOf, signUpOriginsOf, signUpRolesOf, } from "./manifest.js";
16
+ export { ActionManifest, actionConnectionKeys, canonicalJson, ConnectionManifest, EntityManifest, EntityPermissionsManifest, decodeManifestDocument, encodeManifest, formatManifest, IndexManifest, isValueMatched, MANIFEST_VERSION, manifestHash, ModelMetricManifest, OntologyManifest, OntologyManifestWire, PropertyManifest, RelationshipManifest, RoleManifest, ActionTriggerManifest, ScopeManifest, CronTriggerManifest, isActionTrigger, isCronTrigger, isWebhookTrigger, OtherTriggerManifest, WebhookTriggerManifest, WorkflowManifest, WorkflowTriggerManifest, SelectOptionManifest, SignInManifest, GuestManifest, guestOf, signInPolicyOf, channelPolicyOf, signUpOriginsOf, inboxRolesOf, signUpRolesOf, } from "./manifest.js";
17
17
  export { SYSTEM_PROPERTIES } from "./names.js";
18
18
  export { isMe, isMeMarker, MAX_ME_HOPS, me, ME_KEY, MeMarker, mePathOf, meToWire, MeTypeId, } from "./me.js";
19
19
  export { check, defineOntology } from "./ontology.js";
@@ -89,6 +89,9 @@ import { type ResolvedGuest, type ResolvedSignInOptions, type SignInPolicy } fro
89
89
  * readers ignore it and send nothing through those channels. A channel the workspace defines in
90
90
  * its own code has kind `custom` and no connection, as the agent sends through it; sign-up may open
91
91
  * `channel:<name>`, its people's accounts.
92
+ * Within version 15, the top-level `inbox`, written only when declared, holds the wire names of the
93
+ * `roles` whose people's private chats the agent registers as `agent_chat` records of kind
94
+ * `private`. Older readers ignore it and register none.
92
95
  */
93
96
  export declare const MANIFEST_VERSION = 15;
94
97
  /** The phrase used for a direction the author did not phrase. */
@@ -1149,6 +1152,13 @@ export declare const OntologyManifestWire: Schema.encodeKeys<Schema.Struct<{
1149
1152
  readonly separator: Schema.optionalKey<Schema.String>;
1150
1153
  }>>;
1151
1154
  }>>;
1155
+ /**
1156
+ * Whose private chats join the inbox, within version 15: the wire names of their roles. Written
1157
+ * only when declared; absent registers no private chat, and older readers ignore it.
1158
+ */
1159
+ readonly inbox: Schema.optionalKey<Schema.Struct<{
1160
+ readonly roles: Schema.$Array<Schema.String>;
1161
+ }>>;
1152
1162
  /**
1153
1163
  * The metrics of the model, since version 8. Written only when there are some; absent reads as
1154
1164
  * none.
@@ -1541,6 +1551,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1541
1551
  readonly footer?: string | undefined;
1542
1552
  };
1543
1553
  } | undefined;
1554
+ readonly inbox?: {
1555
+ readonly roles: readonly string[];
1556
+ } | undefined;
1544
1557
  readonly toolsets?: readonly {
1545
1558
  readonly name: string;
1546
1559
  readonly description: string;
@@ -1850,6 +1863,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
1850
1863
  readonly footer?: string | undefined;
1851
1864
  };
1852
1865
  } | undefined;
1866
+ readonly inbox?: {
1867
+ readonly roles: readonly string[];
1868
+ } | undefined;
1853
1869
  readonly toolsets?: readonly {
1854
1870
  readonly name: string;
1855
1871
  readonly description: string;
@@ -2124,6 +2140,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2124
2140
  readonly footer?: string | undefined;
2125
2141
  };
2126
2142
  } | undefined;
2143
+ readonly inbox?: {
2144
+ readonly roles: readonly string[];
2145
+ } | undefined;
2127
2146
  readonly toolsets?: readonly {
2128
2147
  readonly name: string;
2129
2148
  readonly description: string;
@@ -2468,6 +2487,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2468
2487
  readonly footer?: string | undefined;
2469
2488
  };
2470
2489
  } | undefined;
2490
+ readonly inbox?: {
2491
+ readonly roles: readonly string[];
2492
+ } | undefined;
2471
2493
  readonly toolsets?: readonly {
2472
2494
  readonly name: string;
2473
2495
  readonly description: string;
@@ -2806,6 +2828,13 @@ export declare const OntologyManifest: Schema.declareConstructor<{
2806
2828
  readonly separator: Schema.optionalKey<Schema.String>;
2807
2829
  }>>;
2808
2830
  }>>;
2831
+ /**
2832
+ * Whose private chats join the inbox, within version 15: the wire names of their roles. Written
2833
+ * only when declared; absent registers no private chat, and older readers ignore it.
2834
+ */
2835
+ readonly inbox: Schema.optionalKey<Schema.Struct<{
2836
+ readonly roles: Schema.$Array<Schema.String>;
2837
+ }>>;
2809
2838
  /**
2810
2839
  * The metrics of the model, since version 8. Written only when there are some; absent reads as
2811
2840
  * none.
@@ -3214,6 +3243,13 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3214
3243
  readonly separator: Schema.optionalKey<Schema.String>;
3215
3244
  }>>;
3216
3245
  }>>;
3246
+ /**
3247
+ * Whose private chats join the inbox, within version 15: the wire names of their roles. Written
3248
+ * only when declared; absent registers no private chat, and older readers ignore it.
3249
+ */
3250
+ readonly inbox: Schema.optionalKey<Schema.Struct<{
3251
+ readonly roles: Schema.$Array<Schema.String>;
3252
+ }>>;
3217
3253
  /**
3218
3254
  * The metrics of the model, since version 8. Written only when there are some; absent reads as
3219
3255
  * none.
@@ -3598,6 +3634,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3598
3634
  readonly footer?: string | undefined;
3599
3635
  };
3600
3636
  } | undefined;
3637
+ readonly inbox?: {
3638
+ readonly roles: readonly string[];
3639
+ } | undefined;
3601
3640
  readonly toolsets?: readonly {
3602
3641
  readonly name: string;
3603
3642
  readonly description: string;
@@ -3907,6 +3946,9 @@ export declare const OntologyManifest: Schema.declareConstructor<{
3907
3946
  readonly footer?: string | undefined;
3908
3947
  };
3909
3948
  } | undefined;
3949
+ readonly inbox?: {
3950
+ readonly roles: readonly string[];
3951
+ } | undefined;
3910
3952
  readonly toolsets?: readonly {
3911
3953
  readonly name: string;
3912
3954
  readonly description: string;
@@ -4222,6 +4264,9 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
4222
4264
  readonly footer?: string | undefined;
4223
4265
  };
4224
4266
  } | undefined;
4267
+ readonly inbox?: {
4268
+ readonly roles: readonly string[];
4269
+ } | undefined;
4225
4270
  readonly toolsets?: readonly {
4226
4271
  readonly name: string;
4227
4272
  readonly description: string;
@@ -4531,6 +4576,9 @@ export declare const decodeManifestDocument: (value: unknown) => Effect.Effect<{
4531
4576
  readonly footer?: string | undefined;
4532
4577
  };
4533
4578
  } | undefined;
4579
+ readonly inbox?: {
4580
+ readonly roles: readonly string[];
4581
+ } | undefined;
4534
4582
  readonly toolsets?: readonly {
4535
4583
  readonly name: string;
4536
4584
  readonly description: string;
@@ -4579,6 +4627,8 @@ export declare function signInPolicyOf(manifest: Pick<OntologyManifest, "signIn"
4579
4627
  * the channel is closed to sign-up: not a channel this reader knows, or no well-formed entry.
4580
4628
  */
4581
4629
  export declare function signUpRolesOf(manifest: Pick<OntologyManifest, "signIn">, channel: string): ReadonlyArray<string> | undefined;
4630
+ /** The wire names of the roles whose people's private chats join the inbox; empty without one. */
4631
+ export declare function inboxRolesOf(manifest: Pick<OntologyManifest, "inbox">): ReadonlySet<string>;
4582
4632
  /**
4583
4633
  * The websites whose visitors may sign up on `web`, by origin: empty while `web` is closed to
4584
4634
  * sign-up. Entries that are not an origin `signUp.origins` accepts are left out.
@@ -4629,6 +4679,9 @@ export interface ChatManifestInput {
4629
4679
  export declare function buildManifest(input: {
4630
4680
  readonly feedback?: ResolvedFeedback;
4631
4681
  readonly chat?: ChatManifestInput;
4682
+ readonly inbox?: {
4683
+ readonly roles: ReadonlyArray<string>;
4684
+ };
4632
4685
  readonly entities: ReadonlyArray<ResolvedEntity>;
4633
4686
  readonly roles: ReadonlyArray<Role>;
4634
4687
  readonly signIn: ResolvedSignInOptions;
package/dist/manifest.js CHANGED
@@ -89,6 +89,9 @@ import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isGuestBotCheckScheme, isGue
89
89
  * readers ignore it and send nothing through those channels. A channel the workspace defines in
90
90
  * its own code has kind `custom` and no connection, as the agent sends through it; sign-up may open
91
91
  * `channel:<name>`, its people's accounts.
92
+ * Within version 15, the top-level `inbox`, written only when declared, holds the wire names of the
93
+ * `roles` whose people's private chats the agent registers as `agent_chat` records of kind
94
+ * `private`. Older readers ignore it and register none.
92
95
  */
93
96
  export const MANIFEST_VERSION = 15;
94
97
  /** The first version whose documents use snake_case names on the wire. */
@@ -543,6 +546,11 @@ const OntologyManifestModel = Schema.Struct({
543
546
  separator: Schema.optionalKey(Schema.String),
544
547
  })),
545
548
  })),
549
+ /**
550
+ * Whose private chats join the inbox, within version 15: the wire names of their roles. Written
551
+ * only when declared; absent registers no private chat, and older readers ignore it.
552
+ */
553
+ inbox: Schema.optionalKey(Schema.Struct({ roles: Schema.Array(Schema.String) })),
546
554
  /**
547
555
  * The metrics of the model, since version 8. Written only when there are some; absent reads as
548
556
  * none.
@@ -637,6 +645,10 @@ export function signUpRolesOf(manifest, channel) {
637
645
  ? roles
638
646
  : undefined;
639
647
  }
648
+ /** The wire names of the roles whose people's private chats join the inbox; empty without one. */
649
+ export function inboxRolesOf(manifest) {
650
+ return new Set(manifest.inbox?.roles ?? []);
651
+ }
640
652
  /**
641
653
  * The websites whose visitors may sign up on `web`, by origin: empty while `web` is closed to
642
654
  * sign-up. Entries that are not an origin `signUp.origins` accepts are left out.
@@ -974,6 +986,7 @@ export function buildManifest(input) {
974
986
  },
975
987
  ...(Object.keys(emails).length > 0 ? { emails } : {}),
976
988
  ...(input.chat === undefined ? {} : { chat: input.chat }),
989
+ ...(input.inbox === undefined ? {} : { inbox: { roles: [...input.inbox.roles] } }),
977
990
  ...(connections.length > 0
978
991
  ? {
979
992
  connections: connections.map((candidate) => ({
@@ -555,6 +555,9 @@ export declare const MigrationPlan: Schema.Struct<{
555
555
  readonly footer?: string | undefined;
556
556
  };
557
557
  } | undefined;
558
+ readonly inbox?: {
559
+ readonly roles: readonly string[];
560
+ } | undefined;
558
561
  readonly toolsets?: readonly {
559
562
  readonly name: string;
560
563
  readonly description: string;
@@ -864,6 +867,9 @@ export declare const MigrationPlan: Schema.Struct<{
864
867
  readonly footer?: string | undefined;
865
868
  };
866
869
  } | undefined;
870
+ readonly inbox?: {
871
+ readonly roles: readonly string[];
872
+ } | undefined;
867
873
  readonly toolsets?: readonly {
868
874
  readonly name: string;
869
875
  readonly description: string;
@@ -1138,6 +1144,9 @@ export declare const MigrationPlan: Schema.Struct<{
1138
1144
  readonly footer?: string | undefined;
1139
1145
  };
1140
1146
  } | undefined;
1147
+ readonly inbox?: {
1148
+ readonly roles: readonly string[];
1149
+ } | undefined;
1141
1150
  readonly toolsets?: readonly {
1142
1151
  readonly name: string;
1143
1152
  readonly description: string;
@@ -1482,6 +1491,9 @@ export declare const MigrationPlan: Schema.Struct<{
1482
1491
  readonly footer?: string | undefined;
1483
1492
  };
1484
1493
  } | undefined;
1494
+ readonly inbox?: {
1495
+ readonly roles: readonly string[];
1496
+ } | undefined;
1485
1497
  readonly toolsets?: readonly {
1486
1498
  readonly name: string;
1487
1499
  readonly description: string;
@@ -1761,6 +1773,9 @@ export declare const MigrationPlan: Schema.Struct<{
1761
1773
  readonly separator: Schema.optionalKey<Schema.String>;
1762
1774
  }>>;
1763
1775
  }>>;
1776
+ readonly inbox: Schema.optionalKey<Schema.Struct<{
1777
+ readonly roles: Schema.$Array<Schema.String>;
1778
+ }>>;
1764
1779
  readonly metrics: Schema.optionalKey<Schema.$Array<Schema.Struct<{
1765
1780
  readonly name: Schema.String;
1766
1781
  readonly label: Schema.String;
@@ -2066,6 +2081,9 @@ export declare const MigrationPlan: Schema.Struct<{
2066
2081
  readonly separator: Schema.optionalKey<Schema.String>;
2067
2082
  }>>;
2068
2083
  }>>;
2084
+ readonly inbox: Schema.optionalKey<Schema.Struct<{
2085
+ readonly roles: Schema.$Array<Schema.String>;
2086
+ }>>;
2069
2087
  readonly metrics: Schema.optionalKey<Schema.$Array<Schema.Struct<{
2070
2088
  readonly name: Schema.String;
2071
2089
  readonly label: Schema.String;
@@ -2414,6 +2432,9 @@ export declare const MigrationPlan: Schema.Struct<{
2414
2432
  readonly footer?: string | undefined;
2415
2433
  };
2416
2434
  } | undefined;
2435
+ readonly inbox?: {
2436
+ readonly roles: readonly string[];
2437
+ } | undefined;
2417
2438
  readonly toolsets?: readonly {
2418
2439
  readonly name: string;
2419
2440
  readonly description: string;
@@ -2723,6 +2744,9 @@ export declare const MigrationPlan: Schema.Struct<{
2723
2744
  readonly footer?: string | undefined;
2724
2745
  };
2725
2746
  } | undefined;
2747
+ readonly inbox?: {
2748
+ readonly roles: readonly string[];
2749
+ } | undefined;
2726
2750
  readonly toolsets?: readonly {
2727
2751
  readonly name: string;
2728
2752
  readonly description: string;
@@ -1,7 +1,7 @@
1
1
  import { Effect } from "effect";
2
2
  import { SqlClient } from "effect/unstable/sql";
3
3
  import type { Ontology } from "../ontology.js";
4
- import { type AgentStore, type ResolveIdentityInput, type ChannelSignInInput } from "../service/runtime-contract.js";
4
+ import { type AgentResolution, type AgentStore, type ResolveIdentityInput, type ChannelSignInInput } from "../service/runtime-contract.js";
5
5
  /**
6
6
  * The agent store on the runtime's agent tables, as `ontology_app`. Expiry is the database's
7
7
  * `now()`; a pairing is consumed with one `UPDATE … WHERE "consumed_at" IS NULL`, so two concurrent
@@ -10,6 +10,6 @@ import { type AgentStore, type ResolveIdentityInput, type ChannelSignInInput } f
10
10
  */
11
11
  export declare function sqlAgentStore(ontology: Ontology, sql: SqlClient.SqlClient): AgentStore;
12
12
  /** Shared verified admission for agents and channel-app adapters; never expose trusted inputs to browsers. */
13
- export declare function resolveChannelIdentity(ontology: Ontology, sql: SqlClient.SqlClient, input: ResolveIdentityInput): Effect.Effect<import("../index.js").AgentResolution, never, never>;
13
+ export declare function resolveChannelIdentity(ontology: Ontology, sql: SqlClient.SqlClient, input: ResolveIdentityInput): Effect.Effect<AgentResolution, never, never>;
14
14
  /** Call only after verifying a channel-app assertion. Shares admission, limits and onboarding with agents. */
15
- export declare function resolveChannelSignIn(ontology: Ontology, sql: SqlClient.SqlClient, input: ChannelSignInInput): Effect.Effect<import("../index.js").AgentResolution, never, never>;
15
+ export declare function resolveChannelSignIn(ontology: Ontology, sql: SqlClient.SqlClient, input: ChannelSignInInput): Effect.Effect<AgentResolution, never, never>;
@@ -6,6 +6,7 @@ import { AgentChat } from "../agent-chat.js";
6
6
  import { chatChannelKind } from "../chat-channel.js";
7
7
  import { AgentReview } from "../agent-review.js";
8
8
  import { AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, CHANNEL_USERS_TABLE, IDENTITY_NOTICES_TABLE, USER_TABLE, } from "../migrate/storage.js";
9
+ import { inboxRolesOf } from "../manifest.js";
9
10
  import { MAX_QUERY_LIMIT } from "../query.js";
10
11
  import { beginReplicationWrite } from "../replication/transaction.js";
11
12
  import { IdentityInUse, } from "../service/runtime-contract.js";
@@ -215,7 +216,7 @@ export function sqlAgentStore(ontology, sql) {
215
216
  return created === undefined ? undefined : identityOf(created);
216
217
  }))
217
218
  .pipe(Effect.catchIf((error) => error._tag !== "IdentityInUse", (error) => Effect.die(error))),
218
- resolveIdentity: (input) => resolveAgentIdentity(ontology, sql, store, input),
219
+ resolveIdentity: (input) => resolveAgentIdentity(ontology, sql, store, input).pipe(Effect.map((resolution) => inInbox(ontology, input, resolution))),
219
220
  completeLimitNotice: (input) => completeAgentLimitNotice(sql, input),
220
221
  setMemberBlocked: (input) => setMemberBlocked(ontology, input).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.as(true), Effect.catchTag("MemberNotFound", () => Effect.succeed(false))),
221
222
  // The notice is operational state beside the identity; the legacy columns are kept in step.
@@ -446,6 +447,96 @@ export function sqlAgentStore(ontology, sql) {
446
447
  };
447
448
  }))
448
449
  .pipe(Effect.orDie),
450
+ seeInboxChat: (input) => Effect.gen(function* () {
451
+ const roles = inboxRolesOf(ontology.manifest);
452
+ const member = isRecordId(input.memberId) ? yield* store.member(input.memberId) : undefined;
453
+ // Only the private chats of people whose roles the inbox takes are recorded.
454
+ if (member === undefined || !member.principal.roles.some((role) => roles.has(role))) {
455
+ return undefined;
456
+ }
457
+ return yield* sql.withTransaction(Effect.gen(function* () {
458
+ yield* beginReplicationWrite(sql);
459
+ // Calls for one chat run one after the other: the first creates it, the rest find it.
460
+ yield* rows(`SELECT pg_advisory_xact_lock(hashtext($1))`, [
461
+ `chat:${input.provider}:${input.externalId}`,
462
+ ]);
463
+ const runtime = makeOntologyRuntime(ontology, sql, {
464
+ action: `${AgentChat.name}.seen`,
465
+ actionId: randomUUID(),
466
+ principalId: null,
467
+ });
468
+ const [found] = yield* runtime.find({
469
+ entity: AgentChat.name,
470
+ options: {
471
+ where: { provider: input.provider, external_id: input.externalId },
472
+ limit: 1,
473
+ forUpdate: true,
474
+ },
475
+ });
476
+ // A group chat's id is never a person's private chat.
477
+ if (found !== undefined && found.kind !== "private") {
478
+ return undefined;
479
+ }
480
+ const now = new Date();
481
+ const recipient = input.recipient ?? null;
482
+ const threadId = input.threadId ?? null;
483
+ const changes = {
484
+ ...(found?.title === input.title ? {} : { title: input.title }),
485
+ ...((found?.recipient ?? null) === recipient ? {} : { recipient }),
486
+ ...((found?.thread_id ?? null) === threadId ? {} : { thread_id: threadId }),
487
+ ...(messageDue(found?.last_message_at, now)
488
+ ? { last_message_at: now.toISOString() }
489
+ : {}),
490
+ };
491
+ const chat = found === undefined
492
+ ? yield* runtime.create({
493
+ entity: AgentChat.name,
494
+ values: {
495
+ provider: input.provider,
496
+ external_id: input.externalId,
497
+ kind: "private",
498
+ ...changes,
499
+ },
500
+ })
501
+ : Object.keys(changes).length === 0
502
+ ? found
503
+ : yield* runtime.update({
504
+ entity: AgentChat.name,
505
+ id: String(found.id),
506
+ values: changes,
507
+ });
508
+ // A private chat has one member, its person now: an account paired with someone else
509
+ // since leaves the earlier person out. A link already there changes nothing.
510
+ const members = yield* runtime.related({
511
+ entity: AgentChat.name,
512
+ id: String(chat.id),
513
+ relationship: "members",
514
+ query: { limit: MAX_QUERY_LIMIT },
515
+ });
516
+ for (const member of members.items) {
517
+ if (String(member.id) !== input.memberId) {
518
+ yield* runtime.unlink({
519
+ entity: AgentChat.name,
520
+ relationship: "members",
521
+ id: String(chat.id),
522
+ targetId: String(member.id),
523
+ });
524
+ }
525
+ }
526
+ yield* runtime.link({
527
+ entity: AgentChat.name,
528
+ relationship: "members",
529
+ id: String(chat.id),
530
+ targetId: input.memberId,
531
+ });
532
+ return {
533
+ id: String(chat.id),
534
+ title: String(chat.title),
535
+ purpose: nullableText(chat.purpose),
536
+ whenToUse: nullableText(chat.when_to_use),
537
+ };
538
+ }));
539
+ }).pipe(Effect.orDie),
449
540
  holdReply: (input) => sql
450
541
  .withTransaction(Effect.gen(function* () {
451
542
  if (!isRecordId(input.memberId)) {
@@ -522,3 +613,15 @@ export function resolveChannelSignIn(ontology, sql, input) {
522
613
  };
523
614
  return resolveAgentIdentity(ontology, sql, sqlAgentStore(ontology, sql), identity, "channel_app");
524
615
  }
616
+ /**
617
+ * Marks an admitted person's private chat for the inbox when they hold one of its roles, so the
618
+ * agent reports the chat and the ontology registers it.
619
+ */
620
+ function inInbox(ontology, input, resolution) {
621
+ const roles = inboxRolesOf(ontology.manifest);
622
+ return (resolution.status === "existing" || resolution.status === "created") &&
623
+ input.chat === "private" &&
624
+ resolution.member.principal.roles.some((role) => roles.has(role))
625
+ ? { ...resolution, inbox: true }
626
+ : resolution;
627
+ }
@@ -34,6 +34,11 @@ export type ChatArchiveTransport = (input: {
34
34
  * `agent_chat:read`, as their attachments are; see `withChatMembership`.
35
35
  */
36
36
  readonly memberGroups?: ReadonlyArray<string>;
37
+ /**
38
+ * Chats (`provider:chatId`) of any type the ontology checked the member may read, such as a
39
+ * private chat its inbox registered, which `agent_chat:read` within its scope reads.
40
+ */
41
+ readonly chats?: ReadonlyArray<string>;
37
42
  }) => Effect.Effect<ChatPage, ChatArchiveUnavailable | PermissionDenied>;
38
43
  /** The authenticated ontology service forwards its resolved member, never a caller-supplied ID. */
39
44
  export declare function platformChatArchive(environment: OntologyEnvironment, fetchImpl?: typeof fetch): ChatArchiveTransport;
@@ -22,7 +22,7 @@ export class ChatArchiveUnavailable extends Schema.TaggedError()("ChatArchiveUna
22
22
  }
23
23
  /** The authenticated ontology service forwards its resolved member, never a caller-supplied ID. */
24
24
  export function platformChatArchive(environment, fetchImpl = fetch) {
25
- return ({ search, principal, identityToken, memberGroups }) => {
25
+ return ({ search, principal, identityToken, memberGroups, chats }) => {
26
26
  if (principal.kind !== "member") {
27
27
  return Effect.fail(new PermissionDenied({
28
28
  message: "Only members may read chats.",
@@ -49,6 +49,7 @@ export function platformChatArchive(environment, fetchImpl = fetch) {
49
49
  participantId: principal.id,
50
50
  groups: isAllowed("agent_chat:read", principal),
51
51
  groupChats: memberGroups ?? [],
52
+ ...(chats === undefined || chats.length === 0 ? {} : { chats }),
52
53
  admin: false,
53
54
  },
54
55
  }),
@@ -123,6 +123,9 @@ export declare const ChatSeenRequest: Schema.Struct<{
123
123
  readonly leftMemberId: Schema.optionalKey<Schema.String>;
124
124
  readonly agentLeft: Schema.optionalKey<Schema.Literal<true>>;
125
125
  readonly migratedFrom: Schema.optionalKey<Schema.String>;
126
+ readonly kind: Schema.optionalKey<Schema.Literal<"private">>;
127
+ readonly recipient: Schema.optionalKey<Schema.String>;
128
+ readonly threadId: Schema.optionalKey<Schema.String>;
126
129
  }>;
127
130
  /**
128
131
  * `POST /api/ontology/agent/reviews`: a reply the agent held for a member to review, for the member
@@ -151,6 +151,14 @@ export const ChatSeenRequest = Schema.Struct({
151
151
  migratedFrom: Schema.optionalKey(ChatId.annotate({
152
152
  description: "The chat's id before it became a supergroup: its record moves to externalId.",
153
153
  })),
154
+ kind: Schema.optionalKey(Schema.Literal("private").annotate({
155
+ description: "A person's private chat, which the inbox registers when memberId holds one of its roles; " +
156
+ "absent for a group chat.",
157
+ })),
158
+ recipient: Schema.optionalKey(ChatId.annotate({
159
+ description: "Whom a reply in the private chat is sent to, where it differs from externalId.",
160
+ })),
161
+ threadId: Schema.optionalKey(ChatId.annotate({ description: "The thread a reply in the private chat stays in." })),
154
162
  });
155
163
  /**
156
164
  * `POST /api/ontology/agent/reviews`: a reply the agent held for a member to review, for the member
@@ -208,6 +208,7 @@ function resolveChannelIdentity(store, agentTools) {
208
208
  provisioned: resolution.provisioned,
209
209
  notice_due: resolution.noticeDue,
210
210
  on_new_user_pending: resolution.onNewUserPending,
211
+ ...(resolution.inbox === true ? { inbox: true } : {}),
211
212
  });
212
213
  case "limited":
213
214
  return json({
@@ -278,7 +279,30 @@ function seeChat(store) {
278
279
  if (Result.isFailure(decoded)) {
279
280
  return invalidBody(requestId, schemaIssues(decoded.failure));
280
281
  }
281
- const chat = yield* store.seeChat(decoded.success);
282
+ const { kind, recipient, threadId, ...seen } = decoded.success;
283
+ if (kind === "private") {
284
+ // A person's private chat joins the inbox, which records nothing for anyone else.
285
+ const inboxed = seen.memberId === undefined ||
286
+ store.seeInboxChat === undefined ||
287
+ seen.leftMemberId !== undefined ||
288
+ seen.agentLeft !== undefined ||
289
+ seen.migratedFrom !== undefined
290
+ ? undefined
291
+ : yield* store.seeInboxChat({
292
+ provider: seen.provider,
293
+ externalId: seen.externalId,
294
+ title: seen.title,
295
+ memberId: seen.memberId,
296
+ ...(recipient === undefined ? {} : { recipient }),
297
+ ...(threadId === undefined ? {} : { threadId }),
298
+ });
299
+ if (inboxed === undefined) {
300
+ return toServerResponse(notFound(requestId, "The chat is not one the inbox takes."));
301
+ }
302
+ yield* Effect.logInfo("ontology.agent.chat_reported").pipe(Effect.annotateLogs({ requestId, provider: seen.provider, chatId: seen.externalId }));
303
+ return json(inboxed);
304
+ }
305
+ const chat = yield* store.seeChat(seen);
282
306
  yield* Effect.logInfo("ontology.agent.chat_reported").pipe(Effect.annotateLogs({
283
307
  requestId,
284
308
  provider: decoded.success.provider,
@@ -71,7 +71,7 @@ declare const CurrentChatCall_base: Context.ServiceClass<CurrentChatCall, "@segm
71
71
  readonly live_period?: number | undefined;
72
72
  } | 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;
@@ -125,7 +125,7 @@ export declare function consumeChatEnvelope(args: Readonly<Record<string, unknow
125
125
  readonly live_period?: number | undefined;
126
126
  } | 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;
@@ -8,6 +8,32 @@ import { chatAttribution } from "./attribution.js";
8
8
  import { chatResolver, groupChatKey, isChatMember } from "./resolve.js";
9
9
  /** The kinds of channel whose archived chats are keyed by the chat a destination names. */
10
10
  const HISTORY_KINDS = new Set(["telegram"]);
11
+ const UUID = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
12
+ /**
13
+ * A private chat the inbox registered, by its record id, when the caller may read it: a member with
14
+ * `agent_chat:read` whose scope holds the record (`staff`), or the person in it. Its `externalId` is
15
+ * the chat's id in the archive on every channel. `undefined` for any other id.
16
+ */
17
+ function registeredPrivateChat(backend, principal, id) {
18
+ return Effect.gen(function* () {
19
+ const [chat] = (yield* backend
20
+ .find({
21
+ entity: "agent_chat",
22
+ query: { where: { and: [{ id: { eq: id } }, { kind: { eq: "private" } }] }, limit: 1 },
23
+ })
24
+ .pipe(Effect.mapError((cause) => new ActionRejected({ message: "The chat directory could not be read.", cause })))).items;
25
+ // A group chat is read as before; only a private chat the inbox registered is read here.
26
+ if (chat === undefined || chat.kind !== "private") {
27
+ return undefined;
28
+ }
29
+ const staff = isAllowed("agent_chat:read", principal) &&
30
+ (yield* backend.get({ entity: "agent_chat", id, reader: principal }).pipe(Effect.as(true), Effect.catchTag("NotFound", () => Effect.succeed(false))));
31
+ if (!staff && !(yield* isChatMember(backend, principal, id))) {
32
+ return yield* new PermissionDenied({ message: "This chat is not readable by the caller." });
33
+ }
34
+ return { provider: String(chat.provider), externalId: String(chat.external_id), staff };
35
+ });
36
+ }
11
37
  export function chatReads(backend, options) {
12
38
  const { providers, chatHistory, attribution } = options;
13
39
  const kindOf = options.kindOf ?? ((channel) => channel);
@@ -53,6 +79,30 @@ export function chatReads(backend, options) {
53
79
  if (principal.kind !== "member") {
54
80
  return yield* new PermissionDenied({ message: "Only members may read chatHistory." });
55
81
  }
82
+ const registered = UUID.test(input.chat)
83
+ ? yield* registeredPrivateChat(backend, principal, input.chat)
84
+ : undefined;
85
+ if (registered !== undefined) {
86
+ if (!chatHistory) {
87
+ return yield* new ActionRejected({ message: "The chat archive is not configured." });
88
+ }
89
+ const key = `${registered.provider}:${registered.externalId}`;
90
+ // Staff read the chat's messages whoever wrote them; its person reads the messages they
91
+ // took part in, as in any private chat, so an account paired with someone else since
92
+ // shows the earlier person nothing newer.
93
+ return yield* chatHistory({
94
+ principal,
95
+ identityToken,
96
+ search: {
97
+ provider: registered.provider,
98
+ chatId: registered.externalId,
99
+ ...(input.before === undefined ? {} : { before: input.before }),
100
+ ...(input.limit === undefined ? {} : { limit: input.limit }),
101
+ },
102
+ memberGroups: [],
103
+ ...(registered.staff ? { chats: [key] } : {}),
104
+ });
105
+ }
56
106
  // History reads the chats of Telegram channels only. Other channels archive a chat under
57
107
  // their session's address with private coordinates, not under the chat a destination
58
108
  // names, so their history would be incomplete until the archive keys them the same way.
@@ -40,7 +40,10 @@ export function memberGroupChats(backend, principal) {
40
40
  if (principal.kind !== "member") {
41
41
  return [];
42
42
  }
43
- return (yield* records(backend, "agent_chat", { where: memberOf(principal) })).map(groupChatKey);
43
+ // A private chat the inbox registered is no group, whose person reads it as a participant.
44
+ return (yield* records(backend, "agent_chat", {
45
+ where: { and: [memberOf(principal), { kind: { ne: "private" } }] },
46
+ })).map(groupChatKey);
44
47
  });
45
48
  }
46
49
  /** Whether a member is in one group chat, which lets them read its history without agent_chat:read. */
@@ -87,6 +90,8 @@ export function chatResolver(backend, principal, providers, options = {}) {
87
90
  const groupId = chat !== undefined && UUID.test(chat);
88
91
  const filters = [
89
92
  { provider: { in: [...providers] } },
93
+ // A private chat the inbox registered is read by its record id, never a destination here.
94
+ { kind: { ne: "private" } },
90
95
  ...(chat === undefined ? [] : [groupId ? { id: { eq: chat } } : { title: { eq: chat } }]),
91
96
  ...(canGroup ? [] : [memberOf(principal)]),
92
97
  ];
@@ -800,7 +800,9 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
800
800
  name: "chat_history",
801
801
  title: "Read chat history",
802
802
  description: "Read messages for an exact chat ID/title, with their own pagination. " +
803
- "Reads a group chat you are in (every group with agent_chat:read) or your own private chat.",
803
+ "Reads a group chat you are in (every group with agent_chat:read), your own private chat, " +
804
+ "or, by its agent_chat id, a person's private chat the inbox registered, with " +
805
+ "agent_chat:read within your scope.",
804
806
  inputSchema: encodedJsonSchema(ChatHistory),
805
807
  annotations: READ,
806
808
  permissions: [],
@@ -518,6 +518,11 @@ export type AgentResolution = {
518
518
  readonly provisioned: boolean;
519
519
  readonly noticeDue: boolean;
520
520
  readonly onNewUserPending: boolean;
521
+ /**
522
+ * The person holds a role of the ontology's `inbox` and wrote in a private chat: the agent
523
+ * reports the chat (`POST /api/ontology/agent/chats/seen`), which registers it.
524
+ */
525
+ readonly inbox?: true;
521
526
  } | {
522
527
  readonly status: "pairing_required";
523
528
  } | {
@@ -624,6 +629,14 @@ export interface AgentStore {
624
629
  readonly agentLeft?: true;
625
630
  readonly migratedFrom?: string;
626
631
  }) => Effect.Effect<SeenChat>;
632
+ /**
633
+ * Records a person's private chat with the agent for the inbox: creates the `agent_chat` of kind
634
+ * `private`, with the person as its one member, or keeps its title, recipient and thread current,
635
+ * and records when it last had a message, as `seeChat` does. `undefined`, recording nothing,
636
+ * unless the person is an active member holding a role of the ontology's `inbox`. Absent on
637
+ * stores that predate the inbox.
638
+ */
639
+ readonly seeInboxChat?: (input: InboxChatInput) => Effect.Effect<SeenChat | undefined>;
627
640
  /**
628
641
  * A reply the agent held for review becomes a pending `agent_review` for the member it answers,
629
642
  * once per `key`: a repeated report answers the review it created. `undefined` when the member is
@@ -651,6 +664,21 @@ export interface HeldReplyInput {
651
664
  readonly mode: "always" | "whenUnsure";
652
665
  readonly confidence: number | null;
653
666
  }
667
+ /** A person's private chat the agent saw, as `POST /api/ontology/agent/chats/seen` reports it. */
668
+ export interface InboxChatInput {
669
+ /** The channel the chat is on, by name. */
670
+ readonly provider: string;
671
+ /** The chat's id in the chat archive. */
672
+ readonly externalId: string;
673
+ /** The person's name on the channel. */
674
+ readonly title: string;
675
+ /** The person, a user id. */
676
+ readonly memberId: string;
677
+ /** Whom a reply is sent to, where it differs from `externalId`. */
678
+ readonly recipient?: string;
679
+ /** The thread a reply stays in. */
680
+ readonly threadId?: string;
681
+ }
654
682
  /** The review a held reply became. */
655
683
  export interface HeldReview {
656
684
  readonly id: string;
@@ -545,6 +545,9 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
545
545
  readonly separator: Schema.optionalKey<Schema.String>;
546
546
  }>>;
547
547
  }>>;
548
+ readonly inbox: Schema.optionalKey<Schema.Struct<{
549
+ readonly roles: Schema.$Array<Schema.String>;
550
+ }>>;
548
551
  readonly metrics: Schema.optionalKey<Schema.$Array<Schema.Struct<{
549
552
  readonly name: Schema.String;
550
553
  readonly label: Schema.String;
@@ -863,6 +866,9 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
863
866
  readonly separator: Schema.optionalKey<Schema.String>;
864
867
  }>>;
865
868
  }>>>;
869
+ readonly inbox: Schema.toEncoded<Schema.optionalKey<Schema.Struct<{
870
+ readonly roles: Schema.$Array<Schema.String>;
871
+ }>>>;
866
872
  readonly metrics: Schema.toEncoded<Schema.optionalKey<Schema.$Array<Schema.Struct<{
867
873
  readonly name: Schema.String;
868
874
  readonly label: Schema.String;
@@ -107,7 +107,10 @@ export function attachmentRuntime(ontology, sql, provider) {
107
107
  const binding = provider.binding;
108
108
  const missing = (id) => new NotFound({ entity: "attachment", id, message: "Attachment not found." });
109
109
  const unavailable = (message) => new Conflict({ entity: "attachment", message });
110
- /** The registry contains groups only. Neither a tool argument nor a caller's roles name a group. */
110
+ /**
111
+ * Group chats come from the registry, whose private chats the inbox registered stay private
112
+ * here. Neither a tool argument nor a caller's roles name a group.
113
+ */
111
114
  const accessScope = (caller) => Effect.gen(function* () {
112
115
  const [member] = yield* sql.unsafe(`SELECT kind::text, active FROM "user" WHERE id = $1::uuid FOR SHARE`, [caller.principal.id]);
113
116
  if (member?.kind !== "member" || !member.active) {
@@ -124,7 +127,7 @@ export function attachmentRuntime(ontology, sql, provider) {
124
127
  }
125
128
  const separator = caller.chat.indexOf(":");
126
129
  const [chat] = yield* sql.unsafe(`SELECT id::text FROM "agent_chat"
127
- WHERE provider = $1 AND external_id = $2 FOR SHARE`, [caller.chat.slice(0, separator), caller.chat.slice(separator + 1)]);
130
+ WHERE provider = $1 AND external_id = $2 AND kind::text = 'group' FOR SHARE`, [caller.chat.slice(0, separator), caller.chat.slice(separator + 1)]);
128
131
  if (chat === undefined) {
129
132
  return "private";
130
133
  }
@@ -619,9 +622,11 @@ export function attachmentRuntime(ontology, sql, provider) {
619
622
  const rows = yield* sql.unsafe(`${SELECT} WHERE a.branch_id = $1
620
623
  AND ($2 OR EXISTS (
621
624
  SELECT 1 FROM "agent_chat" c JOIN "agent_chat_members" m ON m.agent_chat_id = c.id
622
- WHERE c.provider || ':' || c.external_id = a.conversation AND m.user_id = $3::uuid
625
+ WHERE c.provider || ':' || c.external_id = a.conversation AND c.kind::text = 'group'
626
+ AND m.user_id = $3::uuid
623
627
  ) OR (a.owner_id = $3::uuid AND NOT EXISTS (
624
- SELECT 1 FROM "agent_chat" c WHERE c.provider || ':' || c.external_id = a.conversation
628
+ SELECT 1 FROM "agent_chat" c
629
+ WHERE c.provider || ':' || c.external_id = a.conversation AND c.kind::text = 'group'
625
630
  )))
626
631
  AND ($4::text IS NULL OR a.conversation = $4)
627
632
  AND ($5::uuid IS NULL OR a.owner_id = $5::uuid)
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.114.0",
3
+ "version": "0.115.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",