@segmentstream/ontology 0.109.0 → 0.111.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 (79) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +28 -1
  3. package/dist/agent-review.d.ts +2 -0
  4. package/dist/agent-review.js +11 -1
  5. package/dist/analyze.d.ts +34 -34
  6. package/dist/analyze.js +104 -29
  7. package/dist/chat-channel.d.ts +22 -0
  8. package/dist/chat-channel.js +35 -0
  9. package/dist/index.d.ts +8 -6
  10. package/dist/index.js +3 -2
  11. package/dist/manifest.d.ts +194 -29
  12. package/dist/manifest.js +54 -10
  13. package/dist/migrate/apply.d.ts +4 -3
  14. package/dist/migrate/apply.js +8 -3
  15. package/dist/migrate/model.d.ts +90 -2
  16. package/dist/migrate/plan.js +1 -1
  17. package/dist/migrate/preview.js +2 -1
  18. package/dist/migrate/storage.d.ts +13 -1
  19. package/dist/migrate/storage.js +33 -1
  20. package/dist/runtime/agent-counters.d.ts +36 -0
  21. package/dist/runtime/agent-counters.js +84 -0
  22. package/dist/runtime/agent-web.d.ts +1 -1
  23. package/dist/runtime/agent-web.js +175 -3
  24. package/dist/runtime/agents.js +3 -0
  25. package/dist/runtime/batch.js +4 -6
  26. package/dist/runtime/history.d.ts +24 -0
  27. package/dist/runtime/history.js +35 -1
  28. package/dist/runtime/pipeline.js +3 -0
  29. package/dist/runtime/principals.d.ts +6 -0
  30. package/dist/runtime/principals.js +25 -6
  31. package/dist/runtime/reads.js +9 -2
  32. package/dist/runtime/sign-in-links.d.ts +10 -0
  33. package/dist/runtime/sign-in-links.js +26 -25
  34. package/dist/runtime/sql-runtime.d.ts +1 -1
  35. package/dist/runtime/sql-runtime.js +3 -2
  36. package/dist/runtime/writes.js +4 -6
  37. package/dist/runtime-source.d.ts +4 -0
  38. package/dist/runtime-source.js +5 -0
  39. package/dist/runtime.d.ts +21 -0
  40. package/dist/service/agent/authentication.d.ts +3 -2
  41. package/dist/service/agent/authentication.js +2 -11
  42. package/dist/service/agent/bot-check.d.ts +42 -0
  43. package/dist/service/agent/bot-check.js +32 -0
  44. package/dist/service/agent/guest-sign-up.d.ts +140 -0
  45. package/dist/service/agent/guest-sign-up.js +545 -0
  46. package/dist/service/agent/protocol.d.ts +34 -1
  47. package/dist/service/agent/protocol.js +46 -1
  48. package/dist/service/agent/server.d.ts +17 -0
  49. package/dist/service/agent/server.js +53 -3
  50. package/dist/service/agent/web-tokens.d.ts +21 -3
  51. package/dist/service/agent/web-tokens.js +79 -6
  52. package/dist/service/authentication.d.ts +9 -1
  53. package/dist/service/authentication.js +31 -5
  54. package/dist/service/chat/delivery.js +9 -5
  55. package/dist/service/chat/envelope.d.ts +6 -0
  56. package/dist/service/chat/providers/index.d.ts +19 -9
  57. package/dist/service/chat/providers/index.js +31 -11
  58. package/dist/service/chat/reads.d.ts +6 -3
  59. package/dist/service/chat/reads.js +26 -14
  60. package/dist/service/chat/resolve.d.ts +6 -2
  61. package/dist/service/chat/resolve.js +7 -3
  62. package/dist/service/chat/review-delivery.d.ts +2 -2
  63. package/dist/service/chat/review-delivery.js +16 -8
  64. package/dist/service/chat/routes.js +2 -1
  65. package/dist/service/chat/schemas.d.ts +2 -0
  66. package/dist/service/chat/schemas.js +8 -1
  67. package/dist/service/config.d.ts +10 -0
  68. package/dist/service/mcp/server.js +2 -1
  69. package/dist/service/operations.d.ts +5 -0
  70. package/dist/service/runtime-contract.d.ts +133 -1
  71. package/dist/service/runtime-identity.d.ts +23 -0
  72. package/dist/service/runtime-identity.js +31 -0
  73. package/dist/service/schemas.d.ts +54 -2
  74. package/dist/service/service.js +27 -1
  75. package/dist/service/webhooks.d.ts +15 -0
  76. package/dist/service/webhooks.js +15 -4
  77. package/dist/sign-in.d.ts +29 -0
  78. package/dist/sign-in.js +8 -0
  79. package/package.json +1 -1
@@ -1,4 +1,5 @@
1
1
  import { Schema } from "effect";
2
+ import { ChatChannelName } from "./chat-channel.js";
2
3
  const Id = Schema.String.check(Schema.isMinLength(1), Schema.isMaxLength(512));
3
4
  /**
4
5
  * The location a Telegram message shared, as the Bot API sends it: a live location's latest update
@@ -13,6 +14,8 @@ const TelegramLocation = Schema.Struct({
13
14
  /** A Telegram chat, with the references Telegram's own actions and attachments use. */
14
15
  const TelegramRuntimeSource = Schema.Struct({
15
16
  provider: Schema.Literal("telegram"),
17
+ /** The bot's channel when it is not the channel named `telegram`. */
18
+ channel: Schema.optionalKey(ChatChannelName),
16
19
  chat_id: Id,
17
20
  thread_id: Schema.String.check(Schema.isMaxLength(512)),
18
21
  message_id: Schema.optionalKey(Id),
@@ -44,6 +47,8 @@ const TelegramRuntimeSource = Schema.Struct({
44
47
  */
45
48
  const ChannelRuntimeSource = Schema.Struct({
46
49
  provider: Schema.Literals(["slack", "whatsapp"]),
50
+ /** The channel when it is not the one named after its kind. */
51
+ channel: Schema.optionalKey(ChatChannelName),
47
52
  chat_id: Id,
48
53
  thread_id: Schema.String.check(Schema.isMaxLength(512)),
49
54
  kind: Schema.Literals(["private", "group"]),
package/dist/runtime.d.ts CHANGED
@@ -5,9 +5,30 @@ import type { ScopedPermission } from "./permissions.js";
5
5
  import type { Where } from "./query.js";
6
6
  import type { WorkloadExecution } from "./runtime/workload.js";
7
7
  /** Who runs an action: an app member or a service principal, both `user` records. */
8
+ /**
9
+ * The chat the app's agent acted in, as the chat archive names it, and the agent's session there.
10
+ * Only the deployment's own agent runtime reports it; a web chat is checked against the member or
11
+ * guest it acts for.
12
+ */
13
+ export interface ChatProvenance {
14
+ /**
15
+ * The chat's channel, by its name as the archive keys it: `web`, or the agent's channel, such as
16
+ * `telegram` or `sales_whatsapp`.
17
+ */
18
+ readonly provider: string;
19
+ /** The chat's id there, such as `guest:<id>` or `member:<id>` on the web, or `-100123`. */
20
+ readonly chatId: string;
21
+ /** The agent's session in the chat. */
22
+ readonly sessionId?: string;
23
+ }
8
24
  export interface Principal {
9
25
  /** Present only for a verified managed pipeline worker. */
10
26
  readonly execution?: WorkloadExecution;
27
+ /**
28
+ * Present only when the app's own agent acts for the principal in a chat, a guest's included:
29
+ * the chat and session the request came from. History keeps it with every change it makes.
30
+ */
31
+ readonly chat?: ChatProvenance;
11
32
  /**
12
33
  * Present only for a workflow's user: the workflow's wire name, whose runs it acts in, and its
13
34
  * identity subject, `workflows:<workspace id>:<workflow name>`.
@@ -5,8 +5,7 @@ import { RequestId } from "../errors.js";
5
5
  import type { Principal } from "../../runtime.js";
6
6
  import type { AgentStore, OntologyBackend } from "../runtime-contract.js";
7
7
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
8
- export declare const CHAT_HEADER = "x-segmentstream-agent-chat";
9
- export declare const SESSION_HEADER = "x-segmentstream-agent-session";
8
+ export { CHAT_HEADER, SESSION_HEADER } from "../runtime-identity.js";
10
9
  /** Authenticate the runtime and resolve its member; attachment storage also checks chat access. */
11
10
  export declare function authenticateAgentCaller(input: {
12
11
  readonly request: HttpServerRequest.HttpServerRequest;
@@ -77,6 +76,7 @@ export declare function delegatedAgentMember(request: HttpServerRequest.HttpServ
77
76
  readonly member: {
78
77
  authenticatedVia: string;
79
78
  execution?: import("../../index.js").WorkloadExecution;
79
+ chat?: import("../../runtime.js").ChatProvenance;
80
80
  workflow?: {
81
81
  readonly name: string;
82
82
  readonly subject: string;
@@ -105,6 +105,7 @@ export declare function delegatedAccount(agents: AgentStore, actAs: string, prov
105
105
  member: {
106
106
  authenticatedVia: string;
107
107
  execution?: import("../../index.js").WorkloadExecution;
108
+ chat?: import("../../runtime.js").ChatProvenance;
108
109
  workflow?: {
109
110
  readonly name: string;
110
111
  readonly subject: string;
@@ -4,17 +4,8 @@ import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { RequestId, forbidden, notFound, toServerResponse, unauthorized, unavailable, } from "../errors.js";
5
5
  import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
6
  import { GUEST_ACT_AS_PREFIX, actingGuestId } from "../../runtime/guests.js";
7
- import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
8
- export const CHAT_HEADER = "x-segmentstream-agent-chat";
9
- export const SESSION_HEADER = "x-segmentstream-agent-session";
10
- /** @legacy agent.conversation-header The chat's header from agents built before it took the name. */
11
- const EARLIER_CHAT_HEADER = "x-segmentstream-agent-conversation";
12
- /**
13
- * `provider:chat id`. An email chat is a Gmail thread and the person's address
14
- * (`email:<thread>:<address>`), so an id may hold an address's `@`, `.` and `+`.
15
- */
16
- const CHAT = /^[a-z][a-z0-9_-]{0,31}:[A-Za-z0-9:_.@+-]{1,320}$/;
17
- const SESSION = /^[A-Za-z0-9:_.-]{1,200}$/;
7
+ import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, CHAT, CHAT_HEADER, EARLIER_CHAT_HEADER, SESSION, SESSION_HEADER, WEB_PROVIDER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
8
+ export { CHAT_HEADER, SESSION_HEADER } from "../runtime-identity.js";
18
9
  /** Authenticate the runtime and resolve its member; attachment storage also checks chat access. */
19
10
  export function authenticateAgentCaller(input) {
20
11
  return Effect.gen(function* () {
@@ -0,0 +1,42 @@
1
+ import type { Redacted } from "effect";
2
+ import type { GuestBotCheck } from "../../sign-in.js";
3
+ import { type WebhookVerification } from "../webhooks.js";
4
+ /**
5
+ * A website's bot check before a guest exists: the website shows the challenge `guest.botCheck`
6
+ * names, and the visitor's browser sends the challenge's token with its request for a guest's agent
7
+ * token. The ontology never holds the challenge's secret key: it is a workspace secret, and
8
+ * SegmentStream's backend checks the token with the provider, as it checks webhook signatures.
9
+ */
10
+ /** The longest challenge token the ontology passes on; providers issue shorter ones. */
11
+ export declare const MAX_BOT_CHECK_TOKEN_LENGTH = 2048;
12
+ /**
13
+ * What the check answered: `valid`, with the hostname of the page the challenge was solved on,
14
+ * `invalid`, `secret_missing` or `unavailable`.
15
+ */
16
+ export type BotCheckVerification = WebhookVerification;
17
+ export interface BotCheckRequest {
18
+ readonly check: GuestBotCheck;
19
+ /** The token the website's challenge gave the visitor. */
20
+ readonly token: string;
21
+ /** The visitor's network address, which the provider compares with the challenge's. */
22
+ readonly remoteIp?: string | undefined;
23
+ /** The deployment's Vercel OIDC token, which proves the workspace application. */
24
+ readonly identityToken: string | undefined;
25
+ readonly requestId: string;
26
+ }
27
+ /** Checks a visitor's challenge token. The service asks SegmentStream's backend by default. */
28
+ export type BotCheckVerifier = (request: BotCheckRequest) => Promise<BotCheckVerification>;
29
+ /**
30
+ * The verifier of a deployed ontology service: `POST
31
+ * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-challenge` on SegmentStream with the
32
+ * request's Vercel OIDC token, admitted only for the secret the deployed ontology's `guest.botCheck`
33
+ * names. Each check carries a new idempotency key, which the provider takes to tell a retried
34
+ * check from a token used twice.
35
+ */
36
+ export declare function deployedBotCheckVerifier(environment: {
37
+ readonly segmentstreamUrl: string;
38
+ readonly workspaceId: string;
39
+ readonly organizationId: string;
40
+ readonly deploymentId?: string | undefined;
41
+ readonly previewCredential?: Redacted.Redacted<string> | undefined;
42
+ }, fetchImpl?: typeof fetch): BotCheckVerifier;
@@ -0,0 +1,32 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { deployedSecretVerifier } from "../webhooks.js";
3
+ /**
4
+ * A website's bot check before a guest exists: the website shows the challenge `guest.botCheck`
5
+ * names, and the visitor's browser sends the challenge's token with its request for a guest's agent
6
+ * token. The ontology never holds the challenge's secret key: it is a workspace secret, and
7
+ * SegmentStream's backend checks the token with the provider, as it checks webhook signatures.
8
+ */
9
+ /** The longest challenge token the ontology passes on; providers issue shorter ones. */
10
+ export const MAX_BOT_CHECK_TOKEN_LENGTH = 2048;
11
+ /**
12
+ * The verifier of a deployed ontology service: `POST
13
+ * /api/internal/v1/workspaces/{id}/secrets/{name}/verify-challenge` on SegmentStream with the
14
+ * request's Vercel OIDC token, admitted only for the secret the deployed ontology's `guest.botCheck`
15
+ * names. Each check carries a new idempotency key, which the provider takes to tell a retried
16
+ * check from a token used twice.
17
+ */
18
+ export function deployedBotCheckVerifier(environment, fetchImpl = fetch) {
19
+ const verify = deployedSecretVerifier(environment, "verify-challenge", fetchImpl);
20
+ return (request) => verify({
21
+ secret: request.check.secret,
22
+ identityToken: request.identityToken,
23
+ requestId: request.requestId,
24
+ }, {
25
+ scheme: request.check.scheme,
26
+ token: request.token,
27
+ idempotencyKey: randomUUID(),
28
+ ...(request.remoteIp === undefined || request.remoteIp === ""
29
+ ? {}
30
+ : { remoteIp: request.remoteIp }),
31
+ });
32
+ }
@@ -0,0 +1,140 @@
1
+ import { Effect } from "effect";
2
+ import { HttpServerRequest, HttpServerResponse } from "effect/unstable/http";
3
+ import { type SessionExchange, type TokenVerifier } from "../authentication.js";
4
+ import { RequestId } from "../errors.js";
5
+ import type { AgentWebStore, OAuthStore, SignInIdentity } from "../runtime-contract.js";
6
+ /**
7
+ * A guest becomes a user by proving an email address, as anyone signs up by email in the app,
8
+ * through the app's own email sign-in. The website's chat asks for an address, and the ontology
9
+ * has the app's sign-in email it: the six-digit code to an address whose Neon Auth account
10
+ * receives codes, else a sign-in link, which also creates the account. Either way the answer is
11
+ * the same, so it reveals nothing about the address.
12
+ *
13
+ * - The code comes back from the website's chat; the ontology checks it with the app's sign-in and
14
+ * verifies the session it opens as it verifies any sign-in token.
15
+ * - The link signs in the browser that opens it on the app's origin, then lands on the ontology's
16
+ * `GET /api/ontology/agent/guests/link?nonce=…`, which reads that session, admits the user and
17
+ * returns to the guest's website with a single-use handoff in the fragment. Only the guest who
18
+ * asked for the link may take it, so a link opened in another browser signs the person up and
19
+ * hands nothing to that browser: someone who types another person's address into a website's
20
+ * chat never gets their account.
21
+ *
22
+ * Once the address is proven the guest becomes the user `signUp` created with it, or a new one,
23
+ * and their grant to the agent becomes that user's. Every refusal is a code alone: the website
24
+ * says it in its own words.
25
+ */
26
+ /** Sign-in emails one guest may ask for an hour, and one address may be sent from guests. */
27
+ export declare const GUEST_EMAIL_CODES_PER_HOUR = 5;
28
+ /** Codes and handoffs one guest may try an hour; each code also allows only a few tries. */
29
+ export declare const GUEST_SIGN_UP_ATTEMPTS_PER_HOUR = 10;
30
+ /** Where an emailed link lands once it signed its browser in on the app's origin. */
31
+ export declare const GUEST_LINK_PATH = "/api/ontology/agent/guests/link";
32
+ /** How long a link works: as long as the app's sign-in links. */
33
+ export declare const GUEST_LINK_TTL_MS: number;
34
+ /** How long the handoff of an opened link waits for the guest's browser. */
35
+ export declare const GUEST_HANDOFF_TTL_MS: number;
36
+ /** The fragment key that carries a handoff to the guest's website, and the one for a refusal. */
37
+ export declare const GUEST_HANDOFF_FRAGMENT = "segmentstream_guest";
38
+ export declare const GUEST_ERROR_FRAGMENT = "segmentstream_guest_error";
39
+ /**
40
+ * The app's email sign-in could not answer: `cause` is the failure or the step that failed, and
41
+ * `httpStatus` Neon Auth's answer when it gave one. Operators read them in the log under the
42
+ * request's id; the guest only reads `email_unavailable`.
43
+ */
44
+ export interface EmailUnavailable {
45
+ readonly status: "unavailable";
46
+ readonly cause: unknown;
47
+ readonly httpStatus?: number;
48
+ }
49
+ /** What asking for a sign-in email answered. */
50
+ export type EmailCodeSend = {
51
+ readonly status: "sent" | "invalid" | "limited";
52
+ } | EmailUnavailable;
53
+ /** What checking a code answered: the identity it proved, or why not. */
54
+ export type EmailCodeCheck = {
55
+ readonly status: "verified";
56
+ readonly identity: SignInIdentity;
57
+ } | {
58
+ readonly status: "invalid";
59
+ } | {
60
+ readonly status: "limited";
61
+ } | EmailUnavailable;
62
+ /**
63
+ * The app's email sign-in, from the ontology's side: send an address a code, or a sign-in link to
64
+ * `callbackPath` on the app's production origin, and check a code.
65
+ */
66
+ export interface EmailCodes {
67
+ readonly send: (email: string) => Promise<EmailCodeSend>;
68
+ readonly sendLink: (email: string, callbackPath: string) => Promise<EmailCodeSend>;
69
+ readonly verify: (email: string, code: string) => Promise<EmailCodeCheck>;
70
+ }
71
+ /**
72
+ * {@link EmailCodes} through the app's Neon Auth, server to server, as the app's sign-in page calls
73
+ * it, with the app's production origin, which Neon Auth trusts: the address gets the app's own
74
+ * sign-in email. A checked code opens a Neon Auth session, whose token the ontology verifies like
75
+ * any sign-in token, and the session is closed again: the browser holds none. A link is the app's
76
+ * sign-in link, which the platform's email webhook sends as it sends every one.
77
+ */
78
+ export declare function neonEmailCodes(config: {
79
+ readonly baseUrl: string;
80
+ readonly origin: string;
81
+ readonly verifyToken: TokenVerifier;
82
+ readonly fetch?: typeof fetch;
83
+ }): EmailCodes;
84
+ /**
85
+ * The page of a guest website a link returns to, without its fragment: an `https` address, or
86
+ * `http` on `localhost` and `127.0.0.1`, on one of the guests' websites. `undefined` for anything
87
+ * else.
88
+ */
89
+ export declare function guestReturnTo(value: string, origins: ReadonlyArray<string>): string | undefined;
90
+ export interface GuestSignUpOptions {
91
+ /** Whether `signUp` lists `email`, which a guest signs up on. */
92
+ readonly emailSignUp: boolean;
93
+ readonly web: AgentWebStore;
94
+ readonly oauth: OAuthStore;
95
+ /** The websites whose visitors are guests. */
96
+ readonly origins: ReadonlyArray<string>;
97
+ /** The app's email sign-in; `undefined` where the ontology cannot send its emails. */
98
+ readonly emailCodes: EmailCodes | undefined;
99
+ /** Turns the app's session cookie a link set into its token. */
100
+ readonly exchangeSession: SessionExchange | undefined;
101
+ readonly verifyToken: TokenVerifier;
102
+ }
103
+ type Answer = Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
104
+ /**
105
+ * The routes a website's guest uses to become a user. The first two take the guest's agent token
106
+ * as their bearer, from a declared website:
107
+ *
108
+ * - `POST /api/ontology/agent/guests/email-code` with `{ email, return_to? }` has the app's sign-in
109
+ * email the address a code or a link, and answers `{ sent: true }` either way. `return_to` is the
110
+ * page of a guest website the link returns to.
111
+ * - `POST /api/ontology/agent/guests/sign-up` with `{ email, code }`, or with the `{ handoff }` an
112
+ * opened link gave the browser, makes the guest that user and answers
113
+ * `{ token, expires_at, refresh_token, chat, user_id, created }`: the user's agent token and
114
+ * refresh token, of the grant that was the guest's, and the user's own chat.
115
+ * - `GET /api/ontology/agent/guests/link?nonce=…` is where the link lands, signed in on the app's
116
+ * origin: it admits the user and redirects to `return_to` with `#segmentstream_guest=<handoff>`,
117
+ * or `#segmentstream_guest_error=<code>`.
118
+ *
119
+ * Refusals: `email_sign_up_closed` when `signUp` does not list `email`, `member_address` for an
120
+ * address of a user sign-up did not create, `code_invalid`, `link_invalid`, `handoff_invalid`,
121
+ * `handoff_other_browser` for a handoff minted for another guest, `rate_limited` with `Retry-After`,
122
+ * `email_unavailable` when the app's email sign-in cannot be reached, and `forbidden` for a guest
123
+ * who is gone.
124
+ */
125
+ export declare function guestSignUpRoutes(options: GuestSignUpOptions): {
126
+ emailCode: (request: HttpServerRequest.HttpServerRequest) => Answer;
127
+ signUp: (request: HttpServerRequest.HttpServerRequest) => Answer;
128
+ link: (request: HttpServerRequest.HttpServerRequest) => Answer;
129
+ };
130
+ /**
131
+ * `OPTIONS` of the guests' routes: lets a browser on one of the guests' websites call them with
132
+ * the guest's agent token; any other origin gets no permission.
133
+ */
134
+ export declare function guestRoutesPreflight(origins: ReadonlyArray<string>): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, never>;
135
+ /**
136
+ * `POST /api/ontology/agent/guests/usage` (runtime): adds the model cost of a guest's turn to the
137
+ * guests' spend, once per `key`, and answers 204.
138
+ */
139
+ export declare function recordGuestUsage(web: AgentWebStore): (request: HttpServerRequest.HttpServerRequest) => Answer;
140
+ export {};