@segmentstream/ontology 0.101.0 → 0.102.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.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,22 @@
1
1
  # Changelog
2
2
 
3
+ ## 0.102.0
4
+
5
+ The agent's limits for people who signed up now apply to the web. Each message a member sends from
6
+ the browser starts a turn that the ontology counts against `limits` when `signUp` created them, by
7
+ email too, on the same counters as their turns on a messenger. Invited and paired members are never
8
+ counted. A turn beyond the limits is refused before it reaches the model with `429 rate_limited` and
9
+ `Retry-After`, and `useAgent()` reports it, like every refusal of the agent's routes, as a
10
+ `SegmentStreamApiError` with its code. The counts use the `limits` the agent last sent with a
11
+ messenger's turn, or the platform's defaults.
12
+
13
+ The agent token introspection (`POST /api/ontology/agent/tokens/introspect`) accepts `turn: true`
14
+ and then answers `limited: { scope, retry_after_seconds }` for a turn beyond the limits.
15
+
16
+ Action required: upgrade the ontology SDK together with the agent SDK. With an ontology SDK released
17
+ before this one, the agent asks again without the turn and web turns stay uncounted until
18
+ 2027-02-15; after that date they fail.
19
+
3
20
  ## 0.101.0
4
21
 
5
22
  A member signed in to the app can reach the app's agent from the browser with an agent token: an
package/README.md CHANGED
@@ -11,6 +11,9 @@ database and the HTTP service under `/api/ontology`. Every read and every action
11
11
  a permission that the caller's roles grant, and every change to a record goes through an
12
12
  action and is kept in history.
13
13
 
14
+ Guides named by path below, such as `docs/ontology.md`, are in every workspace project;
15
+ `segmentstream sync` keeps them current.
16
+
14
17
  TypeScript definitions, handler records and SDK calls use camelCase: `jobTitle`,
15
18
  `assignedOwnerId`, `createdAt`, and `changeStatus`. The SDK converts ontology names,
16
19
  select identifiers and declared action input fields to snake_case for the generated
@@ -118,7 +121,7 @@ every aggregate, so that a metric reads only the rows its conditions accept (`m.
118
121
  it or filter it to one day. Aggregate requests
119
122
  take the `notEquals`, `notIn`, `gt`, `gte`, `lt`, `lte`, `contains`, `startsWith`, `endsWith` and
120
123
  `inPeriod` operators, the `hour`, `quarter` and `year` granularities and a `timezone`. See
121
- [ontology metrics](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-metrics.md).
124
+ ontology metrics (`docs/ontology-metrics.md`).
122
125
 
123
126
  SDK 0.14.0 lets the app's own agent call the service as a paired member (see
124
127
  [Agents](#agents)). Its migration adds the agent's runtime tables.
@@ -132,7 +135,7 @@ fields and business relationships. Existing history captures immutable snapshots
132
135
  service wakes the publisher after commits. Upgrade and redeploy to activate it; workspace
133
136
  configuration can intentionally exclude exported data. Automatic repairs build a private replacement
134
137
  while the serving analytical projection keeps receiving changes and answering queries. See
135
- [replication lifecycle](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-replication.md).
138
+ replication lifecycle (`docs/ontology-replication.md`).
136
139
  The next release supports schema changes during active copies: property renames adapt views over retained
137
140
  JSON, and restored or newly included data is exported through scoped resumable scans. No manual pause
138
141
  is required for deployment or recovery. Explicit opt-outs and supported-writer fences remain in force.
@@ -141,7 +144,7 @@ SDK 0.13.0 writes manifest version 6. Relationships may target warehouse-backed
141
144
  stored or warehouse-backed entities, matched by value through `on`, and `unique` is allowed on
142
145
  warehouse-backed properties as an unenforced assertion. Upgrading: 0.12 accepted an explicit `onDelete`, or `optional: true`, on a
143
146
  warehouse → stored relationship; 0.13.0 `check` refuses both, so remove them. See
144
- [ontology metrics](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-metrics.md#relationships).
147
+ ontology metrics (`docs/ontology-metrics.md#relationships`).
145
148
 
146
149
  SDK 0.13.0 also serves aggregates. Upgrade notes:
147
150
 
@@ -161,8 +164,7 @@ SDK 0.13.0 also serves aggregates. Upgrade notes:
161
164
  warehouse-backed entities through aggregates. Grant those to `member` by name
162
165
  (`acme_sales:read`), or keep the `invited` policy.
163
166
 
164
- See [ontology metrics](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-metrics.md)
165
- and [ontology analytics](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-aggregates-spec.md).
167
+ See `docs/ontology-metrics.md`.
166
168
 
167
169
  ## File storage
168
170
 
@@ -227,7 +229,7 @@ allow more types, then check, migrate and redeploy the ontology. The app SDK sto
227
229
  0.13.1 or later uses `application/octet-stream` when the browser supplies no MIME type.
228
230
  REST callers should supply that type themselves for unknown formats.
229
231
 
230
- See [blob storage](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-blob-storage-implementation.md)
232
+ See `docs/ontology.md#file-transfers`
231
233
  for upload tickets, transfer grants and retained revisions.
232
234
 
233
235
  SDK 0.56.0 adds server-side file transfers through `Files`. In an action, declare
@@ -238,7 +240,7 @@ authorized retained revision for sending to another provider. Use `files: []` wh
238
240
  preparation only reads files and has no connections. Callers of staging actions provide
239
241
  an idempotency key; workflow action calls derive a stable key from the run, step and input
240
242
  when omitted. Streams stay within the step; carry tickets and references between steps.
241
- See [server-side file transfers](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-blob-storage-implementation.md#server-side-file-transfers)
243
+ See `docs/ontology.md#file-transfers`
242
244
  for the API and recovery rules.
243
245
 
244
246
  Buffered `get`/`post`/`request` calls receive the provider's response through a streamed
@@ -263,7 +265,7 @@ commit. They are never replayed. This declaration is independent of
263
265
  timeouts, cancellation, permission failures, cleanup failures or uncertain commits.
264
266
  Custom service runtime implementations own their retry policy; wrappers around
265
267
  the default backend are not replayed. See
266
- [action deadlines and load](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology.md#action-deadlines-and-load)
268
+ action deadlines and load (`docs/ontology.md#action-deadlines-and-load`)
267
269
  for the full replay contract.
268
270
 
269
271
  An action with `hints: { connectionsReadOnly: true, destructive: false }` may read
@@ -905,7 +907,7 @@ selects. Metric queries lock nothing: lock the record the decision depends on wi
905
907
  `forUpdate`. Balance
906
908
  metrics, model metrics and workflow steps stay with the warehouse's `query_metrics`.
907
909
  `aggregate`, the earlier name of `queryMetrics`, remains as a deprecated alias.
908
- See [fresh metric queries inside an action](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology.md#fresh-metric-queries-inside-an-action).
910
+ See fresh metric queries inside an action (`docs/ontology.md#fresh-metric-queries-inside-an-action`).
909
911
 
910
912
  ## Permissions
911
913
 
@@ -1258,7 +1260,7 @@ API from the ontology's MCP server: each tool in the lock, written by
1258
1260
  confirmed. Fixed values the connection declares are removed from the tool's input and added to each
1259
1261
  call, and backend-next admits only the declared tools and values. A toolset has no records. It is
1260
1262
  served over MCP only: not by the REST API, to workflows or under the OAuth `ontology:read` scope.
1261
- See [MCP connections](https://github.com/segmentstream/segmentstream/blob/main/docs/mcp-connections-spec.md).
1263
+ See `docs/ontology.md#provider-mcp-tools-toolsets` and `docs/connections.md#declare-an-mcp-server`.
1262
1264
 
1263
1265
  ## Agents
1264
1266
 
@@ -1728,9 +1730,9 @@ Apache-2.0
1728
1730
 
1729
1731
  ## Entity sources and metric queries
1730
1732
 
1731
- Entities with a warehouse source declare mapped properties, metrics and relationships without ontology storage tables or actions. `find`, `query` and `get` read observations through the workspace's warehouse API, with opaque source-key record IDs and bounded, permission-checked relationship reads. See [warehouse record reads](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-record-reads.md). Stored entities may declare metrics too; they are computed over the entity's replication view, whose columns are the properties' snake_case names. See [ontology metrics](https://github.com/segmentstream/segmentstream/blob/main/docs/ontology-metrics.md) for declaration rules, metric query paths, source verification and workspace authorization.
1733
+ Entities with a warehouse source declare mapped properties, metrics and relationships without ontology storage tables or actions. `find`, `query` and `get` read observations through the workspace's warehouse API, with opaque source-key record IDs and bounded, permission-checked relationship reads. See warehouse record reads (`docs/ontology-record-reads.md`). Stored entities may declare metrics too; they are computed over the entity's replication view, whose columns are the properties' snake_case names. See ontology metrics (`docs/ontology-metrics.md`) for declaration rules, metric query paths, source verification and workspace authorization.
1732
1734
 
1733
- See [release order and rollback](../../docs/agent-chat-delivery-migration.md).
1735
+ See release order and rollback (`docs/agent-chat-delivery-migration.md`).
1734
1736
 
1735
1737
  ### Telegram link previews
1736
1738
 
package/dist/index.d.ts CHANGED
@@ -86,7 +86,7 @@ export { configFromEnv, ENVIRONMENT_VARIABLES, NEON_AUTH_ENVIRONMENT_VARIABLES,
86
86
  export type { ActionCommitted, AfterCommitHook, NeonAuthEnvironment, OntologyEnvironment, OntologyServiceConfig, } from "./service/config.js";
87
87
  export type { Decide, DecisionRequest } from "./service/decisions.js";
88
88
  export { IdentityInUse, NotInvited, OntologyBackend } from "./service/runtime-contract.js";
89
- export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
89
+ export type { AgentIdentity, AgentMember, AgentLimits, AgentLimitScope, ChannelSignInInput, AgentResolution, ResolveIdentityInput, AgentPairing, AgentStore, AgentWebStore, WebTurnLimit, SeenChat, HeldReplyInput, HeldReview, GeneratedActionsProvider, IdentityProvider, OAuthClient, OAuthClientAuthMethod, OAuthGrant, OAuthDevice, DevicePoll, OAuthRequest, OAuthStore, OAuthToken, OAuthTokenKind, OntologyServiceRuntime, RunActionInput, SignInIdentity, UsedOAuthToken, } from "./service/runtime-contract.js";
90
90
  export { createOntologyService, ONTOLOGY_HASH_HEADER, REQUEST_ID_HEADER, } from "./service/service.js";
91
91
  export { AGENT_PATH, AGENT_TOKEN_INTROSPECTION_PATH, AGENT_TOKENS_PATH, } from "./service/agent/server.js";
92
92
  export { AGENT_TASK_PATH, AGENT_TASK_RESULT_PATH } from "./service/agent/tasks.js";
@@ -1,8 +1,10 @@
1
1
  import { randomUUID } from "node:crypto";
2
2
  import { Effect } from "effect";
3
- import { OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, USER_TABLE } from "../migrate/storage.js";
3
+ import { CHANNEL_USERS_TABLE, OAUTH_CLIENTS_TABLE, OAUTH_GRANTS_TABLE, USER_TABLE, } from "../migrate/storage.js";
4
4
  import { AGENT_WEB_CLIENT_ID } from "../service/agent/web-tokens.js";
5
5
  import { ACCESS_TOKEN_PREFIX, FULL_SCOPE, newSecret, secretHash, } from "../service/oauth/protocol.js";
6
+ import { completeAgentLimitNotice, countAgentAttempt, effectiveChannelLimits, } from "./agent-counters.js";
7
+ import { channelUsersAvailable } from "./member-tables.js";
6
8
  import { sqlOAuthStore } from "./oauth.js";
7
9
  import { isMemberBlocked } from "./principals.js";
8
10
  import { isRecordId } from "./records.js";
@@ -57,5 +59,42 @@ export function sqlAgentWebStore(ontology, sql) {
57
59
  .pipe(Effect.orDie);
58
60
  return standing === undefined ? undefined : yield* oauth.memberPrincipal(userId);
59
61
  }),
62
+ countTurn: (userId) => Effect.gen(function* () {
63
+ // @legacy ontology.pre-upgrade-database-tolerance
64
+ if (!isRecordId(userId) || !(yield* channelUsersAvailable(sql))) {
65
+ return undefined;
66
+ }
67
+ const [lifecycle] = yield* sql.unsafe(`SELECT COALESCE(to_jsonb("c") ->> 'signed_up', 'false') = 'true' AS "signed_up"
68
+ FROM "${CHANNEL_USERS_TABLE}" AS "c" WHERE "c"."user_id" = $1::uuid`, [userId]);
69
+ if (lifecycle?.signed_up !== true) {
70
+ return undefined;
71
+ }
72
+ const limits = yield* effectiveChannelLimits(sql);
73
+ for (const [scope, subject, window] of [
74
+ ["turnsPerMinute", userId, "minute"],
75
+ ["turnsPerDay", userId, "day"],
76
+ ["workspaceTurnsPerDay", "workspace", "day"],
77
+ ]) {
78
+ const limited = yield* countAgentAttempt(sql, {
79
+ scope,
80
+ subject,
81
+ window,
82
+ limit: scope === "workspaceTurnsPerDay"
83
+ ? limits.workspaceTurnsPerDay
84
+ : limits.perSender[scope],
85
+ });
86
+ if (limited !== undefined) {
87
+ // The refusal the browser gets is this window's notice, on every channel.
88
+ if (limited.notificationId !== undefined) {
89
+ yield* completeAgentLimitNotice(sql, {
90
+ notificationId: limited.notificationId,
91
+ delivered: true,
92
+ });
93
+ }
94
+ return { scope: limited.scope, retryAfterSeconds: limited.retryAfterSeconds };
95
+ }
96
+ }
97
+ return undefined;
98
+ }).pipe(Effect.orDie),
60
99
  };
61
100
  }
@@ -434,7 +434,7 @@ export function agentLayer(options) {
434
434
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
435
435
  if (store.web !== undefined && backend.oauth !== undefined) {
436
436
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
437
- yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, backend.oauth)));
437
+ yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth)));
438
438
  }
439
439
  }));
440
440
  }
@@ -26,6 +26,8 @@ export declare function issueAgentToken(store: AgentStore, web: AgentWebStore, l
26
26
  /**
27
27
  * `POST /api/ontology/agent/tokens/introspect`, for the agent only (RFC 7662 in spirit): whom an
28
28
  * agent token a browser showed stands for. `{ active: false }` for any token that is not a live
29
- * `agent-web` token for the origin, or whose member may no longer sign in.
29
+ * `agent-web` token for the origin, or whose member may no longer sign in. With `turn: true` the
30
+ * member is starting a turn: someone `signUp` created has it counted against the agent's limits,
31
+ * and the answer names the limit it exceeds as `limited`.
30
32
  */
31
- export declare function introspectAgentToken(store: AgentStore, oauth: OAuthStore): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
33
+ export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
@@ -59,6 +59,8 @@ const IntrospectionRequest = Schema.Struct({
59
59
  token: Schema.String.check(Schema.isMaxLength(512)),
60
60
  /** The origin the member reached the agent on; by default the one the agent calls this on. */
61
61
  origin: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2048))),
62
+ /** The token starts a turn: count it against the agent's limits for people who signed up. */
63
+ turn: Schema.optionalKey(Schema.Boolean),
62
64
  });
63
65
  function originOf(value, request) {
64
66
  if (value === undefined) {
@@ -72,9 +74,11 @@ function originOf(value, request) {
72
74
  /**
73
75
  * `POST /api/ontology/agent/tokens/introspect`, for the agent only (RFC 7662 in spirit): whom an
74
76
  * agent token a browser showed stands for. `{ active: false }` for any token that is not a live
75
- * `agent-web` token for the origin, or whose member may no longer sign in.
77
+ * `agent-web` token for the origin, or whose member may no longer sign in. With `turn: true` the
78
+ * member is starting a turn: someone `signUp` created has it counted against the agent's limits,
79
+ * and the answer names the limit it exceeds as `limited`.
76
80
  */
77
- export function introspectAgentToken(store, oauth) {
81
+ export function introspectAgentToken(store, web, oauth) {
78
82
  return (request) => Effect.gen(function* () {
79
83
  const requestId = yield* RequestId;
80
84
  const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
@@ -109,6 +113,7 @@ export function introspectAgentToken(store, oauth) {
109
113
  if (authenticated === undefined || member === undefined) {
110
114
  return json({ active: false });
111
115
  }
116
+ const limited = decoded.success.turn === true ? yield* web.countTurn(member.principal.id) : undefined;
112
117
  return json({
113
118
  active: true,
114
119
  member_id: member.principal.id,
@@ -116,6 +121,11 @@ export function introspectAgentToken(store, oauth) {
116
121
  roles: member.principal.roles,
117
122
  grant_id: authenticated.grantId,
118
123
  chat: personalChat(member.principal.id),
124
+ ...(limited === undefined
125
+ ? {}
126
+ : {
127
+ limited: { scope: limited.scope, retry_after_seconds: limited.retryAfterSeconds },
128
+ }),
119
129
  });
120
130
  });
121
131
  }
@@ -254,6 +254,17 @@ export interface AgentWebStore {
254
254
  readonly grantId: string;
255
255
  readonly userId: string;
256
256
  }) => Effect.Effect<Principal | undefined>;
257
+ /**
258
+ * Counts one turn a member starts on the web against the agent's limits when `signUp` created
259
+ * them, as their turns on a messenger are counted, on the same counters; invited and paired
260
+ * members are never counted. The limit the turn exceeds, or `undefined` when it may run.
261
+ */
262
+ readonly countTurn: (userId: string) => Effect.Effect<WebTurnLimit | undefined>;
263
+ }
264
+ /** The limit a member's turn on the web exceeds, and when the next one may run. */
265
+ export interface WebTurnLimit {
266
+ readonly scope: AgentLimitScope;
267
+ readonly retryAfterSeconds: number;
257
268
  }
258
269
  /** A member as the agent names them: their user's name and the roles they hold now. */
259
270
  export interface AgentMember {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@segmentstream/ontology",
3
- "version": "0.101.0",
3
+ "version": "0.102.0",
4
4
  "description": "Define a SegmentStream workspace app's ontology: entities, relationships, roles and actions, written with Effect.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "SegmentStream",