@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
@@ -409,6 +409,12 @@ export declare const MigrationPlan: Schema.Struct<{
409
409
  readonly slack?: {
410
410
  readonly connection: string;
411
411
  } | undefined;
412
+ readonly channels?: {
413
+ readonly [x: string]: {
414
+ readonly kind: "telegram" | "email" | "whatsapp" | "slack";
415
+ readonly connection: string;
416
+ };
417
+ } | undefined;
412
418
  readonly attribution?: {
413
419
  readonly template?: string | undefined;
414
420
  readonly separator?: string | undefined;
@@ -484,6 +490,11 @@ export declare const MigrationPlan: Schema.Struct<{
484
490
  readonly guest?: {
485
491
  readonly channels: readonly string[];
486
492
  readonly origins: readonly string[];
493
+ readonly botCheck?: {
494
+ readonly scheme: string;
495
+ readonly secret: string;
496
+ } | undefined;
497
+ readonly confirmations?: boolean | undefined;
487
498
  } | undefined;
488
499
  readonly browser?: {
489
500
  readonly methods: readonly string[];
@@ -700,6 +711,12 @@ export declare const MigrationPlan: Schema.Struct<{
700
711
  readonly slack?: {
701
712
  readonly connection: string;
702
713
  } | undefined;
714
+ readonly channels?: {
715
+ readonly [x: string]: {
716
+ readonly kind: "telegram" | "email" | "whatsapp" | "slack";
717
+ readonly connection: string;
718
+ };
719
+ } | undefined;
703
720
  readonly attribution?: {
704
721
  readonly template?: string | undefined;
705
722
  readonly separator?: string | undefined;
@@ -775,6 +792,11 @@ export declare const MigrationPlan: Schema.Struct<{
775
792
  readonly guest?: {
776
793
  readonly channels: readonly string[];
777
794
  readonly origins: readonly string[];
795
+ readonly botCheck?: {
796
+ readonly scheme: string;
797
+ readonly secret: string;
798
+ } | undefined;
799
+ readonly confirmations?: boolean | undefined;
778
800
  } | undefined;
779
801
  readonly browser?: {
780
802
  readonly methods: readonly string[];
@@ -991,6 +1013,12 @@ export declare const MigrationPlan: Schema.Struct<{
991
1013
  readonly slack?: {
992
1014
  readonly connection: string;
993
1015
  } | undefined;
1016
+ readonly channels?: {
1017
+ readonly [x: string]: {
1018
+ readonly kind: "telegram" | "email" | "whatsapp" | "slack";
1019
+ readonly connection: string;
1020
+ };
1021
+ } | undefined;
994
1022
  readonly attribution?: {
995
1023
  readonly template?: string | undefined;
996
1024
  readonly separator?: string | undefined;
@@ -1131,6 +1159,11 @@ export declare const MigrationPlan: Schema.Struct<{
1131
1159
  readonly guest?: {
1132
1160
  readonly channels: readonly string[];
1133
1161
  readonly origins: readonly string[];
1162
+ readonly confirmations?: boolean | undefined;
1163
+ readonly bot_check?: {
1164
+ readonly scheme: string;
1165
+ readonly secret: string;
1166
+ } | undefined;
1134
1167
  } | undefined;
1135
1168
  readonly browser?: {
1136
1169
  readonly methods: readonly string[];
@@ -1282,6 +1315,12 @@ export declare const MigrationPlan: Schema.Struct<{
1282
1315
  readonly slack?: {
1283
1316
  readonly connection: string;
1284
1317
  } | undefined;
1318
+ readonly channels?: {
1319
+ readonly [x: string]: {
1320
+ readonly kind: "telegram" | "email" | "whatsapp" | "slack";
1321
+ readonly connection: string;
1322
+ };
1323
+ } | undefined;
1285
1324
  readonly attribution?: {
1286
1325
  readonly template?: string | undefined;
1287
1326
  readonly separator?: string | undefined;
@@ -1357,6 +1396,11 @@ export declare const MigrationPlan: Schema.Struct<{
1357
1396
  readonly guest?: {
1358
1397
  readonly channels: readonly string[];
1359
1398
  readonly origins: readonly string[];
1399
+ readonly confirmations?: boolean | undefined;
1400
+ readonly bot_check?: {
1401
+ readonly scheme: string;
1402
+ readonly secret: string;
1403
+ } | undefined;
1360
1404
  } | undefined;
1361
1405
  readonly browser?: {
1362
1406
  readonly methods: readonly string[];
@@ -1602,9 +1646,16 @@ export declare const MigrationPlan: Schema.Struct<{
1602
1646
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
1603
1647
  }>>;
1604
1648
  readonly onSignUp: Schema.optionalKey<Schema.String>;
1605
- readonly guest: Schema.optionalKey<Schema.Struct<{
1649
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
1606
1650
  readonly channels: Schema.$Array<Schema.String>;
1607
1651
  readonly origins: Schema.$Array<Schema.String>;
1652
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
1653
+ readonly scheme: Schema.String;
1654
+ readonly secret: Schema.String;
1655
+ }>>;
1656
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
1657
+ }>, {
1658
+ readonly botCheck: "bot_check";
1608
1659
  }>>;
1609
1660
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
1610
1661
  }>, {
@@ -1662,6 +1713,10 @@ export declare const MigrationPlan: Schema.Struct<{
1662
1713
  readonly email: Schema.optionalKey<Schema.Struct<{
1663
1714
  readonly connection: Schema.String;
1664
1715
  }>>;
1716
+ readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
1717
+ readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email"]>;
1718
+ readonly connection: Schema.String;
1719
+ }>>>;
1665
1720
  readonly attribution: Schema.optionalKey<Schema.Struct<{
1666
1721
  readonly template: Schema.optionalKey<Schema.String>;
1667
1722
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -1885,9 +1940,16 @@ export declare const MigrationPlan: Schema.Struct<{
1885
1940
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
1886
1941
  }>>;
1887
1942
  readonly onSignUp: Schema.optionalKey<Schema.String>;
1888
- readonly guest: Schema.optionalKey<Schema.Struct<{
1943
+ readonly guest: Schema.optionalKey<Schema.encodeKeys<Schema.Struct<{
1889
1944
  readonly channels: Schema.$Array<Schema.String>;
1890
1945
  readonly origins: Schema.$Array<Schema.String>;
1946
+ readonly botCheck: Schema.optionalKey<Schema.Struct<{
1947
+ readonly scheme: Schema.String;
1948
+ readonly secret: Schema.String;
1949
+ }>>;
1950
+ readonly confirmations: Schema.optionalKey<Schema.Boolean>;
1951
+ }>, {
1952
+ readonly botCheck: "bot_check";
1891
1953
  }>>;
1892
1954
  readonly invitationEmail: Schema.optionalKey<Schema.String>;
1893
1955
  }>, {
@@ -1945,6 +2007,10 @@ export declare const MigrationPlan: Schema.Struct<{
1945
2007
  readonly email: Schema.optionalKey<Schema.Struct<{
1946
2008
  readonly connection: Schema.String;
1947
2009
  }>>;
2010
+ readonly channels: Schema.optionalKey<Schema.$Record<Schema.String, Schema.Struct<{
2011
+ readonly kind: Schema.Literals<readonly ["telegram", "slack", "whatsapp", "email"]>;
2012
+ readonly connection: Schema.String;
2013
+ }>>>;
1948
2014
  readonly attribution: Schema.optionalKey<Schema.Struct<{
1949
2015
  readonly template: Schema.optionalKey<Schema.String>;
1950
2016
  readonly separator: Schema.optionalKey<Schema.String>;
@@ -2152,6 +2218,12 @@ export declare const MigrationPlan: Schema.Struct<{
2152
2218
  readonly slack?: {
2153
2219
  readonly connection: string;
2154
2220
  } | undefined;
2221
+ readonly channels?: {
2222
+ readonly [x: string]: {
2223
+ readonly kind: "telegram" | "email" | "whatsapp" | "slack";
2224
+ readonly connection: string;
2225
+ };
2226
+ } | undefined;
2155
2227
  readonly attribution?: {
2156
2228
  readonly template?: string | undefined;
2157
2229
  readonly separator?: string | undefined;
@@ -2227,6 +2299,11 @@ export declare const MigrationPlan: Schema.Struct<{
2227
2299
  readonly guest?: {
2228
2300
  readonly channels: readonly string[];
2229
2301
  readonly origins: readonly string[];
2302
+ readonly botCheck?: {
2303
+ readonly scheme: string;
2304
+ readonly secret: string;
2305
+ } | undefined;
2306
+ readonly confirmations?: boolean | undefined;
2230
2307
  } | undefined;
2231
2308
  readonly browser?: {
2232
2309
  readonly methods: readonly string[];
@@ -2443,6 +2520,12 @@ export declare const MigrationPlan: Schema.Struct<{
2443
2520
  readonly slack?: {
2444
2521
  readonly connection: string;
2445
2522
  } | undefined;
2523
+ readonly channels?: {
2524
+ readonly [x: string]: {
2525
+ readonly kind: "telegram" | "email" | "whatsapp" | "slack";
2526
+ readonly connection: string;
2527
+ };
2528
+ } | undefined;
2446
2529
  readonly attribution?: {
2447
2530
  readonly template?: string | undefined;
2448
2531
  readonly separator?: string | undefined;
@@ -2518,6 +2601,11 @@ export declare const MigrationPlan: Schema.Struct<{
2518
2601
  readonly guest?: {
2519
2602
  readonly channels: readonly string[];
2520
2603
  readonly origins: readonly string[];
2604
+ readonly botCheck?: {
2605
+ readonly scheme: string;
2606
+ readonly secret: string;
2607
+ } | undefined;
2608
+ readonly confirmations?: boolean | undefined;
2521
2609
  } | undefined;
2522
2610
  readonly browser?: {
2523
2611
  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. */