@opengeni/core 2.0.1 → 2.0.2-canary.38789554071001

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.
@@ -27,7 +27,12 @@ export declare function lockActiveCustomModelForAdmission(db: Database, input: {
27
27
  accountId: string;
28
28
  workspaceId: string;
29
29
  reference: WorkspaceCustomModelReference;
30
- claudeAuthority?: OrganizationClaudeModelAdmissionAuthority;
30
+ /**
31
+ * The accepted Claude authority this admission re-reads. Every caller
32
+ * states it: an organization Claude model is never admitted without it,
33
+ * so an omitted value would refuse that model silently.
34
+ */
35
+ claudeAuthority: OrganizationClaudeModelAdmissionAuthority | null;
31
36
  }): Promise<boolean>;
32
37
  /**
33
38
  * Resolve the deployment catalog without making synchronous env settings read
@@ -118,8 +118,21 @@ export type FleetSwapResult = {
118
118
  activeSandboxId: string | null;
119
119
  activeEpoch: number;
120
120
  reason?: string;
121
- code?: BackendUnresolvableCode | "invalid_working_directory" | "concurrent_swap" | "recovery_in_progress" | "recovery_degraded" | "recovery_unrecoverable";
121
+ code?: BackendUnresolvableCode | "invalid_working_directory" | "concurrent_swap" | PersonalMachineRefusalCode | "recovery_in_progress" | "recovery_degraded" | "recovery_unrecoverable";
122
122
  };
123
+ export type PersonalMachineRefusalCode = "personal_machine_permission_required" | "personal_machine_not_permitted";
124
+ /**
125
+ * Plain refusal for a personal ("Only me") Connected Machine that the database
126
+ * admission (`authorize_session_attempt_personal_machine`) turned down. The
127
+ * function raises SQLSTATE 42501 for policy refusals and P0002 when a required
128
+ * owner, authority or enrollment row is not current. Only failures of that
129
+ * admission statement are mapped; anything else is a real failure and stays an
130
+ * error. The raw database error is never shown.
131
+ */
132
+ export declare function personalMachineRefusal(error: unknown): {
133
+ code: PersonalMachineRefusalCode;
134
+ reason: string;
135
+ } | null;
123
136
  /**
124
137
  * List the fleet: the session's own group box when it has one (a synthetic
125
138
  * entry) + the workspace's first-class selfhosted sandboxes (each probed for
@@ -1,5 +1,5 @@
1
1
  import { type Settings } from "@opengeni/config";
2
- import { type Database, type SandboxRetainedProcess } from "@opengeni/db";
2
+ import { type Database, type EnrollmentRecord, type SandboxRetainedProcess } from "@opengeni/db";
3
3
  import { type EventBus } from "@opengeni/events";
4
4
  import { type EstablishedSandboxSession, type ResolvedActiveBackend, type RoutingRetainedProcess, type RoutingRetainedProcessTerminalProof, type RoutingSandboxOperationObserver, type RoutingSandboxCaptureWaitObserver, type SelfhostedRelayConfig } from "@opengeni/runtime/sandbox";
5
5
  type DirectRetainedProcessRoute = {
@@ -33,6 +33,35 @@ export type ChannelARoutingServices = {
33
33
  onSandboxCaptureWait?: RoutingSandboxCaptureWaitObserver;
34
34
  waitSignal?: AbortSignal;
35
35
  };
36
+ /**
37
+ * Whose access a Channel-A request uses to reach a Connected Machine. A person
38
+ * uses their own. An agent acts for the person who started its turn, never as
39
+ * itself, so it reaches the same machines that person can; a personal (Only me)
40
+ * machine additionally needs that exact running attempt's per-chat permission,
41
+ * rechecked before every routed operation like the worker's turn path.
42
+ */
43
+ export type ChannelAMachineAuthority = {
44
+ subjectId: string;
45
+ personalMachineAttempt: {
46
+ turnId: string;
47
+ attemptId: string;
48
+ executionGeneration: number;
49
+ } | null;
50
+ };
51
+ /**
52
+ * Resolve a Connected Machine's live runner for one Channel-A request. The
53
+ * machine's audience can change in place, so its current scope is read from the
54
+ * enrollment itself. An agent attempt reaches a personal machine only through
55
+ * the same attempt admission as swap and run_on; everything else keeps the
56
+ * caller-scoped lookup.
57
+ */
58
+ export declare function resolveChannelAMachineConnection(db: Database, input: {
59
+ accountId: string;
60
+ workspaceId: string;
61
+ sessionId: string;
62
+ machineWorkspaceId: string;
63
+ enrollmentId: string;
64
+ }, authority: ChannelAMachineAuthority): Promise<EnrollmentRecord | null>;
36
65
  /** Map the deployment relay URL to the leaf's `SelfhostedRelayConfig` shape. The
37
66
  * relay URL (`OPENGENI_SELFHOSTED_RELAY_URL`) may carry a path (the relay's wss
38
67
  * route); a path-less URL defaults to the relay's `/stream` route (M8b). */
@@ -62,6 +91,10 @@ export declare function wrapChannelABoxWithRouting(services: ChannelARoutingServ
62
91
  workspaceId: string;
63
92
  sessionId: string;
64
93
  resourceSubjectId: string;
94
+ /** Whose access reaches Connected Machines (see ChannelAMachineAuthority).
95
+ * Resolved lazily, once, only when a request routes to a machine. Omitted,
96
+ * the request uses `resourceSubjectId`'s own access. */
97
+ machineAuthority?: () => Promise<ChannelAMachineAuthority>;
65
98
  homeLease?: {
66
99
  sandboxGroupId: string;
67
100
  leaseEpoch: number;
@@ -0,0 +1,71 @@
1
+ import type { AccessGrant } from "@opengeni/contracts";
2
+ import { type Database } from "@opengeni/db";
3
+ /**
4
+ * Whether an agent acts for a Site page: its session, a spawning ancestor or
5
+ * its root session was started from a Site (a published Site or an inline or
6
+ * preview frame), or its current or a spawning ancestor turn arrived from one.
7
+ * The same evidence the Site Data agent clamp uses
8
+ * (apps/api/src/site-data/service.ts), plus frame origins without a
9
+ * published Site id.
10
+ */
11
+ export type SiteAgentClamp = {
12
+ clamped: boolean;
13
+ /** Published Sites in the lineage; empty for frames without a published Site. */
14
+ originSiteIds: string[];
15
+ };
16
+ /** Null when the grant is not an agent session. */
17
+ export declare function siteAgentClamp(db: Database, grant: AccessGrant): Promise<SiteAgentClamp | null>;
18
+ /**
19
+ * The Site clamp of an agent running in `sessionId` (and `turnId`, when
20
+ * known). A turn's clamp is computed once a minute at most per process: the
21
+ * evidence it reads (where the session, its ancestors and that turn came
22
+ * from) does not change during the turn. Without a turn id it is always
23
+ * read fresh.
24
+ */
25
+ export declare function siteSessionClamp(db: Database, scope: {
26
+ accountId: string;
27
+ workspaceId: string;
28
+ }, sessionId: string, turnId: string | null): Promise<SiteAgentClamp>;
29
+ /** What a Site-clamped agent may not create or change. */
30
+ export type SiteClampedResource = "schedules" | "automations" | "Site publications" | "workspace instructions" | "Skills" | "Knowledge" | "secrets" | "workspace members, connections or settings" | "the organization profile" | "Connected Machines" | "sandbox environments" | "browser or computer sessions" | "documents, spreadsheets or presentations the Site did not declare" | "workspace settings";
31
+ /** The refusal message for a Site-clamped agent. */
32
+ export declare function siteClampedAgentMessage(what: SiteClampedResource): string;
33
+ /**
34
+ * The refusal when a Site-clamped agent reaches for compute beyond its own
35
+ * session's: `run_on`, attaching, swapping or provisioning a sandbox, or
36
+ * starting a worker on a chosen machine or another session's sandbox.
37
+ */
38
+ export declare const SITE_AGENT_COMPUTE_MESSAGE = "An agent started from a Site page cannot run on, attach, provision or choose sandboxes or Connected Machines";
39
+ /**
40
+ * Refuse a Site-clamped agent's session create that chooses compute: a
41
+ * machine target, a self-hosted backend or another session's sandbox group.
42
+ * Its workers run in its own sandbox (shared) or a new managed one.
43
+ */
44
+ export declare function assertSiteAgentMayChooseCompute(db: Database, grant: AccessGrant, payload: {
45
+ sandbox?: unknown;
46
+ sandboxBackend?: unknown;
47
+ targetSandboxId?: unknown;
48
+ workingDir?: unknown;
49
+ }): Promise<void>;
50
+ /**
51
+ * Refuse a Site-clamped agent: an agent started from a Site page acts with
52
+ * that page's reach and cannot create or change schedules, automations, Site
53
+ * publications, workspace instructions, Skills, Knowledge, secrets,
54
+ * workspace members, connections and settings, the organization profile,
55
+ * Connected Machines, sandbox environments or other workspace settings.
56
+ */
57
+ export declare function assertNotSiteClampedAgent(db: Database, grant: AccessGrant, what: SiteClampedResource): Promise<void>;
58
+ /**
59
+ * Whether an agent running in `caller` may message, steer or control
60
+ * `targetSessionId`. An unclamped agent is not limited here. A Site-clamped
61
+ * agent reaches only sessions that act for the same Site: clamped themselves
62
+ * (its own lineage, or another session the Site started) and naming no
63
+ * published Site the caller does not.
64
+ */
65
+ export declare function siteAgentMayReachSession(db: Database, scope: {
66
+ accountId: string;
67
+ workspaceId: string;
68
+ }, caller: {
69
+ sessionId: string;
70
+ turnId: string | null;
71
+ }, targetSessionId: string): Promise<boolean>;
@@ -1,9 +1,44 @@
1
+ /**
2
+ * Which Site page a request came from. Provenance, plus the key the API uses
3
+ * to keep one Site's pages away from another Site's sessions.
4
+ *
5
+ * A published Site has a `siteId` (and `versionId` when the host pinned one).
6
+ * Inline HTML and Codemode preview frames have no published id: they record
7
+ * `siteId: null`, the `frame` kind and the host-minted `frameId` of the
8
+ * mounted page, so a frame reaches only the sessions it started itself.
9
+ */
1
10
  export type SiteSessionOrigin = {
2
- siteId: string;
11
+ siteId: string | null;
3
12
  title: string;
13
+ versionId?: string;
14
+ frame?: "inline" | "preview";
15
+ frameId?: string;
4
16
  };
5
- /** Request-local provenance, set only after the API validates a published Site version. */
17
+ export declare const SITE_ORIGIN_METADATA_KEY = "_opengeniSiteOrigin";
18
+ /**
19
+ * Request-local provenance, set only after the API validated the Site the
20
+ * request came from (a published Site version the caller can see, or a
21
+ * host-marked inline or preview frame).
22
+ */
6
23
  export declare function withSiteSessionOrigin<T>(origin: SiteSessionOrigin, run: () => T): T;
7
24
  export declare function sessionCreationMetadata(metadata: Record<string, unknown>): Record<string, unknown>;
8
25
  /** The validated Site origin of the current request, if any. Provenance only. */
9
26
  export declare function currentSiteSessionOrigin(): SiteSessionOrigin | undefined;
27
+ /**
28
+ * Replace any caller-supplied Site origin in `metadata` with `origin` (or drop
29
+ * it). Callers never choose their own provenance.
30
+ */
31
+ export declare function withSiteOriginMetadata(metadata: Record<string, unknown>, origin: SiteSessionOrigin | null | undefined): Record<string, unknown>;
32
+ /**
33
+ * Read the recorded Site origin from session (or schedule agent config)
34
+ * metadata. Any object under the key counts as a Site origin, so a malformed
35
+ * record still marks the session as Site-started (fail closed).
36
+ */
37
+ export declare function siteSessionOriginFromMetadata(metadata: Record<string, unknown> | null | undefined): SiteSessionOrigin | null;
38
+ /**
39
+ * Whether a request from the `requester` Site page may reach a session (or
40
+ * schedule) whose recorded origin is `target`. Same published Site, or, for
41
+ * frames without a published id, the same mounted frame. Anything without a
42
+ * Site origin is out of reach for a Site page.
43
+ */
44
+ export declare function siteOriginsMatch(requester: SiteSessionOrigin, target: SiteSessionOrigin | null | undefined): boolean;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@opengeni/core",
3
- "version": "2.0.1",
3
+ "version": "2.0.2-canary.38789554071001",
4
4
  "description": "Opengeni framework-agnostic core: the domain, access, and billing layers (neutral access, off-HTTP V2 surface). Behavior-preserving extraction from apps/api — keeps Hono's HTTPException for error throwing (typed-errors cleanup deferred).",
5
5
  "license": "Apache-2.0",
6
6
  "repository": {
@@ -50,18 +50,18 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@modelcontextprotocol/sdk": "^1.29.0",
53
- "@opengeni/capabilities": "2.0.1",
54
- "@opengeni/codex": "2.0.1",
55
- "@opengeni/config": "2.0.1",
56
- "@opengeni/contracts": "2.0.1",
57
- "@opengeni/db": "2.0.1",
58
- "@opengeni/documents": "2.0.1",
59
- "@opengeni/events": "2.0.1",
60
- "@opengeni/network": "2.0.1",
61
- "@opengeni/observability": "2.0.1",
62
- "@opengeni/runtime": "2.0.1",
63
- "@opengeni/storage": "2.0.1",
64
- "@opengeni/vaults": "2.0.1",
53
+ "@opengeni/capabilities": "2.0.2-canary.38789554071001",
54
+ "@opengeni/codex": "2.0.2-canary.38789554071001",
55
+ "@opengeni/config": "2.0.2-canary.38789554071001",
56
+ "@opengeni/contracts": "2.0.2-canary.38789554071001",
57
+ "@opengeni/db": "2.0.2-canary.38789554071001",
58
+ "@opengeni/documents": "2.0.2-canary.38789554071001",
59
+ "@opengeni/events": "2.0.2-canary.38789554071001",
60
+ "@opengeni/network": "2.0.2-canary.38789554071001",
61
+ "@opengeni/observability": "2.0.2-canary.38789554071001",
62
+ "@opengeni/runtime": "2.0.2-canary.38789554071001",
63
+ "@opengeni/storage": "2.0.2-canary.38789554071001",
64
+ "@opengeni/vaults": "2.0.2-canary.38789554071001",
65
65
  "hono": "^4.12.18",
66
66
  "zod": "^4.2.1"
67
67
  },
@@ -119,7 +119,8 @@ export type ManagedEmailMessage = {
119
119
  | "email_verification"
120
120
  | "password_reset"
121
121
  | "organization_user_setup"
122
- | "sign_in_method_changed";
122
+ | "sign_in_method_changed"
123
+ | "site_abuse_notice";
123
124
  from: string;
124
125
  to: string;
125
126
  subject: string;
@@ -59,6 +59,7 @@ export function validateToolRefs(tools: ToolRef[], settings: McpSettings): ToolR
59
59
  id: tool.id,
60
60
  ...(optional ? { optional: true } : {}),
61
61
  ...(tool.eager === true ? { eager: true } : {}),
62
+ ...(tool.allowedTools !== undefined ? { allowedTools: [...new Set(tool.allowedTools)] } : {}),
62
63
  });
63
64
  }
64
65
  return mergeToolRefs([], out);
@@ -160,8 +161,18 @@ export function assertToolRefsSubset(
160
161
  allowed: ToolRef[],
161
162
  message = "requested tools exceed the session tool policy",
162
163
  ): void {
163
- const allowedIds = new Set(allowed.map((tool) => `${tool.kind}:${tool.id}`));
164
- const widened = requested.find((tool) => !allowedIds.has(`${tool.kind}:${tool.id}`));
164
+ const allowedById = new Map(
165
+ mergeToolRefs([], allowed).map((tool) => [`${tool.kind}:${tool.id}`, tool]),
166
+ );
167
+ const widened = requested.find((tool) => {
168
+ const ceiling = allowedById.get(`${tool.kind}:${tool.id}`);
169
+ return (
170
+ !ceiling ||
171
+ (ceiling.allowedTools !== undefined &&
172
+ (tool.allowedTools === undefined ||
173
+ tool.allowedTools.some((name) => !ceiling.allowedTools!.includes(name))))
174
+ );
175
+ });
165
176
  if (widened) {
166
177
  throw new HTTPException(403, { message: `${message}: ${widened.id}` });
167
178
  }
@@ -15,6 +15,7 @@ import {
15
15
  } from "@opengeni/db";
16
16
  import { HTTPException } from "hono/http-exception";
17
17
  import { hasPermission } from "../access";
18
+ import { assertNotSiteClampedAgent } from "../site-agent-clamp";
18
19
  import {
19
20
  privacyDeploymentLimits,
20
21
  resolveOrganizationPrivacy,
@@ -154,6 +155,7 @@ export async function pausePrivateScheduledTaskAsAdmin(
154
155
  taskId: string,
155
156
  viewer: ScheduledTaskViewer,
156
157
  ): Promise<PrivateScheduledTaskSummary> {
158
+ await assertNotSiteClampedAgent(db, grant, "schedules");
157
159
  if (!viewer.seesPrivateSummaries) throw scheduledTaskNotFound();
158
160
  const paused = await pausePrivateScheduledTask(db, {
159
161
  workspaceId: grant.workspaceId,
@@ -90,6 +90,14 @@ import {
90
90
  import { HTTPException } from "hono/http-exception";
91
91
  import { GOOGLE_DRIVE_PUBLICATION_SERVER_ID } from "@opengeni/contracts/google-drive";
92
92
  import { PERSONAL_GITHUB_CONNECTION_SURFACE_ID } from "@opengeni/contracts/personal-github";
93
+ import {
94
+ currentSiteSessionOrigin,
95
+ SITE_ORIGIN_METADATA_KEY,
96
+ siteOriginsMatch,
97
+ siteSessionOriginFromMetadata,
98
+ withSiteOriginMetadata,
99
+ } from "../site-session-origin";
100
+ import { assertNotSiteClampedAgent } from "../site-agent-clamp";
93
101
  import { personalGitHubRepositoryResources } from "./resources";
94
102
  import { knowledgeContextForAccess } from "./knowledge";
95
103
  import { fileOwnerContextForAccess, fileOwnerContextForAgent } from "./file-owner";
@@ -211,14 +219,12 @@ function workspaceCustomModelCommitGuard(input: {
211
219
  accountId: input.accountId,
212
220
  workspaceId: input.workspaceId,
213
221
  reference,
214
- ...(input.claudeAuthoritySnapshot
222
+ claudeAuthority: input.claudeAuthoritySnapshot
215
223
  ? {
216
- claudeAuthority: {
217
- authoritySnapshot: input.claudeAuthoritySnapshot,
218
- ...(input.scheduledTaskId ? { scheduledTaskId: input.scheduledTaskId } : {}),
219
- },
224
+ authoritySnapshot: input.claudeAuthoritySnapshot,
225
+ ...(input.scheduledTaskId ? { scheduledTaskId: input.scheduledTaskId } : {}),
220
226
  }
221
- : {}),
227
+ : null,
222
228
  });
223
229
  if (!active) {
224
230
  throw modelUnavailableHttpException(input.modelId);
@@ -365,6 +371,8 @@ export async function createValidatedScheduledTask(input: {
365
371
  /** Proves the bot may post in a newly chosen task Slack channel. */
366
372
  verifySlackChannel?: ScheduledTaskSlackChannelVerifier | undefined;
367
373
  }): Promise<ScheduledTask> {
374
+ // An agent started from a Site page acts with the page's reach: no schedules.
375
+ await assertNotSiteClampedAgent(input.db, input.grant, "schedules");
368
376
  // Variable Sets were replaced by vaults (RM-1).
369
377
  if (input.payload.variableSetId) throw variableSetsRemovedError("variableSetId");
370
378
  if (input.payload.runMode === "existing_session") {
@@ -421,10 +429,20 @@ export async function createValidatedScheduledTask(input: {
421
429
  action: knowledgeAction,
422
430
  });
423
431
  }
424
- const agentConfig: ScheduledTaskAgentConfig = await validateScheduledTaskAgentConfig({
432
+ const validatedAgentConfig: ScheduledTaskAgentConfig = await validateScheduledTaskAgentConfig({
425
433
  ...input,
426
434
  workspaceId: input.grant.workspaceId,
427
435
  });
436
+ // A schedule created from a Site page records which Site. Each run's
437
+ // session copies this metadata, so runs record it too and act with the
438
+ // page's reach (the Site agent clamp). Callers never supply it themselves.
439
+ const agentConfig: ScheduledTaskAgentConfig = {
440
+ ...validatedAgentConfig,
441
+ metadata: withSiteOriginMetadata(
442
+ validatedAgentConfig.metadata ?? {},
443
+ currentSiteSessionOrigin(),
444
+ ),
445
+ };
428
446
  // Connector accounts are never saved from what the schedule would resolve
429
447
  // now. Only accounts a person explicitly pins are stored, and only on a
430
448
  // schedule that starts its own session; everything else follows the owner's
@@ -950,6 +968,8 @@ export async function assertScheduledTaskMutationOwner(
950
968
  grant: AccessGrant,
951
969
  taskId: string,
952
970
  ): Promise<void> {
971
+ await assertNotSiteClampedAgent(db, grant, "schedules");
972
+ await assertSiteMayReachScheduledTask(db, grant, taskId);
953
973
  const writer = scheduledTaskInitiatorForGrant(grant);
954
974
  const matches = await scheduledTaskMutationOwnerMatches(db, {
955
975
  workspaceId: grant.workspaceId,
@@ -964,6 +984,22 @@ export async function assertScheduledTaskMutationOwner(
964
984
  });
965
985
  }
966
986
 
987
+ /**
988
+ * A request from a Site page (a tool the page called) may change or run only
989
+ * a schedule that same Site created. Refused as a missing schedule.
990
+ */
991
+ async function assertSiteMayReachScheduledTask(
992
+ db: Database,
993
+ grant: AccessGrant,
994
+ taskId: string,
995
+ ): Promise<void> {
996
+ const origin = currentSiteSessionOrigin();
997
+ if (!origin) return;
998
+ const task = await getScheduledTask(db, grant.workspaceId, taskId);
999
+ if (!siteOriginsMatch(origin, siteSessionOriginFromMetadata(task?.agentConfig.metadata)))
1000
+ throw new HTTPException(404, { message: "scheduled task not found" });
1001
+ }
1002
+
967
1003
  /**
968
1004
  * An admin's pause of a schedule they do not own. Pausing is reversible and
969
1005
  * changes nothing else; only the owner can change, run or resume it again.
@@ -978,6 +1014,9 @@ export async function pauseScheduledTaskAsAdmin(
978
1014
  );
979
1015
  }
980
1016
 
1017
+ export const SCHEDULED_TASK_PAUSED_TRIGGER_MESSAGE =
1018
+ "This schedule is paused, so it cannot run now. Resume it first, then trigger it.";
1019
+
981
1020
  export async function triggerScheduledTaskForGrant(
982
1021
  db: Database,
983
1022
  grant: AccessGrant,
@@ -988,6 +1027,10 @@ export async function triggerScheduledTaskForGrant(
988
1027
  await assertScheduledTaskMutationOwner(tx, grant, input.task.id);
989
1028
  if (isRetiredNativeAtlassianTask(input.task))
990
1029
  throw new HTTPException(410, { message: ATLASSIAN_NATIVE_RETIRED_MESSAGE });
1030
+ // The worker never runs a paused schedule. Refuse here so the caller is
1031
+ // told, instead of accepting a trigger that would silently do nothing.
1032
+ if (input.task.status === "paused")
1033
+ throw new HTTPException(409, { message: SCHEDULED_TASK_PAUSED_TRIGGER_MESSAGE });
991
1034
  const actor = creationInitiatorForGrant(grant).actor ?? null;
992
1035
  const restriction = await scheduledTaskCredentialRestrictionForGrant(tx, grant, actor);
993
1036
  // A caller cannot supply or clear the trusted ceiling. Ownerless and
@@ -1702,6 +1745,13 @@ async function validatedScheduledTaskUpdateWithoutAudience(input: {
1702
1745
  if (retainedPrompt !== undefined) {
1703
1746
  nextAgentConfig.resources = input.existing.agentConfig.resources;
1704
1747
  }
1748
+ // The Site a schedule was created from stays recorded; an update never
1749
+ // sets, changes or clears it.
1750
+ const recordedOrigin = input.existing.agentConfig.metadata?.[SITE_ORIGIN_METADATA_KEY];
1751
+ nextAgentConfig.metadata = {
1752
+ ...withSiteOriginMetadata(nextAgentConfig.metadata ?? {}, null),
1753
+ ...(recordedOrigin !== undefined ? { [SITE_ORIGIN_METADATA_KEY]: recordedOrigin } : {}),
1754
+ };
1705
1755
  update.agentConfig = nextAgentConfig;
1706
1756
  }
1707
1757
  // Pins are the only saved account choice, a person's explicit one, and only
@@ -26,7 +26,13 @@ import { withSessionRlsActorContext } from "@opengeni/db";
26
26
  import { fileOwnerContextForAccess, fileOwnerContextForAgent } from "./file-owner";
27
27
  import { assertSessionIsNotImported } from "@opengeni/db";
28
28
  import { CODEX_MODEL_ID_PREFIX, isCodexBilledModel } from "@opengeni/codex";
29
- import { sessionCreationMetadata } from "../site-session-origin";
29
+ import {
30
+ currentSiteSessionOrigin,
31
+ sessionCreationMetadata,
32
+ SITE_ORIGIN_METADATA_KEY,
33
+ } from "../site-session-origin";
34
+ import { assertSiteAgentMayChooseCompute } from "../site-agent-clamp";
35
+ import { currentHostSessionUsageLimit } from "../host-session-usage-limit";
30
36
  import { measureSessionStartPhase, type SessionStartObservability } from "./session-start-timing";
31
37
  import {
32
38
  requireDeveloperSetupDelegatedPermissions,
@@ -2049,6 +2055,8 @@ export async function postUserMessageTurn(
2049
2055
  const { db, settings, accountId, workspaceId, sessionId } = input;
2050
2056
  const requestedModel = canonicalConfiguredModel(settings, input.model ?? null) ?? null;
2051
2057
  const requestedReasoningEffort = input.reasoningEffort ?? null;
2058
+ // A message sent from a Site page records which Site (and version) on its turn.
2059
+ const siteOrigin = currentSiteSessionOrigin();
2052
2060
  // Reject an explicit per-message model the host does not expose; an omitted
2053
2061
  // model inherits the session's model downstream (always a configured id).
2054
2062
  assertConfiguredModel(settings, requestedModel);
@@ -2125,6 +2133,7 @@ export async function postUserMessageTurn(
2125
2133
  personalConnectionDelegations: input.personalConnectionDelegations ?? [],
2126
2134
  mcpAccountBindings: input.mcpAccountBindings ?? null,
2127
2135
  connectionAccountIntent: input.connectionAccountIntent ?? null,
2136
+ ...(siteOrigin ? { turnMetadata: { [SITE_ORIGIN_METADATA_KEY]: siteOrigin } } : {}),
2128
2137
 
2129
2138
  ...(input.captureTurnAuthority
2130
2139
  ? { captureTurnAuthority: input.captureTurnAuthority }
@@ -2536,6 +2545,9 @@ async function createSessionForRequestInFileScope(
2536
2545
  requestOptions: SessionCreateRequestOptions = {},
2537
2546
  ): Promise<CreateSessionRequestOutcome> {
2538
2547
  const payload = CreateSessionRequest.parse(rawPayload);
2548
+ // An agent started from a Site page keeps its workers off chosen machines
2549
+ // and other sessions' sandboxes.
2550
+ await assertSiteAgentMayChooseCompute(unresolvedDeps.db, grant, payload);
2539
2551
  // A tool whose backing workload this deployment does not run is dropped, not
2540
2552
  // rejected: a client echoing a full catalog must not fail on a deployment fact.
2541
2553
  if (payload.firstPartyMcpTools) {
@@ -2626,6 +2638,25 @@ async function createSessionForRequestInFileScope(
2626
2638
  "Usage limits are not enabled on this server.",
2627
2639
  );
2628
2640
  }
2641
+ // The trusted server in this process (published Site runtime) may attach a
2642
+ // limit to a root session it creates as its own service principal, so the
2643
+ // limit is in place before the first model call. Requests cannot set it.
2644
+ const hostUsageLimit = currentHostSessionUsageLimit();
2645
+ const hostInitialUsageLimit =
2646
+ payload.usageLimitMicros === undefined &&
2647
+ !parentSessionId &&
2648
+ hostUsageLimit !== undefined &&
2649
+ hostUsageLimit.subjectId === grant.subjectId
2650
+ ? hostUsageLimit
2651
+ : null;
2652
+ if (hostInitialUsageLimit && !sessionUsageLimitsProducerEnabled(unresolvedDeps.settings)) {
2653
+ recordSessionUsageLimitEvent(unresolvedDeps.observability, "create", "disabled");
2654
+ throw new SessionUsageLimitHttpError(
2655
+ 422,
2656
+ "session_usage_limit_disabled",
2657
+ "Usage limits are not enabled on this server.",
2658
+ );
2659
+ }
2629
2660
  // A task whose usage limit is reached cannot start more inference by
2630
2661
  // spawning another agent.
2631
2662
  if (parentSessionId) {
@@ -3829,7 +3860,12 @@ async function createSessionForRequestInFileScope(
3829
3860
  const initialUsageLimit =
3830
3861
  initialUsageLimitActor && payload.usageLimitMicros != null
3831
3862
  ? { actor: initialUsageLimitActor, limitMicros: payload.usageLimitMicros }
3832
- : null;
3863
+ : hostInitialUsageLimit
3864
+ ? {
3865
+ actor: { type: "host" as const, subjectId: hostInitialUsageLimit.subjectId },
3866
+ limitMicros: hostInitialUsageLimit.limitMicros,
3867
+ }
3868
+ : null;
3833
3869
  const applyInitialUsageLimit = initialUsageLimit
3834
3870
  ? async (tx: Database, sessionId: string) =>
3835
3871
  await applyInitialSessionUsageLimit(tx, {
@@ -433,6 +433,12 @@ export const LINKED_VAULT_SEARCH_MAX_AGE_MS = 10 * 60_000;
433
433
  export const LINKED_VAULT_MISS_MAX_AGE_MS = 2 * 60_000;
434
434
  /** How long a search or resolution waits for refreshes before answering. */
435
435
  export const LINKED_VAULT_REFRESH_WAIT_MS = 8_000;
436
+ /**
437
+ * How long a person opening a linked vault waits for its stale mirror to
438
+ * refresh before the page shows what is mirrored; a slower refresh finishes in
439
+ * the background and the next load shows it.
440
+ */
441
+ export const LINKED_VAULT_OPEN_WAIT_MS = 3_000;
436
442
 
437
443
  /** The vault fields a freshness check needs (a `VaultRow` has them all). */
438
444
  export type LinkedVaultFreshness = {
@@ -92,7 +92,11 @@ import {
92
92
  type VaultCallerAuthority,
93
93
  } from "./mapping";
94
94
  import { vaultErrorCodeForProvider } from "./provider-registry";
95
- import { LINKED_VAULT_SEARCH_MAX_AGE_MS, refreshStaleLinkedVaults } from "./provider-sync";
95
+ import {
96
+ LINKED_VAULT_OPEN_WAIT_MS,
97
+ LINKED_VAULT_SEARCH_MAX_AGE_MS,
98
+ refreshStaleLinkedVaults,
99
+ } from "./provider-sync";
96
100
  import {
97
101
  archiveProviderVaultItem,
98
102
  writeProviderVaultItem,
@@ -767,7 +771,22 @@ export function createVaultService(deps: VaultServiceDeps): VaultService {
767
771
  },
768
772
 
769
773
  async listItems(actor, workspaceId, vaultId, q) {
770
- const result = await listVaultItems(deps.db, subjectContext(actor, workspaceId), {
774
+ const context = subjectContext(actor, workspaceId);
775
+ // Opening a linked vault shows items added straight in the provider
776
+ // (1Password) without anyone pressing Sync: the first page refreshes a
777
+ // stale mirror, on the same budget as agent search.
778
+ if (deps.providers && q.cursor === undefined) {
779
+ const vault = await getVault(deps.db, context, { vaultId });
780
+ await refreshStaleLinkedVaults({
781
+ db: deps.db,
782
+ context,
783
+ vaults: [vault],
784
+ providers: deps.providers,
785
+ maxAgeMs: LINKED_VAULT_SEARCH_MAX_AGE_MS,
786
+ waitMs: LINKED_VAULT_OPEN_WAIT_MS,
787
+ });
788
+ }
789
+ const result = await listVaultItems(deps.db, context, {
771
790
  vaultId,
772
791
  ...(q.q !== undefined ? { q: q.q } : {}),
773
792
  ...(q.type !== undefined ? { type: q.type } : {}),
@@ -0,0 +1,25 @@
1
+ import { AsyncLocalStorage } from "node:async_hooks";
2
+
3
+ /**
4
+ * A task usage limit the trusted server applies to a root session it creates
5
+ * in this process, as the host actor `subjectId`. Published Site agents use
6
+ * it: site-runtime creates each conversation as `site:<siteId>` through an
7
+ * in-process dispatch, and the per-conversation budget must be in place in the
8
+ * create transaction, before the first model call. Only code in this process
9
+ * can set it; a request cannot.
10
+ */
11
+ export type HostSessionUsageLimit = {
12
+ /** The service principal the session is created as; other callers are ignored. */
13
+ subjectId: string;
14
+ limitMicros: number;
15
+ };
16
+
17
+ const limits = new AsyncLocalStorage<HostSessionUsageLimit>();
18
+
19
+ export function withHostSessionUsageLimit<T>(limit: HostSessionUsageLimit, run: () => T): T {
20
+ return limits.run(limit, run);
21
+ }
22
+
23
+ export function currentHostSessionUsageLimit(): HostSessionUsageLimit | undefined {
24
+ return limits.getStore();
25
+ }
package/src/index.ts CHANGED
@@ -159,7 +159,30 @@ export * from "./editable-artifact-live";
159
159
 
160
160
  // Transport-neutral editable-artifact domain service, ports, and contracts.
161
161
  export * from "./editable-artifacts";
162
- export { withSiteSessionOrigin } from "./site-session-origin";
162
+ export {
163
+ currentSiteSessionOrigin,
164
+ siteOriginsMatch,
165
+ siteSessionOriginFromMetadata,
166
+ withSiteOriginMetadata,
167
+ withSiteSessionOrigin,
168
+ type SiteSessionOrigin,
169
+ } from "./site-session-origin";
170
+ export {
171
+ assertNotSiteClampedAgent,
172
+ assertSiteAgentMayChooseCompute,
173
+ SITE_AGENT_COMPUTE_MESSAGE,
174
+ siteAgentClamp,
175
+ siteAgentMayReachSession,
176
+ siteClampedAgentMessage,
177
+ siteSessionClamp,
178
+ type SiteAgentClamp,
179
+ type SiteClampedResource,
180
+ } from "./site-agent-clamp";
181
+ export {
182
+ currentHostSessionUsageLimit,
183
+ withHostSessionUsageLimit,
184
+ type HostSessionUsageLimit,
185
+ } from "./host-session-usage-limit";
163
186
  export { resolveTurnSurface } from "./turn-surface";
164
187
 
165
188
  export { fileOwnerContextForAccess, fileOwnerContextForAgent } from "./domain/file-owner";
@@ -179,7 +179,12 @@ export async function lockActiveCustomModelForAdmission(
179
179
  accountId: string;
180
180
  workspaceId: string;
181
181
  reference: WorkspaceCustomModelReference;
182
- claudeAuthority?: OrganizationClaudeModelAdmissionAuthority;
182
+ /**
183
+ * The accepted Claude authority this admission re-reads. Every caller
184
+ * states it: an organization Claude model is never admitted without it,
185
+ * so an omitted value would refuse that model silently.
186
+ */
187
+ claudeAuthority: OrganizationClaudeModelAdmissionAuthority | null;
183
188
  },
184
189
  ): Promise<boolean> {
185
190
  if (input.reference.scope === "organization") {