@opengeni/api-router 3.2.2 → 3.3.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.
@@ -1,6 +1,8 @@
1
1
  import {
2
2
  InsightsCallsResponse,
3
3
  InsightsUsageResponse,
4
+ InsightsSiteUsageQuery,
5
+ InsightsSiteUsageResponse,
4
6
  OrganizationInsightsCallsQuery,
5
7
  OrganizationInsightsUsageQuery,
6
8
  WorkspaceInsightsCallsQuery,
@@ -10,10 +12,12 @@ import type { AccessContext } from "@opengeni/contracts";
10
12
  import {
11
13
  accountScopedApiKeyWorkspaceAuthority,
12
14
  getInsightsUsage,
15
+ getInsightsSiteUsage,
13
16
  hasPermission,
14
17
  listInsightsCalls,
15
18
  requireAccessContext,
16
19
  requireAccessGrant,
20
+ siteViewerForGrant,
17
21
  type ApiRouteDeps,
18
22
  type InsightsQueryScope,
19
23
  } from "@opengeni/core";
@@ -221,6 +225,24 @@ export function registerInsightsUsageRoutes(app: Hono, deps: ApiRouteDeps): void
221
225
  });
222
226
  }
223
227
 
228
+ app.get("/v1/workspaces/:workspaceId/insights/sites", async (c) => {
229
+ const workspaceId = c.req.param("workspaceId");
230
+ const grant = await requireAccessGrant(c, deps, workspaceId, "workspace:admin");
231
+ const query = InsightsSiteUsageQuery.safeParse(insightsQueryParameters(c.req.queries()));
232
+ if (!query.success) throw new HTTPException(400, { message: "invalid Site Insights query" });
233
+ const viewer = await siteViewerForGrant(deps.db, grant);
234
+ const response = await insightsWithFriendlyTimeout(() =>
235
+ getInsightsSiteUsage(deps.db, {
236
+ accountId: grant.accountId,
237
+ workspaceId,
238
+ query: query.data,
239
+ viewerSubjectId: viewer.subjectId,
240
+ }),
241
+ );
242
+ c.header("cache-control", "private, no-store");
243
+ return c.json(InsightsSiteUsageResponse.parse(response));
244
+ });
245
+
224
246
  app.get("/v1/workspaces/:workspaceId/insights/usage", async (c) => {
225
247
  const workspaceId = c.req.param("workspaceId");
226
248
  const grant = await requireAccessGrant(c, deps, workspaceId, "workspace:admin");
@@ -30,7 +30,12 @@ import {
30
30
  SITE_FRAME_SESSION_CREATE_FIELDS,
31
31
  siteFrameBodyRefusal,
32
32
  } from "@opengeni/contracts/site-session-http";
33
- import { requireWorkspace, scheduledSessionIds } from "@opengeni/db";
33
+ import {
34
+ requireWorkspace,
35
+ scheduledSessionIds,
36
+ currentSiteViewerRlsContext,
37
+ nestedPostgresSqlState,
38
+ } from "@opengeni/db";
34
39
  import {
35
40
  currentSiteSessionOrigin,
36
41
  isVerifiedDelegatedHumanAuthorization,
@@ -329,6 +334,7 @@ import {
329
334
  } from "@opengeni/core";
330
335
  import type { ApiRouteDeps } from "@opengeni/core";
331
336
  import { SessionRetryConflictError } from "@opengeni/db";
337
+ import { reauthorizeSiteSessionRequest } from "../site-publishing/session-request-authority";
332
338
  import {
333
339
  attachViewer,
334
340
  detachViewer,
@@ -761,7 +767,7 @@ export function registerSessionRoutes(app: Hono, deps: SessionRouteDeps): void {
761
767
  // nothing else: the session gets the minimal Site profile. Only the Site
762
768
  // itself, running its published agent as `site:<siteId>`, chooses tools.
763
769
  const siteOrigin = origin ?? currentSiteSessionOrigin();
764
- if (siteOrigin && grant.subjectId !== `site:${siteOrigin.siteId}`) {
770
+ if (siteOrigin && currentSiteViewerRlsContext()?.siteId !== siteOrigin.siteId) {
765
771
  const refused = siteFrameBodyRefusal("sessions.create", "/sessions", payload);
766
772
  if (refused)
767
773
  return c.json(
@@ -778,6 +784,11 @@ export function registerSessionRoutes(app: Hono, deps: SessionRouteDeps): void {
778
784
  siteId: siteOrigin.siteId,
779
785
  versionId: siteOrigin.versionId ?? null,
780
786
  });
787
+ // Ordinary Site viewers use native Only-me ownership. An agent preview
788
+ // inherits its parent's native visibility; the Site audience binding
789
+ // additionally restricts that execution to the parent's real owner.
790
+ if (grant.principalKind !== "agent_attempt")
791
+ (payload as Record<string, unknown>).visibility = "private";
781
792
  }
782
793
  const create = () =>
783
794
  createSessionForRequest(deps, grant, workspaceId, payload, authorization);
@@ -3597,6 +3608,7 @@ export function registerSessionRoutes(app: Hono, deps: SessionRouteDeps): void {
3597
3608
  reauthorizeAfterMs:
3598
3609
  authorization?.reauthorizeAfterMs ?? SESSION_AUTHORIZATION_DEFAULT_REAUTHORIZE_MS,
3599
3610
  reauthorize: async () => {
3611
+ await reauthorizeSiteSessionRequest(c.req.raw);
3600
3612
  const freshGrant = await requireFreshAccessGrant(c, deps, workspaceId, "sessions:read");
3601
3613
  await requireSessionAuthorization(deps, freshGrant, {
3602
3614
  sessionId,
@@ -5671,7 +5683,10 @@ export function sessionTenancyHttpError(error: unknown): Error {
5671
5683
  retryable: false,
5672
5684
  });
5673
5685
  }
5674
- if (error instanceof SessionTenancyNotActivatedError) {
5686
+ if (
5687
+ error instanceof SessionTenancyNotActivatedError ||
5688
+ nestedPostgresSqlState(error) === "P0793"
5689
+ ) {
5675
5690
  return new ApiHttpError(409, {
5676
5691
  code: "conflict",
5677
5692
  message: "Only-me chats are not enabled for this organization.",
@@ -6552,7 +6567,10 @@ export function sessionCreateErrorResponse(c: Context, error: unknown): Response
6552
6567
  403,
6553
6568
  );
6554
6569
  }
6555
- if (error instanceof SessionTenancyNotActivatedError) {
6570
+ if (
6571
+ error instanceof SessionTenancyNotActivatedError ||
6572
+ nestedPostgresSqlState(error) === "P0793"
6573
+ ) {
6556
6574
  return c.json(
6557
6575
  {
6558
6576
  code: "SESSION_TENANCY_NOT_ACTIVATED",
@@ -1,5 +1,8 @@
1
1
  import { createHash, randomBytes, randomUUID, timingSafeEqual } from "node:crypto";
2
2
  import {
3
+ ReasoningEffort,
4
+ LatencyMode,
5
+ permissionsRequiredByFirstPartyTools,
3
6
  DeleteSessionQueueItemRequest,
4
7
  EditSessionQueueItemRequest,
5
8
  matchSiteOperation,
@@ -30,6 +33,7 @@ import {
30
33
  type ToolRef,
31
34
  } from "@opengeni/contracts";
32
35
  import {
36
+ cancelPublishedSiteSession,
33
37
  withHostSessionUsageLimit,
34
38
  withSiteSessionOrigin,
35
39
  admissibleWorkspaceModel,
@@ -42,6 +46,7 @@ import {
42
46
  consumeSiteAuthCode,
43
47
  finishSiteRuntimeAdmission,
44
48
  withSiteRuntimeAdmission,
49
+ withSiteViewerRlsContext,
45
50
  createSiteAbuseReport,
46
51
  getSiteWorkspaceMemberPermissions,
47
52
  readSitePlatformUsage,
@@ -65,7 +70,6 @@ import {
65
70
  type SiteRuntimeConversationRecord,
66
71
  } from "@opengeni/db";
67
72
  import {
68
- SITE_AGENT_DATA_TOOL_PERMISSIONS,
69
73
  siteAgentDataToolsForStart,
70
74
  siteAgentInstructions,
71
75
  sitePublishedDataViewer,
@@ -145,7 +149,7 @@ import {
145
149
  configuredSitesDomain,
146
150
  healSiteEdgeIfStale,
147
151
  notifySiteAbuse,
148
- setSitePublishingDispatch,
152
+ setSitePublishingCancellation,
149
153
  siteHostMapRecord,
150
154
  sitePublishingError,
151
155
  } from "../site-publishing/service";
@@ -212,6 +216,9 @@ const CreateConversationRequest = z
212
216
  .object({
213
217
  initialMessage: z.string().trim().min(1).max(MESSAGE_MAX_CHARS),
214
218
  idempotencyKey: z.string().min(1).max(200).optional(),
219
+ model: z.string().min(1).optional(),
220
+ reasoningEffort: ReasoningEffort.optional(),
221
+ latencyMode: LatencyMode.optional(),
215
222
  })
216
223
  .passthrough();
217
224
  const SendMessageRequest = z
@@ -497,8 +504,8 @@ type RuntimeRequest = {
497
504
  export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
498
505
  const dispatch = async (request: Request): Promise<Response> =>
499
506
  await app.fetch(markLocalInternalDispatch(request));
500
- // Publication changes cancel a Site's conversations through this dispatch.
501
- setSitePublishingDispatch(deps.settings, dispatch);
507
+ // Lifecycle cancellation is a native internal command, never viewer dispatch.
508
+ setSitePublishingCancellation(deps.settings, (input) => cancelPublishedSiteSession(deps, input));
502
509
 
503
510
  const handler = async (context: Context): Promise<Response> => {
504
511
  const domain = configuredSitesDomain(deps.settings);
@@ -1232,7 +1239,7 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1232
1239
  throw unsupported();
1233
1240
  };
1234
1241
 
1235
- /** The viewer's own agent conversations on this Site, run as `site:<siteId>`. */
1242
+ /** The viewer's own conversations, with native member or viewer-bound outsider authority. */
1236
1243
  const sessions = async (
1237
1244
  request: RuntimeRequest,
1238
1245
  id: string,
@@ -1246,6 +1253,20 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1246
1253
  // carries the Site and version headers the API's Site frame guard
1247
1254
  // validates; sessions and turns it starts record this Site and version.
1248
1255
  const siteOrigin = { siteId: host.site.id, title: host.site.title, versionId: host.versionId };
1256
+ const reauthorizeViewer = async () => {
1257
+ const liveHost = await requireServedSiteRuntimeHost(deps, host.domain, request.fields.host);
1258
+ const liveViewer = await resolveSiteRuntimeViewer(deps, liveHost, request.fields);
1259
+ if (
1260
+ liveHost.site.id !== host.site.id ||
1261
+ liveViewer.principal !== viewer.principal ||
1262
+ liveViewer.kind !== viewer.kind ||
1263
+ liveViewer.sessionId !== viewer.sessionId
1264
+ )
1265
+ throw siteNotAvailableForViewer(
1266
+ "agent",
1267
+ "This conversation is no longer available to this viewer",
1268
+ );
1269
+ };
1249
1270
  let pendingAdmission: { sessionId: string; admissionId: string } | undefined;
1250
1271
  const send = async (
1251
1272
  method: string,
@@ -1253,16 +1274,20 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1253
1274
  body?: unknown,
1254
1275
  extraPermissions?: readonly Permission[],
1255
1276
  ) => {
1277
+ await reauthorizeViewer();
1256
1278
  const execute = () =>
1257
- withSiteSessionOrigin(siteOrigin, async () =>
1258
- dispatch(
1259
- await siteRuntimeSessionRequest(deps, host, viewer, {
1260
- origin: url.origin,
1261
- method,
1262
- path,
1263
- ...(body === undefined ? {} : { body }),
1264
- ...(extraPermissions ? { extraPermissions } : {}),
1265
- }),
1279
+ withSiteViewerRlsContext({ siteId: host.site.id, principal: viewer.principal }, () =>
1280
+ withSiteSessionOrigin(siteOrigin, async () =>
1281
+ dispatch(
1282
+ await siteRuntimeSessionRequest(deps, host, viewer, {
1283
+ origin: url.origin,
1284
+ method,
1285
+ path,
1286
+ reauthorize: reauthorizeViewer,
1287
+ ...(body === undefined ? {} : { body }),
1288
+ ...(extraPermissions ? { extraPermissions } : {}),
1289
+ }),
1290
+ ),
1266
1291
  ),
1267
1292
  );
1268
1293
  const pending = pendingAdmission;
@@ -1344,6 +1369,11 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1344
1369
  if (viewer.kind === "guest" || viewer.kind === "user")
1345
1370
  await requireSitePlatformOpen(deps, "guest_agent");
1346
1371
  const models = await siteViewerModels(host, viewer, limits);
1372
+ if (input.model && !models.allowed.includes(input.model))
1373
+ throw siteNotAvailableForViewer(
1374
+ "agent_model",
1375
+ "This model is not available to you on this Site",
1376
+ );
1347
1377
  if (models.unavailable)
1348
1378
  throw siteNotAvailableForViewer(
1349
1379
  "agent_model",
@@ -1402,6 +1432,11 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1402
1432
  }
1403
1433
  }
1404
1434
  // Settle the viewer's recent spend so the day budget sees it.
1435
+ if (!repair && viewer.kind !== "member" && deps.settings.privacyOnlyMeAllowed === false)
1436
+ throw siteNotAvailableForViewer(
1437
+ "private_conversations",
1438
+ "Private Site conversations are disabled by this deployment",
1439
+ );
1405
1440
  for (const conversation of await listOwnedSiteRuntimeConversations(deps.db, host.scope, {
1406
1441
  siteId: host.site.id,
1407
1442
  viewerPrincipal: viewer.principal,
@@ -1455,7 +1490,9 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1455
1490
  host.scope,
1456
1491
  host.site.id,
1457
1492
  viewer.kind,
1493
+ viewer.kind === "member" ? (memberPermissions ?? []) : undefined,
1458
1494
  );
1495
+ const dataToolPermissions = permissionsRequiredByFirstPartyTools(dataTools);
1459
1496
  // One transaction counts the start and reserves a per-turn estimate
1460
1497
  // against the visitor's and the Site's windows; only the funded allowance
1461
1498
  // becomes the session's usage limit, set in the create transaction. The
@@ -1491,15 +1528,14 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1491
1528
  const body = {
1492
1529
  initialMessage: input.initialMessage,
1493
1530
  requestedSessionId,
1531
+ ...(viewer.kind === "member" ? { visibility: "private" } : {}),
1494
1532
  startMode: "standard",
1495
1533
  agentAccess: "session",
1496
1534
  memoryScope: "off",
1497
1535
  rigId: null,
1498
1536
  // Only this Site's data tools; never management or workspace tools.
1499
1537
  firstPartyMcpTools: dataTools,
1500
- ...(dataTools.length > 0
1501
- ? { firstPartyMcpPermissions: [...SITE_AGENT_DATA_TOOL_PERMISSIONS] }
1502
- : {}),
1538
+ ...(dataTools.length > 0 ? { firstPartyMcpPermissions: dataToolPermissions } : {}),
1503
1539
  agent: {
1504
1540
  capabilities: {
1505
1541
  from: "none",
@@ -1511,7 +1547,13 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1511
1547
  // No sandbox: a Site's agent answers from the page and the Site's
1512
1548
  // data, with no shell or workspace files.
1513
1549
  sandboxBackend: "none",
1514
- ...(repair ? { model: repair.model } : models.default ? { model: models.default } : {}),
1550
+ ...(repair
1551
+ ? { model: repair.model }
1552
+ : input.model || models.default
1553
+ ? { model: input.model ?? models.default }
1554
+ : {}),
1555
+ ...(input.reasoningEffort === undefined ? {} : { reasoningEffort: input.reasoningEffort }),
1556
+ ...(input.latencyMode === undefined ? {} : { latencyMode: input.latencyMode }),
1515
1557
  instructions: siteAgentInstructions(host, viewer, dataTools, agent.instructions),
1516
1558
  // Always explicit: an empty list means no workspace tools at all.
1517
1559
  tools: mcpTools,
@@ -1525,8 +1567,7 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1525
1567
  },
1526
1568
  ...(input.idempotencyKey ? { idempotencyKey: `site-runtime:${requestedSessionId}` } : {}),
1527
1569
  };
1528
- const start = () =>
1529
- send("POST", base, body, dataTools.length > 0 ? SITE_AGENT_DATA_TOOL_PERMISSIONS : []);
1570
+ const start = () => send("POST", base, body, dataToolPermissions);
1530
1571
  // Workspace members get no Site budget at all: their conversation is an
1531
1572
  // ordinary session under the workspace's normal limits, so no session
1532
1573
  // usage limit is stamped on it, whatever the Site's limits say.
@@ -1694,6 +1735,7 @@ export function registerSiteRuntimeRoutes(app: Hono, deps: ApiRouteDeps): void {
1694
1735
  viewer,
1695
1736
  conversation.sessionId,
1696
1737
  conversation.toolIds,
1738
+ viewer.kind === "member" ? (memberPermissions ?? []) : undefined,
1697
1739
  );
1698
1740
  const usage = await settleSiteRuntimeSpend(deps, host, conversation);
1699
1741
  // Clear the stamped session cap before dropping the durable conversation
@@ -43,6 +43,7 @@ import {
43
43
  SandboxPaidComputeAdmissionError,
44
44
  withSandboxProviderReadLock,
45
45
  type Database,
46
+ type EnrollmentRecord,
46
47
  type LeaseSnapshot,
47
48
  } from "@opengeni/db";
48
49
  import { appendAndPublishEvents, type EventBus } from "@opengeni/events";
@@ -207,6 +208,15 @@ export type ChannelAHandle = {
207
208
  * who started an agent's turn, or the calling person. Routes that look up
208
209
  * the routed machine again must use it rather than the raw caller grant. */
209
210
  machineAuthority: () => Promise<ChannelAMachineAuthority>;
211
+ /** For a machine-home request, the Connected Machine and live runner this
212
+ * request was pinned to under `machineAuthority`. The routing session fails
213
+ * rather than follow a changed pointer, so a route that resolved this same
214
+ * sandbox can use it instead of looking the machine up again. */
215
+ pinnedMachine: {
216
+ sandboxId: string;
217
+ sandboxWorkspaceId: string;
218
+ enrollment: EnrollmentRecord;
219
+ } | null;
210
220
  requestId: string;
211
221
  };
212
222
 
@@ -629,6 +639,7 @@ async function withChannelAOperation<T>(
629
639
  routed: EstablishedSandboxSession,
630
640
  lease: LeaseSnapshot | null,
631
641
  homeSession: ChannelASession,
642
+ pinnedMachine: ChannelAHandle["pinnedMachine"] = null,
632
643
  ): Promise<T> => {
633
644
  const emit = async (events: { type: string; payload: unknown }[]): Promise<void> => {
634
645
  await appendAndPublishEvents(
@@ -667,6 +678,7 @@ async function withChannelAOperation<T>(
667
678
  homeSession,
668
679
  routingSession,
669
680
  machineAuthority,
681
+ pinnedMachine,
670
682
  requestId,
671
683
  });
672
684
  // The direct request has accepted the result in memory. Finalize every
@@ -770,6 +782,7 @@ async function withChannelAOperation<T>(
770
782
  enrollment.agentCapabilities.operationResourcePolicy === true,
771
783
  operationCpuQuotaSupported: enrollment.agentCapabilities.operationCpuQuota === true,
772
784
  transactionalFsWriteSupported: enrollment.agentCapabilities.transactionalFsWrite === true,
785
+ browserControlHttpSupported: enrollment.agentCapabilities.browserControlHttp === true,
773
786
  ...(settings.agentOpStreamEnabled === true &&
774
787
  enrollment?.opStream === true &&
775
788
  bus.getOpStreamConnection
@@ -812,7 +825,11 @@ async function withChannelAOperation<T>(
812
825
  },
813
826
  established,
814
827
  );
815
- return await runEstablished(routed, null, established.session as ChannelASession);
828
+ return await runEstablished(routed, null, established.session as ChannelASession, {
829
+ sandboxId: sandbox.id,
830
+ sandboxWorkspaceId: originWorkspaceId,
831
+ enrollment,
832
+ });
816
833
  } catch (error) {
817
834
  observeChannelAOperationFailure(services, {
818
835
  workspaceId,
@@ -843,6 +843,7 @@ export function helloRuntimeCapabilities(hello: Hello): Record<string, boolean>
843
843
  operationCpuQuota: caps.operationCpuQuota === true,
844
844
  transactionalFsWrite: caps.transactionalFsWrite === true,
845
845
  credentialRenew: caps.credentialRenew === true,
846
+ browserControlHttp: caps.browserControlHttp === true,
846
847
  screenControl: caps.consentedScreenControl === true,
847
848
  ...(caps.macPermissions ? enrollmentMacPermissionCapabilities(caps.macPermissions) : {}),
848
849
  };
@@ -11,7 +11,7 @@ import {
11
11
  withSiteSessionOrigin,
12
12
  type ApiRouteDeps,
13
13
  } from "@opengeni/core";
14
- import { getSession } from "@opengeni/db";
14
+ import { getSession, getSessionAuthorityProjection } from "@opengeni/db";
15
15
  import type { Context, Next } from "hono";
16
16
  import { HTTPException } from "hono/http-exception";
17
17
  import { ApiHttpError } from "./http/api-error";
@@ -78,10 +78,19 @@ export function siteFrameGuard(deps: ApiRouteDeps) {
78
78
  throw new HTTPException(404, { message: "Unsupported Site session API path" });
79
79
  }
80
80
  if (match.sessionId !== null) {
81
+ const authority = await getSessionAuthorityProjection(
82
+ deps.db,
83
+ grant.workspaceId,
84
+ match.sessionId,
85
+ );
81
86
  const session = await getSession(deps.db, grant.workspaceId, match.sessionId).catch(
82
87
  () => null,
83
88
  );
84
- if (!session || !siteOriginsMatch(origin, siteSessionOriginFromMetadata(session.metadata)))
89
+ if (
90
+ !authority?.siteAccessRootId ||
91
+ !session ||
92
+ !siteOriginsMatch(origin, siteSessionOriginFromMetadata(session.metadata))
93
+ )
85
94
  throw new HTTPException(404, { message: "session not found" });
86
95
  }
87
96
  if (c.req.method !== "GET" && match.operation.id !== "sessions.create") {
@@ -1,10 +1,12 @@
1
1
  import {
2
2
  siteHostname,
3
+ permissionsRequiredByFirstPartyTools,
3
4
  type FirstPartyMcpToolName,
5
+ type Permission,
4
6
  type SiteLimitProfileKind,
5
7
  } from "@opengeni/contracts";
6
8
  import { resolveFirstPartyMcpToolPolicy } from "@opengeni/config";
7
- import type { ApiRouteDeps } from "@opengeni/core";
9
+ import { hasPermission, type ApiRouteDeps } from "@opengeni/core";
8
10
  import {
9
11
  consumeSiteRuntimeRate,
10
12
  findSiteRuntimeAgentConversation,
@@ -47,12 +49,6 @@ export const SITE_AGENT_MEMBER_SQL_TOOLS = Object.freeze([
47
49
  "site_sql_query",
48
50
  ] as const satisfies readonly FirstPartyMcpToolName[]);
49
51
 
50
- /** The first-party permissions those tools need (Site Data writes need publish). */
51
- export const SITE_AGENT_DATA_TOOL_PERMISSIONS = Object.freeze([
52
- "artifacts:read",
53
- "artifacts:publish",
54
- ] as const);
55
-
56
52
  export const SITE_AGENT_OTHER_SITE_MESSAGE = "This Site's assistant can only use this Site's data";
57
53
  export const SITE_AGENT_MANAGEMENT_MESSAGE =
58
54
  "This Site's assistant can use the Site's data, not manage the Site";
@@ -64,13 +60,23 @@ export function siteAgentDataToolNames(input: {
64
60
  siteSql: boolean;
65
61
  /** The deployment's first-party tool allowlist. */
66
62
  allowed: readonly string[];
63
+ /** Live member ceiling; omitted only where the native caller filters tools itself. */
64
+ memberPermissions?: readonly Permission[];
67
65
  }): FirstPartyMcpToolName[] {
68
66
  const names: FirstPartyMcpToolName[] = [
69
67
  ...SITE_AGENT_DATA_TOOLS,
70
68
  ...(input.siteSql ? SITE_AGENT_SQL_TOOLS : []),
71
69
  ...(input.siteSql && input.viewerKind === "member" ? SITE_AGENT_MEMBER_SQL_TOOLS : []),
72
70
  ];
73
- return names.filter((name) => input.allowed.includes(name));
71
+ return names.filter(
72
+ (name) =>
73
+ input.allowed.includes(name) &&
74
+ (input.viewerKind !== "member" ||
75
+ input.memberPermissions === undefined ||
76
+ permissionsRequiredByFirstPartyTools([name]).every((permission) =>
77
+ hasPermission(input.memberPermissions!, permission),
78
+ )),
79
+ );
74
80
  }
75
81
 
76
82
  /** Whether Site SQL is offered on this deployment and turned on for the Site. */
@@ -90,11 +96,13 @@ export async function siteAgentDataToolsForStart(
90
96
  scope: { accountId: string; workspaceId: string },
91
97
  siteId: string,
92
98
  viewerKind: SiteRuntimeConversationViewerKind,
99
+ memberPermissions?: readonly Permission[],
93
100
  ): Promise<FirstPartyMcpToolName[]> {
94
101
  return siteAgentDataToolNames({
95
102
  viewerKind,
96
103
  siteSql: await siteAgentSiteSqlOn(deps, scope, siteId),
97
104
  allowed: resolveFirstPartyMcpToolPolicy(deps.settings).allowed,
105
+ ...(memberPermissions === undefined ? {} : { memberPermissions }),
98
106
  });
99
107
  }
100
108
 
@@ -1,11 +1,16 @@
1
- import { resolveAgentConfig, type SessionToolPolicy, type ToolRef } from "@opengeni/contracts";
1
+ import {
2
+ permissionsRequiredByFirstPartyTools,
3
+ resolveAgentConfig,
4
+ type Permission,
5
+ type SessionToolPolicy,
6
+ type ToolRef,
7
+ } from "@opengeni/contracts";
2
8
  import { agentConfigDeploymentPolicy, resolveFirstPartyMcpToolPolicy } from "@opengeni/config";
3
9
  import { siteSessionOriginFromMetadata, type ApiRouteDeps } from "@opengeni/core";
4
10
  import { appendSessionEventsWithLockedSessionUpdate, getSiteSqlDatabase } from "@opengeni/db";
5
11
  import { publishDurableSessionEvents } from "@opengeni/events";
6
12
  import {
7
13
  resolveSiteAgentDataContext,
8
- SITE_AGENT_DATA_TOOL_PERMISSIONS,
9
14
  siteAgentDataToolNames,
10
15
  siteAgentInstructions,
11
16
  } from "./agent-data-tools";
@@ -14,7 +19,7 @@ import type { SiteRuntimeViewer } from "./viewer";
14
19
  import { sitePublishingError } from "./service";
15
20
  import { siteSqlOffered } from "../site-sql/gateway";
16
21
 
17
- export const SITE_AGENT_DEFAULTS_VERSION = 1;
22
+ export const SITE_AGENT_DEFAULTS_VERSION = 2;
18
23
 
19
24
  /**
20
25
  * Before admitting more work, converge pre-redesign published-host sessions to
@@ -33,6 +38,7 @@ export async function normalizeSiteAgentSession(
33
38
  viewer: SiteRuntimeViewer,
34
39
  sessionId: string,
35
40
  retainedToolIds: readonly string[],
41
+ memberPermissions?: readonly Permission[],
36
42
  ): Promise<void> {
37
43
  const data = await resolveSiteAgentDataContext(deps, host.scope, sessionId);
38
44
  if (
@@ -55,7 +61,9 @@ export async function normalizeSiteAgentSession(
55
61
  viewerKind: viewer.kind,
56
62
  siteSql: sqlEnabled,
57
63
  allowed: resolveFirstPartyMcpToolPolicy(deps.settings).allowed,
64
+ ...(memberPermissions === undefined ? {} : { memberPermissions }),
58
65
  });
66
+ const dataToolPermissions = permissionsRequiredByFirstPartyTools(dataTools);
59
67
  const config = resolveAgentConfig({
60
68
  creator: "api",
61
69
  request: {
@@ -83,7 +91,12 @@ export async function normalizeSiteAgentSession(
83
91
  (session) => {
84
92
  if (
85
93
  session.parentSessionId ||
86
- session.createdBy.subjectId !== `site:${host.site.id}` ||
94
+ (session.createdBy.subjectId !== `site:${host.site.id}` &&
95
+ !(
96
+ viewer.kind === "member" &&
97
+ session.createdBy.kind === "subject" &&
98
+ session.createdBy.subjectId === viewer.subjectId
99
+ )) ||
87
100
  siteSessionOriginFromMetadata(session.metadata)?.siteId !== host.site.id
88
101
  )
89
102
  throw sitePublishingError(
@@ -97,7 +110,12 @@ export async function normalizeSiteAgentSession(
97
110
  raw && typeof raw === "object" && !Array.isArray(raw)
98
111
  ? (raw as Record<string, unknown>)
99
112
  : {};
100
- if (stamp.agentDefaultsVersion === SITE_AGENT_DEFAULTS_VERSION) return { events: [] };
113
+ if (
114
+ stamp.agentDefaultsVersion === SITE_AGENT_DEFAULTS_VERSION &&
115
+ session.firstPartyMcpTools.join(",") === dataTools.join(",") &&
116
+ session.firstPartyMcpPermissions?.join(",") === dataToolPermissions.join(",")
117
+ )
118
+ return { events: [] };
101
119
  // Never restore workspace defaults or add a newly declared connector to
102
120
  // an old conversation. Preserve only its still-authorized exact refs.
103
121
  const allowed = new Set(["opengeni", ...retainedToolIds]);
@@ -126,7 +144,7 @@ export async function normalizeSiteAgentSession(
126
144
  ],
127
145
  update: {
128
146
  firstPartyMcpTools: dataTools,
129
- firstPartyMcpPermissions: [...SITE_AGENT_DATA_TOOL_PERMISSIONS],
147
+ firstPartyMcpPermissions: dataToolPermissions,
130
148
  agentConfig: config,
131
149
  instructions,
132
150
  tools,
@@ -9,7 +9,11 @@ import {
9
9
  type SiteLimits,
10
10
  type SiteViewerCapabilities,
11
11
  } from "@opengeni/contracts";
12
- import { sessionUsageLimitsProducerEnabled, type ApiRouteDeps } from "@opengeni/core";
12
+ import {
13
+ sessionUsageLimitsProducerEnabled,
14
+ stampSiteViewerSessionAuthorization,
15
+ type ApiRouteDeps,
16
+ } from "@opengeni/core";
13
17
  import {
14
18
  consumeSiteRuntimeRate,
15
19
  findSiteHostname,
@@ -40,6 +44,7 @@ import {
40
44
  type SiteRuntimeReservation,
41
45
  } from "@opengeni/db";
42
46
  import type { SiteGatewayFields } from "./gateway-signature";
47
+ import { bindSiteSessionRequestAuthority } from "./session-request-authority";
43
48
  import { effectiveSiteLimits, siteViewerLimits, sourceSiteLimitProfile } from "./limits";
44
49
  import {
45
50
  siteLimitInputs,
@@ -59,8 +64,8 @@ import {
59
64
  /**
60
65
  * Site-runtime: the narrow API a Site gateway calls for one published Site
61
66
  * host, after the gateway signature passed. Everything here works for exactly
62
- * one Site: the host names it, the viewer is resolved for it, and the agent
63
- * principal is `site:<siteId>`.
67
+ * one Site: the host names it and the viewer is resolved for it. Members retain
68
+ * their human identity; outsiders use the viewer-bound `site:<siteId>` principal.
64
69
  */
65
70
 
66
71
  export type SiteRuntimeDeps = Pick<ApiRouteDeps, "db" | "settings" | "objectStorage">;
@@ -219,6 +224,7 @@ export async function resolveSiteRuntimeViewer(
219
224
  /** What a viewer cannot do on a Site: 403 with `details.code` `not_available_for_viewer`. */
220
225
  export type SiteViewerFeature =
221
226
  | "agent"
227
+ | "private_conversations"
222
228
  | "agent_model"
223
229
  | "workspace_tools"
224
230
  | "site_data"
@@ -796,9 +802,9 @@ export async function meterSiteRuntime(
796
802
  // --- in-process dispatch ------------------------------------------------------------
797
803
 
798
804
  /**
799
- * Run an ordinary session route in this process as the Site's service
800
- * principal (`site:<siteId>`), with a 60-second delegated token carrying only
801
- * session permissions and the viewer as its display label. The Site and the
805
+ * Run an ordinary session route in this process as the verified member, or
806
+ * the Site service principal for an outsider. The latter uses a 60-second
807
+ * delegated token plus the separate trusted viewer audience. The Site and the
802
808
  * served version ride along as the request's Site origin, so new sessions and
803
809
  * turns record where they came from. The route authorizes as usual.
804
810
  */
@@ -812,14 +818,30 @@ export async function siteRuntimeSessionRequest(
812
818
  path: string;
813
819
  body?: unknown;
814
820
  extraPermissions?: readonly Permission[];
821
+ reauthorize: () => Promise<void>;
815
822
  },
816
823
  ): Promise<Request> {
817
- return await siteServiceSessionRequest(
824
+ const request = await siteServiceSessionRequest(
818
825
  deps,
819
826
  host.scope,
820
827
  { id: host.site.id, versionId: host.versionId },
821
828
  { ...input, label: `${siteRuntimeViewerLabel(viewer)} on ${host.hostname}` },
822
829
  );
830
+ bindSiteSessionRequestAuthority(request, input.reauthorize);
831
+ if (viewer.kind === "member" && viewer.subjectId && viewer.sessionId) {
832
+ // The gateway already verified the host and opaque Site cookie. Native
833
+ // resolution reloads this person's live membership, roles and models.
834
+ // This is delegated ownership, never fabricated managed-cookie proof.
835
+ stampSiteViewerSessionAuthorization(request, {
836
+ organizationId: host.scope.accountId,
837
+ subjectId: viewer.subjectId,
838
+ permissions: [
839
+ ...new Set([...SITE_RUNTIME_AGENT_PERMISSIONS, ...(input.extraPermissions ?? [])]),
840
+ ],
841
+ workspaceId: host.scope.workspaceId,
842
+ });
843
+ }
844
+ return request;
823
845
  }
824
846
 
825
847
  /** A forwarded response without cookies (site-runtime never sets any). */