@segmentstream/ontology 0.106.2 → 0.107.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 (62) hide show
  1. package/CHANGELOG.md +55 -0
  2. package/README.md +38 -8
  3. package/dist/analyze.d.ts +7 -1
  4. package/dist/analyze.js +237 -13
  5. package/dist/authoring.js +6 -0
  6. package/dist/diagnostics.d.ts +3 -3
  7. package/dist/diagnostics.js +1 -0
  8. package/dist/index.d.ts +6 -6
  9. package/dist/index.js +5 -3
  10. package/dist/manifest.d.ts +69 -1
  11. package/dist/manifest.js +51 -4
  12. package/dist/migrate/apply.d.ts +6 -0
  13. package/dist/migrate/apply.js +25 -5
  14. package/dist/migrate/model.d.ts +32 -0
  15. package/dist/migrate/storage.d.ts +2 -0
  16. package/dist/migrate/storage.js +8 -0
  17. package/dist/names.d.ts +5 -0
  18. package/dist/names.js +5 -0
  19. package/dist/ontology.d.ts +4 -1
  20. package/dist/permissions.d.ts +30 -2
  21. package/dist/permissions.js +51 -6
  22. package/dist/replication/shadow.d.ts +4 -2
  23. package/dist/replication/shadow.js +1 -1
  24. package/dist/replication/store.js +4 -0
  25. package/dist/runtime/agent-counters.d.ts +5 -1
  26. package/dist/runtime/agent-counters.js +21 -6
  27. package/dist/runtime/agent-web.d.ts +9 -6
  28. package/dist/runtime/agent-web.js +101 -5
  29. package/dist/runtime/generated-actions.js +2 -3
  30. package/dist/runtime/guests.d.ts +32 -0
  31. package/dist/runtime/guests.js +64 -0
  32. package/dist/runtime/new-user-hook.js +2 -1
  33. package/dist/runtime/oauth.js +7 -1
  34. package/dist/runtime/pipeline.js +3 -2
  35. package/dist/runtime/principals.js +6 -4
  36. package/dist/runtime/service-binding.js +2 -2
  37. package/dist/runtime/sql-runtime.js +2 -1
  38. package/dist/runtime.d.ts +10 -2
  39. package/dist/service/agent/authentication.d.ts +6 -4
  40. package/dist/service/agent/authentication.js +20 -5
  41. package/dist/service/agent/protocol.d.ts +28 -2
  42. package/dist/service/agent/protocol.js +23 -10
  43. package/dist/service/agent/server.d.ts +9 -2
  44. package/dist/service/agent/server.js +12 -12
  45. package/dist/service/agent/tasks.d.ts +3 -0
  46. package/dist/service/agent/tasks.js +5 -3
  47. package/dist/service/agent/web-tokens.d.ts +28 -13
  48. package/dist/service/agent/web-tokens.js +91 -38
  49. package/dist/service/authentication.d.ts +6 -0
  50. package/dist/service/authentication.js +11 -2
  51. package/dist/service/chat/review-delivery.js +4 -0
  52. package/dist/service/mcp/server.js +3 -3
  53. package/dist/service/mcp/tools.d.ts +4 -2
  54. package/dist/service/mcp/tools.js +14 -2
  55. package/dist/service/oauth/protocol.js +8 -2
  56. package/dist/service/oauth/server.js +5 -1
  57. package/dist/service/runtime-contract.d.ts +58 -6
  58. package/dist/service/schemas.d.ts +8 -0
  59. package/dist/service/service.js +15 -4
  60. package/dist/sign-in.d.ts +58 -9
  61. package/dist/sign-in.js +87 -9
  62. package/package.json +1 -1
@@ -6,6 +6,9 @@ import { BASE_PATH } from "../api.js";
6
6
  import { RequestId, errorBodyForWire, forbidden, rateLimited, toServerResponse, } from "../errors.js";
7
7
  import { ACCESS_TOKEN_PREFIX, ACCESS_TOKEN_TTL_MS, callerOfAccessToken, publicOrigin, } from "../oauth/protocol.js";
8
8
  import { clientAddress } from "../rate-limit.js";
9
+ import { matchesWebsite } from "../../sign-in.js";
10
+ import { guestChat } from "../../runtime/guests.js";
11
+ import { AgentLimitsRequest } from "./protocol.js";
9
12
  /**
10
13
  * A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
11
14
  * server (`sso_…`): the token of the member's grant to the first-party client `agent-web`, for the
@@ -61,8 +64,13 @@ const IntrospectionRequest = Schema.Struct({
61
64
  token: Schema.String.check(Schema.isMaxLength(512)),
62
65
  /** The origin the member reached the agent on; by default the one the agent calls this on. */
63
66
  origin: Schema.optionalKey(Schema.String.check(Schema.isMaxLength(2048))),
64
- /** The token starts a turn: count it against the agent's limits for people who signed up. */
67
+ /**
68
+ * The token starts a turn: count it against the agent's limits for people who signed up, or for
69
+ * guests.
70
+ */
65
71
  turn: Schema.optionalKey(Schema.Boolean),
72
+ /** The agent's limits, from its web channel, kept before the turn is counted. */
73
+ limits: Schema.optionalKey(AgentLimitsRequest),
66
74
  });
67
75
  function originOf(value, request) {
68
76
  if (value === undefined) {
@@ -76,11 +84,14 @@ function originOf(value, request) {
76
84
  /**
77
85
  * `POST /api/ontology/agent/tokens/introspect`, for the agent only (RFC 7662 in spirit): whom an
78
86
  * agent token a browser showed stands for. `{ active: false }` for any token that is not a live
79
- * `agent-web` token for the origin, or whose member may no longer sign in. With `turn: true` the
87
+ * `agent-web` token for the origin, or whose member may no longer sign in. An active answer names
88
+ * the member's roles and, in `agent_tools`, the agent's own tools they grant. With `turn: true` the
80
89
  * member is starting a turn: someone `signUp` created has it counted against the agent's limits,
81
- * and the answer names the limit it exceeds as `limited`.
90
+ * and the answer names the limit it exceeds as `limited`. A guest's token is answered
91
+ * `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
92
+ * turns counts against the agent's guest limits.
82
93
  */
83
- export function introspectAgentToken(store, web, oauth) {
94
+ export function introspectAgentToken(store, web, oauth, agentTools) {
84
95
  return (request) => Effect.gen(function* () {
85
96
  const requestId = yield* RequestId;
86
97
  const body = yield* Effect.map(Effect.orDie(request.text), (text) => {
@@ -103,11 +114,31 @@ export function introspectAgentToken(store, web, oauth) {
103
114
  issues: schemaIssues(decoded.failure),
104
115
  }), { status: 400 });
105
116
  }
106
- const { token } = decoded.success;
117
+ const { token, limits } = decoded.success;
107
118
  const origin = originOf(decoded.success.origin, request);
108
119
  const authenticated = origin === undefined || !token.startsWith(ACCESS_TOKEN_PREFIX)
109
120
  ? undefined
110
121
  : yield* callerOfAccessToken(oauth, token, agentResource(origin));
122
+ const limitedAs = (limited) => limited === undefined
123
+ ? {}
124
+ : { limited: { scope: limited.scope, retry_after_seconds: limited.retryAfterSeconds } };
125
+ if (authenticated?.principal.kind === "guest" &&
126
+ authenticated.caller.kind === "oauth" &&
127
+ authenticated.caller.client.id === AGENT_WEB_CLIENT_ID) {
128
+ const guest = authenticated.principal;
129
+ const limited = decoded.success.turn === true && web.countGuestTurn !== undefined
130
+ ? yield* web.countGuestTurn(guest.id, limits)
131
+ : undefined;
132
+ return json({
133
+ active: true,
134
+ guest_id: guest.id,
135
+ roles: guest.roles,
136
+ grant_id: authenticated.grantId,
137
+ chat: guestChat(guest.id),
138
+ agent_tools: agentTools(guest),
139
+ ...limitedAs(limited),
140
+ });
141
+ }
111
142
  const member = authenticated?.caller.kind === "oauth" &&
112
143
  authenticated.caller.client.id === AGENT_WEB_CLIENT_ID
113
144
  ? yield* store.member(authenticated.principal.id)
@@ -115,19 +146,18 @@ export function introspectAgentToken(store, web, oauth) {
115
146
  if (authenticated === undefined || member === undefined) {
116
147
  return json({ active: false });
117
148
  }
118
- const limited = decoded.success.turn === true ? yield* web.countTurn(member.principal.id) : undefined;
149
+ const limited = decoded.success.turn === true
150
+ ? yield* web.countTurn(member.principal.id, limits)
151
+ : undefined;
119
152
  return json({
120
153
  active: true,
121
154
  member_id: member.principal.id,
122
155
  name: member.name,
123
156
  roles: member.principal.roles,
157
+ agent_tools: agentTools(member.principal),
124
158
  grant_id: authenticated.grantId,
125
159
  chat: personalChat(member.principal.id),
126
- ...(limited === undefined
127
- ? {}
128
- : {
129
- limited: { scope: limited.scope, retry_after_seconds: limited.retryAfterSeconds },
130
- }),
160
+ ...limitedAs(limited),
131
161
  });
132
162
  });
133
163
  }
@@ -138,13 +168,14 @@ function websiteHeaders(origin) {
138
168
  /** The declared website a browser's request comes from, when it comes from one. */
139
169
  function websiteOf(request, origins) {
140
170
  const origin = request.headers.origin;
141
- return origin !== undefined && origins.includes(origin) ? origin : undefined;
171
+ return origin !== undefined && matchesWebsite(origins, origin) ? origin : undefined;
142
172
  }
143
173
  /**
144
- * `OPTIONS /api/ontology/agent/visitors`: lets a browser on one of `signUp.origins` sign its visitor
145
- * up; any other origin gets no permission.
174
+ * `OPTIONS /api/ontology/agent/visitors`: lets a browser on one of the declared websites ask for
175
+ * its visitor's agent token; any other origin gets no permission.
146
176
  */
147
- export function visitorPreflight(origins) {
177
+ export function visitorPreflight(websites) {
178
+ const origins = [...websites.guests, ...websites.signUp];
148
179
  return (request) => Effect.sync(() => {
149
180
  const origin = websiteOf(request, origins);
150
181
  return origin === undefined
@@ -161,29 +192,62 @@ export function visitorPreflight(origins) {
161
192
  });
162
193
  }
163
194
  /**
164
- * `POST /api/ontology/agent/visitors`, for a browser on one of the websites `signUp.origins` names:
165
- * signs a new visitor up on `web` with the roles `signUp` gives it, and answers
166
- * `{ token, expires_at, refresh_token, chat }`. The token is an agent token like a member's; the
167
- * refresh token renews it at the ontology's OAuth token endpoint, as client `agent-web`. Any other
168
- * origin is refused. A browser's Origin proves no sender, so the limits on new visitors per network
169
- * address and per workspace, and on each one's turns, are what bound it.
195
+ * `POST /api/ontology/agent/visitors`, for a browser on one of the declared websites, answers
196
+ * `{ token, expires_at, refresh_token, chat }`: an agent token like a member's, whose refresh token
197
+ * renews it at the ontology's OAuth token endpoint, as client `agent-web`, and the visitor's chat.
198
+ * On a website `guest.origins` names, the visitor is a guest: the token is of a grant that names no
199
+ * user, nobody is signed up, and the chat is `guest:<id>`. On a website `signUp.origins` names, the
200
+ * visitor is signed up on `web` with the roles `signUp` gives it. Any other origin is refused. A
201
+ * browser's Origin proves no sender, so the limits on new visitors per network address, and on
202
+ * their turns, are what bound it.
170
203
  */
171
- export function signUpVisitor(web, origins) {
204
+ export function issueVisitorToken(web, websites) {
172
205
  return (request) => Effect.gen(function* () {
173
206
  const requestId = yield* RequestId;
174
- const origin = websiteOf(request, origins);
207
+ const guestSite = websiteOf(request, websites.guests);
208
+ const origin = guestSite ?? websiteOf(request, websites.signUp);
175
209
  if (origin === undefined) {
176
210
  return HttpServerResponse.jsonUnsafe(errorBodyForWire({
177
211
  error: "origin_not_allowed",
178
- detail: "This origin is not one of signUp.origins.",
212
+ detail: "This origin is not one of the declared websites.",
179
213
  requestId,
180
214
  }), { status: 403, headers: { ...NO_STORE, vary: "Origin" } });
181
215
  }
182
216
  const headers = { ...NO_STORE, ...websiteHeaders(origin) };
217
+ const limitedResponse = (retryAfterSeconds) => HttpServerResponse.jsonUnsafe(errorBodyForWire({
218
+ error: "rate_limited",
219
+ detail: "Too many new visitors; try again later.",
220
+ requestId,
221
+ }), { status: 429, headers: { ...headers, "retry-after": String(retryAfterSeconds) } });
222
+ const refusedResponse = () => HttpServerResponse.jsonUnsafe(errorBodyForWire({
223
+ error: "forbidden",
224
+ detail: "The visitor could not be admitted.",
225
+ requestId,
226
+ }), { status: 403, headers });
227
+ const client = createHash("sha256").update(clientAddress(request)).digest("hex");
228
+ if (guestSite !== undefined) {
229
+ const issued = web.guest === undefined
230
+ ? { status: "refused" }
231
+ : yield* web.guest({ resource: agentResource(publicOrigin(request)), client });
232
+ switch (issued.status) {
233
+ case "issued":
234
+ return HttpServerResponse.jsonUnsafe({
235
+ token: issued.token,
236
+ expires_at: issued.expiresAt.toISOString(),
237
+ refresh_token: issued.refreshToken,
238
+ chat: guestChat(issued.guestId),
239
+ }, { status: 200, headers });
240
+ case "limited":
241
+ return limitedResponse(issued.retryAfterSeconds);
242
+ case "refused":
243
+ return refusedResponse();
244
+ }
245
+ }
246
+ // @legacy ontology.sign-up-web
183
247
  const signedUp = yield* web.visitor({
184
248
  visitorId: randomUUID(),
185
249
  resource: agentResource(publicOrigin(request)),
186
- client: createHash("sha256").update(clientAddress(request)).digest("hex"),
250
+ client,
187
251
  });
188
252
  switch (signedUp.status) {
189
253
  case "signed_up":
@@ -194,20 +258,9 @@ export function signUpVisitor(web, origins) {
194
258
  chat: personalChat(signedUp.userId),
195
259
  }, { status: 200, headers });
196
260
  case "limited":
197
- return HttpServerResponse.jsonUnsafe(errorBodyForWire({
198
- error: "rate_limited",
199
- detail: "Too many new visitors; try again later.",
200
- requestId,
201
- }), {
202
- status: 429,
203
- headers: { ...headers, "retry-after": String(signedUp.retryAfterSeconds) },
204
- });
261
+ return limitedResponse(signedUp.retryAfterSeconds);
205
262
  case "refused":
206
- return HttpServerResponse.jsonUnsafe(errorBodyForWire({
207
- error: "forbidden",
208
- detail: "The visitor could not be signed up.",
209
- requestId,
210
- }), { status: 403, headers });
263
+ return refusedResponse();
211
264
  }
212
265
  });
213
266
  }
@@ -198,6 +198,12 @@ export interface CredentialOptions {
198
198
  readonly agentTasks?: {
199
199
  readonly workspaceId: string;
200
200
  };
201
+ /**
202
+ * This route admits the app's agent acting for a guest, named `guest:<id>` with the grant of their
203
+ * agent token. Only `/mcp` does: a guest uses the ontology's tools there, as their permissions
204
+ * allow, and reaches no other route.
205
+ */
206
+ readonly guests?: true;
201
207
  }
202
208
  /** Resolves a bearer credential to its current principal and verified credential provenance. */
203
209
  export declare function authenticate(credential: Redacted.Redacted<string>, verifyToken: TokenVerifier, options?: CredentialOptions): Effect.Effect<Authenticated, never, OntologyBackend>;
@@ -455,7 +455,7 @@ export function sessionMayAuthenticate(request) {
455
455
  * roles they hold now, while they are active and paired with the agent. Without the header, the
456
456
  * runtime may call only the agent's own routes, which authenticate it themselves.
457
457
  */
458
- function actingMember(actAs, provider, grant) {
458
+ function actingMember(actAs, provider, grant, guests = false) {
459
459
  return Effect.gen(function* () {
460
460
  const backend = yield* OntologyBackend;
461
461
  if (actAs === undefined) {
@@ -475,6 +475,15 @@ function actingMember(actAs, provider, grant) {
475
475
  : provider === WEB_PROVIDER
476
476
  ? yield* webMember(backend.agents, actAs, grant)
477
477
  : yield* backend.agents.actingMember(actAs, provider);
478
+ if (member?.kind === "guest") {
479
+ return guests
480
+ ? {
481
+ status: "authenticated",
482
+ principal: member,
483
+ caller: { kind: "runtime", subjectId: member.id },
484
+ }
485
+ : { status: "forbidden", detail: "This route does not admit guests." };
486
+ }
478
487
  return member === undefined || member.kind !== "member"
479
488
  ? {
480
489
  status: "forbidden",
@@ -653,7 +662,7 @@ export function authenticate(credential, verifyToken, options = {}) {
653
662
  switch (runtime.status) {
654
663
  case "valid":
655
664
  return agentTask === undefined
656
- ? yield* actingMember(actAs, provider, options.runtime.grant)
665
+ ? yield* actingMember(actAs, provider, options.runtime.grant, options.guests === true)
657
666
  : yield* agentTaskPrincipal(agentTask, actAs, options.agentTasks);
658
667
  case "invalid":
659
668
  yield* logRuntimeRejection(runtime.reason);
@@ -98,6 +98,10 @@ export function reviewSender(input) {
98
98
  "sent or truncated.",
99
99
  });
100
100
  }
101
+ // A guest is no user; `agent_review` is not theirs to approve.
102
+ if (principal.kind === "guest") {
103
+ return yield* new PermissionDenied({ message: "The approver is unknown." });
104
+ }
101
105
  const user = yield* backend
102
106
  .get({ entity: "user", id: principal.id })
103
107
  .pipe(Effect.mapError(() => new PermissionDenied({ message: "The approver is unknown." })));
@@ -761,10 +761,10 @@ function withMcpPrincipal(request, verifyToken, verifyRuntime, backend, answer,
761
761
  const origin = publicOrigin(request);
762
762
  const runtime = runtimeCredential(verifyRuntime, request);
763
763
  // With the OAuth tables, members' access tokens work here, and a 401 tells the client where
764
- // the member authorizes it. The app's agent calls as the member it names, or, running a task a
765
- // workflow handed it, as the workflow's user.
764
+ // the member authorizes it. The app's agent calls as the member or guest it names, or, running
765
+ // a task a workflow handed it, as the workflow's user.
766
766
  return yield* withPrincipal(bearer, verifyToken, backend, answer, {
767
- ...(runtime === undefined ? {} : { runtime }),
767
+ ...(runtime === undefined ? {} : { runtime, guests: true }),
768
768
  ...(workspaceId === undefined ? {} : { agentTasks: { workspaceId } }),
769
769
  ...(backend.oauth === undefined
770
770
  ? {}
@@ -99,6 +99,8 @@ export declare function mcpTools(built: BuiltApi, chatHistory?: boolean, storage
99
99
  }, navigation?: boolean): ReadonlyArray<McpTool>;
100
100
  /**
101
101
  * The tools a caller may see: those whose every permission the caller's roles grant, each with the
102
- * caller's input schema.
102
+ * caller's input schema. A guest sees none of the tools only a user has.
103
103
  */
104
- export declare function visibleTools(tools: ReadonlyArray<McpTool>, caller: PermissionHolder, provenance?: CallerContext): ReadonlyArray<McpTool>;
104
+ export declare function visibleTools(tools: ReadonlyArray<McpTool>, caller: PermissionHolder & {
105
+ readonly kind?: string;
106
+ }, provenance?: CallerContext): ReadonlyArray<McpTool>;
@@ -940,13 +940,25 @@ export function mcpTools(built, chatHistory = false, storage = {}, navigation =
940
940
  : {}),
941
941
  }));
942
942
  }
943
+ /**
944
+ * The tools only a user has: who they are, their files and attachments, and the chats they take
945
+ * part in. A guest is no user, so none of them is listed or run for a guest.
946
+ */
947
+ const USER_TOOL_TARGETS = new Set([
948
+ "me",
949
+ "member-file",
950
+ "chat-search",
951
+ "chat-list",
952
+ "chat-history",
953
+ ]);
943
954
  /**
944
955
  * The tools a caller may see: those whose every permission the caller's roles grant, each with the
945
- * caller's input schema.
956
+ * caller's input schema. A guest sees none of the tools only a user has.
946
957
  */
947
958
  export function visibleTools(tools, caller, provenance = { kind: "unverified" }) {
948
959
  return tools.flatMap((tool) => {
949
- if (!runtimeAllows(provenance, tool) ||
960
+ if ((caller.kind === "guest" && USER_TOOL_TARGETS.has(tool.target.kind)) ||
961
+ !runtimeAllows(provenance, tool) ||
950
962
  (tool.target.kind === "toolset" && isReadScoped(provenance)) ||
951
963
  !tool.permissions.every((required) => isAllowed(required, caller))) {
952
964
  return [];
@@ -120,9 +120,15 @@ export function callerOfAccessToken(store, token, resource) {
120
120
  if (!sameResource(grant.resource, resource)) {
121
121
  return yield* rejectedAccessToken("resource_mismatch", grant.id);
122
122
  }
123
- const member = yield* store.memberPrincipal(grant.userId);
123
+ // A grant without a user is a guest's, to the agent alone, and only while guests are admitted.
124
+ const member = grant.userId === null
125
+ ? yield* store.guestPrincipal?.(grant) ?? Effect.succeed(undefined)
126
+ : yield* store.memberPrincipal(grant.userId);
124
127
  const client = yield* store.findClient(grant.clientId);
125
- if (member === undefined || member.kind !== "member" || member.id !== grant.userId) {
128
+ if (member === undefined ||
129
+ (grant.userId === null
130
+ ? member.kind !== "guest" || member.id !== grant.id
131
+ : member.kind !== "member" || member.id !== grant.userId)) {
126
132
  return yield* rejectedAccessToken("member_unavailable", grant.id);
127
133
  }
128
134
  if (client === undefined || client.id !== grant.clientId) {
@@ -579,7 +579,11 @@ function token(store, graceMs) {
579
579
  if (params.resource !== undefined && !sameResource(params.resource, owner.resource)) {
580
580
  return oauthError("invalid_target", "The grant is for a different resource.");
581
581
  }
582
- if ((yield* store.memberPrincipal(owner.userId)) === undefined) {
582
+ // A guest's grant names no user; it renews while the ontology admits guests.
583
+ const holder = owner.userId === null
584
+ ? yield* store.guestPrincipal?.(owner) ?? Effect.succeed(undefined)
585
+ : yield* store.memberPrincipal(owner.userId);
586
+ if (holder === undefined) {
583
587
  // Deny access without permanently destroying authorization on an inconclusive lookup.
584
588
  return oauthError("invalid_grant", "The member can no longer use this app.");
585
589
  }
@@ -127,7 +127,11 @@ export type DevicePoll = {
127
127
  export interface OAuthGrant {
128
128
  readonly id: string;
129
129
  readonly clientId: string;
130
- readonly userId: string;
130
+ /**
131
+ * The user the grant acts for; `null` for a guest's grant to the agent (`agent-web`), whose id is
132
+ * the guest's, since a guest is no user.
133
+ */
134
+ readonly userId: string | null;
131
135
  readonly scope: string;
132
136
  readonly resource: string;
133
137
  /** Present on access-token lookup, for absolute session expiry. */
@@ -191,8 +195,10 @@ export interface OAuthStore {
191
195
  readonly findRequest: (id: string) => Effect.Effect<OAuthRequest | undefined>;
192
196
  /** Removes a request that has not expired and returns it: a request is decided once. */
193
197
  readonly takeRequest: (id: string) => Effect.Effect<OAuthRequest | undefined>;
194
- /** Records a grant, with its PKCE code when using browser authorization. */
195
- readonly saveGrant: (grant: OAuthGrant, code?: OAuthToken) => Effect.Effect<void>;
198
+ /** Records a member's grant, with its PKCE code when using browser authorization. */
199
+ readonly saveGrant: (grant: OAuthGrant & {
200
+ readonly userId: string;
201
+ }, code?: OAuthToken) => Effect.Effect<void>;
196
202
  /** Uses a code or refresh token, once, before it expires and while its grant stands. */
197
203
  readonly useToken: (hash: string, kind: "code" | "refresh") => Effect.Effect<UsedOAuthToken>;
198
204
  /** Stores new tokens, and forgets the expired ones. */
@@ -204,6 +210,11 @@ export interface OAuthStore {
204
210
  readonly revokeGrant: (id: string) => Effect.Effect<void>;
205
211
  /** The member a grant acts for, with the roles they hold now; undefined once they may not sign in. */
206
212
  readonly memberPrincipal: (userId: string) => Effect.Effect<Principal | undefined>;
213
+ /**
214
+ * The guest a grant without a user stands for: a guest's grant to the agent (`agent-web`) while
215
+ * the ontology admits guests; `undefined` for any other grant. Absent on a store without guests.
216
+ */
217
+ readonly guestPrincipal?: (grant: OAuthGrant) => Effect.Effect<Principal | undefined>;
207
218
  }
208
219
  /** A channel account waiting, for ten minutes, for a member to claim it with its pairing code. */
209
220
  export interface AgentPairing {
@@ -258,9 +269,30 @@ export interface AgentWebStore {
258
269
  * Counts one turn a member starts on the web against the agent's limits when `signUp` created
259
270
  * them, as their turns on a messenger are counted, on the same counters; invited and paired
260
271
  * members are never counted. Their `onSignUp`, if it is still pending, runs again first. The
261
- * limit the turn exceeds, or `undefined` when it may run.
272
+ * limit the turn exceeds, or `undefined` when it may run. `limits`, the agent's own, are kept as
273
+ * a messenger's turn keeps them, before counting.
274
+ */
275
+ readonly countTurn: (userId: string, limits?: ResolveIdentityInput["limits"]) => Effect.Effect<WebTurnLimit | undefined>;
276
+ /**
277
+ * The guest an `agent-web` grant without a user stands for, while it stands and the ontology
278
+ * admits guests; `undefined` otherwise. The grant's id is the guest's.
279
+ */
280
+ readonly grantGuest?: (grantId: string) => Effect.Effect<Principal | undefined>;
281
+ /**
282
+ * Counts one turn a guest starts against the agent's guest limits, per guest and for every guest
283
+ * together, apart from the counters of people who signed up. `limits` are kept first, as for
284
+ * {@link countTurn}. The limit the turn exceeds, or `undefined` when it may run.
285
+ */
286
+ readonly countGuestTurn?: (guestId: string, limits?: ResolveIdentityInput["limits"]) => Effect.Effect<WebTurnLimit | undefined>;
287
+ /**
288
+ * A new guest of a declared website: a grant to the agent at `resource` that names no user, with
289
+ * its access and refresh tokens. No user or identity is created. `client` keys how many guests one
290
+ * network address may start an hour; it counts toward no limit of new users.
262
291
  */
263
- readonly countTurn: (userId: string) => Effect.Effect<WebTurnLimit | undefined>;
292
+ readonly guest?: (input: {
293
+ readonly resource: string;
294
+ readonly client: string;
295
+ }) => Effect.Effect<GuestIssue>;
264
296
  /**
265
297
  * Signs up a new visitor of a website on `web`: the user `signUp` creates for them, and the access
266
298
  * and refresh tokens of their grant to the agent at `resource`. `client` keys how many visitors one
@@ -285,6 +317,20 @@ export type VisitorSignUp = {
285
317
  } | {
286
318
  readonly status: "refused";
287
319
  };
320
+ /** A guest's credential, as {@link AgentWebStore.guest} answers it. */
321
+ export type GuestIssue = {
322
+ readonly status: "issued";
323
+ /** The guest's id: the id of their grant, which names no user. */
324
+ readonly guestId: string;
325
+ readonly token: string;
326
+ readonly refreshToken: string;
327
+ readonly expiresAt: Date;
328
+ } | {
329
+ readonly status: "limited";
330
+ readonly retryAfterSeconds: number;
331
+ } | {
332
+ readonly status: "refused";
333
+ };
288
334
  /** The limit a member's turn on the web exceeds, and when the next one may run. */
289
335
  export interface WebTurnLimit {
290
336
  readonly scope: AgentLimitScope;
@@ -303,8 +349,13 @@ export interface AgentLimits {
303
349
  };
304
350
  readonly newUsersPerHour: number;
305
351
  readonly workspaceTurnsPerDay: number;
352
+ /** Guests' turns, apart from those of people who signed up: per guest and for all together. */
353
+ readonly guest: {
354
+ readonly turnsPerDay: number;
355
+ readonly workspaceTurnsPerDay: number;
356
+ };
306
357
  }
307
- export type AgentLimitScope = "turnsPerMinute" | "turnsPerDay" | "newUsersPerHour" | "workspaceTurnsPerDay";
358
+ export type AgentLimitScope = "turnsPerMinute" | "turnsPerDay" | "newUsersPerHour" | "workspaceTurnsPerDay" | "guestTurnsPerDay" | "guestWorkspaceTurnsPerDay" | "newGuestsPerHour";
308
359
  export interface ResolveIdentityInput {
309
360
  readonly provider: string;
310
361
  readonly externalId: string;
@@ -323,6 +374,7 @@ export interface ResolveIdentityInput {
323
374
  readonly perSender?: Partial<AgentLimits["perSender"]>;
324
375
  readonly newUsersPerHour?: number;
325
376
  readonly workspaceTurnsPerDay?: number;
377
+ readonly guest?: Partial<AgentLimits["guest"]>;
326
378
  };
327
379
  }
328
380
  /** Verified provider facts only; channel-app callers cannot submit policy or bot-turn fields. */
@@ -428,6 +428,10 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
428
428
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
429
429
  }>>;
430
430
  readonly onSignUp: Schema.optionalKey<Schema.String>;
431
+ readonly guest: Schema.optionalKey<Schema.Struct<{
432
+ readonly channels: Schema.$Array<Schema.String>;
433
+ readonly origins: Schema.$Array<Schema.String>;
434
+ }>>;
431
435
  }>, {
432
436
  readonly onNewUser: "on_new_user";
433
437
  readonly codeLink: "code_link";
@@ -704,6 +708,10 @@ export declare const Catalog: Schema.decodeTo<Schema.Struct<{
704
708
  readonly origins: Schema.optionalKey<Schema.$Array<Schema.String>>;
705
709
  }>>;
706
710
  readonly onSignUp: Schema.optionalKey<Schema.String>;
711
+ readonly guest: Schema.optionalKey<Schema.Struct<{
712
+ readonly channels: Schema.$Array<Schema.String>;
713
+ readonly origins: Schema.$Array<Schema.String>;
714
+ }>>;
707
715
  }>, {
708
716
  readonly onNewUser: "on_new_user";
709
717
  readonly codeLink: "code_link";
@@ -9,8 +9,9 @@ import { RuntimeDeployment } from "../runtime/deployment.js";
9
9
  import { nameToWire } from "../authoring-names.js";
10
10
  import { bundledNavigationCatalog } from "../navigation-artifact.js";
11
11
  import { parsePageCatalog } from "../navigation-catalog.js";
12
- import { signUpOriginsOf } from "../manifest.js";
12
+ import { guestOf, signUpOriginsOf } from "../manifest.js";
13
13
  import { isAllowed } from "../permissions.js";
14
+ import { agentToolsFor } from "../runtime/guests.js";
14
15
  import { sqlServiceRuntime } from "../runtime/service-binding.js";
15
16
  import { neonSignInLinks, segmentstreamSignInLinks } from "../runtime/sign-in-links.js";
16
17
  import { memberFileRoutes } from "./member-file-routes.js";
@@ -350,13 +351,19 @@ export function createOntologyService(ontology, config) {
350
351
  ErrorResponsesLive,
351
352
  storageMaintenanceAuthenticationLayer(config.storageMaintenanceKey),
352
353
  ]));
353
- const visitorOrigins = signUpOriginsOf(ontology.manifest);
354
+ // The websites whose visitors are guests, and those whose visitors still sign up on web.
355
+ // @legacy ontology.sign-up-web
356
+ const visitorWebsites = {
357
+ guests: guestOf(ontology.manifest)?.origins ?? [],
358
+ signUp: signUpOriginsOf(ontology.manifest),
359
+ };
360
+ const visitors = visitorWebsites.guests.length > 0 || visitorWebsites.signUp.length > 0;
354
361
  const oauth = preview
355
362
  ? Layer.empty
356
363
  : oauthLayer({ verifyToken, refreshReuseGraceMs: config.oauthRefreshReuseGraceMs });
357
364
  const mcp = config.mcp === false
358
365
  ? // A website's visitors renew their agent tokens at the OAuth token endpoint.
359
- visitorOrigins.length > 0
366
+ visitors
360
367
  ? oauth
361
368
  : Layer.empty
362
369
  : Layer.mergeAll(mcpLayer({
@@ -375,13 +382,16 @@ export function createOntologyService(ontology, config) {
375
382
  workspaceId: config.workspaceId,
376
383
  decide: config.decisions,
377
384
  }), oauth);
385
+ // Every answer that tells the agent whom it acts for names the agent's own tools they hold.
386
+ const agentTools = (principal) => agentToolsFor(ontology, principal);
378
387
  const agent = preview
379
388
  ? Layer.empty
380
389
  : agentLayer({
381
390
  verifyToken,
382
391
  verifyRuntime,
383
392
  exchangeSession,
384
- visitorOrigins,
393
+ visitorWebsites,
394
+ agentTools,
385
395
  });
386
396
  const agentTasks = preview
387
397
  ? Layer.empty
@@ -390,6 +400,7 @@ export function createOntologyService(ontology, config) {
390
400
  verifyRuntime,
391
401
  workspaceId: config.workspaceId,
392
402
  engine: config.workflowEngine ?? vercelWorkflowEngine,
403
+ agentTools,
393
404
  });
394
405
  const attachments = preview
395
406
  ? Layer.empty