@segmentstream/ontology 0.106.3 → 0.108.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 (59) hide show
  1. package/CHANGELOG.md +64 -0
  2. package/README.md +45 -11
  3. package/dist/analyze.d.ts +7 -1
  4. package/dist/analyze.js +271 -16
  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/emails.d.ts +36 -5
  9. package/dist/emails.js +139 -2
  10. package/dist/index.d.ts +7 -7
  11. package/dist/index.js +5 -3
  12. package/dist/manifest.d.ts +262 -1
  13. package/dist/manifest.js +73 -4
  14. package/dist/migrate/apply.js +8 -1
  15. package/dist/migrate/model.d.ts +154 -0
  16. package/dist/migrate/storage.d.ts +2 -0
  17. package/dist/migrate/storage.js +8 -0
  18. package/dist/names.d.ts +5 -0
  19. package/dist/names.js +5 -0
  20. package/dist/ontology.d.ts +4 -1
  21. package/dist/permissions.d.ts +30 -2
  22. package/dist/permissions.js +51 -6
  23. package/dist/runtime/agent-counters.d.ts +5 -1
  24. package/dist/runtime/agent-counters.js +21 -6
  25. package/dist/runtime/agent-web.d.ts +9 -6
  26. package/dist/runtime/agent-web.js +101 -5
  27. package/dist/runtime/generated-actions.js +2 -3
  28. package/dist/runtime/guests.d.ts +32 -0
  29. package/dist/runtime/guests.js +64 -0
  30. package/dist/runtime/new-user-hook.js +2 -1
  31. package/dist/runtime/oauth.js +7 -1
  32. package/dist/runtime/pipeline.js +3 -2
  33. package/dist/runtime/principals.js +6 -4
  34. package/dist/runtime/sql-runtime.js +2 -1
  35. package/dist/runtime.d.ts +10 -2
  36. package/dist/service/agent/authentication.d.ts +6 -4
  37. package/dist/service/agent/authentication.js +20 -5
  38. package/dist/service/agent/protocol.d.ts +28 -2
  39. package/dist/service/agent/protocol.js +23 -10
  40. package/dist/service/agent/server.d.ts +9 -2
  41. package/dist/service/agent/server.js +12 -12
  42. package/dist/service/agent/tasks.d.ts +3 -0
  43. package/dist/service/agent/tasks.js +5 -3
  44. package/dist/service/agent/web-tokens.d.ts +28 -13
  45. package/dist/service/agent/web-tokens.js +91 -38
  46. package/dist/service/authentication.d.ts +6 -0
  47. package/dist/service/authentication.js +11 -2
  48. package/dist/service/chat/review-delivery.js +4 -0
  49. package/dist/service/mcp/server.js +3 -3
  50. package/dist/service/mcp/tools.d.ts +4 -2
  51. package/dist/service/mcp/tools.js +14 -2
  52. package/dist/service/oauth/protocol.js +8 -2
  53. package/dist/service/oauth/server.js +5 -1
  54. package/dist/service/runtime-contract.d.ts +58 -6
  55. package/dist/service/schemas.d.ts +40 -0
  56. package/dist/service/service.js +15 -4
  57. package/dist/sign-in.d.ts +66 -9
  58. package/dist/sign-in.js +87 -9
  59. package/package.json +1 -1
@@ -13,7 +13,7 @@ import { clientAddress, fixedWindowLimiter, } from "../rate-limit.js";
13
13
  import { OntologyBackend } from "../runtime-contract.js";
14
14
  import { AGENT_TASK_HEADER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
15
15
  import { ChatSeenRequest, ReviewRequest, ResolveIdentityRequest, IdentityNoticeRequest, LimitNoticeRequest, PAIRING_TTL_MS, PairingRequest, canonicalPairingCode, identityForWire, memberForWire, newPairingCode, } from "./protocol.js";
16
- import { AGENT_TOKEN_LIMIT, introspectAgentToken, issueAgentToken, signUpVisitor, visitorPreflight, } from "./web-tokens.js";
16
+ import { AGENT_TOKEN_LIMIT, introspectAgentToken, issueAgentToken, issueVisitorToken, visitorPreflight, } from "./web-tokens.js";
17
17
  /** The agent's endpoints, under the ontology service's path. */
18
18
  export const AGENT_PATH = `${BASE_PATH}/agent`;
19
19
  const PAIRINGS_PATH = `${AGENT_PATH}/pairings`;
@@ -152,7 +152,7 @@ function approvePairing(store, member) {
152
152
  * as, with the roles they hold now. 404 for an account nobody paired; 403 once its identity was
153
153
  * revoked or its member deactivated.
154
154
  */
155
- function resolveIdentity(store) {
155
+ function resolveIdentity(store, agentTools) {
156
156
  return Effect.gen(function* () {
157
157
  const requestId = yield* RequestId;
158
158
  const provider = yield* routeParam("provider");
@@ -168,11 +168,11 @@ function resolveIdentity(store) {
168
168
  if (member === undefined) {
169
169
  return toServerResponse(forbidden(requestId, "The member is inactive."));
170
170
  }
171
- return json(memberForWire(member));
171
+ return json(memberForWire(member, agentTools));
172
172
  });
173
173
  }
174
174
  /** Runtime-only admission; expected refusals and limits are 200 discriminated results. */
175
- function resolveChannelIdentity(store) {
175
+ function resolveChannelIdentity(store, agentTools) {
176
176
  return (request) => Effect.gen(function* () {
177
177
  const requestId = yield* RequestId;
178
178
  const decoded = Schema.decodeUnknownResult(ResolveIdentityRequest)(yield* jsonBody(request), {
@@ -195,7 +195,7 @@ function resolveChannelIdentity(store) {
195
195
  case "created":
196
196
  return json({
197
197
  status: resolution.status,
198
- ...memberForWire(resolution.member),
198
+ ...memberForWire(resolution.member, agentTools),
199
199
  provisioned: resolution.provisioned,
200
200
  notice_due: resolution.noticeDue,
201
201
  on_new_user_pending: resolution.onNewUserPending,
@@ -417,8 +417,8 @@ export function agentLayer(options) {
417
417
  yield* router.add("GET", `${PAIRINGS_PATH}/:code`, asMember(() => describePairing(store)));
418
418
  yield* router.add("POST", `${PAIRINGS_PATH}/:code/approve`, asMember((_, member) => approvePairing(store, member)));
419
419
  yield* router.add("GET", IDENTITIES_PATH, asMember((_, member) => listIdentities(store, member)));
420
- yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store), { delegated: true }));
421
- yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store)));
420
+ yield* router.add("GET", `${IDENTITIES_PATH}/:provider/:external_id`, asRuntime(() => resolveIdentity(store, options.agentTools), { delegated: true }));
421
+ yield* router.add("POST", `${IDENTITIES_PATH}/resolve`, asRuntime(resolveChannelIdentity(store, options.agentTools)));
422
422
  yield* router.add("POST", `${IDENTITIES_PATH}/notice`, asRuntime(recordNotice(store)));
423
423
  yield* router.add("POST", `${IDENTITIES_PATH}/limit-notice`, asRuntime(completeLimitNotice(store)));
424
424
  for (const blocked of [true, false]) {
@@ -437,11 +437,11 @@ export function agentLayer(options) {
437
437
  yield* router.add("DELETE", `${IDENTITIES_PATH}/:id`, asMember((_, member) => revokeIdentity(store, member)));
438
438
  if (store.web !== undefined && backend.oauth !== undefined) {
439
439
  yield* router.add("POST", AGENT_TOKENS_PATH, asMember(issueAgentToken(store, store.web, fixedWindowLimiter(AGENT_TOKEN_LIMIT))));
440
- yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth)));
441
- const origins = options.visitorOrigins ?? [];
442
- if (origins.length > 0) {
443
- yield* router.add("OPTIONS", AGENT_VISITORS_PATH, visitorPreflight(origins));
444
- yield* router.add("POST", AGENT_VISITORS_PATH, signUpVisitor(store.web, origins));
440
+ yield* router.add("POST", AGENT_TOKEN_INTROSPECTION_PATH, asRuntime(introspectAgentToken(store, store.web, backend.oauth, options.agentTools)));
441
+ const websites = options.visitorWebsites ?? { guests: [], signUp: [] };
442
+ if (websites.guests.length > 0 || websites.signUp.length > 0) {
443
+ yield* router.add("OPTIONS", AGENT_VISITORS_PATH, visitorPreflight(websites));
444
+ yield* router.add("POST", AGENT_VISITORS_PATH, issueVisitorToken(store.web, websites));
445
445
  }
446
446
  }
447
447
  }));
@@ -5,6 +5,7 @@ import { RequestId } from "../errors.js";
5
5
  import { OntologyBackend } from "../runtime-contract.js";
6
6
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
7
7
  import type { WorkflowEngine } from "../workflows.js";
8
+ import type { AgentToolsOf } from "./protocol.js";
8
9
  /** The task the agent runs, as its secret names it. */
9
10
  export declare const AGENT_TASK_PATH = "/api/ontology/agent/tasks/current";
10
11
  /** Where the agent reports the task's outcome. */
@@ -30,6 +31,8 @@ export interface AgentTaskRoutesOptions {
30
31
  readonly workspaceId: string;
31
32
  /** Resumes the workflow waiting on a task. */
32
33
  readonly engine: WorkflowEngine;
34
+ /** The agent's own tools a caller holds, which the task's answer carries for its user. */
35
+ readonly agentTools: AgentToolsOf;
33
36
  }
34
37
  /**
35
38
  * The routes of the tasks workflows hand the app's agent with `agentTask`. Both take only the
@@ -29,9 +29,10 @@ function json(body, status = 200) {
29
29
  }
30
30
  /**
31
31
  * `GET /api/ontology/agent/tasks/current`: the task, its prompt and deadline, and the user it acts
32
- * as, from the ontology's records, never from the agent's request.
32
+ * as, from the ontology's records, never from the agent's request: their roles, and in
33
+ * `agent_tools` the agent's own tools those roles grant.
33
34
  */
34
- function currentTask(backend, { task, principal }) {
35
+ function currentTask(backend, { task, principal }, agentTools) {
35
36
  return Effect.gen(function* () {
36
37
  const user = yield* backend
37
38
  .get({ entity: "user", id: principal.id })
@@ -45,6 +46,7 @@ function currentTask(backend, { task, principal }) {
45
46
  id: principal.id,
46
47
  name: typeof user?.name === "string" ? user.name : task.workflow,
47
48
  roles: [...new Set([...principal.roles, MEMBER_ROLE])],
49
+ agent_tools: agentTools(principal),
48
50
  },
49
51
  });
50
52
  });
@@ -149,7 +151,7 @@ export function agentTasksLayer(options) {
149
151
  ? refused(caller.detail)
150
152
  : yield* answer(request, caller);
151
153
  });
152
- yield* router.add("GET", AGENT_TASK_PATH, asTask((_, live) => currentTask(backend, live)));
154
+ yield* router.add("GET", AGENT_TASK_PATH, asTask((_, live) => currentTask(backend, live, options.agentTools)));
153
155
  yield* router.add("POST", AGENT_TASK_RESULT_PATH, asTask((request, live) => reportResult(store, options.engine, request, live)));
154
156
  }));
155
157
  }
@@ -4,6 +4,7 @@ import type { Principal } from "../../runtime.js";
4
4
  import { RequestId } from "../errors.js";
5
5
  import { type RateLimit, type RateLimiter } from "../rate-limit.js";
6
6
  import type { AgentStore, AgentWebStore, OAuthStore } from "../runtime-contract.js";
7
+ import { type AgentToolsOf } from "./protocol.js";
7
8
  /**
8
9
  * A member's browser reaches the app's agent with an ordinary access token of the ontology's OAuth
9
10
  * server (`sso_…`): the token of the member's grant to the first-party client `agent-web`, for the
@@ -26,22 +27,36 @@ export declare function issueAgentToken(store: AgentStore, web: AgentWebStore, l
26
27
  /**
27
28
  * `POST /api/ontology/agent/tokens/introspect`, for the agent only (RFC 7662 in spirit): whom an
28
29
  * 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. With `turn: true` the
30
+ * `agent-web` token for the origin, or whose member may no longer sign in. An active answer names
31
+ * the member's roles and, in `agent_tools`, the agent's own tools they grant. With `turn: true` the
30
32
  * 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`.
33
+ * and the answer names the limit it exceeds as `limited`. A guest's token is answered
34
+ * `{ active, guest_id, roles, grant_id, chat, agent_tools }`, without a member, and each of their
35
+ * turns counts against the agent's guest limits.
32
36
  */
33
- export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
37
+ export declare function introspectAgentToken(store: AgentStore, web: AgentWebStore, oauth: OAuthStore, agentTools: AgentToolsOf): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
34
38
  /**
35
- * `OPTIONS /api/ontology/agent/visitors`: lets a browser on one of `signUp.origins` sign its visitor
36
- * up; any other origin gets no permission.
39
+ * The websites whose visitors get an agent token at `POST /api/ontology/agent/visitors`: those whose
40
+ * visitors are guests, and those whose visitors sign up on `web`. A website both declare is the
41
+ * guests'.
37
42
  */
38
- export declare function visitorPreflight(origins: ReadonlyArray<string>): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, never>;
43
+ export interface VisitorWebsites {
44
+ readonly guests: ReadonlyArray<string>;
45
+ readonly signUp: ReadonlyArray<string>;
46
+ }
39
47
  /**
40
- * `POST /api/ontology/agent/visitors`, for a browser on one of the websites `signUp.origins` names:
41
- * signs a new visitor up on `web` with the roles `signUp` gives it, and answers
42
- * `{ token, expires_at, refresh_token, chat }`. The token is an agent token like a member's; the
43
- * refresh token renews it at the ontology's OAuth token endpoint, as client `agent-web`. Any other
44
- * origin is refused. A browser's Origin proves no sender, so the limits on new visitors per network
45
- * address and per workspace, and on each one's turns, are what bound it.
48
+ * `OPTIONS /api/ontology/agent/visitors`: lets a browser on one of the declared websites ask for
49
+ * its visitor's agent token; any other origin gets no permission.
46
50
  */
47
- export declare function signUpVisitor(web: AgentWebStore, origins: ReadonlyArray<string>): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
51
+ export declare function visitorPreflight(websites: VisitorWebsites): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, never>;
52
+ /**
53
+ * `POST /api/ontology/agent/visitors`, for a browser on one of the declared websites, answers
54
+ * `{ token, expires_at, refresh_token, chat }`: an agent token like a member's, whose refresh token
55
+ * renews it at the ontology's OAuth token endpoint, as client `agent-web`, and the visitor's chat.
56
+ * On a website `guest.origins` names, the visitor is a guest: the token is of a grant that names no
57
+ * user, nobody is signed up, and the chat is `guest:<id>`. On a website `signUp.origins` names, the
58
+ * visitor is signed up on `web` with the roles `signUp` gives it. Any other origin is refused. A
59
+ * browser's Origin proves no sender, so the limits on new visitors per network address, and on
60
+ * their turns, are what bound it.
61
+ */
62
+ export declare function issueVisitorToken(web: AgentWebStore, websites: VisitorWebsites): (request: HttpServerRequest.HttpServerRequest) => Effect.Effect<HttpServerResponse.HttpServerResponse, never, RequestId>;
@@ -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
  }