@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
@@ -18,6 +18,7 @@ import { User } from "../user.js";
18
18
  import { MemberNotFound, PrincipalRejected, UnknownRole } from "./errors.js";
19
19
  import { channelUsersAvailable, recordUserCreation, revokeMemberSessions, } from "./member-tables.js";
20
20
  import { refuseMember, requireGrantable } from "./member-writes.js";
21
+ import { isGuestRole, userRoleNames } from "./guests.js";
21
22
  import { isRecordId } from "./records.js";
22
23
  import { makeOntologyRuntime, makePrincipalUserWriter, } from "./sql-runtime.js";
23
24
  import { accountOfLegacy, CHANNEL_IDENTITIES_FROM, liveSignInIdentities, LIVE_CHANNEL_IDENTITY, LIVE_CHANNEL_RECORD, makeIdentityWriter, NEON_AUTH_PROVIDER, OIDC_PROVIDER, SIGN_IN_ORIGIN_SQL, USER_IDENTITY_TABLE, userIdentitiesAvailable, userOfAccount, } from "./user-identities.js";
@@ -148,8 +149,9 @@ export function rolesOf(ontology, sql, user) {
148
149
  function principalState(ontology, sql, user) {
149
150
  return Effect.gen(function* () {
150
151
  const stored = yield* storedRoles(sql, user.id);
151
- // Ignore forged or historical stored assignments: reporter authority is never persisted.
152
- const assigned = stored.roles.filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE);
152
+ // Ignore forged or historical stored assignments: reporter authority is never persisted, and
153
+ // the guests' role is never a user's.
154
+ const assigned = stored.roles.filter((role) => toSnakeCase(role) !== FEEDBACK_REPORTER_ROLE && !isGuestRole(ontology, role));
153
155
  const roles = user.kind === "member" && stored.signedUp
154
156
  ? assigned.filter((role) => role !== MEMBER_ROLE)
155
157
  : user.kind === "member"
@@ -838,7 +840,7 @@ export function revokeApiKey(input) {
838
840
  /** Replaces a user's roles inside the caller's transaction, failing on a role the ontology lacks. */
839
841
  function writeUserRoles(ontology, sql, input) {
840
842
  return Effect.gen(function* () {
841
- const known = new Set(ontology.roles.map((candidate) => candidate.name));
843
+ const known = new Set(userRoleNames(ontology));
842
844
  const unknown = input.roles.find((role) => toSnakeCase(role) === FEEDBACK_REPORTER_ROLE || !known.has(role));
843
845
  if (unknown !== undefined) {
844
846
  return yield* new UnknownRole({
@@ -1228,7 +1230,7 @@ export function updateMemberRoles(ontology, change) {
1228
1230
  const key = "id" in change ? { id: change.id } : { email: normalizeEmail(change.email) };
1229
1231
  const grant = change.grant === undefined ? undefined : [...new Set(change.grant)];
1230
1232
  const revoke = change.revoke === "all" ? "all" : [...new Set(change.revoke ?? [])];
1231
- const declared = ontology.roles.map((candidate) => candidate.name);
1233
+ const declared = userRoleNames(ontology);
1232
1234
  // Refused before anything is read, whoever the member is.
1233
1235
  yield* requireGrantable(declared, grant ?? []);
1234
1236
  yield* refuseMember(revoke === "all" ? [] : revoke);
@@ -9,7 +9,7 @@ import { attachmentRuntime } from "../storage/attachments.js";
9
9
  import { blobRuntime } from "../storage/sessions.js";
10
10
  import { FileAccess, unavailableFiles } from "../storage/file-access.js";
11
11
  import { validateDeploymentStorage } from "../storage/provider.js";
12
- import { readCatalog } from "../migrate/apply.js";
12
+ import { readCatalogHash } from "../migrate/apply.js";
13
13
  import { RuntimeDeployment } from "./deployment.js";
14
14
  import { NotInvited, OntologyBackend, } from "../service/runtime-contract.js";
15
15
  import { WorkflowRecoveryUnavailable } from "./errors.js";
@@ -228,7 +228,7 @@ export function backendLayer(ontology, blobStorage, workflowStarter, deployment,
228
228
  : withSql(checkSignIn(ontology, email)),
229
229
  resolveApiKey: (key) => withSql(resolvePrincipalByApiKey(ontology, Redacted.value(key))).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("api_key"))),
230
230
  resolveApiKeyCredential: (key) => withSql(resolveApiKeyCredential(ontology, Redacted.value(key))).pipe(Effect.catchTag("PrincipalRejected", rejectedAs("api_key"))),
231
- appliedHash: readCatalog({ sql }).pipe(Effect.map((manifest) => manifest?.hash), Effect.orDie),
231
+ appliedHash: readCatalogHash({ sql }).pipe(Effect.orDie),
232
232
  replicationEnabled: Effect.gen(function* () {
233
233
  const [presence] = yield* sql.unsafe("SELECT to_regclass('_ontology_replication') IS NOT NULL AS present");
234
234
  if (!presence?.present) {
@@ -13,6 +13,7 @@ import { InvalidQuery, UndeclaredWrite, UnknownRole, WriteOutsideAction } from "
13
13
  import { grantMemberRoles, inviteMember, queueSignInEmail, revokeMemberRoles, setMemberActive, } from "./member-writes.js";
14
14
  import { entityModel, ontologyModel } from "./model.js";
15
15
  import { loadRecord, notFound, readHistory, relatedCondition, runQuery, validateQuery, } from "./reads.js";
16
+ import { userRoleNames } from "./guests.js";
16
17
  import { createRecord, deleteRecord, linkRecords, unlinkRecords, updateRecord, upsertRecord, } from "./writes.js";
17
18
  import { readScopeOf } from "./where.js";
18
19
  /** A handler wrote an entity its action's `writes` does not list. */
@@ -274,7 +275,7 @@ export function makeOntologyRuntime(ontology, sql, scope) {
274
275
  const identityAction = (action, operation) => scope?.action === action && scope.principalId !== null
275
276
  ? operation(scope)
276
277
  : Effect.die(new Error(`Sign-in identities change only through ${action}, never in another action.`));
277
- const declaredRoles = ontology.roles.map((candidate) => candidate.name);
278
+ const declaredRoles = userRoleNames(ontology);
278
279
  const memberWrite = (operation) => write(User.name, (writeContext, entity) => operation({ ...writeContext, sql, roles: declaredRoles }, entity));
279
280
  const members = {
280
281
  grantRoles: (input) => memberWrite((context, entity) => grantMemberRoles(context, entity, input)).pipe(Effect.catchTag("Conflict", (error) => Effect.die(error))),
package/dist/runtime.d.ts CHANGED
@@ -18,9 +18,17 @@ export interface Principal {
18
18
  };
19
19
  /** Verified authentication mechanism for this request; action contexts always expose it. */
20
20
  readonly authenticatedVia?: string;
21
- /** The id of the principal's `user` record. */
21
+ /**
22
+ * The id of the principal's `user` record. A guest has none: theirs is the id of their session,
23
+ * which names no user, so records they change are created and updated by nobody.
24
+ */
22
25
  readonly id: string;
23
- readonly kind: "member" | "service";
26
+ /**
27
+ * `member`, a person's user; `service`, a service's user, such as an API key's or a workflow's;
28
+ * `guest`, a visitor of a website the ontology's `guest` names, who is no user and holds the
29
+ * built-in role `guest` alone.
30
+ */
31
+ readonly kind: "member" | "service" | "guest";
24
32
  /** Role names the principal holds. Every active member holds `member`. */
25
33
  readonly roles: ReadonlyArray<string>;
26
34
  /**
@@ -28,8 +28,10 @@ export declare function authenticateAgentCaller(input: {
28
28
  readonly response?: undefined;
29
29
  }, never, RequestId | HttpServerRequest.ParsedSearchParams>;
30
30
  /**
31
- * The member the agent acts for on the web: the OAuth grant behind the agent token they showed
32
- * names them and stands, and they are active. `undefined` on a store without web grants.
31
+ * Whom the agent acts for on the web: the member the OAuth grant behind the agent token they showed
32
+ * names, while it stands and they are active; or, for `guest:<id>`, the guest whose grant, which
33
+ * names no user, has that id, while it stands and the ontology admits guests. `undefined` on a
34
+ * store without web grants. A guest is admitted only where the caller says so.
33
35
  */
34
36
  export declare function webMember(agents: AgentStore, userId: string, grantId: string): Effect.Effect<Principal | undefined>;
35
37
  /**
@@ -80,7 +82,7 @@ export declare function delegatedAgentMember(request: HttpServerRequest.HttpServ
80
82
  readonly subject: string;
81
83
  };
82
84
  id: string;
83
- kind: "member" | "service";
85
+ kind: "member" | "service" | "guest";
84
86
  roles: ReadonlyArray<string>;
85
87
  permissions: ReadonlyArray<string>;
86
88
  scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
@@ -108,7 +110,7 @@ export declare function delegatedAccount(agents: AgentStore, actAs: string, prov
108
110
  readonly subject: string;
109
111
  };
110
112
  id: string;
111
- kind: "member" | "service";
113
+ kind: "member" | "service" | "guest";
112
114
  roles: ReadonlyArray<string>;
113
115
  permissions: ReadonlyArray<string>;
114
116
  scopes?: ReadonlyArray<import("../../permissions.js").ScopedPermission>;
@@ -3,6 +3,7 @@ import { HttpServerRequest } from "effect/unstable/http";
3
3
  import { HttpApiBuilder, HttpApiSecurity } from "effect/unstable/httpapi";
4
4
  import { RequestId, forbidden, notFound, toServerResponse, unauthorized, unavailable, } from "../errors.js";
5
5
  import { API_KEY_PREFIX } from "../../runtime/principals.js";
6
+ import { GUEST_ACT_AS_PREFIX, actingGuestId } from "../../runtime/guests.js";
6
7
  import { ACT_AS_HEADER, ACT_AS_PROVIDER_HEADER, AGENT_GRANT_HEADER, AGENT_TASK_HEADER, WEB_PROVIDER, agentTaskSecret, logRuntimeRejection, } from "../runtime-identity.js";
7
8
  export const CHAT_HEADER = "x-segmentstream-agent-chat";
8
9
  export const SESSION_HEADER = "x-segmentstream-agent-session";
@@ -49,17 +50,31 @@ export function authenticateAgentCaller(input) {
49
50
  ? notFound(requestId, "Attachment not found.")
50
51
  : forbidden(requestId, "The member is inactive or has not paired with the agent."));
51
52
  }
53
+ // Attachments, member files and the workspace's code are a member's; a guest has none.
54
+ if (member.kind === "guest") {
55
+ return denied(forbidden(requestId, "A guest has no attachments or files."));
56
+ }
52
57
  return agentCaller(request, requestId, member);
53
58
  });
54
59
  }
55
60
  /**
56
- * The member the agent acts for on the web: the OAuth grant behind the agent token they showed
57
- * names them and stands, and they are active. `undefined` on a store without web grants.
61
+ * Whom the agent acts for on the web: the member the OAuth grant behind the agent token they showed
62
+ * names, while it stands and they are active; or, for `guest:<id>`, the guest whose grant, which
63
+ * names no user, has that id, while it stands and the ontology admits guests. `undefined` on a
64
+ * store without web grants. A guest is admitted only where the caller says so.
58
65
  */
59
66
  export function webMember(agents, userId, grantId) {
60
- return agents.web === undefined
61
- ? Effect.succeed(undefined)
62
- : Effect.map(agents.web.grantMember({ grantId, userId }), (member) => member === undefined ? undefined : { ...member, authenticatedVia: WEB_PROVIDER });
67
+ const web = agents.web;
68
+ if (web === undefined) {
69
+ return Effect.succeed(undefined);
70
+ }
71
+ if (userId.startsWith(GUEST_ACT_AS_PREFIX)) {
72
+ const guestId = actingGuestId(userId);
73
+ return guestId === undefined || guestId !== grantId || web.grantGuest === undefined
74
+ ? Effect.succeed(undefined)
75
+ : web.grantGuest(grantId);
76
+ }
77
+ return Effect.map(web.grantMember({ grantId, userId }), (member) => member === undefined ? undefined : { ...member, authenticatedVia: WEB_PROVIDER });
63
78
  }
64
79
  /**
65
80
  * The member the runtime acts for: a web member by the grant their agent token stands for, anyone
@@ -25,6 +25,22 @@ export declare const PairingRequest: Schema.Struct<{
25
25
  readonly external_id: Schema.String;
26
26
  readonly display: Schema.optionalKey<Schema.NullOr<Schema.String>>;
27
27
  }>;
28
+ /**
29
+ * The agent's limits, as it sends them with a turn: each can only lower the platform's ceiling.
30
+ * `guest` limits guests' turns, apart from those of people who signed up.
31
+ */
32
+ export declare const AgentLimitsRequest: Schema.Struct<{
33
+ readonly perSender: Schema.optionalKey<Schema.Struct<{
34
+ readonly turnsPerMinute: Schema.optionalKey<Schema.Int>;
35
+ readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
36
+ }>>;
37
+ readonly newUsersPerHour: Schema.optionalKey<Schema.Int>;
38
+ readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
39
+ readonly guest: Schema.optionalKey<Schema.Struct<{
40
+ readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
41
+ readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
42
+ }>>;
43
+ }>;
28
44
  export declare const ResolveIdentityRequest: Schema.Struct<{
29
45
  readonly chat: Schema.Literals<readonly ["private", "group"]>;
30
46
  readonly turn: Schema.Boolean;
@@ -39,6 +55,10 @@ export declare const ResolveIdentityRequest: Schema.Struct<{
39
55
  }>>;
40
56
  readonly newUsersPerHour: Schema.optionalKey<Schema.Int>;
41
57
  readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
58
+ readonly guest: Schema.optionalKey<Schema.Struct<{
59
+ readonly turnsPerDay: Schema.optionalKey<Schema.Int>;
60
+ readonly workspaceTurnsPerDay: Schema.optionalKey<Schema.Int>;
61
+ }>>;
42
62
  }>>;
43
63
  readonly provider: Schema.String;
44
64
  readonly external_id: Schema.String;
@@ -96,14 +116,20 @@ export declare function identityForWire(identity: AgentIdentity): {
96
116
  external_id: string;
97
117
  display: string | null;
98
118
  };
99
- /** The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers. */
119
+ /** Which of the agent's own tools a caller holds: `agentToolsOf` over the ontology's roles. */
120
+ export type AgentToolsOf = (principal: Principal) => ReadonlyArray<string>;
121
+ /**
122
+ * The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers: their
123
+ * roles, and in `agent_tools` the agent's own tools those roles grant, such as `sandbox`.
124
+ */
100
125
  export declare function memberForWire(input: {
101
126
  readonly name: string;
102
127
  readonly principal: Principal;
103
- }): {
128
+ }, agentTools: AgentToolsOf): {
104
129
  user: {
105
130
  id: string;
106
131
  name: string;
107
132
  };
108
133
  roles: readonly string[];
134
+ agent_tools: readonly string[];
109
135
  };
@@ -42,6 +42,22 @@ export const PairingRequest = Schema.Struct({
42
42
  });
43
43
  /** Trusted runtime resolution: channel admission and limits run before expensive processing. */
44
44
  const PositiveLimit = Schema.Int.check(Schema.isGreaterThan(0), Schema.isLessThanOrEqualTo(1_000_000_000));
45
+ /**
46
+ * The agent's limits, as it sends them with a turn: each can only lower the platform's ceiling.
47
+ * `guest` limits guests' turns, apart from those of people who signed up.
48
+ */
49
+ export const AgentLimitsRequest = Schema.Struct({
50
+ perSender: Schema.optionalKey(Schema.Struct({
51
+ turnsPerMinute: Schema.optionalKey(PositiveLimit),
52
+ turnsPerDay: Schema.optionalKey(PositiveLimit),
53
+ })),
54
+ newUsersPerHour: Schema.optionalKey(PositiveLimit),
55
+ workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
56
+ guest: Schema.optionalKey(Schema.Struct({
57
+ turnsPerDay: Schema.optionalKey(PositiveLimit),
58
+ workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
59
+ })),
60
+ });
45
61
  export const ResolveIdentityRequest = Schema.Struct({
46
62
  ...PairingRequest.fields,
47
63
  chat: Schema.Literals(["private", "group"]),
@@ -53,14 +69,7 @@ export const ResolveIdentityRequest = Schema.Struct({
53
69
  description: "Whether the receiving server proved the sender's address, as DMARC does for mail. An " +
54
70
  "email account is admitted only when it is.",
55
71
  }),
56
- limits: Schema.optionalKey(Schema.Struct({
57
- perSender: Schema.optionalKey(Schema.Struct({
58
- turnsPerMinute: Schema.optionalKey(PositiveLimit),
59
- turnsPerDay: Schema.optionalKey(PositiveLimit),
60
- })),
61
- newUsersPerHour: Schema.optionalKey(PositiveLimit),
62
- workspaceTurnsPerDay: Schema.optionalKey(PositiveLimit),
63
- })),
72
+ limits: Schema.optionalKey(AgentLimitsRequest),
64
73
  });
65
74
  export const IdentityNoticeRequest = Schema.Struct({
66
75
  provider: Provider,
@@ -142,10 +151,14 @@ export function identityForWire(identity) {
142
151
  created_at: identity.createdAt.toISOString(),
143
152
  };
144
153
  }
145
- /** The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers. */
146
- export function memberForWire(input) {
154
+ /**
155
+ * The member the agent acts for, as `GET …/identities/{provider}/{external_id}` answers: their
156
+ * roles, and in `agent_tools` the agent's own tools those roles grant, such as `sandbox`.
157
+ */
158
+ export function memberForWire(input, agentTools) {
147
159
  return {
148
160
  user: { id: input.principal.id, name: input.name },
149
161
  roles: input.principal.roles,
162
+ agent_tools: agentTools(input.principal),
150
163
  };
151
164
  }
@@ -5,6 +5,8 @@ import { RequestId } from "../errors.js";
5
5
  import { type RateLimit } from "../rate-limit.js";
6
6
  import { OntologyBackend } from "../runtime-contract.js";
7
7
  import { type RuntimeTokenVerifier } from "../runtime-identity.js";
8
+ import { type AgentToolsOf } from "./protocol.js";
9
+ import { type VisitorWebsites } from "./web-tokens.js";
8
10
  /** The agent's endpoints, under the ontology service's path. */
9
11
  export declare const AGENT_PATH = "/api/ontology/agent";
10
12
  /** Where a signed-in member gets an agent token, and where the agent asks whom one stands for. */
@@ -19,11 +21,16 @@ export declare const AGENT_VISITORS_PATH = "/api/ontology/agent/visitors";
19
21
  export declare const PAIRING_LIMIT: RateLimit;
20
22
  export interface AgentServerOptions {
21
23
  readonly verifyToken: TokenVerifier;
22
- /** The websites whose visitors may sign up on `web`, by origin; none while `web` is closed. */
23
- readonly visitorOrigins?: ReadonlyArray<string>;
24
+ /**
25
+ * The websites whose visitors get an agent token: as guests, and, while `web` is open to sign-up,
26
+ * by signing up. None by default.
27
+ */
28
+ readonly visitorWebsites?: VisitorWebsites;
24
29
  /** The deployment's runtime tokens; `undefined` while runtime authentication is disabled. */
25
30
  readonly verifyRuntime: RuntimeTokenVerifier | undefined;
26
31
  readonly exchangeSession: SessionExchange | undefined;
32
+ /** The agent's own tools a caller holds, which every answer naming whom the agent acts for carries. */
33
+ readonly agentTools: AgentToolsOf;
27
34
  }
28
35
  /**
29
36
  * The routes that pair channel accounts with members for the app's own agent, and record the group
@@ -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>;