@segmentstream/ontology 0.108.0 → 0.110.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 (61) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/README.md +21 -0
  3. package/dist/analyze.js +55 -3
  4. package/dist/email.d.ts +18 -2
  5. package/dist/email.js +57 -7
  6. package/dist/index.d.ts +5 -5
  7. package/dist/index.js +2 -2
  8. package/dist/manifest.d.ts +94 -5
  9. package/dist/manifest.js +41 -6
  10. package/dist/migrate/apply.d.ts +4 -3
  11. package/dist/migrate/apply.js +8 -3
  12. package/dist/migrate/model.d.ts +46 -2
  13. package/dist/migrate/plan.js +1 -1
  14. package/dist/migrate/preview.js +2 -1
  15. package/dist/migrate/storage.d.ts +13 -1
  16. package/dist/migrate/storage.js +33 -1
  17. package/dist/runtime/agent-counters.d.ts +36 -0
  18. package/dist/runtime/agent-counters.js +84 -0
  19. package/dist/runtime/agent-web.d.ts +1 -1
  20. package/dist/runtime/agent-web.js +175 -3
  21. package/dist/runtime/batch.js +4 -6
  22. package/dist/runtime/history.d.ts +24 -0
  23. package/dist/runtime/history.js +35 -1
  24. package/dist/runtime/pipeline.js +3 -0
  25. package/dist/runtime/principals.d.ts +6 -0
  26. package/dist/runtime/principals.js +25 -6
  27. package/dist/runtime/reads.js +9 -2
  28. package/dist/runtime/sign-in-links.d.ts +10 -0
  29. package/dist/runtime/sign-in-links.js +26 -25
  30. package/dist/runtime/sql-runtime.d.ts +1 -1
  31. package/dist/runtime/sql-runtime.js +3 -2
  32. package/dist/runtime/writes.js +4 -6
  33. package/dist/runtime.d.ts +18 -0
  34. package/dist/service/agent/authentication.d.ts +3 -2
  35. package/dist/service/agent/authentication.js +2 -7
  36. package/dist/service/agent/bot-check.d.ts +42 -0
  37. package/dist/service/agent/bot-check.js +32 -0
  38. package/dist/service/agent/guest-sign-up.d.ts +140 -0
  39. package/dist/service/agent/guest-sign-up.js +545 -0
  40. package/dist/service/agent/protocol.d.ts +33 -1
  41. package/dist/service/agent/protocol.js +41 -1
  42. package/dist/service/agent/server.d.ts +17 -0
  43. package/dist/service/agent/server.js +42 -3
  44. package/dist/service/agent/web-tokens.d.ts +21 -3
  45. package/dist/service/agent/web-tokens.js +79 -6
  46. package/dist/service/authentication.d.ts +8 -1
  47. package/dist/service/authentication.js +26 -5
  48. package/dist/service/chat/providers/email.d.ts +3 -1
  49. package/dist/service/chat/providers/email.js +8 -1
  50. package/dist/service/config.d.ts +10 -0
  51. package/dist/service/operations.d.ts +5 -0
  52. package/dist/service/runtime-contract.d.ts +124 -1
  53. package/dist/service/runtime-identity.d.ts +23 -0
  54. package/dist/service/runtime-identity.js +31 -0
  55. package/dist/service/schemas.d.ts +46 -2
  56. package/dist/service/service.js +27 -1
  57. package/dist/service/webhooks.d.ts +15 -0
  58. package/dist/service/webhooks.js +15 -4
  59. package/dist/sign-in.d.ts +29 -0
  60. package/dist/sign-in.js +8 -0
  61. package/package.json +1 -1
@@ -1,19 +1,22 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { Effect } from "effect";
3
- import { CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
3
+ import { SqlClient } from "effect/unstable/sql";
4
+ import { signUpRolesOf } from "../manifest.js";
5
+ import { AGENT_GUEST_LINKS_TABLE, CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, OAUTH_TOKENS_TABLE, USER_TABLE, } from "../migrate/storage.js";
4
6
  import { AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
5
7
  import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, FULL_SCOPE, REFRESH_TOKEN_PREFIX, REFRESH_TOKEN_TTL_MS, newSecret, secretHash, } from "../service/oauth/protocol.js";
6
- import { completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, } from "./agent-counters.js";
8
+ import { addGuestSpend, completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, guestSpendLimited, } from "./agent-counters.js";
7
9
  import { channelUsersAvailable } from "./member-tables.js";
8
10
  import { runNewUserHook } from "./new-user-hook.js";
9
11
  import { CHANNEL_IDENTITIES_FROM, LIVE_CHANNEL_IDENTITY } from "./user-identity-sql.js";
10
12
  import { WEB_PROVIDER } from "../service/runtime-identity.js";
11
13
  import { guestPrincipal } from "./guests.js";
12
14
  import { sqlOAuthStore } from "./oauth.js";
13
- import { isMemberBlocked } from "./principals.js";
15
+ import { isMemberBlocked, resolveSignInState, signsInWithCode } from "./principals.js";
14
16
  import { isRecordId } from "./records.js";
15
17
  const GRANTS = `"${OAUTH_GRANTS_TABLE}"`;
16
18
  const TOKENS = `"${OAUTH_TOKENS_TABLE}"`;
19
+ const LINKS = `"${AGENT_GUEST_LINKS_TABLE}"`;
17
20
  // @legacy ontology.sign-up-web
18
21
  /** How many new website visitors one network address may sign up an hour. */
19
22
  export const VISITORS_PER_CLIENT_PER_HOUR = 10;
@@ -29,6 +32,98 @@ const EXPIRED_GUESTS_PER_ISSUE = 100;
29
32
  */
30
33
  export function sqlAgentWebStore(ontology, sql, admission) {
31
34
  const oauth = sqlOAuthStore(ontology, sql);
35
+ /** Whether a guest's grant still stands: it names no user and nobody revoked it. */
36
+ const guestStands = (guestId) => Effect.map(sql.unsafe(`SELECT 1 FROM ${GRANTS} WHERE "id" = $1::uuid AND "user_id" IS NULL
37
+ AND "client_id" = $2 AND "revoked_at" IS NULL`, [guestId, AGENT_WEB_CLIENT_ID]), (rows) => rows.length > 0);
38
+ /**
39
+ * The user an address a guest proved with the app's email sign-in belongs to: the user sign-up
40
+ * created with it, or a new one `signUp` creates on `email` with its roles, through the app's
41
+ * own sign-in. An address another kind of user holds is refused, as the email channel refuses to
42
+ * link a member's address: a member signs in in the app, never through a website's chat.
43
+ */
44
+ const admitEmail = (identity) => Effect.gen(function* () {
45
+ const email = identity.email?.trim().toLowerCase();
46
+ if (ontology.signIn.guest === undefined ||
47
+ identity.provider !== "neon-auth" ||
48
+ email === undefined ||
49
+ email === "") {
50
+ return { status: "refused" };
51
+ }
52
+ if (signUpRolesOf(ontology.manifest, "email") === undefined) {
53
+ return { status: "sign_up_closed" };
54
+ }
55
+ const [owner] = yield* sql.unsafe(`SELECT "u"."kind"::text AS "kind",
56
+ COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up"
57
+ FROM "${USER_TABLE}" AS "u"
58
+ LEFT JOIN "${CHANNEL_USERS_TABLE}" AS "c" ON "c"."user_id" = "u"."id"
59
+ WHERE "u"."email" = $1 LIMIT 1`, [email]);
60
+ if (owner !== undefined && (owner.kind !== "member" || owner.signed_up !== true)) {
61
+ return { status: "member_address" };
62
+ }
63
+ const state = yield* resolveSignInState(ontology, {
64
+ identityProvider: identity.provider,
65
+ identitySubject: identity.subject,
66
+ email,
67
+ ...(identity.name === undefined ? {} : { name: identity.name }),
68
+ }).pipe(Effect.provideService(SqlClient.SqlClient, sql), Effect.catchTag("PrincipalRejected", () => Effect.succeed(undefined)));
69
+ if (state === undefined) {
70
+ return { status: "refused" };
71
+ }
72
+ const [lifecycle] = yield* sql.unsafe(`SELECT COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up"
73
+ FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid`, [state.principal.id]);
74
+ // A member invited with the address since the check above signs in through the app.
75
+ if (lifecycle?.signed_up !== true) {
76
+ return { status: "member_address" };
77
+ }
78
+ // Onboarding runs before the user's first turn, as for anyone email sign-up created.
79
+ if (state.signUpPending) {
80
+ yield* runNewUserHook(ontology, sql, state.principal);
81
+ }
82
+ return {
83
+ status: "admitted",
84
+ userId: state.principal.id,
85
+ created: owner === undefined,
86
+ };
87
+ });
88
+ /**
89
+ * The guest's grant becomes the user's, so the chat their browser holds goes on as theirs: the
90
+ * guest's tokens stand for nobody, and the user's new ones are answered.
91
+ */
92
+ const moveGrant = (input) => sql.withTransaction(Effect.gen(function* () {
93
+ const { guestId, userId, expiresAt } = input;
94
+ // Same lock as the member's lifecycle operations, so a blocked user gets nothing.
95
+ const [member] = yield* sql.unsafe(`SELECT "kind"::text AS "kind", "active" FROM "${USER_TABLE}"
96
+ WHERE "id" = $1::uuid FOR SHARE`, [userId]);
97
+ if (member?.kind !== "member" || !member.active || (yield* isMemberBlocked(sql, userId))) {
98
+ return { status: "refused" };
99
+ }
100
+ const [moved] = yield* sql.unsafe(`UPDATE ${GRANTS} SET "user_id" = $2::uuid
101
+ WHERE "id" = $1::uuid AND "user_id" IS NULL AND "client_id" = $3
102
+ AND "revoked_at" IS NULL RETURNING "id"`, [guestId, userId, AGENT_WEB_CLIENT_ID]);
103
+ if (moved === undefined) {
104
+ return { status: "refused" };
105
+ }
106
+ yield* sql.unsafe(`DELETE FROM ${TOKENS} WHERE "grant_id" = $1::uuid`, [guestId]);
107
+ const token = newSecret(ACCESS_TOKEN_PREFIX);
108
+ const refreshToken = newSecret(REFRESH_TOKEN_PREFIX);
109
+ yield* oauth.saveTokens([
110
+ { hash: secretHash(token), grantId: guestId, kind: "access", expiresAt },
111
+ {
112
+ hash: secretHash(refreshToken),
113
+ grantId: guestId,
114
+ kind: "refresh",
115
+ expiresAt: new Date(Date.now() + REFRESH_TOKEN_TTL_MS),
116
+ },
117
+ ]);
118
+ return {
119
+ status: "upgraded",
120
+ userId,
121
+ created: input.created,
122
+ token,
123
+ refreshToken,
124
+ expiresAt,
125
+ };
126
+ }));
32
127
  return {
33
128
  issue: ({ userId, resource, expiresAt }) => sql
34
129
  .withTransaction(Effect.gen(function* () {
@@ -87,6 +182,11 @@ export function sqlAgentWebStore(ontology, sql, admission) {
87
182
  return undefined;
88
183
  }
89
184
  const limits = yield* effectiveChannelLimits(sql, input);
185
+ // Money first: a guest past a cap starts no turn, and the turn is not counted.
186
+ const spent = yield* guestSpendLimited(sql, { guestId, limits });
187
+ if (spent !== undefined) {
188
+ return spent;
189
+ }
90
190
  for (const [scope, subject, limit] of [
91
191
  ["guestTurnsPerDay", guestId, limits.guest.turnsPerDay],
92
192
  ["guestWorkspaceTurnsPerDay", "workspace", limits.guest.workspaceTurnsPerDay],
@@ -105,6 +205,78 @@ export function sqlAgentWebStore(ontology, sql, admission) {
105
205
  }
106
206
  return undefined;
107
207
  }).pipe(Effect.orDie),
208
+ recordGuestUsage: ({ guestId, costUsd, key }) => isRecordId(guestId) ? addGuestSpend(sql, { guestId, costUsd, key }) : Effect.void,
209
+ countGuestAttempt: ({ scope, subject, limit }) => countAgentAttempt(sql, { scope, subject, window: "hour", limit }).pipe(Effect.map((limited) => limited?.retryAfterSeconds)),
210
+ upgradeGuest: ({ guestId, identity, expiresAt }) => Effect.gen(function* () {
211
+ if (!isRecordId(guestId) || !(yield* guestStands(guestId))) {
212
+ return { status: "refused" };
213
+ }
214
+ const admitted = yield* admitEmail(identity);
215
+ return admitted.status === "admitted"
216
+ ? yield* moveGrant({ guestId, ...admitted, expiresAt })
217
+ : admitted;
218
+ }).pipe(Effect.orDie),
219
+ guestEmailMethod: (email) => Effect.map(signsInWithCode(sql, email), (code) => (code ? "code" : "link")),
220
+ requestGuestLink: ({ guestId, email, returnTo, nonceHash, expiresAt }) => sql
221
+ .withTransaction(Effect.gen(function* () {
222
+ // Links outlive their expiry a day at most: a few go with each new one.
223
+ yield* sql.unsafe(`DELETE FROM ${LINKS} WHERE ctid IN (
224
+ SELECT ctid FROM ${LINKS} WHERE "created_at" < now() - interval '2 days'
225
+ LIMIT 100 FOR UPDATE SKIP LOCKED
226
+ )`);
227
+ yield* sql.unsafe(`INSERT INTO ${LINKS} ("nonce_hash", "guest_id", "email", "return_to", "expires_at")
228
+ VALUES ($1, $2::uuid, $3, $4, $5::timestamptz)`, [nonceHash, guestId, email, returnTo ?? null, expiresAt.toISOString()]);
229
+ }))
230
+ .pipe(Effect.asVoid, Effect.orDie),
231
+ openGuestLink: ({ nonceHash, identity, handoffHash, handoffExpiresAt }) => Effect.gen(function* () {
232
+ // Opened once: a link the address's owner opens again, or anyone else, finds nothing.
233
+ const [link] = yield* sql.unsafe(`UPDATE ${LINKS} SET "opened_at" = now()
234
+ WHERE "nonce_hash" = $1 AND "opened_at" IS NULL AND "expires_at" > now()
235
+ RETURNING "email", "return_to"`, [nonceHash]);
236
+ if (link === undefined) {
237
+ return { status: "link_invalid" };
238
+ }
239
+ const returnTo = link.return_to ?? undefined;
240
+ // The session must have proven the very address the guest asked the link for.
241
+ if (identity.email?.trim().toLowerCase() !== link.email) {
242
+ return { status: "link_invalid", returnTo };
243
+ }
244
+ const admitted = yield* admitEmail(identity);
245
+ if (admitted.status !== "admitted") {
246
+ return { status: admitted.status, returnTo };
247
+ }
248
+ yield* sql.unsafe(`UPDATE ${LINKS} SET "user_id" = $2::uuid, "user_created" = $3,
249
+ "handoff_hash" = $4, "handoff_expires_at" = $5::timestamptz
250
+ WHERE "nonce_hash" = $1`, [
251
+ nonceHash,
252
+ admitted.userId,
253
+ admitted.created,
254
+ handoffHash,
255
+ handoffExpiresAt.toISOString(),
256
+ ]);
257
+ return { status: "handed_off", returnTo, created: admitted.created };
258
+ }).pipe(Effect.orDie),
259
+ takeGuestHandoff: ({ handoffHash, guestId, expiresAt }) => sql
260
+ .withTransaction(Effect.gen(function* () {
261
+ const [handoff] = yield* sql.unsafe(`SELECT "guest_id"::text AS "guest_id", "user_id"::text AS "user_id", "user_created"
262
+ FROM ${LINKS} WHERE "handoff_hash" = $1 AND "handed_off_at" IS NULL
263
+ AND "handoff_expires_at" > now() AND "user_id" IS NOT NULL FOR UPDATE`, [handoffHash]);
264
+ if (handoff === undefined) {
265
+ return { status: "handoff_invalid" };
266
+ }
267
+ // Only the guest who asked for the link: another browser's guest leaves it untaken.
268
+ if (handoff.guest_id !== guestId) {
269
+ return { status: "handoff_other_browser" };
270
+ }
271
+ yield* sql.unsafe(`UPDATE ${LINKS} SET "handed_off_at" = now() WHERE "handoff_hash" = $1`, [handoffHash]);
272
+ return yield* moveGrant({
273
+ guestId,
274
+ userId: handoff.user_id,
275
+ created: handoff.user_created === true,
276
+ expiresAt,
277
+ });
278
+ }))
279
+ .pipe(Effect.orDie),
108
280
  guest: ({ resource, client }) => Effect.gen(function* () {
109
281
  if (ontology.signIn.guest === undefined) {
110
282
  return { status: "refused" };
@@ -1,8 +1,8 @@
1
1
  import { Effect, Schema } from "effect";
2
2
  import { ActionRejected, Conflict, NotFound } from "../errors.js";
3
- import { ACTION_ATTRIBUTION_TABLE, quoteIdentifier } from "../migrate/storage.js";
3
+ import { quoteIdentifier } from "../migrate/storage.js";
4
4
  import { InvalidValues, StoredRecordMismatch } from "./errors.js";
5
- import { diffRecords } from "./history.js";
5
+ import { attributed, diffRecords, insertAttribution } from "./history.js";
6
6
  import { uuidv7 } from "./ids.js";
7
7
  import { entityModel } from "./model.js";
8
8
  import { normalizeId } from "./reads.js";
@@ -420,11 +420,9 @@ function recordBatchEdits(context, entity, edits) {
420
420
  if (edits.length === 0) {
421
421
  return;
422
422
  }
423
- if (context.scope.execution !== undefined && !context.attributionInitialized) {
423
+ if (attributed(context.scope) && !context.attributionInitialized) {
424
424
  const params = new Params();
425
- yield* context.run(`INSERT INTO "${ACTION_ATTRIBUTION_TABLE}" (action_id, execution) VALUES (` +
426
- `${params.add(context.scope.actionId, "uuid")}, ` +
427
- `${params.add(JSON.stringify(context.scope.execution), "jsonb")}) ON CONFLICT DO NOTHING`, params);
425
+ yield* context.run(insertAttribution(context.scope, params), params);
428
426
  }
429
427
  for (const part of yield* chunks(edits, 7, (edit) => Buffer.byteLength(JSON.stringify(edit.changes)))) {
430
428
  const params = new Params();
@@ -30,6 +30,15 @@ export declare const Edit: Schema.Struct<{
30
30
  }>>;
31
31
  }>;
32
32
  export type Edit = typeof Edit.Type;
33
+ /**
34
+ * The chat the app's agent acted in when it ran the action, and its session there, as the chat
35
+ * archive names them: a guest's chat is `web` and `guest:<id>`.
36
+ */
37
+ export declare const ChatProvenance: Schema.Struct<{
38
+ readonly provider: Schema.String;
39
+ readonly chatId: Schema.String;
40
+ readonly sessionId: Schema.optionalKey<Schema.String>;
41
+ }>;
33
42
  /** A row of `<entity>_history`. */
34
43
  export declare const HistoryEntry: Schema.Struct<{
35
44
  readonly execution: Schema.optionalKey<Schema.Struct<{
@@ -52,6 +61,12 @@ export declare const HistoryEntry: Schema.Struct<{
52
61
  readonly issuedAt: Schema.Number;
53
62
  readonly expiresAt: Schema.Number;
54
63
  }>>;
64
+ /** The chat the app's agent ran the action from, for anyone it acted for, a guest included. */
65
+ readonly chat: Schema.optionalKey<Schema.Struct<{
66
+ readonly provider: Schema.String;
67
+ readonly chatId: Schema.String;
68
+ readonly sessionId: Schema.optionalKey<Schema.String>;
69
+ }>>;
55
70
  readonly id: Schema.String;
56
71
  readonly recordId: Schema.String;
57
72
  /** The qualified action, for example `lead.changeStatus`. */
@@ -76,6 +91,7 @@ export interface HistoryWrite {
76
91
  }
77
92
  export interface HistoryScope {
78
93
  readonly execution?: WorkloadExecution;
94
+ readonly chat?: typeof ChatProvenance.Type;
79
95
  readonly workflow?: {
80
96
  readonly name: string;
81
97
  readonly subject: string;
@@ -87,5 +103,13 @@ export interface HistoryScope {
87
103
  readonly blobActionKey?: string;
88
104
  readonly createIntent?: string;
89
105
  }
106
+ /** Whether one run of an action keeps verified attribution beside its history rows. */
107
+ export declare function attributed(scope: HistoryScope): boolean;
108
+ /**
109
+ * `INSERT` of the action's attribution, once per run: the verified pipeline execution, or the chat
110
+ * the app's agent acted in. Only the columns that hold a value are named, so a database migrated
111
+ * before `chat` keeps taking a pipeline's attribution.
112
+ */
113
+ export declare function insertAttribution(scope: HistoryScope, params: Params): string;
90
114
  /** `INSERT` of one history row; `at` is the transaction's time, shared by the whole action. */
91
115
  export declare function insertHistory(scope: HistoryScope, write: HistoryWrite, params: Params): string;
@@ -1,7 +1,7 @@
1
1
  import { Schema } from "effect";
2
2
  import { canonicalJson } from "../manifest.js";
3
3
  import { WorkloadExecution } from "./workload.js";
4
- import { quoteIdentifier } from "../migrate/storage.js";
4
+ import { ACTION_ATTRIBUTION_TABLE, quoteIdentifier } from "../migrate/storage.js";
5
5
  import { uuidv7 } from "./ids.js";
6
6
  export const EditKind = Schema.Literals(["create", "update", "delete", "link", "unlink"]);
7
7
  /** One property's change. A relationship's change carries record ids. */
@@ -20,9 +20,20 @@ export const Edit = Schema.Struct({
20
20
  kind: EditKind,
21
21
  changes: Changes,
22
22
  });
23
+ /**
24
+ * The chat the app's agent acted in when it ran the action, and its session there, as the chat
25
+ * archive names them: a guest's chat is `web` and `guest:<id>`.
26
+ */
27
+ export const ChatProvenance = Schema.Struct({
28
+ provider: Schema.String,
29
+ chatId: Schema.String,
30
+ sessionId: Schema.optionalKey(Schema.String),
31
+ });
23
32
  /** A row of `<entity>_history`. */
24
33
  export const HistoryEntry = Schema.Struct({
25
34
  execution: Schema.optionalKey(WorkloadExecution),
35
+ /** The chat the app's agent ran the action from, for anyone it acted for, a guest included. */
36
+ chat: Schema.optionalKey(ChatProvenance),
26
37
  id: Schema.String,
27
38
  recordId: Schema.String,
28
39
  /** The qualified action, for example `lead.changeStatus`. */
@@ -58,6 +69,29 @@ export function diffRecords(entity, before, after) {
58
69
  }
59
70
  return changes;
60
71
  }
72
+ /** Whether one run of an action keeps verified attribution beside its history rows. */
73
+ export function attributed(scope) {
74
+ return scope.execution !== undefined || scope.chat !== undefined;
75
+ }
76
+ /**
77
+ * `INSERT` of the action's attribution, once per run: the verified pipeline execution, or the chat
78
+ * the app's agent acted in. Only the columns that hold a value are named, so a database migrated
79
+ * before `chat` keeps taking a pipeline's attribution.
80
+ */
81
+ export function insertAttribution(scope, params) {
82
+ const columns = ['"action_id"'];
83
+ const values = [params.add(scope.actionId, "uuid")];
84
+ if (scope.execution !== undefined) {
85
+ columns.push('"execution"');
86
+ values.push(params.add(JSON.stringify(scope.execution), "jsonb"));
87
+ }
88
+ if (scope.chat !== undefined) {
89
+ columns.push('"chat"');
90
+ values.push(params.add(JSON.stringify(scope.chat), "jsonb"));
91
+ }
92
+ return (`INSERT INTO "${ACTION_ATTRIBUTION_TABLE}" (${columns.join(", ")}) ` +
93
+ `VALUES (${values.join(", ")}) ON CONFLICT DO NOTHING`);
94
+ }
61
95
  /** `INSERT` of one history row; `at` is the transaction's time, shared by the whole action. */
62
96
  export function insertHistory(scope, write, params) {
63
97
  const table = quoteIdentifier(write.entity.historyTable);
@@ -352,6 +352,9 @@ export function runAction(ontology, request) {
352
352
  // A guest is no user: what they create or change was created and updated by nobody.
353
353
  principalId: request.principal.kind === "guest" ? null : request.principal.id,
354
354
  ...(request.principal.execution ? { execution: request.principal.execution } : {}),
355
+ // The chat the app's agent acted in: history keeps it, so a record, a guest's too,
356
+ // leads back to the chat it came from.
357
+ ...(request.principal.chat ? { chat: request.principal.chat } : {}),
355
358
  ...(request.principal.workflow ? { workflow: request.principal.workflow } : {}),
356
359
  ...(key ? { blobActionKey: key } : {}),
357
360
  ...(request.branchId ? { branchId: request.branchId } : {}),
@@ -270,6 +270,12 @@ export type MemberKey = {
270
270
  };
271
271
  /** Every member, signed in or not, by email. */
272
272
  export declare function listMembers(): Effect.Effect<ReadonlyArray<MemberSummary>, never, SqlClient.SqlClient>;
273
+ /**
274
+ * Whether an address can receive the app's sign-in code: a user holds it who has signed in with
275
+ * Neon Auth before, as `checkSignIn` answers `code`. Neon Auth sends codes only to its existing
276
+ * accounts; anyone else signs in with a link.
277
+ */
278
+ export declare function signsInWithCode(sql: SqlClient.SqlClient, email: string): Effect.Effect<boolean>;
273
279
  /**
274
280
  * Whether a person may sign in with this address, and how; it reads and changes nothing else.
275
281
  * Under `invited`, an active member who signed in with Neon Auth before gets `code`, an active
@@ -1143,6 +1143,30 @@ const SignInRow = Schema.Struct({
1143
1143
  neon_auth: Schema.Boolean,
1144
1144
  });
1145
1145
  const decodeSignInRow = Schema.decodeUnknownSync(SignInRow);
1146
+ /**
1147
+ * Whether the user `"u"` has a Neon Auth account, which receives sign-in codes: their live email
1148
+ * sign-in identity. `$2` is the Neon Auth provider.
1149
+ */
1150
+ function neonAuthAccountSql(sql) {
1151
+ return Effect.map(userIdentitiesAvailable(sql), (available) => available
1152
+ ? `EXISTS (SELECT 1 FROM "${USER_IDENTITY_TABLE}" AS "i" WHERE "i"."user_id" = "u"."id" ` +
1153
+ `AND "i"."provider" = $2 AND "i"."origin"::text IN ${SIGN_IN_ORIGIN_SQL} ` +
1154
+ `AND "i"."revoked_at" IS NULL)`
1155
+ : `("u"."identity_provider" = $2 AND "u"."identity_subject" IS NOT NULL)`);
1156
+ }
1157
+ /**
1158
+ * Whether an address can receive the app's sign-in code: a user holds it who has signed in with
1159
+ * Neon Auth before, as `checkSignIn` answers `code`. Neon Auth sends codes only to its existing
1160
+ * accounts; anyone else signs in with a link.
1161
+ */
1162
+ export function signsInWithCode(sql, email) {
1163
+ return Effect.gen(function* () {
1164
+ const neonAuth = yield* neonAuthAccountSql(sql);
1165
+ const [row] = yield* sql.unsafe(`SELECT ${neonAuth} AS "code" FROM "${USER_TABLE}" AS "u" ` +
1166
+ `WHERE "u"."kind" = 'member' AND "u"."email" = $1 LIMIT 1`, [normalizeEmail(email), NEON_AUTH_PROVIDER]);
1167
+ return row?.code === true;
1168
+ }).pipe(Effect.orDie);
1169
+ }
1146
1170
  /**
1147
1171
  * Whether a person may sign in with this address, and how; it reads and changes nothing else.
1148
1172
  * Under `invited`, an active member who signed in with Neon Auth before gets `code`, an active
@@ -1156,12 +1180,7 @@ export function checkSignIn(ontology, email) {
1156
1180
  return { allowed: false };
1157
1181
  }
1158
1182
  const sql = yield* SqlClient.SqlClient;
1159
- // Neon Auth accounts receive sign-in codes: the member's live email sign-in identity.
1160
- const neonAuth = (yield* userIdentitiesAvailable(sql))
1161
- ? `EXISTS (SELECT 1 FROM "${USER_IDENTITY_TABLE}" AS "i" WHERE "i"."user_id" = "u"."id" ` +
1162
- `AND "i"."provider" = $2 AND "i"."origin"::text IN ${SIGN_IN_ORIGIN_SQL} ` +
1163
- `AND "i"."revoked_at" IS NULL)`
1164
- : `("u"."identity_provider" = $2 AND "u"."identity_subject" IS NOT NULL)`;
1183
+ const neonAuth = yield* neonAuthAccountSql(sql);
1165
1184
  const [row] = yield* sql.unsafe(`SELECT "u"."id"::text AS "id", "u"."active" AS "active", ${neonAuth} AS "neon_auth" ` +
1166
1185
  `FROM "${USER_TABLE}" AS "u" WHERE "u"."kind" = 'member' AND "u"."email" = $1 LIMIT 1`, [address, NEON_AUTH_PROVIDER]);
1167
1186
  // Anyone may sign in where email is open to sign-up, so the answer reveals nothing.
@@ -283,14 +283,20 @@ export function readHistory(context, entity, input) {
283
283
  conditions.push(`("h"."at" < ${at} OR ("h"."at" = ${at} AND "h"."id" < ${params.add(cursor[1], "uuid")}))`);
284
284
  }
285
285
  const presenceParams = new Params();
286
- const [presence] = yield* context.run("SELECT to_regclass('_ontology_action_attribution') IS NOT NULL AS present", presenceParams);
286
+ // @legacy ontology.pre-upgrade-database-tolerance
287
+ // A database migrated before an attribution table, or before its `chat`, reads without them.
288
+ const [presence] = yield* context.run("SELECT to_regclass('_ontology_action_attribution') IS NOT NULL AS present, " +
289
+ "EXISTS (SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() " +
290
+ "AND table_name = '_ontology_action_attribution' AND column_name = 'chat') AS chat", presenceParams);
287
291
  const attribution = presence?.present === true;
292
+ const chat = attribution && presence?.chat === true;
288
293
  const rows = yield* context.run(`SELECT "h"."id"::text AS "id", "h"."record_id"::text AS "recordId", "h"."action" AS "action", ` +
289
294
  `"h"."action_id"::text AS "actionId", "h"."kind" AS "kind", ` +
290
295
  `"h"."principal_id"::text AS "principalId", ` +
291
296
  `to_char("h"."at" AT TIME ZONE 'UTC', 'YYYY-MM-DD"T"HH24:MI:SS.US"Z"') AS "at", ` +
292
297
  `"h"."changes"::text AS "changes" ` +
293
298
  (attribution ? `, "a"."execution" AS "execution" ` : "") +
299
+ (chat ? `, "a"."chat" AS "chat" ` : "") +
294
300
  `FROM ${quoteIdentifier(entity.historyTable)} AS "h" ` +
295
301
  (attribution
296
302
  ? `LEFT JOIN "_ontology_action_attribution" AS "a" ON "a"."action_id" = "h"."action_id" `
@@ -299,8 +305,9 @@ export function readHistory(context, entity, input) {
299
305
  `ORDER BY "h"."at" DESC, "h"."id" DESC ` +
300
306
  `LIMIT ${params.add(limit + 1, "bigint")}`, params);
301
307
  const items = rows.slice(0, limit).map((row) => Schema.decodeUnknownSync(HistoryEntry)({
302
- ...Object.fromEntries(Object.entries(row).filter(([key, value]) => key !== "execution" || value != null)),
308
+ ...Object.fromEntries(Object.entries(row).filter(([key, value]) => (key !== "execution" && key !== "chat") || value != null)),
303
309
  ...(row.execution == null ? {} : { execution: row.execution }),
310
+ ...(row.chat == null ? {} : { chat: row.chat }),
304
311
  at: canonicalInstant(String(row.at)),
305
312
  changes: JSON.parse(String(row.changes)),
306
313
  }));
@@ -31,6 +31,16 @@ export declare function neonSignInLinks(config: {
31
31
  readonly origin: string;
32
32
  readonly fetch?: typeof fetch;
33
33
  }): SignInLinks["Service"];
34
+ /**
35
+ * Asks the app's Neon Auth for a sign-in link to `callbackUrl`, on the app's production origin,
36
+ * for `email`; the platform's email webhook sends it, as for every sign-in link. A link creates
37
+ * the Neon Auth account of an address that has none. Undefined once Neon Auth issued it.
38
+ */
39
+ export declare function requestNeonSignInLink(config: {
40
+ readonly baseUrl: string;
41
+ readonly origin: string;
42
+ readonly fetch?: typeof fetch;
43
+ }, email: string, callbackUrl: string): Promise<SignInLinkFailure | undefined>;
34
44
  /**
35
45
  * Requests the links of the emails an action queued, after its commit, in the same request, and
36
46
  * records each outcome on its row; rows older than {@link SIGN_IN_EMAIL_RETENTION_DAYS} days go.
@@ -29,34 +29,35 @@ export function signInEmailCallback(origin, email) {
29
29
  * no magic links yet; it is reconciled for them.
30
30
  */
31
31
  export function neonSignInLinks(config) {
32
- const fetcher = config.fetch ?? fetch;
33
- const endpoint = `${config.baseUrl.replace(/\/+$/, "")}/sign-in/magic-link`;
34
32
  return {
35
- request: (email) => Effect.promise(async () => {
36
- let response;
37
- try {
38
- response = await fetcher(endpoint, {
39
- method: "POST",
40
- redirect: "error",
41
- signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
42
- headers: { "content-type": "application/json", origin: config.origin },
43
- body: JSON.stringify({
44
- email: email.email,
45
- callbackURL: signInEmailCallback(config.origin, email),
46
- }),
47
- });
48
- }
49
- catch {
50
- return "unreachable";
51
- }
52
- void response.body?.cancel().catch(() => undefined);
53
- if (response.ok) {
54
- return undefined;
55
- }
56
- return response.status === 404 ? "disabled" : "refused";
57
- }),
33
+ request: (email) => Effect.promise(() => requestNeonSignInLink(config, email.email, signInEmailCallback(config.origin, email))),
58
34
  };
59
35
  }
36
+ /**
37
+ * Asks the app's Neon Auth for a sign-in link to `callbackUrl`, on the app's production origin,
38
+ * for `email`; the platform's email webhook sends it, as for every sign-in link. A link creates
39
+ * the Neon Auth account of an address that has none. Undefined once Neon Auth issued it.
40
+ */
41
+ export async function requestNeonSignInLink(config, email, callbackUrl) {
42
+ let response;
43
+ try {
44
+ response = await (config.fetch ?? fetch)(`${config.baseUrl.replace(/\/+$/, "")}/sign-in/magic-link`, {
45
+ method: "POST",
46
+ redirect: "error",
47
+ signal: AbortSignal.timeout(REQUEST_TIMEOUT_MS),
48
+ headers: { "content-type": "application/json", origin: config.origin },
49
+ body: JSON.stringify({ email, callbackURL: callbackUrl }),
50
+ });
51
+ }
52
+ catch {
53
+ return "unreachable";
54
+ }
55
+ void response.body?.cancel().catch(() => undefined);
56
+ if (response.ok) {
57
+ return undefined;
58
+ }
59
+ return response.status === 404 ? "disabled" : "refused";
60
+ }
60
61
  /**
61
62
  * Requests the links of the emails an action queued, after its commit, in the same request, and
62
63
  * records each outcome on its row; rows older than {@link SIGN_IN_EMAIL_RETENTION_DAYS} days go.
@@ -8,7 +8,7 @@ import type { OntologyRuntimeService, StoredRecord, StoredValues } from "../runt
8
8
  import { type AttachIdentityInput } from "./channel-identity-admin.js";
9
9
  import { type BatchOperation } from "./batch.js";
10
10
  import { InvalidQuery, UnknownRole } from "./errors.js";
11
- import type { Edit, HistoryEntry, HistoryScope } from "./history.js";
11
+ import { type Edit, type HistoryEntry, type HistoryScope } from "./history.js";
12
12
  import { type QueuedSignInEmail } from "./member-writes.js";
13
13
  import { type EntityModel } from "./model.js";
14
14
  import { type RecordSnapshot, type WriteGuard } from "./writes.js";
@@ -10,6 +10,7 @@ import { ACTION_MAX_BATCH_ROWS, BATCH_MAX_BYTES, BATCH_MAX_ROWS, batchInputBytes
10
10
  import { logBatchConflict } from "./batch-diagnostics.js";
11
11
  import { runMetricQuery } from "./metric-query.js";
12
12
  import { InvalidQuery, UndeclaredWrite, UnknownRole, WriteOutsideAction } from "./errors.js";
13
+ import { attributed } from "./history.js";
13
14
  import { grantMemberRoles, inviteMember, queueSignInEmail, revokeMemberRoles, setMemberActive, } from "./member-writes.js";
14
15
  import { entityModel, ontologyModel } from "./model.js";
15
16
  import { loadRecord, notFound, readHistory, relatedCondition, runQuery, validateQuery, } from "./reads.js";
@@ -167,7 +168,7 @@ export function makeOntologyRuntime(ontology, sql, scope) {
167
168
  for (const snapshot of snapshots ?? []) {
168
169
  scope.onSnapshot?.(snapshot);
169
170
  }
170
- if (edits.length > 0 && scope.execution !== undefined) {
171
+ if (edits.length > 0 && attributed(scope)) {
171
172
  attributionInitialized = true;
172
173
  }
173
174
  return result;
@@ -252,7 +253,7 @@ export function makeOntologyRuntime(ontology, sql, scope) {
252
253
  for (const snapshot of snapshots ?? []) {
253
254
  scope.onSnapshot?.(snapshot);
254
255
  }
255
- if (edits.length > 0 && scope.execution !== undefined) {
256
+ if (edits.length > 0 && attributed(scope)) {
256
257
  attributionInitialized = true;
257
258
  }
258
259
  return result;
@@ -1,12 +1,12 @@
1
1
  import { Effect } from "effect";
2
2
  import { resolveBlobWrites } from "../storage/writes.js";
3
3
  import { Conflict, ScopeViolated } from "../errors.js";
4
- import { ACTION_ATTRIBUTION_TABLE, USER_ROLES_TABLE, quoteIdentifier } from "../migrate/storage.js";
4
+ import { USER_ROLES_TABLE, quoteIdentifier } from "../migrate/storage.js";
5
5
  import { canonicalJson } from "../manifest.js";
6
6
  import { User } from "../user.js";
7
7
  import { InvalidValues } from "./errors.js";
8
8
  import { uuidv7 } from "./ids.js";
9
- import { diffRecords, insertHistory, } from "./history.js";
9
+ import { diffRecords, attributed, insertAttribution, insertHistory, } from "./history.js";
10
10
  import { entityModel } from "./model.js";
11
11
  import { loadRecord, normalizeId, notFound, requireRecords } from "./reads.js";
12
12
  import { bindValue, decodeRecord, prepareWrite, selectList, } from "./records.js";
@@ -51,11 +51,9 @@ export function scopeViolated(entity, check, id, batch) {
51
51
  function recordEdit(context, entity, edit, snapshot) {
52
52
  return Effect.gen(function* () {
53
53
  const params = new Params();
54
- if (context.scope.execution !== undefined) {
54
+ if (attributed(context.scope)) {
55
55
  const attribution = new Params();
56
- yield* context.run(`INSERT INTO "${ACTION_ATTRIBUTION_TABLE}" (action_id, execution) VALUES (` +
57
- `${attribution.add(context.scope.actionId, "uuid")}, ` +
58
- `${attribution.add(JSON.stringify(context.scope.execution), "jsonb")}) ON CONFLICT DO NOTHING`, attribution);
56
+ yield* context.run(insertAttribution(context.scope, attribution), attribution);
59
57
  }
60
58
  yield* context.run(insertHistory(context.scope, { entity, edit }, params), params);
61
59
  context.edits.push(edit);
package/dist/runtime.d.ts CHANGED
@@ -5,9 +5,27 @@ 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
+ /** The chat's provider: `web`, `telegram`, `slack`, `whatsapp` or `email`. */
15
+ readonly provider: string;
16
+ /** The chat's id there, such as `guest:<id>` or `member:<id>` on the web, or `-100123`. */
17
+ readonly chatId: string;
18
+ /** The agent's session in the chat. */
19
+ readonly sessionId?: string;
20
+ }
8
21
  export interface Principal {
9
22
  /** Present only for a verified managed pipeline worker. */
10
23
  readonly execution?: WorkloadExecution;
24
+ /**
25
+ * Present only when the app's own agent acts for the principal in a chat, a guest's included:
26
+ * the chat and session the request came from. History keeps it with every change it makes.
27
+ */
28
+ readonly chat?: ChatProvenance;
11
29
  /**
12
30
  * Present only for a workflow's user: the workflow's wire name, whose runs it acts in, and its
13
31
  * identity subject, `workflows:<workspace id>:<workflow name>`.