@segmentstream/ontology 0.109.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 (57) hide show
  1. package/CHANGELOG.md +57 -0
  2. package/README.md +21 -0
  3. package/dist/analyze.js +55 -3
  4. package/dist/index.d.ts +5 -5
  5. package/dist/index.js +2 -2
  6. package/dist/manifest.d.ts +94 -5
  7. package/dist/manifest.js +41 -6
  8. package/dist/migrate/apply.d.ts +4 -3
  9. package/dist/migrate/apply.js +8 -3
  10. package/dist/migrate/model.d.ts +46 -2
  11. package/dist/migrate/plan.js +1 -1
  12. package/dist/migrate/preview.js +2 -1
  13. package/dist/migrate/storage.d.ts +13 -1
  14. package/dist/migrate/storage.js +33 -1
  15. package/dist/runtime/agent-counters.d.ts +36 -0
  16. package/dist/runtime/agent-counters.js +84 -0
  17. package/dist/runtime/agent-web.d.ts +1 -1
  18. package/dist/runtime/agent-web.js +175 -3
  19. package/dist/runtime/batch.js +4 -6
  20. package/dist/runtime/history.d.ts +24 -0
  21. package/dist/runtime/history.js +35 -1
  22. package/dist/runtime/pipeline.js +3 -0
  23. package/dist/runtime/principals.d.ts +6 -0
  24. package/dist/runtime/principals.js +25 -6
  25. package/dist/runtime/reads.js +9 -2
  26. package/dist/runtime/sign-in-links.d.ts +10 -0
  27. package/dist/runtime/sign-in-links.js +26 -25
  28. package/dist/runtime/sql-runtime.d.ts +1 -1
  29. package/dist/runtime/sql-runtime.js +3 -2
  30. package/dist/runtime/writes.js +4 -6
  31. package/dist/runtime.d.ts +18 -0
  32. package/dist/service/agent/authentication.d.ts +3 -2
  33. package/dist/service/agent/authentication.js +2 -11
  34. package/dist/service/agent/bot-check.d.ts +42 -0
  35. package/dist/service/agent/bot-check.js +32 -0
  36. package/dist/service/agent/guest-sign-up.d.ts +140 -0
  37. package/dist/service/agent/guest-sign-up.js +545 -0
  38. package/dist/service/agent/protocol.d.ts +33 -1
  39. package/dist/service/agent/protocol.js +41 -1
  40. package/dist/service/agent/server.d.ts +17 -0
  41. package/dist/service/agent/server.js +42 -3
  42. package/dist/service/agent/web-tokens.d.ts +21 -3
  43. package/dist/service/agent/web-tokens.js +79 -6
  44. package/dist/service/authentication.d.ts +8 -1
  45. package/dist/service/authentication.js +26 -5
  46. package/dist/service/config.d.ts +10 -0
  47. package/dist/service/operations.d.ts +5 -0
  48. package/dist/service/runtime-contract.d.ts +124 -1
  49. package/dist/service/runtime-identity.d.ts +23 -0
  50. package/dist/service/runtime-identity.js +31 -0
  51. package/dist/service/schemas.d.ts +46 -2
  52. package/dist/service/service.js +27 -1
  53. package/dist/service/webhooks.d.ts +15 -0
  54. package/dist/service/webhooks.js +15 -4
  55. package/dist/sign-in.d.ts +29 -0
  56. package/dist/sign-in.js +8 -0
  57. package/package.json +1 -1
@@ -484,6 +484,11 @@ export declare const MigrationPlan: Schema.Struct<{
484
484
  readonly guest?: {
485
485
  readonly channels: readonly string[];
486
486
  readonly origins: readonly string[];
487
+ readonly botCheck?: {
488
+ readonly scheme: string;
489
+ readonly secret: string;
490
+ } | undefined;
491
+ readonly confirmations?: boolean | undefined;
487
492
  } | undefined;
488
493
  readonly browser?: {
489
494
  readonly methods: readonly string[];
@@ -775,6 +780,11 @@ export declare const MigrationPlan: Schema.Struct<{
775
780
  readonly guest?: {
776
781
  readonly channels: readonly string[];
777
782
  readonly origins: readonly string[];
783
+ readonly botCheck?: {
784
+ readonly scheme: string;
785
+ readonly secret: string;
786
+ } | undefined;
787
+ readonly confirmations?: boolean | undefined;
778
788
  } | undefined;
779
789
  readonly browser?: {
780
790
  readonly methods: readonly string[];
@@ -1131,6 +1141,11 @@ export declare const MigrationPlan: Schema.Struct<{
1131
1141
  readonly guest?: {
1132
1142
  readonly channels: readonly string[];
1133
1143
  readonly origins: readonly string[];
1144
+ readonly confirmations?: boolean | undefined;
1145
+ readonly bot_check?: {
1146
+ readonly scheme: string;
1147
+ readonly secret: string;
1148
+ } | undefined;
1134
1149
  } | undefined;
1135
1150
  readonly browser?: {
1136
1151
  readonly methods: readonly string[];
@@ -1357,6 +1372,11 @@ export declare const MigrationPlan: Schema.Struct<{
1357
1372
  readonly guest?: {
1358
1373
  readonly channels: readonly string[];
1359
1374
  readonly origins: readonly string[];
1375
+ readonly confirmations?: boolean | undefined;
1376
+ readonly bot_check?: {
1377
+ readonly scheme: string;
1378
+ readonly secret: string;
1379
+ } | undefined;
1360
1380
  } | undefined;
1361
1381
  readonly browser?: {
1362
1382
  readonly methods: readonly string[];
@@ -1602,9 +1622,16 @@ export declare const MigrationPlan: Schema.Struct<{
1602
1622
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
1603
1623
  }>>;
1604
1624
  readonly onSignUp: Schema.optionalKey<Schema.String>;
1605
- readonly guest: Schema.optionalKey<Schema.Struct<{
1625
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
1606
1626
  readonly channels: Schema.$Array<Schema.String>;
1607
1627
  readonly origins: Schema.$Array<Schema.String>;
1628
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
1629
+ readonly scheme: Schema.String;
1630
+ readonly secret: Schema.String;
1631
+ }>>;
1632
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
1633
+ }>, {
1634
+ readonly botCheck: "bot_check";
1608
1635
  }>>;
1609
1636
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
1610
1637
  }>, {
@@ -1885,9 +1912,16 @@ export declare const MigrationPlan: Schema.Struct<{
1885
1912
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
1886
1913
  }>>;
1887
1914
  readonly onSignUp: Schema.optionalKey<Schema.String>;
1888
- readonly guest: Schema.optionalKey<Schema.Struct<{
1915
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
1889
1916
  readonly channels: Schema.$Array<Schema.String>;
1890
1917
  readonly origins: Schema.$Array<Schema.String>;
1918
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
1919
+ readonly scheme: Schema.String;
1920
+ readonly secret: Schema.String;
1921
+ }>>;
1922
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
1923
+ }>, {
1924
+ readonly botCheck: "bot_check";
1891
1925
  }>>;
1892
1926
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
1893
1927
  }>, {
@@ -2227,6 +2261,11 @@ export declare const MigrationPlan: Schema.Struct<{
2227
2261
  readonly guest?: {
2228
2262
  readonly channels: readonly string[];
2229
2263
  readonly origins: readonly string[];
2264
+ readonly botCheck?: {
2265
+ readonly scheme: string;
2266
+ readonly secret: string;
2267
+ } | undefined;
2268
+ readonly confirmations?: boolean | undefined;
2230
2269
  } | undefined;
2231
2270
  readonly browser?: {
2232
2271
  readonly methods: readonly string[];
@@ -2518,6 +2557,11 @@ export declare const MigrationPlan: Schema.Struct<{
2518
2557
  readonly guest?: {
2519
2558
  readonly channels: readonly string[];
2520
2559
  readonly origins: readonly string[];
2560
+ readonly botCheck?: {
2561
+ readonly scheme: string;
2562
+ readonly secret: string;
2563
+ } | undefined;
2564
+ readonly confirmations?: boolean | undefined;
2521
2565
  } | undefined;
2522
2566
  readonly browser?: {
2523
2567
  readonly methods: readonly string[];
@@ -154,7 +154,7 @@ export function planMigration(input) {
154
154
  draft.runtimeTables.push(step({
155
155
  kind: "createCatalog",
156
156
  classification: "additive",
157
- description: "Create the runtime's verified pipeline action attribution table.",
157
+ description: "Create the runtime's verified action attribution table, with its chat.",
158
158
  sql: ACTION_ATTRIBUTION_DDL,
159
159
  }));
160
160
  }
@@ -2,7 +2,7 @@ import { Effect } from "effect";
2
2
  import { AGENT_TASKS_TABLE, ATTACHMENTS_TABLE, SIGN_IN_EMAILS_TABLE, WORKFLOW_STARTS_TABLE, } from "../storage/tables.js";
3
3
  import { CONFIRMATION_TABLE } from "../runtime/confirmations.js";
4
4
  import { CHANNEL_ORIGIN_SQL, USER_IDENTITY_TABLE } from "../runtime/user-identity-sql.js";
5
- import { AGENT_COUNTERS_TABLE, AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, API_KEYS_TABLE, IDENTITY_NOTICES_TABLE, OAUTH_TABLES, quoteIdentifier, } from "./storage.js";
5
+ import { AGENT_COUNTERS_TABLE, AGENT_GUEST_LINKS_TABLE, AGENT_IDENTITIES_TABLE, AGENT_PAIRINGS_TABLE, API_KEYS_TABLE, IDENTITY_NOTICES_TABLE, OAUTH_TABLES, quoteIdentifier, } from "./storage.js";
6
6
  /**
7
7
  * Invalidate copied SDK credentials and runnable state on a verified, unexposed child database.
8
8
  * The caller owns branch verification and provider-side Neon Auth invalidation/configuration.
@@ -31,6 +31,7 @@ export function preparePreviewDatabase({ sql, }) {
31
31
  AGENT_IDENTITIES_TABLE,
32
32
  IDENTITY_NOTICES_TABLE,
33
33
  AGENT_PAIRINGS_TABLE,
34
+ AGENT_GUEST_LINKS_TABLE,
34
35
  AGENT_TASKS_TABLE,
35
36
  SIGN_IN_EMAILS_TABLE,
36
37
  WORKFLOW_STARTS_TABLE,
@@ -197,6 +197,14 @@ export declare const AGENT_COUNTERS_TABLE = "_agent_counters";
197
197
  /** User-scoped channel lifecycle and trusted effective limits shared across entry points. */
198
198
  export declare const CHANNEL_USERS_TABLE = "_channel_users";
199
199
  export declare const CHANNEL_LIMITS_TABLE = "_channel_limits";
200
+ /**
201
+ * A website guest's sign-up by an emailed link, while it is pending: the guest, the address the
202
+ * link proves and where it returns to, with the link's nonce stored only as a SHA-256 hash; then
203
+ * the user it admitted and the hash of the single-use handoff that gives the guest's browser that
204
+ * user's tokens. Neither an OAuth token row, which holds a grant's secret and names no address or
205
+ * other user, nor a queued sign-in email, which needs an existing user, holds these.
206
+ */
207
+ export declare const AGENT_GUEST_LINKS_TABLE = "_agent_guest_links";
200
208
  /** The agent's tables, in the order they are created. */
201
209
  export declare const AGENT_TABLES: ReadonlyArray<string>;
202
210
  /**
@@ -211,7 +219,11 @@ export declare const AGENT_TABLES_DDL: ReadonlyArray<string>;
211
219
  * because they refer to the built-in user table, and every statement is idempotent.
212
220
  */
213
221
  export declare const ACTION_ATTRIBUTION_TABLE = "_ontology_action_attribution";
214
- /** Runtime audit metadata deliberately has no foreign key: deleted records retain their history. */
222
+ /**
223
+ * Runtime audit metadata deliberately has no foreign key: deleted records retain their history.
224
+ * A row holds a pipeline's verified `execution`, the `chat` the app's agent acted in, or both.
225
+ * Idempotent: a database an earlier SDK migrated gains `chat` on its next migration.
226
+ */
215
227
  export declare const ACTION_ATTRIBUTION_DDL: ReadonlyArray<string>;
216
228
  /**
217
229
  * The API keys of the app's services: each names a `user` and holds the PBKDF2 hash of its secret.
@@ -606,6 +606,14 @@ export const AGENT_COUNTERS_TABLE = "_agent_counters";
606
606
  /** User-scoped channel lifecycle and trusted effective limits shared across entry points. */
607
607
  export const CHANNEL_USERS_TABLE = "_channel_users";
608
608
  export const CHANNEL_LIMITS_TABLE = "_channel_limits";
609
+ /**
610
+ * A website guest's sign-up by an emailed link, while it is pending: the guest, the address the
611
+ * link proves and where it returns to, with the link's nonce stored only as a SHA-256 hash; then
612
+ * the user it admitted and the hash of the single-use handoff that gives the guest's browser that
613
+ * user's tokens. Neither an OAuth token row, which holds a grant's secret and names no address or
614
+ * other user, nor a queued sign-in email, which needs an existing user, holds these.
615
+ */
616
+ export const AGENT_GUEST_LINKS_TABLE = "_agent_guest_links";
609
617
  /** The agent's tables, in the order they are created. */
610
618
  export const AGENT_TABLES = [
611
619
  AGENT_PAIRINGS_TABLE,
@@ -615,6 +623,7 @@ export const AGENT_TABLES = [
615
623
  CHANNEL_LIMITS_TABLE,
616
624
  CONFIRMATION_TABLE,
617
625
  IDENTITY_NOTICES_TABLE,
626
+ AGENT_GUEST_LINKS_TABLE,
618
627
  ];
619
628
  /**
620
629
  * The tables of the app's agent: pairing codes, stored only as SHA-256 hashes, the legacy channel
@@ -697,19 +706,42 @@ export const AGENT_TABLES_DDL = [
697
706
  "notice_sha256" text,
698
707
  "notice_version" text
699
708
  )`,
709
+ // No foreign key to the guest's grant: an expired guest's grant goes with its rows' expiry.
710
+ `CREATE TABLE IF NOT EXISTS "${AGENT_GUEST_LINKS_TABLE}" (
711
+ "nonce_hash" text PRIMARY KEY,
712
+ "guest_id" uuid NOT NULL,
713
+ "email" text NOT NULL,
714
+ "return_to" text,
715
+ "expires_at" timestamptz NOT NULL,
716
+ "opened_at" timestamptz,
717
+ "user_id" uuid REFERENCES "${USER_TABLE}" ("id") ON DELETE CASCADE,
718
+ "user_created" boolean,
719
+ "handoff_hash" text UNIQUE,
720
+ "handoff_expires_at" timestamptz,
721
+ "handed_off_at" timestamptz,
722
+ "created_at" timestamptz NOT NULL DEFAULT now()
723
+ )`,
724
+ `CREATE INDEX IF NOT EXISTS "${AGENT_GUEST_LINKS_TABLE}_created_idx" ` +
725
+ `ON "${AGENT_GUEST_LINKS_TABLE}" ("created_at")`,
700
726
  ];
701
727
  /**
702
728
  * The runtime's own tables beside the catalog. They are created with it, after the entity tables
703
729
  * because they refer to the built-in user table, and every statement is idempotent.
704
730
  */
705
731
  export const ACTION_ATTRIBUTION_TABLE = "_ontology_action_attribution";
706
- /** Runtime audit metadata deliberately has no foreign key: deleted records retain their history. */
732
+ /**
733
+ * Runtime audit metadata deliberately has no foreign key: deleted records retain their history.
734
+ * A row holds a pipeline's verified `execution`, the `chat` the app's agent acted in, or both.
735
+ * Idempotent: a database an earlier SDK migrated gains `chat` on its next migration.
736
+ */
707
737
  export const ACTION_ATTRIBUTION_DDL = [
708
738
  `CREATE TABLE IF NOT EXISTS "${ACTION_ATTRIBUTION_TABLE}" (
709
739
  "action_id" uuid PRIMARY KEY,
710
740
  "execution" jsonb NOT NULL,
711
741
  "at" timestamptz NOT NULL DEFAULT now()
712
742
  )`,
743
+ `ALTER TABLE "${ACTION_ATTRIBUTION_TABLE}" ADD COLUMN IF NOT EXISTS "chat" jsonb`,
744
+ `ALTER TABLE "${ACTION_ATTRIBUTION_TABLE}" ALTER COLUMN "execution" DROP NOT NULL`,
713
745
  ];
714
746
  /**
715
747
  * The API keys of the app's services: each names a `user` and holds the PBKDF2 hash of its secret.
@@ -5,6 +5,21 @@ import type { AgentLimits, AgentLimitScope, AgentResolution, ResolveIdentityInpu
5
5
  export declare const DEFAULT_AGENT_LIMITS: AgentLimits;
6
6
  /** Platform ceilings. Workspace policy can only lower these values. */
7
7
  export declare const PLATFORM_CHANNEL_LIMITS: AgentLimits;
8
+ /**
9
+ * Ceilings of the guests' daily model cost, in US dollars. Unlike the turn limits they have no
10
+ * default: a cap the agent does not set does not apply.
11
+ */
12
+ export declare const GUEST_USD_CEILINGS: Readonly<{
13
+ usdPerDay: 100;
14
+ workspaceUsdPerDay: 10000;
15
+ }>;
16
+ /**
17
+ * The unit the guests' spend is counted in, in US dollars: a ten-thousandth of a dollar, so that a
18
+ * day's spend of every guest together fits the counters at their ceiling many times over.
19
+ */
20
+ export declare const GUEST_USD_UNIT = 0.0001;
21
+ /** The most one usage report may add, in US dollars; a turn costing more is counted at this. */
22
+ export declare const MAX_GUEST_USAGE_REPORT_USD = 100;
8
23
  export declare function clampChannelLimits(input: ResolveIdentityInput["limits"]): AgentLimits;
9
24
  /**
10
25
  * Only trusted runtimes submit limits; channel-app callers omit them and reuse the latest policy.
@@ -27,4 +42,25 @@ export declare function countAgentAttempt(sql: SqlClient.SqlClient, input: {
27
42
  readonly window: "minute" | "hour" | "day";
28
43
  readonly limit: number;
29
44
  }): Effect.Effect<Limited | undefined>;
45
+ /**
46
+ * Adds a guest's model cost to the day's spend of the guest and of every guest together, once per
47
+ * `key`: the report's own counter row, in the same day's window, records that it was counted.
48
+ */
49
+ export declare function addGuestSpend(sql: SqlClient.SqlClient, input: {
50
+ readonly guestId: string;
51
+ readonly costUsd: number;
52
+ readonly key: string;
53
+ }): Effect.Effect<void>;
54
+ /**
55
+ * The money cap a guest's new turn would exceed: the guest's own spend that day against
56
+ * `usdPerDay`, then every guest's together against `workspaceUsdPerDay`, with the seconds until
57
+ * the day's window ends. A cap the limits do not set does not apply.
58
+ */
59
+ export declare function guestSpendLimited(sql: SqlClient.SqlClient, input: {
60
+ readonly guestId: string;
61
+ readonly limits: AgentLimits;
62
+ }): Effect.Effect<{
63
+ readonly scope: "guestUsdPerDay" | "guestWorkspaceUsdPerDay";
64
+ readonly retryAfterSeconds: number;
65
+ } | undefined>;
30
66
  export {};
@@ -10,6 +10,18 @@ export const DEFAULT_AGENT_LIMITS = Object.freeze({
10
10
  });
11
11
  /** Platform ceilings. Workspace policy can only lower these values. */
12
12
  export const PLATFORM_CHANNEL_LIMITS = DEFAULT_AGENT_LIMITS;
13
+ /**
14
+ * Ceilings of the guests' daily model cost, in US dollars. Unlike the turn limits they have no
15
+ * default: a cap the agent does not set does not apply.
16
+ */
17
+ export const GUEST_USD_CEILINGS = Object.freeze({ usdPerDay: 100, workspaceUsdPerDay: 10_000 });
18
+ /**
19
+ * The unit the guests' spend is counted in, in US dollars: a ten-thousandth of a dollar, so that a
20
+ * day's spend of every guest together fits the counters at their ceiling many times over.
21
+ */
22
+ export const GUEST_USD_UNIT = 0.0001;
23
+ /** The most one usage report may add, in US dollars; a turn costing more is counted at this. */
24
+ export const MAX_GUEST_USAGE_REPORT_USD = 100;
13
25
  const Limits = Schema.Struct({
14
26
  perSender: Schema.Struct({ turnsPerMinute: Schema.Int, turnsPerDay: Schema.Int }),
15
27
  newUsersPerHour: Schema.Int,
@@ -18,10 +30,21 @@ const Limits = Schema.Struct({
18
30
  guest: Schema.optionalKey(Schema.Struct({
19
31
  turnsPerDay: Schema.optionalKey(Schema.Int),
20
32
  workspaceTurnsPerDay: Schema.optionalKey(Schema.Int),
33
+ // Absent from limits an SDK before guests' money caps kept, and when no cap is set.
34
+ usdPerDay: Schema.optionalKey(Schema.Number),
35
+ workspaceUsdPerDay: Schema.optionalKey(Schema.Number),
21
36
  })),
22
37
  });
38
+ /** A money cap as the agent set it, at most its ceiling; `undefined` when it set none. */
39
+ function clampUsd(value, ceiling) {
40
+ return value !== undefined && Number.isFinite(value) && value > 0
41
+ ? Math.min(value, ceiling)
42
+ : undefined;
43
+ }
23
44
  export function clampChannelLimits(input) {
24
45
  const clamp = (value, ceiling) => Number.isSafeInteger(value) && value > 0 ? Math.min(value, ceiling) : ceiling;
46
+ const usdPerDay = clampUsd(input?.guest?.usdPerDay, GUEST_USD_CEILINGS.usdPerDay);
47
+ const workspaceUsdPerDay = clampUsd(input?.guest?.workspaceUsdPerDay, GUEST_USD_CEILINGS.workspaceUsdPerDay);
25
48
  return {
26
49
  perSender: {
27
50
  turnsPerMinute: clamp(input?.perSender?.turnsPerMinute, PLATFORM_CHANNEL_LIMITS.perSender.turnsPerMinute),
@@ -32,6 +55,8 @@ export function clampChannelLimits(input) {
32
55
  guest: {
33
56
  turnsPerDay: clamp(input?.guest?.turnsPerDay, PLATFORM_CHANNEL_LIMITS.guest.turnsPerDay),
34
57
  workspaceTurnsPerDay: clamp(input?.guest?.workspaceTurnsPerDay, PLATFORM_CHANNEL_LIMITS.guest.workspaceTurnsPerDay),
58
+ ...(usdPerDay === undefined ? {} : { usdPerDay }),
59
+ ...(workspaceUsdPerDay === undefined ? {} : { workspaceUsdPerDay }),
35
60
  },
36
61
  };
37
62
  }
@@ -111,3 +136,62 @@ export function countAgentAttempt(sql, input) {
111
136
  };
112
137
  }).pipe(Effect.orDie);
113
138
  }
139
+ /** The counter a guest's spend, or every guest's together (`workspace`), is kept on, by day. */
140
+ function spendKey(scope, subject) {
141
+ return `${scope}:${subject}`;
142
+ }
143
+ /**
144
+ * Adds a guest's model cost to the day's spend of the guest and of every guest together, once per
145
+ * `key`: the report's own counter row, in the same day's window, records that it was counted.
146
+ */
147
+ export function addGuestSpend(sql, input) {
148
+ const units = Math.ceil(Math.min(Math.max(input.costUsd, 0), MAX_GUEST_USAGE_REPORT_USD) / GUEST_USD_UNIT);
149
+ if (!Number.isFinite(units) || units <= 0) {
150
+ return Effect.void;
151
+ }
152
+ return sql
153
+ .withTransaction(Effect.gen(function* () {
154
+ const [first] = yield* sql.unsafe(`INSERT INTO "${AGENT_COUNTERS_TABLE}" ("key", "window_start", "count")
155
+ VALUES ($1, date_trunc('day', now()), 1)
156
+ ON CONFLICT ("key", "window_start") DO NOTHING RETURNING 1 AS "counted"`, [`guestUsage:${input.guestId}:${input.key}`]);
157
+ if (first === undefined) {
158
+ return;
159
+ }
160
+ for (const [scope, subject] of [
161
+ ["guestUsdPerDay", input.guestId],
162
+ ["guestWorkspaceUsdPerDay", "workspace"],
163
+ ]) {
164
+ yield* sql.unsafe(`INSERT INTO "${AGENT_COUNTERS_TABLE}" ("key", "window_start", "count")
165
+ VALUES ($1, date_trunc('day', now()), $2)
166
+ ON CONFLICT ("key", "window_start") DO UPDATE
167
+ SET "count" = "${AGENT_COUNTERS_TABLE}"."count" + EXCLUDED."count"`, [spendKey(scope, subject), units]);
168
+ }
169
+ }))
170
+ .pipe(Effect.orDie);
171
+ }
172
+ /**
173
+ * The money cap a guest's new turn would exceed: the guest's own spend that day against
174
+ * `usdPerDay`, then every guest's together against `workspaceUsdPerDay`, with the seconds until
175
+ * the day's window ends. A cap the limits do not set does not apply.
176
+ */
177
+ export function guestSpendLimited(sql, input) {
178
+ return Effect.gen(function* () {
179
+ const caps = [
180
+ ["guestUsdPerDay", input.guestId, input.limits.guest.usdPerDay],
181
+ ["guestWorkspaceUsdPerDay", "workspace", input.limits.guest.workspaceUsdPerDay],
182
+ ];
183
+ for (const [scope, subject, cap] of caps) {
184
+ if (cap === undefined) {
185
+ continue;
186
+ }
187
+ const [spent] = yield* sql.unsafe(`SELECT "count", ceil(extract(epoch FROM
188
+ date_trunc('day', now()) + interval '1 day' - now()))::int AS "retry_after"
189
+ FROM "${AGENT_COUNTERS_TABLE}"
190
+ WHERE "key" = $1 AND "window_start" = date_trunc('day', now())`, [spendKey(scope, subject)]);
191
+ if (spent !== undefined && Number(spent.count) >= Math.round(cap / GUEST_USD_UNIT)) {
192
+ return { scope, retryAfterSeconds: Math.max(1, Number(spent.retry_after)) };
193
+ }
194
+ }
195
+ return undefined;
196
+ }).pipe(Effect.orDie);
197
+ }
@@ -1,5 +1,5 @@
1
1
  import { Effect } from "effect";
2
- import type { SqlClient } from "effect/unstable/sql";
2
+ import { SqlClient } from "effect/unstable/sql";
3
3
  import type { Ontology } from "../ontology.js";
4
4
  import type { AgentResolution, AgentWebStore } from "../service/runtime-contract.js";
5
5
  /** How many new website visitors one network address may sign up an hour. */
@@ -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();