@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
package/dist/manifest.js CHANGED
@@ -4,7 +4,7 @@ import { acceptingEarlierManifestNames, withEarlierManifestNames } from "./legac
4
4
  import { humanize, MEMBER_ROLE, FEEDBACK_REPORTER_ROLE, GUEST_ROLE } from "./names.js";
5
5
  import { PROPERTY_TYPES } from "./property.js";
6
6
  import { ON_DELETE } from "./relationship.js";
7
- import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isGuestChannel, isSignInPolicy, isSignUpChannel, websiteOrigin, } from "./sign-in.js";
7
+ import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isGuestBotCheckScheme, isGuestChannel, isSignInPolicy, isSignUpChannel, websiteOrigin, } from "./sign-in.js";
8
8
  /**
9
9
  * The manifest format this SDK writes. Readers accept any version and ignore unknown fields. Version
10
10
  * 2 replaced the actions' `allow` with `permission`, and added the roles' `permissions` and the
@@ -73,6 +73,10 @@ import { CHANNEL_PROVIDERS, DEFAULT_SIGN_IN_POLICY, isGuestChannel, isSignInPoli
73
73
  * declared: the wire name of the email the platform sends instead of its own invitation. Older
74
74
  * readers ignore `sections` and `invitationEmail`, leave the two values empty and send the
75
75
  * platform's invitation.
76
+ * Within version 15, `guest` may carry `bot_check`, `{ scheme, secret }`, the challenge a new
77
+ * guest passes and the workspace secret its verification reads, and `confirmations: true`, written
78
+ * only when declared. Older readers ignore both: they ask new guests for no challenge, and keep
79
+ * refusing guests the actions that need a confirmation.
76
80
  */
77
81
  export const MANIFEST_VERSION = 15;
78
82
  /** The first version whose documents use snake_case names on the wire. */
@@ -415,7 +419,11 @@ export const SignUpManifest = Schema.Struct({
415
419
  export const GuestManifest = Schema.Struct({
416
420
  channels: Schema.Array(Schema.String),
417
421
  origins: Schema.Array(Schema.String),
418
- });
422
+ /** The challenge a new guest passes, and the workspace secret holding its secret key. */
423
+ botCheck: Schema.optionalKey(Schema.Struct({ scheme: Schema.String, secret: Schema.String })),
424
+ /** Guests may confirm actions that need a confirmation. */
425
+ confirmations: Schema.optionalKey(Schema.Boolean),
426
+ }).pipe(Schema.encodeKeys({ botCheck: "bot_check" }));
419
427
  export const SignInManifest = Schema.Struct({
420
428
  browser: Schema.optionalKey(BrowserSignInManifest),
421
429
  policy: Schema.String,
@@ -622,7 +630,7 @@ export function guestOf(manifest) {
622
630
  if (typeof declared !== "object" || declared === null) {
623
631
  return undefined;
624
632
  }
625
- const { channels, origins } = declared;
633
+ const { channels, origins, botCheck, confirmations } = declared;
626
634
  const known = Array.isArray(channels) ? channels.filter(isGuestChannel) : [];
627
635
  const websites = Array.isArray(origins)
628
636
  ? origins.flatMap((candidate) => {
@@ -630,9 +638,27 @@ export function guestOf(manifest) {
630
638
  return origin === undefined ? [] : [origin];
631
639
  })
632
640
  : [];
633
- return known.length === 0 || websites.length === 0
634
- ? undefined
635
- : { channels: [...new Set(known)], origins: websites };
641
+ const check = botCheck;
642
+ if (known.length === 0 || websites.length === 0) {
643
+ return undefined;
644
+ }
645
+ // A bot check this reader cannot verify admits no new guest, rather than none without a check.
646
+ if (check !== undefined &&
647
+ (typeof check !== "object" ||
648
+ check === null ||
649
+ !isGuestBotCheckScheme(check.scheme) ||
650
+ typeof check.secret !== "string" ||
651
+ check.secret === "")) {
652
+ return undefined;
653
+ }
654
+ return {
655
+ channels: [...new Set(known)],
656
+ origins: websites,
657
+ ...(check === undefined
658
+ ? {}
659
+ : { botCheck: { scheme: check.scheme, secret: check.secret } }),
660
+ ...(confirmations === true ? { confirmations: true } : {}),
661
+ };
636
662
  }
637
663
  // @legacy ontology.legacy-channel-admission
638
664
  /** Unsupported providers and missing or unknown channel policies require invitation. */
@@ -899,6 +925,15 @@ export function buildManifest(input) {
899
925
  guest: {
900
926
  channels: [...input.signIn.guest.channels],
901
927
  origins: [...input.signIn.guest.origins],
928
+ ...(input.signIn.guest.botCheck === undefined
929
+ ? {}
930
+ : {
931
+ botCheck: {
932
+ scheme: input.signIn.guest.botCheck.scheme,
933
+ secret: input.signIn.guest.botCheck.secret,
934
+ },
935
+ }),
936
+ ...(input.signIn.guest.confirmations === true ? { confirmations: true } : {}),
902
937
  },
903
938
  }),
904
939
  },
@@ -88,9 +88,10 @@ export declare const RUNTIME_TABLES: ReadonlyArray<string>;
88
88
  * The runtime tables the database has, for `planMigration`'s `existingTables`: a database that an
89
89
  * earlier SDK migrated lacks the tables added since.
90
90
  * A grants table without app-session binding is reported incomplete so the idempotent OAuth DDL
91
- * also upgrades an unchanged manifest, and so is an API keys table without `delegation` and an
92
- * attachments table whose source check predates one of {@link ATTACHMENT_SOURCES}, which the
93
- * idempotent API key and attachment DDL add and widen.
91
+ * also upgrades an unchanged manifest, and so is an action attribution table without `chat`, an
92
+ * API keys table without `delegation` and an attachments table whose source check predates one of
93
+ * {@link ATTACHMENT_SOURCES}, which the idempotent attribution, API key and attachment DDL add and
94
+ * widen.
94
95
  */
95
96
  export declare const readRuntimeTables: (input: CatalogInput) => Effect.Effect<ReadonlySet<string>, SqlError>;
96
97
  /** Only valid, complete covering indexes satisfy the upgrade; failed builds are retried. */
@@ -491,9 +491,10 @@ export const RUNTIME_TABLES = [
491
491
  * The runtime tables the database has, for `planMigration`'s `existingTables`: a database that an
492
492
  * earlier SDK migrated lacks the tables added since.
493
493
  * A grants table without app-session binding is reported incomplete so the idempotent OAuth DDL
494
- * also upgrades an unchanged manifest, and so is an API keys table without `delegation` and an
495
- * attachments table whose source check predates one of {@link ATTACHMENT_SOURCES}, which the
496
- * idempotent API key and attachment DDL add and widen.
494
+ * also upgrades an unchanged manifest, and so is an action attribution table without `chat`, an
495
+ * API keys table without `delegation` and an attachments table whose source check predates one of
496
+ * {@link ATTACHMENT_SOURCES}, which the idempotent attribution, API key and attachment DDL add and
497
+ * widen.
497
498
  */
498
499
  export const readRuntimeTables = (input) => input.sql
499
500
  .unsafe(`SELECT "tablename" AS "name" FROM "pg_catalog"."pg_tables" ` +
@@ -513,6 +514,10 @@ export const readRuntimeTables = (input) => input.sql
513
514
  `AND ("tablename" <> ${quoteLiteral(CHANNEL_USERS_TABLE)} OR EXISTS (` +
514
515
  `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
515
516
  `AND table_name = ${quoteLiteral(CHANNEL_USERS_TABLE)} AND column_name = 'signed_up')) ` +
517
+ // Without `chat` the attribution DDL runs again and adds it.
518
+ `AND ("tablename" <> ${quoteLiteral(ACTION_ATTRIBUTION_TABLE)} OR EXISTS (` +
519
+ `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
520
+ `AND table_name = ${quoteLiteral(ACTION_ATTRIBUTION_TABLE)} AND column_name = 'chat')) ` +
516
521
  `AND ("tablename" <> ${quoteLiteral(API_KEYS_TABLE)} OR EXISTS (` +
517
522
  `SELECT 1 FROM information_schema.columns WHERE table_schema = current_schema() ` +
518
523
  `AND table_name = ${quoteLiteral(API_KEYS_TABLE)} AND column_name = 'delegation')) ` +
@@ -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. */