@opengeni/api-router 5.4.1 → 5.5.0-canary.37090756480001

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.
@@ -247,6 +247,7 @@ export function registerComputerSessionRoutes(app: Hono, deps: ApiRouteDeps): vo
247
247
  await authorizeSourceSession(deps, grant, request.sessionId, "session.control");
248
248
  const origin = requestOrigin(context, deps.settings);
249
249
  const authority = controllerAuthorityRoot(deps);
250
+ let prepared: Awaited<ReturnType<typeof prepareComputerSessionCreate>> | null = null;
250
251
 
251
252
  try {
252
253
  const existing = await findComputerSessionControlRecordByOperation(deps.db, {
@@ -260,7 +261,7 @@ export function registerComputerSessionRoutes(app: Hono, deps: ApiRouteDeps): vo
260
261
  );
261
262
  }
262
263
  if (existing) assertCreateReplay(request, existing.session);
263
- let prepared = existing
264
+ prepared = existing
264
265
  ? await prepareComputerSessionCreate(
265
266
  deps.db,
266
267
  computerCreateInput(grant, workspaceId, request, existing.session.placement),
@@ -426,6 +427,18 @@ export function registerComputerSessionRoutes(app: Hono, deps: ApiRouteDeps): vo
426
427
  parsed.operation.state === "completed" && !parsed.operation.replayed ? 201 : 200,
427
428
  );
428
429
  } catch (error) {
430
+ if (prepared) {
431
+ // A concurrent dispatch owns its exact binding, even if this request's
432
+ // placement failed. Settle only the still-undispatched create receipt.
433
+ await failComputerSessionOperation(deps.db, {
434
+ accountId: grant.accountId,
435
+ workspaceId,
436
+ operationId: request.operationId,
437
+ computerSessionId: prepared.session.id,
438
+ onlyIfPreparedCreate: true,
439
+ error: interactionFailure(error),
440
+ }).catch(() => undefined);
441
+ }
429
442
  throw computerRouteError(error);
430
443
  }
431
444
  });
@@ -1451,6 +1464,7 @@ export function registerComputerSessionRoutes(app: Hono, deps: ApiRouteDeps): vo
1451
1464
  },
1452
1465
  os: placement.lease.os,
1453
1466
  image: sandboxRuntime.image,
1467
+ imagePolicy: "new_creates_only",
1454
1468
  rigVersionId: sourceSession.rigVersionId,
1455
1469
  leaseTtlMs: deps.settings.sandboxLeaseTtlMs,
1456
1470
  expectedEpoch: placement.lease.leaseEpoch,
@@ -1,4 +1,5 @@
1
1
  import { createHash, createHmac } from "node:crypto";
2
+ import { verifyDirectModelAccess } from "@opengeni/core";
2
3
  import {
3
4
  assertClaudeWorkspaceCredential,
4
5
  prepareClaudeWorkspaceCredential,
@@ -41,6 +42,7 @@ import {
41
42
  import {
42
43
  API_INTEGRATION_OAUTH_CREDENTIAL_ROLE,
43
44
  ApiIntegrationOAuthStartRequest,
45
+ DirectModelProviderMetadata,
44
46
  ConnectionResponse,
45
47
  CreateConnectionRequest,
46
48
  FikenInstallRequest,
@@ -247,6 +249,44 @@ export function registerConnectionRoutes(app: Hono, deps: ApiRouteDeps): void {
247
249
  const grant = access.grant;
248
250
  const beforeCommit = externalContinuationCommitAuthorizer(access);
249
251
  const payload = await parseRequestJson(c, CreateConnectionRequest);
252
+ if (
253
+ payload.metadata?.directModelProvider !== undefined ||
254
+ String(payload.metadata?.credentialRole ?? "").startsWith("direct_")
255
+ ) {
256
+ const config = DirectModelProviderMetadata.safeParse(payload.metadata?.directModelProvider);
257
+ const domain = config.success
258
+ ? new URL(config.data.endpoint ?? "https://api.openai.com/v1").hostname
259
+ : null;
260
+ if (
261
+ !config.success ||
262
+ payload.subjectId !== null ||
263
+ payload.kind !== "api_key" ||
264
+ canonicalProviderDomain(payload.providerDomain) !== domain ||
265
+ payload.metadata?.credentialRole !== `direct_${config.data.provider}` ||
266
+ typeof payload.credential.apiKey !== "string" ||
267
+ !payload.credential.apiKey.trim() ||
268
+ !payload.operationId ||
269
+ payload.expiresAt
270
+ ) {
271
+ throw new HTTPException(422, {
272
+ message:
273
+ "Invalid OpenAI or Azure OpenAI connection: provide a key, model, and official provider endpoint",
274
+ });
275
+ }
276
+ payload.metadata = { ...payload.metadata, directModelProvider: config.data };
277
+ if (payload.verifyModelAccess) {
278
+ await verifyDirectModelAccess(
279
+ config.data,
280
+ payload.credential.apiKey as string,
281
+ deps.directModelFetch,
282
+ );
283
+ }
284
+ } else if (payload.verifyModelAccess) {
285
+ throw new HTTPException(422, {
286
+ message: "Model checks require an OpenAI or Azure OpenAI connection",
287
+ });
288
+ }
289
+ const directModelKey = payload.metadata?.directModelProvider !== undefined;
250
290
  // All writes in this closure must use the caller-owned scoped transaction.
251
291
  // eslint-disable-next-line no-shadow
252
292
  const persist = async (db: Database) => {
@@ -284,9 +324,10 @@ export function registerConnectionRoutes(app: Hono, deps: ApiRouteDeps): void {
284
324
  kind: payload.kind,
285
325
  metadata: payload.metadata,
286
326
  });
287
- // The model-key lane stores its own `{ apiKey }`; every other api_key
288
- // Connection is brokered and must say where the secret goes.
289
- if (!workspaceProviderKind) assertBrokeredApiKeyCredential(payload.kind, payload.credential);
327
+ // Validated model keys store `{ apiKey }` for model execution. Generic
328
+ // integration credentials still require an explicit broker destination.
329
+ if (!workspaceProviderKind && !directModelKey)
330
+ assertBrokeredApiKeyCredential(payload.kind, payload.credential);
290
331
  const connection = workspaceProviderKind
291
332
  ? await (async () => {
292
333
  const provider = workspaceProviderApiKeyConnectionSpec(workspaceProviderKind);
@@ -385,7 +426,7 @@ export function registerConnectionRoutes(app: Hono, deps: ApiRouteDeps): void {
385
426
  kind: payload.kind,
386
427
  metadata: payload.metadata,
387
428
  });
388
- return modelKey
429
+ return modelKey || directModelKey
389
430
  ? commit(db)
390
431
  : withOrganizationIntegrationAcquisition(
391
432
  db,
@@ -947,6 +988,16 @@ export function registerConnectionRoutes(app: Hono, deps: ApiRouteDeps): void {
947
988
  c.req.param("connectionId"),
948
989
  grant.subjectId,
949
990
  );
991
+ if (
992
+ initial?.metadata.directModelProvider !== undefined ||
993
+ payload.metadata?.directModelProvider !== undefined ||
994
+ String(payload.metadata?.credentialRole ?? "").startsWith("direct_")
995
+ ) {
996
+ throw new HTTPException(422, {
997
+ message:
998
+ "Disconnect and reconnect OpenAI or Azure OpenAI to replace its key or deployment",
999
+ });
1000
+ }
950
1001
  // Model-key rotation owns an advisory -> credential-row prefix. Do
951
1002
  // not take its row first or change that excluded lane's lock order.
952
1003
  if (!initial || !workspaceProviderApiKeyConnectionKind(initial)) {
@@ -4,6 +4,7 @@ import {
4
4
  measureInsightsPhase,
5
5
  workspaceInsightsPhaseMetricObserver,
6
6
  normalizeWorkspaceInsightsFilter,
7
+ normalizeWorkspaceInsightsSessionScope,
7
8
  requireAccessGrant,
8
9
  WorkspaceInsightsFilterValidationError,
9
10
  type ApiRouteDeps,
@@ -19,7 +20,9 @@ export function normalizeWorkspaceInsightsQueryFilter(
19
20
  field: WorkspaceInsightsFilterField,
20
21
  ): string | null {
21
22
  try {
22
- return normalizeWorkspaceInsightsFilter(value, field);
23
+ return field === "rootSessionId" || field === "sessionId"
24
+ ? normalizeWorkspaceInsightsSessionScope(value, field)
25
+ : normalizeWorkspaceInsightsFilter(value, field);
23
26
  } catch (error) {
24
27
  if (error instanceof WorkspaceInsightsFilterValidationError) {
25
28
  throw new HTTPException(400, { message: error.message });
@@ -69,6 +72,8 @@ export function workspaceInsightsCoalesceKey(input: {
69
72
  range: string;
70
73
  provider: string | null;
71
74
  model: string | null;
75
+ rootSessionId?: string | null;
76
+ sessionId?: string | null;
72
77
  rlsActor: string | null;
73
78
  }): string {
74
79
  return JSON.stringify([
@@ -76,6 +81,8 @@ export function workspaceInsightsCoalesceKey(input: {
76
81
  input.range,
77
82
  input.provider,
78
83
  input.model,
84
+ input.rootSessionId ?? null,
85
+ input.sessionId ?? null,
79
86
  input.rlsActor,
80
87
  ]);
81
88
  }
@@ -89,6 +96,8 @@ export function registerInsightsRoutes(app: Hono, deps: ApiRouteDeps): void {
89
96
  const rangeRaw = c.req.query("range") ?? "week";
90
97
  const providerRaw = c.req.query("provider");
91
98
  const modelRaw = c.req.query("model");
99
+ const rootSessionIdRaw = c.req.query("rootSessionId");
100
+ const sessionIdRaw = c.req.query("sessionId");
92
101
  let provider: string | null = null;
93
102
  let model: string | null = null;
94
103
  let outcome = "failed";
@@ -107,6 +116,11 @@ export function registerInsightsRoutes(app: Hono, deps: ApiRouteDeps): void {
107
116
  }
108
117
  provider = normalizeWorkspaceInsightsQueryFilter(providerRaw, "provider");
109
118
  model = normalizeWorkspaceInsightsQueryFilter(modelRaw, "model");
119
+ const rootSessionId = normalizeWorkspaceInsightsQueryFilter(
120
+ rootSessionIdRaw,
121
+ "rootSessionId",
122
+ );
123
+ const sessionId = normalizeWorkspaceInsightsQueryFilter(sessionIdRaw, "sessionId");
110
124
 
111
125
  const response = await coalesce.run(
112
126
  workspaceInsightsCoalesceKey({
@@ -114,6 +128,8 @@ export function registerInsightsRoutes(app: Hono, deps: ApiRouteDeps): void {
114
128
  range: rangeParsed.data,
115
129
  provider,
116
130
  model,
131
+ rootSessionId,
132
+ sessionId,
117
133
  rlsActor: currentSessionRlsActorIdentityKey(),
118
134
  }),
119
135
  () =>
@@ -125,6 +141,8 @@ export function registerInsightsRoutes(app: Hono, deps: ApiRouteDeps): void {
125
141
  range: rangeParsed.data,
126
142
  provider,
127
143
  model,
144
+ rootSessionId,
145
+ sessionId,
128
146
  },
129
147
  observePhase,
130
148
  ),
@@ -14,6 +14,7 @@ import {
14
14
  defaultPrReviewProviderBaseUrl,
15
15
  workspaceCustomModelReference,
16
16
  lockActiveCustomModelForAdmission,
17
+ modelUnavailableHttpException,
17
18
  prReviewWebhookAuthKind,
18
19
  normalizePrReviewProviderBaseUrl,
19
20
  requireAccessGrant,
@@ -576,9 +577,7 @@ function prReviewCustomModelCommitGuard(input: {
576
577
  reference,
577
578
  });
578
579
  if (!active) {
579
- throw new HTTPException(422, {
580
- message: `model is not available: ${input.modelId}`,
581
- });
580
+ throw modelUnavailableHttpException(input.modelId);
582
581
  }
583
582
  };
584
583
  }
@@ -1,4 +1,5 @@
1
1
  import { getRetainedProviderCommand } from "@opengeni/db/retained-provider-commands";
2
+ import { UnsupportedLatencyModeError } from "@opengeni/config";
2
3
  import { searchSessionMessagesForSubject, SessionMessageSearchCursorError } from "@opengeni/db";
3
4
  import { listSessionEventSlices } from "@opengeni/db/session-event-slices";
4
5
  import * as sessionPreviewSchema from "@opengeni/db/schema";
@@ -148,6 +149,7 @@ import {
148
149
  listSessionDiscoverySummaries,
149
150
  listSessionDiscoveryAncestorPaths,
150
151
  listSessionsForSubject,
152
+ listSessionEntriesForSubject,
151
153
  getLatestStartedSessionTurn,
152
154
  listSessionTurns,
153
155
  projectEffectiveControlForRelatedAccess,
@@ -314,8 +316,7 @@ import {
314
316
  workflowIdForSession,
315
317
  sessionWithEffectiveToolPolicy,
316
318
  workspaceSessionEffectiveToolsContext,
317
- workspaceSessionToolPolicyDefaultServerIds,
318
- workspaceSessionToolPolicyServerIds,
319
+ workspaceSessionToolPolicyContext,
319
320
  relayConfigFromSettings,
320
321
  validateVariableSetAttachment,
321
322
  } from "@opengeni/core";
@@ -780,33 +781,48 @@ export function registerSessionRoutes(app: Hono, deps: SessionRouteDeps): void {
780
781
  }
781
782
  const pageView = c.req.query("view") === "page";
782
783
  const query = sessionListQuery(c.req.query(), pageView);
783
- let page: Awaited<ReturnType<typeof listSessionsForSubject>>;
784
+ const projection = c.req.query("projection");
785
+ if (projection !== undefined && projection !== "summary")
786
+ throw new HTTPException(400, { message: 'projection must be "summary"' });
787
+ if (projection && !pageView)
788
+ throw new HTTPException(400, { message: 'summary projection requires view="page"' });
789
+ const summary = projection === "summary";
790
+ let page: Awaited<
791
+ ReturnType<typeof listSessionsForSubject | typeof listSessionEntriesForSubject>
792
+ >;
784
793
  try {
785
- page = await listSessionsForSubject(db, workspaceId, {
786
- subjectId: grant.subjectId,
787
- limit: boundedLimit(query.limit),
788
- materializeSnapshot: pageView,
789
- ...(query.cursor ? { cursor: query.cursor } : {}),
790
- ...(query.search ? { search: query.search } : {}),
791
- ...(query.pinsOnly ? { pinsOnly: true } : {}),
792
- ...(query.archivedOnly ? { archivedOnly: true } : {}),
793
- ...(query.sortBy ? { sortBy: query.sortBy } : {}),
794
- ...(query.archiveStatus ? { archiveStatus: query.archiveStatus } : {}),
795
- ...(query.parentSessionId !== undefined ? { parentSessionId: query.parentSessionId } : {}),
796
- ...(query.channelId !== undefined ? { channelId: query.channelId } : {}),
797
- ...(query.originSiteId ? { originSiteId: query.originSiteId } : {}),
798
- ...(query.createdBy ? { createdBy: query.createdBy } : {}),
799
- ...(query.updatedFrom ? { updatedFrom: query.updatedFrom } : {}),
800
- ...(query.updatedBefore ? { updatedBefore: query.updatedBefore } : {}),
801
- ...(query.createdFrom ? { createdFrom: query.createdFrom } : {}),
802
- ...(query.createdBefore ? { createdBefore: query.createdBefore } : {}),
803
- ...(query.scopeSubjectId ? { scopeSubjectId: query.scopeSubjectId } : {}),
804
- ...(authorizationScope ? { authorizationScope } : {}),
805
- // A managed human's own personal workspace has no membership row, so
806
- // the list's removal fence must fall back to the organization-membership
807
- // pointer, only with verified native or external owning-user provenance.
808
- personalWorkspaceOwnerException: hasVerifiedOwningUserAuthorization(authorization),
809
- });
794
+ page = await (summary ? listSessionEntriesForSubject : listSessionsForSubject)(
795
+ db,
796
+ workspaceId,
797
+ {
798
+ subjectId: grant.subjectId,
799
+ limit: boundedLimit(query.limit),
800
+ materializeSnapshot: pageView,
801
+ ...(query.cursor ? { cursor: query.cursor } : {}),
802
+ ...(query.search ? { search: query.search } : {}),
803
+ ...(query.pinsOnly ? { pinsOnly: true } : {}),
804
+ ...(query.includePinned === false ? { includePinned: false } : {}),
805
+ ...(query.archivedOnly ? { archivedOnly: true } : {}),
806
+ ...(query.sortBy ? { sortBy: query.sortBy } : {}),
807
+ ...(query.archiveStatus ? { archiveStatus: query.archiveStatus } : {}),
808
+ ...(query.parentSessionId !== undefined
809
+ ? { parentSessionId: query.parentSessionId }
810
+ : {}),
811
+ ...(query.channelId !== undefined ? { channelId: query.channelId } : {}),
812
+ ...(query.originSiteId ? { originSiteId: query.originSiteId } : {}),
813
+ ...(query.createdBy ? { createdBy: query.createdBy } : {}),
814
+ ...(query.updatedFrom ? { updatedFrom: query.updatedFrom } : {}),
815
+ ...(query.updatedBefore ? { updatedBefore: query.updatedBefore } : {}),
816
+ ...(query.createdFrom ? { createdFrom: query.createdFrom } : {}),
817
+ ...(query.createdBefore ? { createdBefore: query.createdBefore } : {}),
818
+ ...(query.scopeSubjectId ? { scopeSubjectId: query.scopeSubjectId } : {}),
819
+ ...(authorizationScope ? { authorizationScope } : {}),
820
+ // A managed human's own personal workspace has no membership row, so
821
+ // the list's removal fence must fall back to the organization-membership
822
+ // pointer, only with verified native or external owning-user provenance.
823
+ personalWorkspaceOwnerException: hasVerifiedOwningUserAuthorization(authorization),
824
+ },
825
+ );
810
826
  } catch (error) {
811
827
  if (error instanceof SessionListAccessError) {
812
828
  throw new HTTPException(403, { message: error.message });
@@ -827,10 +843,6 @@ export function registerSessionRoutes(app: Hono, deps: SessionRouteDeps): void {
827
843
  // body for older clients while still making its older-pin omission visible
828
844
  // to raw HTTP consumers without changing that response shape.
829
845
  c.header("x-opengeni-pinned-truncated", page.pinnedTruncated === true ? "true" : "false");
830
- const policy = await loadEffectivePolicyContext(deps, workspaceId, grant.subjectId, [
831
- ...page.pinned,
832
- ...page.sessions,
833
- ]);
834
846
  const commandActivity = await backgroundCommandActivityForSessions(db, {
835
847
  accountId: grant.accountId,
836
848
  workspaceId,
@@ -845,14 +857,35 @@ export function registerSessionRoutes(app: Hono, deps: SessionRouteDeps): void {
845
857
  [...page.pinned, ...page.sessions].map((session) => session.id),
846
858
  )
847
859
  : new Set<string>();
860
+ if ("projection" in page) {
861
+ const decorateEntry = (session: (typeof page.sessions)[number]) => ({
862
+ ...session,
863
+ hasSchedules: scheduleTargets.has(session.id),
864
+ ...(commandActivity.has(session.id)
865
+ ? { backgroundCommandActivity: commandActivity.get(session.id)! }
866
+ : {}),
867
+ });
868
+ return c.json({
869
+ ...page,
870
+ ...(query.hasPageFilters ? { filtersApplied: true as const } : {}),
871
+ ...(query.originSiteId ? { originSiteId: query.originSiteId } : {}),
872
+ pinned: page.pinned.map(decorateEntry),
873
+ sessions: page.sessions.map(decorateEntry),
874
+ });
875
+ }
876
+ const policy = await loadEffectivePolicyContext(deps, workspaceId, grant.subjectId, [
877
+ ...page.pinned,
878
+ ...page.sessions,
879
+ ]);
848
880
  const decorate = (session: Session): Session => {
849
881
  const activity = commandActivity.get(session.id);
882
+ const decorated = {
883
+ ...session,
884
+ hasSchedules: scheduleTargets.has(session.id),
885
+ ...(activity ? { backgroundCommandActivity: activity } : {}),
886
+ };
850
887
  return sessionWithEffectiveToolPolicy(
851
- {
852
- ...session,
853
- hasSchedules: scheduleTargets.has(session.id),
854
- ...(activity ? { backgroundCommandActivity: activity } : {}),
855
- },
888
+ decorated,
856
889
  policy.workspaceServerIds,
857
890
  policy.workspaceDefaultServerIds,
858
891
  policy.effectiveToolsContext,
@@ -5190,6 +5223,7 @@ export function sessionListQuery(
5190
5223
  cursor: ReturnType<typeof decodeSessionListCursor> | undefined;
5191
5224
  search: string | undefined;
5192
5225
  pinsOnly: boolean;
5226
+ includePinned: boolean;
5193
5227
  archivedOnly: boolean;
5194
5228
  sortBy: "updatedAt" | "createdAt" | "name" | undefined;
5195
5229
  archiveStatus: "active" | "archived" | "all" | undefined;
@@ -5235,6 +5269,13 @@ export function sessionListQuery(
5235
5269
  });
5236
5270
  }
5237
5271
  const pinsOnly = query.pinsOnly === "true";
5272
+ if (query.includePinned !== undefined && !["true", "false"].includes(query.includePinned)) {
5273
+ throw new HTTPException(400, { message: 'includePinned must be "true" or "false"' });
5274
+ }
5275
+ const includePinned = query.includePinned !== "false";
5276
+ if (pinsOnly && !includePinned) {
5277
+ throw new HTTPException(400, { message: "pinsOnly requires includePinned" });
5278
+ }
5238
5279
  if (query.archivedOnly !== undefined && query.archivedOnly !== "true") {
5239
5280
  throw new HTTPException(400, { message: 'archivedOnly must be the literal "true"' });
5240
5281
  }
@@ -5356,6 +5397,7 @@ export function sessionListQuery(
5356
5397
  cursor,
5357
5398
  search: search || undefined,
5358
5399
  pinsOnly,
5400
+ includePinned,
5359
5401
  archivedOnly,
5360
5402
  sortBy: sortBy.data,
5361
5403
  archiveStatus: archiveStatus.data,
@@ -5715,6 +5757,21 @@ function optionalEventSequence(raw: string | undefined): number | undefined {
5715
5757
 
5716
5758
  /** Stable, value-free JSON errors for only the create-session boundary. */
5717
5759
  export function sessionCreateErrorResponse(c: Context, error: unknown): Response {
5760
+ if (error instanceof UnsupportedLatencyModeError) {
5761
+ return c.json(
5762
+ {
5763
+ code: "SESSION_CREATE_REJECTED",
5764
+ message: error.message,
5765
+ details: {
5766
+ code: error.code,
5767
+ modelId: error.modelId,
5768
+ latencyMode: error.latencyMode,
5769
+ allowedLatencyModes: [...error.allowedLatencyModes],
5770
+ },
5771
+ },
5772
+ 422,
5773
+ );
5774
+ }
5718
5775
  if (error instanceof SessionCreateConnectionSelectionUnavailableError) {
5719
5776
  return c.json({ code: error.code, message: error.message, retryable: false }, 409);
5720
5777
  }
@@ -5874,12 +5931,11 @@ async function loadEffectivePolicyContext(
5874
5931
  subjectId: string,
5875
5932
  sessions: readonly Session[],
5876
5933
  ): Promise<EffectivePolicyContext> {
5877
- const [workspaceServerIds, workspaceDefaultServerIds, effectiveToolsContext] = await Promise.all([
5878
- workspaceSessionToolPolicyServerIds(deps.db, workspaceId, deps.settings, subjectId),
5879
- workspaceSessionToolPolicyDefaultServerIds(deps.db, workspaceId, deps.settings, subjectId),
5934
+ const [policy, effectiveToolsContext] = await Promise.all([
5935
+ workspaceSessionToolPolicyContext(deps.db, workspaceId, deps.settings, subjectId),
5880
5936
  workspaceSessionEffectiveToolsContext(deps, workspaceId, subjectId, sessions),
5881
5937
  ]);
5882
- return { workspaceServerIds, workspaceDefaultServerIds, effectiveToolsContext };
5938
+ return { ...policy, effectiveToolsContext };
5883
5939
  }
5884
5940
 
5885
5941
  async function withEffectivePolicy(
@@ -1,6 +1,10 @@
1
+ import { withDirectModelProviders } from "@opengeni/config";
2
+ import { listConnectionsMetadata } from "@opengeni/db";
1
3
  import {
2
- getWorkspaceProviderApiKeyConnectionMetadata,
3
- listWorkspaceProviderCustomModels,
4
+ workspaceProviderApiKeyConnectionMetadataFromConnections,
5
+ listWorkspaceProviderCustomModelsByKind,
6
+ getOrganizationModelProviderCatalogForWorkspace,
7
+ type WorkspaceCustomModelProviderKind,
4
8
  } from "@opengeni/db";
5
9
  import { CLAUDE_CONNECTION_KINDS, type ClaudeConnectionCatalog } from "@opengeni/config";
6
10
  import { SessionControlConflictError, WorkspacePauseTimerInputError } from "@opengeni/db";
@@ -79,9 +83,6 @@ import {
79
83
  workspaceControlRequestLockTimeoutMs,
80
84
  workspaceXaiSubscriptionActive,
81
85
  workspaceVercelAiGatewayConnectionActive,
82
- workspaceOpenRouterConnectionActive,
83
- organizationModelProviderConnectionActiveForWorkspace,
84
- listOrganizationModelProviderCustomModelsForWorkspace,
85
86
  WorkspaceGatewayCustomModelHistoryLimitError,
86
87
  WorkspaceOpenRouterCustomModelHistoryLimitError,
87
88
  WorkspaceExternalIdentityConflictError,
@@ -527,6 +528,13 @@ export function registerWorkspaceRoutes(app: Hono, deps: ApiRouteDeps): void {
527
528
  const workspaceId = c.req.param("workspaceId");
528
529
  const grant = await requireAccessGrant(c, deps, workspaceId, "workspace:read");
529
530
  const catalogSettings = deps.resolveCatalogSettings();
531
+ const providerKinds: WorkspaceCustomModelProviderKind[] = [
532
+ "vercel_gateway",
533
+ "openrouter",
534
+ ...CLAUDE_CONNECTION_KINDS.filter(
535
+ (kind) => kind !== "claude_subscription" || deps.settings.claudeSubscriptionEnabled,
536
+ ),
537
+ ];
530
538
  const [
531
539
  connectionModelRestrictions,
532
540
  resolvedCatalog,
@@ -534,14 +542,9 @@ export function registerWorkspaceRoutes(app: Hono, deps: ApiRouteDeps): void {
534
542
  codexSubscriptionActive,
535
543
  codexModelAvailability,
536
544
  xaiSubscriptionActive,
537
- workspaceGatewayConnectionActive,
538
- workspaceGatewayCustomModels,
539
- openRouterConnectionActive,
540
- workspaceOpenRouterCustomModels,
541
- organizationGatewayConnectionActive,
542
- organizationOpenRouterConnectionActive,
543
- organizationGatewayCustomModels,
544
- organizationOpenRouterCustomModels,
545
+ workspaceConnections,
546
+ workspaceCustomModels,
547
+ organizationProviders,
545
548
  workspace,
546
549
  ] = await Promise.all([
547
550
  getWorkspaceConnectionModelRestrictions(deps.db, workspaceId, grant.subjectId),
@@ -552,90 +555,58 @@ export function registerWorkspaceRoutes(app: Hono, deps: ApiRouteDeps): void {
552
555
  loadWorkspaceCodexModelAvailability(deps.db, settings, workspaceId),
553
556
  ),
554
557
  workspaceXaiSubscriptionActive(deps.db, deps.settings, workspaceId, grant.subjectId),
555
- workspaceVercelAiGatewayConnectionActive(deps.db, workspaceId),
556
- listWorkspaceGatewayCustomModels(deps.db, {
557
- accountId: grant.accountId,
558
- workspaceId,
559
- }),
560
- workspaceOpenRouterConnectionActive(deps.db, workspaceId),
561
- listWorkspaceOpenRouterCustomModels(deps.db, {
562
- accountId: grant.accountId,
563
- workspaceId,
564
- }),
565
- organizationModelProviderConnectionActiveForWorkspace(deps.db, {
566
- accountId: grant.accountId,
567
- workspaceId,
568
- providerKind: "vercel_gateway",
569
- }),
570
- organizationModelProviderConnectionActiveForWorkspace(deps.db, {
571
- accountId: grant.accountId,
572
- workspaceId,
573
- providerKind: "openrouter",
574
- }),
575
- listOrganizationModelProviderCustomModelsForWorkspace(deps.db, {
558
+ listConnectionsMetadata(deps.db, workspaceId, null),
559
+ listWorkspaceProviderCustomModelsByKind(deps.db, {
576
560
  accountId: grant.accountId,
577
561
  workspaceId,
578
- providerKind: "vercel_gateway",
562
+ providerKinds,
579
563
  }),
580
- listOrganizationModelProviderCustomModelsForWorkspace(deps.db, {
564
+ getOrganizationModelProviderCatalogForWorkspace(deps.db, {
581
565
  accountId: grant.accountId,
582
566
  workspaceId,
583
- providerKind: "openrouter",
567
+ providerKinds,
584
568
  }),
585
569
  getWorkspace(deps.db, workspaceId),
586
570
  ]);
587
571
  const claudeConnections: ClaudeConnectionCatalog = {};
588
572
  const workspaceClaudeConnections: ClaudeConnectionCatalog = {};
589
- await Promise.all(
590
- CLAUDE_CONNECTION_KINDS.map(async (kind) => {
591
- if (kind === "claude_subscription" && !deps.settings.claudeSubscriptionEnabled) return;
592
- const [active, models] = await Promise.all([
593
- organizationModelProviderConnectionActiveForWorkspace(deps.db, {
594
- accountId: grant.accountId,
595
- workspaceId,
596
- providerKind: kind,
597
- }),
598
- listOrganizationModelProviderCustomModelsForWorkspace(deps.db, {
599
- accountId: grant.accountId,
600
- workspaceId,
601
- providerKind: kind,
602
- }),
603
- ]);
604
- claudeConnections[kind] = { active, models };
605
- const [metadata, workspaceModels] = await Promise.all([
606
- getWorkspaceProviderApiKeyConnectionMetadata(deps.db, workspaceId, kind),
607
- listWorkspaceProviderCustomModels(deps.db, {
608
- accountId: grant.accountId,
609
- workspaceId,
610
- providerKind: kind,
611
- }),
612
- ]);
613
- workspaceClaudeConnections[kind] = { active: metadata !== null, models: workspaceModels };
614
- }),
573
+ const workspaceConnectionActive = (kind: WorkspaceCustomModelProviderKind) =>
574
+ workspaceProviderApiKeyConnectionMetadataFromConnections(workspaceConnections, kind) !== null;
575
+ for (const kind of CLAUDE_CONNECTION_KINDS) {
576
+ if (kind === "claude_subscription" && !deps.settings.claudeSubscriptionEnabled) continue;
577
+ claudeConnections[kind] = organizationProviders[kind];
578
+ workspaceClaudeConnections[kind] = {
579
+ active: workspaceConnectionActive(kind),
580
+ models: workspaceCustomModels[kind],
581
+ };
582
+ }
583
+ const workspaceCatalogSettings = withDirectModelProviders(
584
+ resolvedCatalog.settings,
585
+ workspaceConnections,
615
586
  );
616
587
  const selections = resolveWorkspaceModelSelection({
617
588
  claudeConnections,
618
589
  workspaceClaudeConnections,
619
590
  connectionModelRestrictions,
620
- settings: resolvedCatalog.settings,
591
+ settings: workspaceCatalogSettings,
621
592
  policy,
622
593
  observations: codexModelAvailability,
623
594
  codexSubscriptionActive,
624
595
  xaiSubscriptionActive,
625
- workspaceGatewayConnectionActive,
626
- workspaceGatewayCustomModels,
627
- workspaceOpenRouterConnectionActive: openRouterConnectionActive,
628
- workspaceOpenRouterCustomModels,
629
- organizationGatewayConnectionActive,
630
- organizationOpenRouterConnectionActive,
631
- organizationGatewayCustomModels,
632
- organizationOpenRouterCustomModels,
596
+ workspaceGatewayConnectionActive: workspaceConnectionActive("vercel_gateway"),
597
+ workspaceGatewayCustomModels: workspaceCustomModels.vercel_gateway,
598
+ workspaceOpenRouterConnectionActive: workspaceConnectionActive("openrouter"),
599
+ workspaceOpenRouterCustomModels: workspaceCustomModels.openrouter,
600
+ organizationGatewayConnectionActive: organizationProviders.vercel_gateway.active,
601
+ organizationOpenRouterConnectionActive: organizationProviders.openrouter.active,
602
+ organizationGatewayCustomModels: organizationProviders.vercel_gateway.models,
603
+ organizationOpenRouterCustomModels: organizationProviders.openrouter.models,
633
604
  });
634
605
  // The same precedence the server applies when a new chat, API create, or
635
606
  // scheduled occurrence names no model; published so pickers show it.
636
607
  const workspaceSettings = workspace?.settings ?? {};
637
608
  const defaultSelection = await resolveDefaultSessionModelForSelections(deps.db, {
638
- settings: resolvedCatalog.settings,
609
+ settings: workspaceCatalogSettings,
639
610
  accountId: grant.accountId,
640
611
  workspaceSettings,
641
612
  selections,
@@ -646,7 +617,7 @@ export function registerWorkspaceRoutes(app: Hono, deps: ApiRouteDeps): void {
646
617
  projectWorkspaceModelCatalog(selections, {
647
618
  defaultSelection,
648
619
  creditsSelection: creditsDefaultSessionModel({
649
- settings: resolvedCatalog.settings,
620
+ settings: workspaceCatalogSettings,
650
621
  selections,
651
622
  workspaceSettings,
652
623
  }),
@@ -28,6 +28,15 @@ export async function deleteWorkspaceForRequest(
28
28
  if (state === "P0002") {
29
29
  throw new HTTPException(404, { message: "workspace not found" });
30
30
  }
31
+ if (state === "23503") {
32
+ // Retention and linked-record FKs are intentional deletion boundaries.
33
+ // The failed transaction has rolled back: do not erase history, retry
34
+ // the cascade, or dispatch any external schedule cleanup.
35
+ throw new HTTPException(409, {
36
+ message:
37
+ "workspace deletion is blocked by retained or linked records; keep the workspace, revoke access, and disable scheduled work instead",
38
+ });
39
+ }
31
40
  throw error;
32
41
  }
33
42