@opengeni/core 1.2.1-canary.37222965366001 → 1.4.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.
- package/dist/canonical-human-identities.js +1 -1
- package/dist/{chunk-MM6N7CTO.js → chunk-672TAJCH.js} +45 -5
- package/dist/chunk-672TAJCH.js.map +1 -0
- package/dist/domain/connector-tool-permissions.d.ts +3 -1
- package/dist/domain/knowledge-messages.d.ts +4 -4
- package/dist/domain/realtime-voice-billing.d.ts +81 -0
- package/dist/domain/scheduled-task-access.d.ts +2 -2
- package/dist/domain/scheduled-tasks.d.ts +2 -2
- package/dist/domain/session-connection-accounts.d.ts +1 -1
- package/dist/domain/session-tool-policy.d.ts +4 -4
- package/dist/domain/voice-input-billing.d.ts +76 -0
- package/dist/domain/web-search-billing.d.ts +45 -0
- package/dist/goal-admission.d.ts +24 -0
- package/dist/index.d.ts +4 -1
- package/dist/index.js +963 -211
- package/dist/index.js.map +1 -1
- package/dist/managed-session.d.ts +4 -1
- package/dist/transcription.d.ts +119 -2
- package/package.json +12 -12
- package/src/application/api-integration-servers.ts +9 -0
- package/src/domain/connector-tool-permissions.ts +199 -73
- package/src/domain/realtime-voice-billing.ts +330 -0
- package/src/domain/scheduled-task-access.ts +2 -1
- package/src/domain/scheduled-tasks.ts +3 -2
- package/src/domain/session-connection-accounts.ts +7 -3
- package/src/domain/session-tool-policy.ts +14 -2
- package/src/domain/sessions.ts +17 -4
- package/src/domain/slack-bot.ts +15 -3
- package/src/domain/voice-input-billing.ts +310 -0
- package/src/domain/web-search-billing.ts +154 -0
- package/src/index.ts +5 -0
- package/src/managed-session.ts +59 -5
- package/src/sandbox/routing.ts +59 -25
- package/src/transcription.ts +122 -3
- package/dist/chunk-MM6N7CTO.js.map +0 -1
package/dist/index.js
CHANGED
|
@@ -8,9 +8,11 @@ import {
|
|
|
8
8
|
getManagedAuthRequestActorLeaseStamp,
|
|
9
9
|
getManagedSession,
|
|
10
10
|
markManagedAuthRequestActorTransitionApplied,
|
|
11
|
+
recordManagedAuthLoggedFailure,
|
|
11
12
|
releaseManagedAuthRequestActorLease,
|
|
12
|
-
validateManagedAuthRequestActorLease
|
|
13
|
-
|
|
13
|
+
validateManagedAuthRequestActorLease,
|
|
14
|
+
withManagedAuthSessionLookup
|
|
15
|
+
} from "./chunk-672TAJCH.js";
|
|
14
16
|
import "./chunk-QO5GVFFO.js";
|
|
15
17
|
import {
|
|
16
18
|
EDITABLE_ARTIFACT_HINT_MAX_BYTES,
|
|
@@ -835,7 +837,8 @@ function expandApiIntegrationAccountRoutes(input) {
|
|
|
835
837
|
}
|
|
836
838
|
|
|
837
839
|
// src/domain/session-connection-accounts.ts
|
|
838
|
-
import {
|
|
840
|
+
import { allowedFirstPartyMcpToolsForSession as allowedFirstPartyMcpToolsForSession4 } from "@opengeni/config";
|
|
841
|
+
import { requireSession as requireSession3, requireWorkspace as requireWorkspace6 } from "@opengeni/db";
|
|
839
842
|
|
|
840
843
|
// src/domain/capabilities.ts
|
|
841
844
|
import { Client } from "@modelcontextprotocol/sdk/client/index.js";
|
|
@@ -4832,6 +4835,7 @@ import {
|
|
|
4832
4835
|
ORGANIZATION_GATEWAY_MODEL_ID_PREFIX as ORGANIZATION_GATEWAY_MODEL_ID_PREFIX2,
|
|
4833
4836
|
ORGANIZATION_OPENROUTER_MODEL_ID_PREFIX as ORGANIZATION_OPENROUTER_MODEL_ID_PREFIX2,
|
|
4834
4837
|
allowedFirstPartyMcpToolsForSession as allowedFirstPartyMcpToolsForSession3,
|
|
4838
|
+
deploymentUnavailableFirstPartyMcpTools,
|
|
4835
4839
|
resolveFirstPartyMcpToolPolicy,
|
|
4836
4840
|
policyProviderIdForModel,
|
|
4837
4841
|
resolveTurnExecutionPolicyV1,
|
|
@@ -4886,7 +4890,7 @@ import {
|
|
|
4886
4890
|
listDistinctRigVersionIdsInGroup,
|
|
4887
4891
|
listInstalledPortableSkills,
|
|
4888
4892
|
listEnabledMcpCapabilityServers as listEnabledMcpCapabilityServers2,
|
|
4889
|
-
|
|
4893
|
+
resolveMcpApprovalRecommendation,
|
|
4890
4894
|
getSandbox as getSandbox4,
|
|
4891
4895
|
getSession as getSession3,
|
|
4892
4896
|
getInitializedSessionCreateReplay,
|
|
@@ -4903,7 +4907,7 @@ import {
|
|
|
4903
4907
|
getSessionTurnXaiProviderAccountAuthoritySnapshot,
|
|
4904
4908
|
getSessionTurnClaudeProviderAccountAuthoritySnapshot,
|
|
4905
4909
|
getWorkspaceModelPolicy as getWorkspaceModelPolicy2,
|
|
4906
|
-
requireWorkspace as
|
|
4910
|
+
requireWorkspace as requireWorkspace5,
|
|
4907
4911
|
initializeSessionStartAtomically,
|
|
4908
4912
|
listSessionTurns,
|
|
4909
4913
|
listSessionMcpServersForChildInheritance,
|
|
@@ -5368,6 +5372,7 @@ import {
|
|
|
5368
5372
|
readActiveSandbox,
|
|
5369
5373
|
retainWorkspaceMutationProcess,
|
|
5370
5374
|
SandboxRetainedProcessPromotionFencedError,
|
|
5375
|
+
SandboxWorkspaceMutationOutputRejectedError,
|
|
5371
5376
|
retainedProcessSettlementIdentity,
|
|
5372
5377
|
settleRetainedProcess,
|
|
5373
5378
|
verifyDirectWorkspaceMutationSettlement,
|
|
@@ -5380,6 +5385,7 @@ import {
|
|
|
5380
5385
|
NatsControlRpc,
|
|
5381
5386
|
NatsOpStreamTransport,
|
|
5382
5387
|
RoutingSandboxSession,
|
|
5388
|
+
RoutingMutationOutputRejectedError,
|
|
5383
5389
|
resolveModalCheckpointProviderBindingForSession
|
|
5384
5390
|
} from "@opengeni/runtime/sandbox";
|
|
5385
5391
|
var retainWorkspaceProviderCommand = createProviderCommandRetainer(
|
|
@@ -5538,22 +5544,35 @@ function wrapChannelABoxWithRouting(services, ids, established) {
|
|
|
5538
5544
|
throw new Error(
|
|
5539
5545
|
"Outcome-unknown command settlement requires its exact retained invocation"
|
|
5540
5546
|
);
|
|
5541
|
-
|
|
5542
|
-
|
|
5543
|
-
|
|
5544
|
-
|
|
5545
|
-
|
|
5546
|
-
|
|
5547
|
-
|
|
5548
|
-
|
|
5549
|
-
|
|
5550
|
-
|
|
5551
|
-
|
|
5552
|
-
|
|
5553
|
-
|
|
5554
|
-
|
|
5555
|
-
|
|
5556
|
-
|
|
5547
|
+
try {
|
|
5548
|
+
await verifyDirectWorkspaceMutationSettlement(db, {
|
|
5549
|
+
accountId: ids.accountId,
|
|
5550
|
+
workspaceId: ids.workspaceId,
|
|
5551
|
+
sessionId: ids.sessionId,
|
|
5552
|
+
requestId: ids.directRequest.requestId,
|
|
5553
|
+
holderId: ids.directRequest.holderId,
|
|
5554
|
+
initiatorSubjectId: ids.resourceSubjectId,
|
|
5555
|
+
sandboxGroupId: homeLease.sandboxGroupId,
|
|
5556
|
+
expectedEpoch: backend.leaseEpoch,
|
|
5557
|
+
expectedInstanceId: backend.providerInstanceId,
|
|
5558
|
+
routeTargetId: exactAdmission.routeTargetId,
|
|
5559
|
+
routeEpoch: exactAdmission.routeEpoch,
|
|
5560
|
+
admission: exactAdmission,
|
|
5561
|
+
operation: op,
|
|
5562
|
+
outcome
|
|
5563
|
+
});
|
|
5564
|
+
} catch (error) {
|
|
5565
|
+
if (error instanceof SandboxWorkspaceMutationOutputRejectedError && error.matchesPhysicalSettlement({
|
|
5566
|
+
accountId: ids.accountId,
|
|
5567
|
+
workspaceId: ids.workspaceId,
|
|
5568
|
+
admission: exactAdmission,
|
|
5569
|
+
operation: op,
|
|
5570
|
+
outcome
|
|
5571
|
+
})) {
|
|
5572
|
+
throw new RoutingMutationOutputRejectedError(op, error.code, { cause: error });
|
|
5573
|
+
}
|
|
5574
|
+
throw error;
|
|
5575
|
+
}
|
|
5557
5576
|
} : void 0;
|
|
5558
5577
|
const beforeProcessMutation = homeLease ? async ({
|
|
5559
5578
|
op,
|
|
@@ -5576,15 +5595,28 @@ function wrapChannelABoxWithRouting(services, ids, established) {
|
|
|
5576
5595
|
if (!admission || typeof admission !== "object" || typeof admission.id !== "string" || typeof admission.workspaceGeneration !== "number") {
|
|
5577
5596
|
throw new Error("API retained-process mutation settlement lacked its exact admission");
|
|
5578
5597
|
}
|
|
5579
|
-
|
|
5580
|
-
|
|
5581
|
-
|
|
5582
|
-
|
|
5583
|
-
|
|
5584
|
-
|
|
5585
|
-
|
|
5586
|
-
|
|
5587
|
-
|
|
5598
|
+
try {
|
|
5599
|
+
await verifyRetainedProcessMutationSettlement(db, {
|
|
5600
|
+
accountId: ids.accountId,
|
|
5601
|
+
workspaceId: ids.workspaceId,
|
|
5602
|
+
sessionId: ids.sessionId,
|
|
5603
|
+
processId: process.id,
|
|
5604
|
+
admission,
|
|
5605
|
+
operation: op,
|
|
5606
|
+
outcome
|
|
5607
|
+
});
|
|
5608
|
+
} catch (error) {
|
|
5609
|
+
if (error instanceof SandboxWorkspaceMutationOutputRejectedError && error.matchesPhysicalSettlement({
|
|
5610
|
+
accountId: ids.accountId,
|
|
5611
|
+
workspaceId: ids.workspaceId,
|
|
5612
|
+
admission,
|
|
5613
|
+
operation: op,
|
|
5614
|
+
outcome
|
|
5615
|
+
})) {
|
|
5616
|
+
throw new RoutingMutationOutputRejectedError(op, error.code, { cause: error });
|
|
5617
|
+
}
|
|
5618
|
+
throw error;
|
|
5619
|
+
}
|
|
5588
5620
|
} : void 0;
|
|
5589
5621
|
const settleProcess = homeLease ? async ({
|
|
5590
5622
|
backend,
|
|
@@ -7800,7 +7832,8 @@ import {
|
|
|
7800
7832
|
allowedFirstPartyMcpToolsForSession as allowedFirstPartyMcpToolsForSession2,
|
|
7801
7833
|
codeSearchDeploymentPolicy,
|
|
7802
7834
|
resolveModelProviderForTurn as resolveModelProviderForTurn2,
|
|
7803
|
-
resolveFirstPartyDelegationSecret as resolveFirstPartyDelegationSecret2
|
|
7835
|
+
resolveFirstPartyDelegationSecret as resolveFirstPartyDelegationSecret2,
|
|
7836
|
+
webSearchToolPlan
|
|
7804
7837
|
} from "@opengeni/config";
|
|
7805
7838
|
import {
|
|
7806
7839
|
AGENT_SKILL_MANAGE_TOOL_NAMES,
|
|
@@ -8074,9 +8107,14 @@ function sessionEffectiveToolProjectionInput(session, toolRefs, context) {
|
|
|
8074
8107
|
const sandboxAvailable = context !== void 0 && sandboxBackend !== "none";
|
|
8075
8108
|
const supportsImages = model?.model.api === "responses" && model.model.capabilities.inputModalities.includes("image");
|
|
8076
8109
|
const hostedToolNames = [];
|
|
8110
|
+
const webSearchPlan = context ? webSearchToolPlan(context.settings, {
|
|
8111
|
+
hostedWebSearch: model?.model.hostedWebSearch ?? context.settings.webSearchEnabled,
|
|
8112
|
+
transportHostedSearch: model?.provider.kind === "xai-subscription"
|
|
8113
|
+
}) : { hostedWebSearch: false, providerTools: [] };
|
|
8077
8114
|
if (model?.provider.kind === "xai-subscription") {
|
|
8078
8115
|
if (context?.settings.webSearchEnabled) hostedToolNames.push("web_search", "x_search");
|
|
8079
|
-
} else if (model?.model.hostedWebSearch
|
|
8116
|
+
} else if (model?.model.hostedWebSearch && webSearchPlan.hostedWebSearch)
|
|
8117
|
+
hostedToolNames.push("web_search");
|
|
8080
8118
|
const mediaAttachment = context?.mediaAttachments?.get(session.id) ?? (context?.objectStorageAvailable === false ? { image: null, video: false } : void 0);
|
|
8081
8119
|
const media = resolveAgentMediaToolSurface(session.agent, mediaAttachment);
|
|
8082
8120
|
hostedToolNames.push(...media.hosted);
|
|
@@ -8085,7 +8123,8 @@ function sessionEffectiveToolProjectionInput(session, toolRefs, context) {
|
|
|
8085
8123
|
"list_models",
|
|
8086
8124
|
"skill_read",
|
|
8087
8125
|
...AGENT_SKILL_MANAGE_TOOL_NAMES,
|
|
8088
|
-
...media.runtime
|
|
8126
|
+
...media.runtime,
|
|
8127
|
+
...webSearchPlan.providerTools
|
|
8089
8128
|
] : [];
|
|
8090
8129
|
const sandboxToolNames = sandboxAvailable ? [
|
|
8091
8130
|
"exec_command",
|
|
@@ -8144,6 +8183,7 @@ function sessionEffectiveToolProjectionInput(session, toolRefs, context) {
|
|
|
8144
8183
|
"skill_read",
|
|
8145
8184
|
"request_human_input",
|
|
8146
8185
|
"list_models",
|
|
8186
|
+
...webSearchPlan.providerTools,
|
|
8147
8187
|
...toolRefs.some((ref) => ref.id === "opengeni" && ref.eager === true) || !progressiveDisclosure ? firstPartyMcpTools.filter((name) => !interactionNames.has(name) || !progressiveDisclosure) : [],
|
|
8148
8188
|
...!progressiveDisclosure ? runtimeToolNames : []
|
|
8149
8189
|
]);
|
|
@@ -8153,7 +8193,7 @@ function sessionEffectiveToolProjectionInput(session, toolRefs, context) {
|
|
|
8153
8193
|
...session.toolPolicy.mode !== "workspace_default" ? session.tools.map((tool) => tool.id) : []
|
|
8154
8194
|
]),
|
|
8155
8195
|
hasSkills: context ? sessionHasSkills(session, context) : false,
|
|
8156
|
-
webSearch: hostedToolNames.includes("web_search"),
|
|
8196
|
+
webSearch: hostedToolNames.includes("web_search") || webSearchPlan.providerTools.length > 0,
|
|
8157
8197
|
humanInput: context?.humanInputEnabled ?? false,
|
|
8158
8198
|
media: media.toolsKnown ? media.hosted.length + media.runtime.length > 0 : void 0,
|
|
8159
8199
|
routerInHistory: context?.routerInHistory === true || context?.routerHistorySessionIds?.has(session.id) === true,
|
|
@@ -8444,7 +8484,9 @@ import {
|
|
|
8444
8484
|
areOpenGeniSlackBotScopesAccepted
|
|
8445
8485
|
} from "@opengeni/contracts";
|
|
8446
8486
|
import {
|
|
8447
|
-
getConnectionMetadata as getConnectionMetadata3
|
|
8487
|
+
getConnectionMetadata as getConnectionMetadata3,
|
|
8488
|
+
availableSlackBotConnectionMetadata,
|
|
8489
|
+
requireWorkspace as requireWorkspace4
|
|
8448
8490
|
} from "@opengeni/db";
|
|
8449
8491
|
import { HTTPException as HTTPException16 } from "hono/http-exception";
|
|
8450
8492
|
function openGeniSlackBotMetadata(metadata) {
|
|
@@ -8463,7 +8505,9 @@ function hasReservedOpenGeniSlackBotSessionMetadata(metadata) {
|
|
|
8463
8505
|
);
|
|
8464
8506
|
}
|
|
8465
8507
|
async function requireOpenGeniSlackBotConnection(db, workspaceId, connectionId) {
|
|
8466
|
-
const
|
|
8508
|
+
const local = await getConnectionMetadata3(db, workspaceId, connectionId, null);
|
|
8509
|
+
const workspace = await requireWorkspace4(db, workspaceId);
|
|
8510
|
+
const connection = local ?? (await availableSlackBotConnectionMetadata(db, { accountId: workspace.accountId, workspaceId })).find((candidate) => candidate.id === connectionId) ?? null;
|
|
8467
8511
|
if (!connection || !isOpenGeniSlackBotConnection(connection)) {
|
|
8468
8512
|
throw new HTTPException16(422, {
|
|
8469
8513
|
message: "slackBotConnectionId must reference an Opengeni Slack bot connection"
|
|
@@ -8536,9 +8580,10 @@ async function validateScheduledTaskSlackChannel(input) {
|
|
|
8536
8580
|
});
|
|
8537
8581
|
}
|
|
8538
8582
|
function withScheduledSlackBotPostingTools(tools, agentConfig, allowedTools) {
|
|
8539
|
-
|
|
8583
|
+
const posting = new Set(SCHEDULED_SLACK_BOT_POSTING_TOOLS);
|
|
8584
|
+
const next = tools.filter((tool) => !posting.has(tool));
|
|
8585
|
+
if (!agentConfig.slackBotConnectionId || !agentConfig.slackBotChannelId) return next;
|
|
8540
8586
|
const allowed = new Set(allowedTools);
|
|
8541
|
-
const next = [...tools];
|
|
8542
8587
|
for (const tool of SCHEDULED_SLACK_BOT_POSTING_TOOLS) {
|
|
8543
8588
|
if (allowed.has(tool) && !next.includes(tool)) next.push(tool);
|
|
8544
8589
|
}
|
|
@@ -10160,6 +10205,12 @@ async function withSessionCreateUsageRecording(input) {
|
|
|
10160
10205
|
}
|
|
10161
10206
|
async function createSessionForRequestInFileScope(unresolvedDeps, grant, workspaceId, rawPayload, authorization, agentChildPresentation, requestOptions = {}) {
|
|
10162
10207
|
const payload = CreateSessionRequest.parse(rawPayload);
|
|
10208
|
+
if (payload.firstPartyMcpTools) {
|
|
10209
|
+
const unavailable = deploymentUnavailableFirstPartyMcpTools(unresolvedDeps.settings);
|
|
10210
|
+
payload.firstPartyMcpTools = payload.firstPartyMcpTools.filter(
|
|
10211
|
+
(tool) => !unavailable.has(tool)
|
|
10212
|
+
);
|
|
10213
|
+
}
|
|
10163
10214
|
const surface = resolveTurnSurface({
|
|
10164
10215
|
grant,
|
|
10165
10216
|
authorization,
|
|
@@ -10212,7 +10263,7 @@ async function createSessionForRequestInFileScope(unresolvedDeps, grant, workspa
|
|
|
10212
10263
|
const workspace = await measureSessionStartPhase(
|
|
10213
10264
|
unresolvedDeps.observability,
|
|
10214
10265
|
"workspace_read",
|
|
10215
|
-
() =>
|
|
10266
|
+
() => requireWorkspace5(db, workspaceId)
|
|
10216
10267
|
);
|
|
10217
10268
|
const workspaceSessionToolDefaults = resolveWorkspaceSessionToolDefaults2(workspace.settings);
|
|
10218
10269
|
const parentAuthority = parentSession ? await getSessionAuthorityProjection4(db, workspaceId, parentSession.id) : null;
|
|
@@ -10480,7 +10531,7 @@ async function createSessionForRequestInFileScope(unresolvedDeps, grant, workspa
|
|
|
10480
10531
|
message: `MCP approval policy must name an enabled inherited capability: ${id}${/^api_(openapi|graphql)_/.test(id) ? "; API Integration tool approval is set at install with autoApprovedTools" : ""}`
|
|
10481
10532
|
});
|
|
10482
10533
|
}
|
|
10483
|
-
mcpApprovalPolicies[id] =
|
|
10534
|
+
mcpApprovalPolicies[id] = resolveMcpApprovalRecommendation(policy, inherited.approvalFloor) ?? false;
|
|
10484
10535
|
}
|
|
10485
10536
|
}
|
|
10486
10537
|
const resources = normalizeResources(
|
|
@@ -11454,9 +11505,13 @@ async function acceptSessionUserMessageInFileScope(deps, grant, workspaceId, ses
|
|
|
11454
11505
|
runtimeMcpServers: runtimeSettings.mcpServers,
|
|
11455
11506
|
defaultMcpServerIds: workspaceSessionToolPolicyDefaultServerIdsFor(
|
|
11456
11507
|
capabilityRuntimeSettings.mcpServers,
|
|
11457
|
-
(await
|
|
11508
|
+
(await requireWorkspace5(db, workspaceId)).settings
|
|
11458
11509
|
)
|
|
11459
11510
|
});
|
|
11511
|
+
const existingEffectiveFirstPartyTools = allowedFirstPartyMcpToolsForSession3(
|
|
11512
|
+
settings,
|
|
11513
|
+
existingSession.firstPartyMcpTools
|
|
11514
|
+
);
|
|
11460
11515
|
const { personalConnectionDelegations, mcpAccountBindings } = await freezeConnectionAccounts({
|
|
11461
11516
|
db,
|
|
11462
11517
|
accountId: grant.accountId,
|
|
@@ -11466,7 +11521,7 @@ async function acceptSessionUserMessageInFileScope(deps, grant, workspaceId, ses
|
|
|
11466
11521
|
resources: [...existingSession.resources, ...requestedResources],
|
|
11467
11522
|
source: connectionDelegationSource,
|
|
11468
11523
|
targetSessionId: sessionId,
|
|
11469
|
-
googleDrivePublicationEnabled:
|
|
11524
|
+
googleDrivePublicationEnabled: existingEffectiveFirstPartyTools.includes("editable_artifact_export") && existingEffectiveFirstPartyTools.includes("editable_artifact_export_status") && (!existingSession.firstPartyMcpPermissions?.length || existingSession.firstPartyMcpPermissions.includes("artifacts:read") && existingSession.firstPartyMcpPermissions.includes("artifacts:publish")),
|
|
11470
11525
|
atlassianEnabled: existingSession.firstPartyMcpTools.some((tool) => tool.startsWith("atlassian_")) && (!existingSession.firstPartyMcpPermissions?.length || existingSession.firstPartyMcpPermissions.includes("connections:read")),
|
|
11471
11526
|
...input.connectionAccounts ? { authoritySelections: input.connectionAccounts } : {}
|
|
11472
11527
|
});
|
|
@@ -11765,7 +11820,7 @@ async function updateSessionToolPolicy(deps, grant, sessionId, request) {
|
|
|
11765
11820
|
requirePermission(grant, "sessions:control");
|
|
11766
11821
|
const agentAttemptCaller = grantHasAgentAttemptAuthority(grant);
|
|
11767
11822
|
const existingSession = await requireSession2(deps.db, grant.workspaceId, sessionId);
|
|
11768
|
-
const workspace = await
|
|
11823
|
+
const workspace = await requireWorkspace5(deps.db, grant.workspaceId);
|
|
11769
11824
|
const workspaceSessionToolDefaults = resolveWorkspaceSessionToolDefaults2(workspace.settings);
|
|
11770
11825
|
const capabilityRuntimeSettings = await settingsWithEnabledCapabilityMcpServers(
|
|
11771
11826
|
deps.db,
|
|
@@ -12032,7 +12087,7 @@ async function updateSessionAgent(deps, grant, sessionId, request) {
|
|
|
12032
12087
|
});
|
|
12033
12088
|
requirePermission(grant, "sessions:control");
|
|
12034
12089
|
const agentAttemptCaller = grantHasAgentAttemptAuthority(grant);
|
|
12035
|
-
const workspace = await
|
|
12090
|
+
const workspace = await requireWorkspace5(deps.db, grant.workspaceId);
|
|
12036
12091
|
const goal = await getSessionGoal(deps.db, grant.workspaceId, sessionId);
|
|
12037
12092
|
const goalOpen = goal !== null && goal.status !== "completed";
|
|
12038
12093
|
const deploymentPolicy = agentConfigDeploymentPolicy2(deps.settings);
|
|
@@ -12319,9 +12374,13 @@ async function freezeSessionRealtimeConnectionAccounts(input) {
|
|
|
12319
12374
|
runtimeMcpServers: runtimeSettings.mcpServers,
|
|
12320
12375
|
defaultMcpServerIds: workspaceSessionToolPolicyDefaultServerIdsFor(
|
|
12321
12376
|
capabilitySettings.mcpServers,
|
|
12322
|
-
(await
|
|
12377
|
+
(await requireWorkspace6(db, workspaceId)).settings
|
|
12323
12378
|
)
|
|
12324
12379
|
});
|
|
12380
|
+
const effectiveFirstPartyTools = allowedFirstPartyMcpToolsForSession4(
|
|
12381
|
+
settings,
|
|
12382
|
+
session.firstPartyMcpTools
|
|
12383
|
+
);
|
|
12325
12384
|
return await freezeConnectionAccounts({
|
|
12326
12385
|
db,
|
|
12327
12386
|
settings: runtimeSettings,
|
|
@@ -12331,7 +12390,7 @@ async function freezeSessionRealtimeConnectionAccounts(input) {
|
|
|
12331
12390
|
resources: session.resources,
|
|
12332
12391
|
source: personalConnectionDelegationSourceForGrant(grant),
|
|
12333
12392
|
targetSessionId: sessionId,
|
|
12334
|
-
googleDrivePublicationEnabled:
|
|
12393
|
+
googleDrivePublicationEnabled: effectiveFirstPartyTools.includes("editable_artifact_export") && effectiveFirstPartyTools.includes("editable_artifact_export_status") && (!session.firstPartyMcpPermissions?.length || session.firstPartyMcpPermissions.includes("artifacts:read") && session.firstPartyMcpPermissions.includes("artifacts:publish")),
|
|
12335
12394
|
atlassianEnabled: session.firstPartyMcpTools.some((tool) => tool.startsWith("atlassian_")) && (!session.firstPartyMcpPermissions?.length || session.firstPartyMcpPermissions.includes("connections:read"))
|
|
12336
12395
|
});
|
|
12337
12396
|
}
|
|
@@ -12596,6 +12655,652 @@ async function searchKnowledgeEntries(db, context, input, embedder, settings) {
|
|
|
12596
12655
|
);
|
|
12597
12656
|
}
|
|
12598
12657
|
|
|
12658
|
+
// src/domain/voice-input-billing.ts
|
|
12659
|
+
import {
|
|
12660
|
+
calculateVoiceInputCost,
|
|
12661
|
+
configuredStaticUsageLimits as configuredStaticUsageLimits2,
|
|
12662
|
+
voiceInputCreditBillingActive,
|
|
12663
|
+
voiceInputPricingHasTokenRates
|
|
12664
|
+
} from "@opengeni/config";
|
|
12665
|
+
import {
|
|
12666
|
+
applyCreditDebitAfterUse as applyCreditDebitAfterUse2,
|
|
12667
|
+
checkWorkspaceAllowance as checkWorkspaceAllowance3,
|
|
12668
|
+
creditDebitAttributionMetadata,
|
|
12669
|
+
getSpendableCreditBalance as getSpendableCreditBalance3,
|
|
12670
|
+
listUnsettledVoiceTranscriptionCharges,
|
|
12671
|
+
recordUsageEvent as recordUsageEvent3,
|
|
12672
|
+
sumUsageQuantity as sumUsageQuantity3,
|
|
12673
|
+
VOICE_TRANSCRIPTION_DEBIT_TYPE,
|
|
12674
|
+
VOICE_TRANSCRIPTION_SOURCE_TYPE,
|
|
12675
|
+
voiceTranscriptionSettlementKeys
|
|
12676
|
+
} from "@opengeni/db";
|
|
12677
|
+
|
|
12678
|
+
// src/transcription.ts
|
|
12679
|
+
var TRANSCRIPTION_PROVIDER_REQUEST_TIMEOUT_MILLISECONDS = 10 * 60 * 1e3;
|
|
12680
|
+
var TranscriptionBillingRefusedError = class extends Error {
|
|
12681
|
+
status;
|
|
12682
|
+
code;
|
|
12683
|
+
details;
|
|
12684
|
+
constructor(input) {
|
|
12685
|
+
super(input.message);
|
|
12686
|
+
this.name = "TranscriptionBillingRefusedError";
|
|
12687
|
+
this.code = input.code;
|
|
12688
|
+
this.status = input.code === "monthly_model_cost_limit" ? 429 : 402;
|
|
12689
|
+
this.details = input.details ?? {};
|
|
12690
|
+
}
|
|
12691
|
+
};
|
|
12692
|
+
var TranscriptionServiceError = class extends Error {
|
|
12693
|
+
code;
|
|
12694
|
+
status;
|
|
12695
|
+
retryable;
|
|
12696
|
+
/** Explicit rejection before any transcription result; safe to try another provider. */
|
|
12697
|
+
fallbackSafe;
|
|
12698
|
+
constructor(input) {
|
|
12699
|
+
super(input.message);
|
|
12700
|
+
this.name = "TranscriptionServiceError";
|
|
12701
|
+
this.code = input.code;
|
|
12702
|
+
this.status = input.status ?? statusForVoiceInputError(input.code);
|
|
12703
|
+
this.retryable = input.retryable ?? false;
|
|
12704
|
+
this.fallbackSafe = input.fallbackSafe ?? false;
|
|
12705
|
+
}
|
|
12706
|
+
};
|
|
12707
|
+
function statusForVoiceInputError(code) {
|
|
12708
|
+
switch (code) {
|
|
12709
|
+
case "permission_denied":
|
|
12710
|
+
return 403;
|
|
12711
|
+
case "policy_blocked":
|
|
12712
|
+
return 403;
|
|
12713
|
+
case "not_supported":
|
|
12714
|
+
return 415;
|
|
12715
|
+
case "unavailable":
|
|
12716
|
+
return 503;
|
|
12717
|
+
case "too_large":
|
|
12718
|
+
return 413;
|
|
12719
|
+
case "invalid_audio":
|
|
12720
|
+
return 400;
|
|
12721
|
+
case "timeout":
|
|
12722
|
+
return 504;
|
|
12723
|
+
case "cancelled":
|
|
12724
|
+
return 499;
|
|
12725
|
+
case "network":
|
|
12726
|
+
case "provider":
|
|
12727
|
+
return 502;
|
|
12728
|
+
case "unknown":
|
|
12729
|
+
default:
|
|
12730
|
+
return 500;
|
|
12731
|
+
}
|
|
12732
|
+
}
|
|
12733
|
+
function normalizeMimeType(mimeType) {
|
|
12734
|
+
return mimeType.trim().toLowerCase();
|
|
12735
|
+
}
|
|
12736
|
+
function isAcceptedMimeType(mimeType, accepted) {
|
|
12737
|
+
const normalized = normalizeMimeType(mimeType);
|
|
12738
|
+
if (accepted.some((candidate) => normalizeMimeType(candidate) === normalized)) {
|
|
12739
|
+
return true;
|
|
12740
|
+
}
|
|
12741
|
+
const bare = normalized.split(";")[0]?.trim() ?? normalized;
|
|
12742
|
+
return accepted.some((candidate) => {
|
|
12743
|
+
const allowed = normalizeMimeType(candidate);
|
|
12744
|
+
return allowed === bare || allowed.split(";")[0]?.trim() === bare;
|
|
12745
|
+
});
|
|
12746
|
+
}
|
|
12747
|
+
function filenameForMimeType(mimeType) {
|
|
12748
|
+
const bare = normalizeMimeType(mimeType).split(";")[0] ?? "audio/webm";
|
|
12749
|
+
switch (bare) {
|
|
12750
|
+
case "audio/mp4":
|
|
12751
|
+
case "audio/m4a":
|
|
12752
|
+
return "audio.mp4";
|
|
12753
|
+
case "audio/ogg":
|
|
12754
|
+
return "audio.ogg";
|
|
12755
|
+
case "audio/mpeg":
|
|
12756
|
+
case "audio/mp3":
|
|
12757
|
+
return "audio.mp3";
|
|
12758
|
+
case "audio/wav":
|
|
12759
|
+
case "audio/x-wav":
|
|
12760
|
+
return "audio.wav";
|
|
12761
|
+
case "audio/webm":
|
|
12762
|
+
default:
|
|
12763
|
+
return "audio.webm";
|
|
12764
|
+
}
|
|
12765
|
+
}
|
|
12766
|
+
|
|
12767
|
+
// src/domain/voice-input-billing.ts
|
|
12768
|
+
var VOICE_INPUT_DEBIT_TYPE = VOICE_TRANSCRIPTION_DEBIT_TYPE;
|
|
12769
|
+
var VOICE_INPUT_SOURCE_TYPE = VOICE_TRANSCRIPTION_SOURCE_TYPE;
|
|
12770
|
+
function voiceInputBillableUsage(input) {
|
|
12771
|
+
if (input.usage?.kind === "tokens" && voiceInputPricingHasTokenRates(input.pricing)) {
|
|
12772
|
+
return { usage: input.usage, basis: "provider_tokens" };
|
|
12773
|
+
}
|
|
12774
|
+
if (input.usage?.kind === "duration") {
|
|
12775
|
+
return { usage: input.usage, basis: "provider_duration" };
|
|
12776
|
+
}
|
|
12777
|
+
if (input.trustedDurationSeconds !== void 0 && Number.isFinite(input.trustedDurationSeconds) && input.trustedDurationSeconds >= 0) {
|
|
12778
|
+
return {
|
|
12779
|
+
usage: { kind: "duration", seconds: input.trustedDurationSeconds },
|
|
12780
|
+
basis: "server_duration"
|
|
12781
|
+
};
|
|
12782
|
+
}
|
|
12783
|
+
throw new TranscriptionServiceError({
|
|
12784
|
+
code: "provider",
|
|
12785
|
+
message: "Transcription usage was not reported."
|
|
12786
|
+
});
|
|
12787
|
+
}
|
|
12788
|
+
function initiatingHuman(attribution) {
|
|
12789
|
+
return attribution.kind === "human" || attribution.kind === "turn" ? attribution.initiatingHumanSubjectId : null;
|
|
12790
|
+
}
|
|
12791
|
+
function startOfUtcMonth2() {
|
|
12792
|
+
const now = /* @__PURE__ */ new Date();
|
|
12793
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
12794
|
+
}
|
|
12795
|
+
function createVoiceInputBilling(deps) {
|
|
12796
|
+
const reconcileInterval = deps.reconcileIntervalMilliseconds ?? 5 * 6e4;
|
|
12797
|
+
const lastReconciled = /* @__PURE__ */ new Map();
|
|
12798
|
+
const reconcileDue = (key) => {
|
|
12799
|
+
const now = Date.now();
|
|
12800
|
+
const last = lastReconciled.get(key);
|
|
12801
|
+
if (last !== void 0 && now - last < reconcileInterval) return false;
|
|
12802
|
+
if (lastReconciled.size >= 1e4) lastReconciled.clear();
|
|
12803
|
+
lastReconciled.set(key, now);
|
|
12804
|
+
return true;
|
|
12805
|
+
};
|
|
12806
|
+
return {
|
|
12807
|
+
async admit({ accountId, workspaceId, attribution }) {
|
|
12808
|
+
if (!voiceInputCreditBillingActive(deps.settings)) return;
|
|
12809
|
+
if (attribution.kind === "unknown") {
|
|
12810
|
+
throw new TranscriptionServiceError({
|
|
12811
|
+
code: "policy_blocked",
|
|
12812
|
+
status: 403,
|
|
12813
|
+
message: "Voice input payer could not be verified."
|
|
12814
|
+
});
|
|
12815
|
+
}
|
|
12816
|
+
if (reconcileDue(`${accountId}:${workspaceId}`)) {
|
|
12817
|
+
await reconcileUnsettledVoiceInputCharges(deps.db, { accountId, workspaceId }).catch(
|
|
12818
|
+
(error) => {
|
|
12819
|
+
deps.onReconcileError?.(error, { accountId, workspaceId });
|
|
12820
|
+
}
|
|
12821
|
+
);
|
|
12822
|
+
}
|
|
12823
|
+
const balance = await getSpendableCreditBalance3(deps.db, accountId);
|
|
12824
|
+
if (balance.balanceMicros <= 0) {
|
|
12825
|
+
throw new TranscriptionBillingRefusedError({
|
|
12826
|
+
code: "insufficient_credits",
|
|
12827
|
+
message: "Voice input needs Opengeni credits. Add credits to continue."
|
|
12828
|
+
});
|
|
12829
|
+
}
|
|
12830
|
+
const refusal = await checkWorkspaceAllowance3(deps.db, {
|
|
12831
|
+
accountId,
|
|
12832
|
+
workspaceId,
|
|
12833
|
+
subjectId: initiatingHuman(attribution)
|
|
12834
|
+
});
|
|
12835
|
+
if (refusal) {
|
|
12836
|
+
throw new TranscriptionBillingRefusedError({
|
|
12837
|
+
code: refusal.code,
|
|
12838
|
+
message: refusal.message,
|
|
12839
|
+
details: {
|
|
12840
|
+
scope: refusal.scope,
|
|
12841
|
+
resetsAt: refusal.resetsAt,
|
|
12842
|
+
...refusal.subjectId ? { subjectId: refusal.subjectId } : {}
|
|
12843
|
+
}
|
|
12844
|
+
});
|
|
12845
|
+
}
|
|
12846
|
+
if (deps.settings.usageLimitsMode === "static" || deps.settings.usageLimitsMode === "managed") {
|
|
12847
|
+
const cap = configuredStaticUsageLimits2(deps.settings).maxMonthlyCostMicrosPerAccount;
|
|
12848
|
+
if (cap) {
|
|
12849
|
+
const used = await sumUsageQuantity3(deps.db, {
|
|
12850
|
+
accountId,
|
|
12851
|
+
eventType: "model.cost",
|
|
12852
|
+
since: startOfUtcMonth2()
|
|
12853
|
+
});
|
|
12854
|
+
if (used >= cap) {
|
|
12855
|
+
throw new TranscriptionBillingRefusedError({
|
|
12856
|
+
code: "monthly_model_cost_limit",
|
|
12857
|
+
message: "The monthly model cost limit has been reached."
|
|
12858
|
+
});
|
|
12859
|
+
}
|
|
12860
|
+
}
|
|
12861
|
+
}
|
|
12862
|
+
},
|
|
12863
|
+
async settle(input) {
|
|
12864
|
+
if (!voiceInputCreditBillingActive(deps.settings)) return { creditCostMicros: 0 };
|
|
12865
|
+
const { usage, basis } = voiceInputBillableUsage({
|
|
12866
|
+
pricing: input.pricing,
|
|
12867
|
+
usage: input.usage,
|
|
12868
|
+
trustedDurationSeconds: input.billing.trustedDurationSeconds
|
|
12869
|
+
});
|
|
12870
|
+
const cost = calculateVoiceInputCost(input.pricing, usage);
|
|
12871
|
+
return await settleVoiceInputUsage(deps.db, {
|
|
12872
|
+
accountId: input.accountId,
|
|
12873
|
+
workspaceId: input.workspaceId,
|
|
12874
|
+
providerId: input.providerId,
|
|
12875
|
+
model: input.model,
|
|
12876
|
+
billing: input.billing,
|
|
12877
|
+
usage,
|
|
12878
|
+
basis,
|
|
12879
|
+
providerCostMicros: cost.providerCostMicros,
|
|
12880
|
+
creditCostMicros: cost.creditCostMicros
|
|
12881
|
+
});
|
|
12882
|
+
}
|
|
12883
|
+
};
|
|
12884
|
+
}
|
|
12885
|
+
async function settleVoiceInputUsage(db, input) {
|
|
12886
|
+
const attribution = input.billing.attribution;
|
|
12887
|
+
const keys = voiceTranscriptionSettlementKeys({
|
|
12888
|
+
workspaceId: input.workspaceId,
|
|
12889
|
+
sourceId: input.billing.sourceId
|
|
12890
|
+
});
|
|
12891
|
+
const receipt2 = await recordUsageEvent3(db, {
|
|
12892
|
+
accountId: input.accountId,
|
|
12893
|
+
workspaceId: input.workspaceId,
|
|
12894
|
+
eventType: "model.cost",
|
|
12895
|
+
quantity: input.creditCostMicros,
|
|
12896
|
+
unit: "usd_micros",
|
|
12897
|
+
sourceResourceType: VOICE_TRANSCRIPTION_SOURCE_TYPE,
|
|
12898
|
+
sourceResourceId: input.billing.sourceId,
|
|
12899
|
+
idempotencyKey: keys.usageIdempotencyKey,
|
|
12900
|
+
// The API is the writer; the payer is the trusted attribution snapshot.
|
|
12901
|
+
initiator: { kind: "service", subjectId: "api:voice-input" },
|
|
12902
|
+
initiatorContext: { creditDebitAttribution: attribution }
|
|
12903
|
+
});
|
|
12904
|
+
const amount = Number(receipt2.quantity);
|
|
12905
|
+
if (amount > 0) {
|
|
12906
|
+
await applyCreditDebitAfterUse2(db, {
|
|
12907
|
+
accountId: input.accountId,
|
|
12908
|
+
workspaceId: input.workspaceId,
|
|
12909
|
+
type: VOICE_TRANSCRIPTION_DEBIT_TYPE,
|
|
12910
|
+
amountMicros: amount,
|
|
12911
|
+
sourceType: VOICE_TRANSCRIPTION_SOURCE_TYPE,
|
|
12912
|
+
sourceId: input.billing.sourceId,
|
|
12913
|
+
idempotencyKey: keys.debitIdempotencyKey,
|
|
12914
|
+
metadata: {
|
|
12915
|
+
providerId: input.providerId,
|
|
12916
|
+
model: input.model,
|
|
12917
|
+
basis: input.basis,
|
|
12918
|
+
providerCostMicros: input.providerCostMicros,
|
|
12919
|
+
...input.usage.kind === "tokens" ? {
|
|
12920
|
+
inputTokens: input.usage.inputTokens,
|
|
12921
|
+
audioInputTokens: input.usage.audioInputTokens,
|
|
12922
|
+
textInputTokens: input.usage.textInputTokens,
|
|
12923
|
+
outputTokens: input.usage.outputTokens
|
|
12924
|
+
} : { audioMilliseconds: Math.ceil(input.usage.seconds * 1e3) },
|
|
12925
|
+
...attribution.kind === "unknown" ? {} : creditDebitAttributionMetadata(attribution)
|
|
12926
|
+
}
|
|
12927
|
+
});
|
|
12928
|
+
}
|
|
12929
|
+
return { creditCostMicros: amount };
|
|
12930
|
+
}
|
|
12931
|
+
async function reconcileUnsettledVoiceInputCharges(db, input) {
|
|
12932
|
+
const pending = await listUnsettledVoiceTranscriptionCharges(db, {
|
|
12933
|
+
accountId: input.accountId,
|
|
12934
|
+
workspaceId: input.workspaceId,
|
|
12935
|
+
...input.minAgeMilliseconds !== void 0 ? { minAgeMilliseconds: input.minAgeMilliseconds } : {}
|
|
12936
|
+
});
|
|
12937
|
+
for (const charge of pending) {
|
|
12938
|
+
await applyCreditDebitAfterUse2(db, {
|
|
12939
|
+
accountId: input.accountId,
|
|
12940
|
+
workspaceId: input.workspaceId,
|
|
12941
|
+
type: VOICE_TRANSCRIPTION_DEBIT_TYPE,
|
|
12942
|
+
amountMicros: charge.amountMicros,
|
|
12943
|
+
sourceType: VOICE_TRANSCRIPTION_SOURCE_TYPE,
|
|
12944
|
+
sourceId: charge.sourceId,
|
|
12945
|
+
idempotencyKey: voiceTranscriptionSettlementKeys({
|
|
12946
|
+
workspaceId: input.workspaceId,
|
|
12947
|
+
sourceId: charge.sourceId
|
|
12948
|
+
}).debitIdempotencyKey,
|
|
12949
|
+
metadata: {
|
|
12950
|
+
basis: "reconciled_receipt",
|
|
12951
|
+
...charge.attribution.kind === "unknown" ? {} : creditDebitAttributionMetadata(charge.attribution)
|
|
12952
|
+
}
|
|
12953
|
+
});
|
|
12954
|
+
}
|
|
12955
|
+
return { reconciled: pending.length };
|
|
12956
|
+
}
|
|
12957
|
+
|
|
12958
|
+
// src/domain/web-search-billing.ts
|
|
12959
|
+
import {
|
|
12960
|
+
applyCreditDebitAfterUse as applyCreditDebitAfterUse3,
|
|
12961
|
+
checkWorkspaceAllowance as checkWorkspaceAllowance4,
|
|
12962
|
+
creditDebitAttributionForTurn as creditDebitAttributionForTurn2,
|
|
12963
|
+
creditDebitAttributionMetadata as creditDebitAttributionMetadata2,
|
|
12964
|
+
getSpendableCreditBalance as getSpendableCreditBalance4,
|
|
12965
|
+
recordUsageEvent as recordUsageEvent4,
|
|
12966
|
+
withRlsContext
|
|
12967
|
+
} from "@opengeni/db";
|
|
12968
|
+
var WEB_SEARCH_DEBIT_TYPE = "web_search_debit";
|
|
12969
|
+
var WEB_SEARCH_SOURCE_TYPE = "web_search";
|
|
12970
|
+
var WEB_SEARCH_BILLING_INITIATOR = "worker:web-search";
|
|
12971
|
+
function webSearchCreditBillingActive(settings) {
|
|
12972
|
+
return settings.billingMode === "stripe" || settings.usageLimitsMode === "managed";
|
|
12973
|
+
}
|
|
12974
|
+
var WebSearchBillingRefusedError = class extends Error {
|
|
12975
|
+
constructor(code, message) {
|
|
12976
|
+
super(message);
|
|
12977
|
+
this.code = code;
|
|
12978
|
+
this.name = "WebSearchBillingRefusedError";
|
|
12979
|
+
}
|
|
12980
|
+
};
|
|
12981
|
+
function createWebSearchBilling(deps) {
|
|
12982
|
+
const active = webSearchCreditBillingActive(deps.settings);
|
|
12983
|
+
const attributionByTurn = /* @__PURE__ */ new Map();
|
|
12984
|
+
const attributionFor = (scope) => {
|
|
12985
|
+
let attribution = attributionByTurn.get(scope.turnId);
|
|
12986
|
+
if (!attribution) {
|
|
12987
|
+
attribution = creditDebitAttributionForTurn2(deps.db, scope);
|
|
12988
|
+
attributionByTurn.set(scope.turnId, attribution);
|
|
12989
|
+
attribution.catch(() => attributionByTurn.delete(scope.turnId));
|
|
12990
|
+
}
|
|
12991
|
+
return attribution;
|
|
12992
|
+
};
|
|
12993
|
+
return {
|
|
12994
|
+
active,
|
|
12995
|
+
async admit(scope, expectedProviderMicros) {
|
|
12996
|
+
if (!active || expectedProviderMicros <= 0) return;
|
|
12997
|
+
const attribution = await attributionFor(scope);
|
|
12998
|
+
const balance = await getSpendableCreditBalance4(deps.db, scope.accountId);
|
|
12999
|
+
if (balance.balanceMicros <= 0) {
|
|
13000
|
+
throw new WebSearchBillingRefusedError(
|
|
13001
|
+
"insufficient_credits",
|
|
13002
|
+
"Web search needs Opengeni credits, and this account has none left."
|
|
13003
|
+
);
|
|
13004
|
+
}
|
|
13005
|
+
const refusal = await checkWorkspaceAllowance4(deps.db, {
|
|
13006
|
+
accountId: scope.accountId,
|
|
13007
|
+
workspaceId: scope.workspaceId,
|
|
13008
|
+
subjectId: attribution.kind === "turn" ? attribution.initiatingHumanSubjectId : null
|
|
13009
|
+
});
|
|
13010
|
+
if (refusal) throw new WebSearchBillingRefusedError("allowance_exhausted", refusal.message);
|
|
13011
|
+
},
|
|
13012
|
+
async settle(scope, cost) {
|
|
13013
|
+
const shared = {
|
|
13014
|
+
accountId: scope.accountId,
|
|
13015
|
+
workspaceId: scope.workspaceId,
|
|
13016
|
+
sessionId: scope.sessionId,
|
|
13017
|
+
turnId: scope.turnId,
|
|
13018
|
+
turnAttemptId: scope.attemptId,
|
|
13019
|
+
sourceResourceType: WEB_SEARCH_SOURCE_TYPE,
|
|
13020
|
+
sourceResourceId: `${scope.attemptId}:${cost.operationId}`
|
|
13021
|
+
};
|
|
13022
|
+
await recordUsageEvent4(deps.db, {
|
|
13023
|
+
...shared,
|
|
13024
|
+
eventType: `web_search.${cost.operation}_requests`,
|
|
13025
|
+
quantity: 1,
|
|
13026
|
+
unit: "request",
|
|
13027
|
+
idempotencyKey: `usage:web_search.${cost.operation}_requests:${shared.sourceResourceId}`
|
|
13028
|
+
});
|
|
13029
|
+
if (!active || cost.creditMicros <= 0) return;
|
|
13030
|
+
const attribution = await attributionFor(scope);
|
|
13031
|
+
await withRlsContext(
|
|
13032
|
+
deps.db,
|
|
13033
|
+
{ accountId: scope.accountId, workspaceId: scope.workspaceId },
|
|
13034
|
+
async (tx) => {
|
|
13035
|
+
await recordUsageEvent4(tx, {
|
|
13036
|
+
...shared,
|
|
13037
|
+
eventType: "web_search.cost",
|
|
13038
|
+
quantity: cost.creditMicros,
|
|
13039
|
+
unit: "usd_micros",
|
|
13040
|
+
idempotencyKey: `usage:web_search.cost:${shared.sourceResourceId}`,
|
|
13041
|
+
initiator: { kind: "service", subjectId: WEB_SEARCH_BILLING_INITIATOR },
|
|
13042
|
+
initiatorContext: { creditDebitAttribution: attribution }
|
|
13043
|
+
});
|
|
13044
|
+
await applyCreditDebitAfterUse3(tx, {
|
|
13045
|
+
accountId: scope.accountId,
|
|
13046
|
+
workspaceId: scope.workspaceId,
|
|
13047
|
+
type: WEB_SEARCH_DEBIT_TYPE,
|
|
13048
|
+
amountMicros: cost.creditMicros,
|
|
13049
|
+
sourceType: WEB_SEARCH_SOURCE_TYPE,
|
|
13050
|
+
sourceId: shared.sourceResourceId,
|
|
13051
|
+
idempotencyKey: `credit:${WEB_SEARCH_DEBIT_TYPE}:${shared.sourceResourceId}`,
|
|
13052
|
+
metadata: {
|
|
13053
|
+
// turnId lets the allowance trigger resolve the causal human
|
|
13054
|
+
// from the immutable turn receipt.
|
|
13055
|
+
...creditDebitAttributionMetadata2(attribution),
|
|
13056
|
+
provider: cost.provider,
|
|
13057
|
+
operation: cost.operation,
|
|
13058
|
+
providerCostMicros: cost.providerMicros,
|
|
13059
|
+
marginBps: cost.marginBps,
|
|
13060
|
+
basis: cost.basis
|
|
13061
|
+
}
|
|
13062
|
+
});
|
|
13063
|
+
}
|
|
13064
|
+
);
|
|
13065
|
+
}
|
|
13066
|
+
};
|
|
13067
|
+
}
|
|
13068
|
+
|
|
13069
|
+
// src/domain/realtime-voice-billing.ts
|
|
13070
|
+
import {
|
|
13071
|
+
AI_GATEWAY_REALTIME_MODELS,
|
|
13072
|
+
AZURE_LIVE_REALTIME_MODEL_ID,
|
|
13073
|
+
configuredStaticUsageLimits as configuredStaticUsageLimits3,
|
|
13074
|
+
parseRealtimeVoicePricingJson,
|
|
13075
|
+
parseRealtimeVoicePricingTableJson,
|
|
13076
|
+
realtimeVoiceMinuteCreditMicros,
|
|
13077
|
+
realtimeVoiceStartedMinutes,
|
|
13078
|
+
voiceInputCreditBillingActive as voiceInputCreditBillingActive2
|
|
13079
|
+
} from "@opengeni/config";
|
|
13080
|
+
import {
|
|
13081
|
+
applyCreditDebitAfterUse as applyCreditDebitAfterUse4,
|
|
13082
|
+
checkWorkspaceAllowance as checkWorkspaceAllowance5,
|
|
13083
|
+
creditDebitAttributionMetadata as creditDebitAttributionMetadata3,
|
|
13084
|
+
existingUsageEventIdempotencyKeys,
|
|
13085
|
+
getSpendableCreditBalance as getSpendableCreditBalance5,
|
|
13086
|
+
loadSessionRealtimeBillingFacts,
|
|
13087
|
+
recordUsageEvent as recordUsageEvent5,
|
|
13088
|
+
sumUsageQuantity as sumUsageQuantity4,
|
|
13089
|
+
withRlsContext as withRlsContext2
|
|
13090
|
+
} from "@opengeni/db";
|
|
13091
|
+
var REALTIME_VOICE_DEBIT_TYPE = "voice_realtime_debit";
|
|
13092
|
+
var REALTIME_VOICE_SOURCE_TYPE = "voice_realtime";
|
|
13093
|
+
function deploymentRealtimeVoice(settings, model) {
|
|
13094
|
+
const azureConfigured = Boolean(settings.azureLiveEndpoint && settings.azureLiveApiKey?.trim());
|
|
13095
|
+
if (model === AZURE_LIVE_REALTIME_MODEL_ID) {
|
|
13096
|
+
return {
|
|
13097
|
+
provider: "azure-live",
|
|
13098
|
+
configured: azureConfigured,
|
|
13099
|
+
pricing: parseRealtimeVoicePricingJson(settings.azureLivePricingJson)
|
|
13100
|
+
};
|
|
13101
|
+
}
|
|
13102
|
+
for (const gateway of Object.values(AI_GATEWAY_REALTIME_MODELS)) {
|
|
13103
|
+
if (gateway.managedModelId !== model) continue;
|
|
13104
|
+
return {
|
|
13105
|
+
provider: "ai-gateway",
|
|
13106
|
+
configured: Boolean(settings.vercelAiGatewayApiKey),
|
|
13107
|
+
pricing: parseRealtimeVoicePricingTableJson(settings.aiGatewayRealtimePricingJson)[gateway.upstreamModelId] ?? null
|
|
13108
|
+
};
|
|
13109
|
+
}
|
|
13110
|
+
return null;
|
|
13111
|
+
}
|
|
13112
|
+
var RealtimeVoiceUnavailableError = class extends Error {
|
|
13113
|
+
constructor(code, message) {
|
|
13114
|
+
super(message);
|
|
13115
|
+
this.code = code;
|
|
13116
|
+
}
|
|
13117
|
+
name = "RealtimeVoiceUnavailableError";
|
|
13118
|
+
};
|
|
13119
|
+
function realtimeVoiceOfferProblem(settings, voice) {
|
|
13120
|
+
if (!voice.configured) {
|
|
13121
|
+
return new RealtimeVoiceUnavailableError(
|
|
13122
|
+
"not_configured",
|
|
13123
|
+
"Opengeni live voice is not configured on this deployment."
|
|
13124
|
+
);
|
|
13125
|
+
}
|
|
13126
|
+
if (voiceInputCreditBillingActive2(settings) && !voice.pricing) {
|
|
13127
|
+
return new RealtimeVoiceUnavailableError(
|
|
13128
|
+
"pricing_unconfigured",
|
|
13129
|
+
"Opengeni live voice is not available on this deployment yet."
|
|
13130
|
+
);
|
|
13131
|
+
}
|
|
13132
|
+
return null;
|
|
13133
|
+
}
|
|
13134
|
+
var REALTIME_VOICE_INSUFFICIENT_CREDITS_MESSAGE = "Live voice needs Opengeni credits. Add credits to continue.";
|
|
13135
|
+
function startOfUtcMonth3(now) {
|
|
13136
|
+
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
13137
|
+
}
|
|
13138
|
+
function initiatingHuman2(attribution) {
|
|
13139
|
+
return attribution.kind === "human" || attribution.kind === "turn" ? attribution.initiatingHumanSubjectId : null;
|
|
13140
|
+
}
|
|
13141
|
+
function createRealtimeVoiceBilling(deps) {
|
|
13142
|
+
const billingActive = () => voiceInputCreditBillingActive2(deps.settings);
|
|
13143
|
+
async function refusal(input) {
|
|
13144
|
+
const balance = await getSpendableCreditBalance5(deps.db, input.accountId);
|
|
13145
|
+
if (balance.balanceMicros <= 0) {
|
|
13146
|
+
return new TranscriptionBillingRefusedError({
|
|
13147
|
+
code: "insufficient_credits",
|
|
13148
|
+
message: REALTIME_VOICE_INSUFFICIENT_CREDITS_MESSAGE
|
|
13149
|
+
});
|
|
13150
|
+
}
|
|
13151
|
+
const allowance = await checkWorkspaceAllowance5(deps.db, {
|
|
13152
|
+
accountId: input.accountId,
|
|
13153
|
+
workspaceId: input.workspaceId,
|
|
13154
|
+
subjectId: initiatingHuman2(input.attribution)
|
|
13155
|
+
});
|
|
13156
|
+
if (allowance) {
|
|
13157
|
+
return new TranscriptionBillingRefusedError({
|
|
13158
|
+
code: allowance.code,
|
|
13159
|
+
message: allowance.message,
|
|
13160
|
+
details: {
|
|
13161
|
+
scope: allowance.scope,
|
|
13162
|
+
resetsAt: allowance.resetsAt,
|
|
13163
|
+
...allowance.subjectId ? { subjectId: allowance.subjectId } : {}
|
|
13164
|
+
}
|
|
13165
|
+
});
|
|
13166
|
+
}
|
|
13167
|
+
if (deps.settings.usageLimitsMode === "static" || deps.settings.usageLimitsMode === "managed") {
|
|
13168
|
+
const cap = configuredStaticUsageLimits3(deps.settings).maxMonthlyCostMicrosPerAccount;
|
|
13169
|
+
if (cap) {
|
|
13170
|
+
const used = await sumUsageQuantity4(deps.db, {
|
|
13171
|
+
accountId: input.accountId,
|
|
13172
|
+
eventType: "model.cost",
|
|
13173
|
+
since: startOfUtcMonth3(input.now)
|
|
13174
|
+
});
|
|
13175
|
+
if (used >= cap) {
|
|
13176
|
+
return new TranscriptionBillingRefusedError({
|
|
13177
|
+
code: "monthly_model_cost_limit",
|
|
13178
|
+
message: "The monthly model cost limit has been reached."
|
|
13179
|
+
});
|
|
13180
|
+
}
|
|
13181
|
+
}
|
|
13182
|
+
}
|
|
13183
|
+
return null;
|
|
13184
|
+
}
|
|
13185
|
+
return {
|
|
13186
|
+
/**
|
|
13187
|
+
* Throws RealtimeVoiceUnavailableError when the deployment cannot offer
|
|
13188
|
+
* the model and TranscriptionBillingRefusedError for a credit refusal.
|
|
13189
|
+
* Workspace-funded models are always admitted here.
|
|
13190
|
+
*/
|
|
13191
|
+
async admit(input) {
|
|
13192
|
+
const voice = deploymentRealtimeVoice(deps.settings, input.model);
|
|
13193
|
+
if (!voice) return;
|
|
13194
|
+
const problem = realtimeVoiceOfferProblem(deps.settings, voice);
|
|
13195
|
+
if (problem) throw problem;
|
|
13196
|
+
if (!billingActive()) return;
|
|
13197
|
+
const refused = await refusal({ ...input, now: input.now ?? /* @__PURE__ */ new Date() });
|
|
13198
|
+
if (refused) throw refused;
|
|
13199
|
+
},
|
|
13200
|
+
/** Spendable credits are positive (always true when credits are not enforced). */
|
|
13201
|
+
async hasSpendableCredits(accountId) {
|
|
13202
|
+
if (!billingActive()) return true;
|
|
13203
|
+
const balance = await getSpendableCreditBalance5(deps.db, accountId);
|
|
13204
|
+
return balance.balanceMicros > 0;
|
|
13205
|
+
},
|
|
13206
|
+
/**
|
|
13207
|
+
* Settle every started minute observed so far for one live-voice mode and
|
|
13208
|
+
* report whether the call must stop. Safe to call repeatedly and
|
|
13209
|
+
* concurrently: receipts and debits are idempotent per (connection, minute).
|
|
13210
|
+
*/
|
|
13211
|
+
async settle(input) {
|
|
13212
|
+
const now = input.now ?? /* @__PURE__ */ new Date();
|
|
13213
|
+
if (!billingActive()) return { debitedMicros: 0, stop: null };
|
|
13214
|
+
const facts = await loadSessionRealtimeBillingFacts(deps.db, { ...input, now });
|
|
13215
|
+
if (!facts) return { debitedMicros: 0, stop: null };
|
|
13216
|
+
const voice = deploymentRealtimeVoice(deps.settings, facts.model);
|
|
13217
|
+
if (!voice) return { debitedMicros: 0, stop: null };
|
|
13218
|
+
if (!voice.pricing) {
|
|
13219
|
+
return {
|
|
13220
|
+
debitedMicros: 0,
|
|
13221
|
+
stop: new RealtimeVoiceUnavailableError(
|
|
13222
|
+
"pricing_unconfigured",
|
|
13223
|
+
"Opengeni live voice is no longer available on this deployment."
|
|
13224
|
+
)
|
|
13225
|
+
};
|
|
13226
|
+
}
|
|
13227
|
+
const attribution = input.callerSubjectId === facts.ownerSubjectId ? input.attribution : { kind: "unknown" };
|
|
13228
|
+
const cost = realtimeVoiceMinuteCreditMicros(voice.pricing);
|
|
13229
|
+
const minutes = facts.connections.flatMap(
|
|
13230
|
+
(connection) => Array.from(
|
|
13231
|
+
{ length: realtimeVoiceStartedMinutes(connection.startedAt, connection.observedUntil) },
|
|
13232
|
+
(_, index) => ({
|
|
13233
|
+
connectionId: connection.id,
|
|
13234
|
+
minute: index + 1,
|
|
13235
|
+
startsAt: new Date(connection.startedAt.getTime() + index * 6e4),
|
|
13236
|
+
key: `voice.realtime_cost:${connection.id}:${index + 1}`
|
|
13237
|
+
})
|
|
13238
|
+
)
|
|
13239
|
+
);
|
|
13240
|
+
const recorded = await existingUsageEventIdempotencyKeys(deps.db, {
|
|
13241
|
+
accountId: facts.accountId,
|
|
13242
|
+
workspaceId: facts.workspaceId,
|
|
13243
|
+
keys: minutes.map((minute) => minute.key)
|
|
13244
|
+
});
|
|
13245
|
+
let debitedMicros = 0;
|
|
13246
|
+
for (const minute of minutes) {
|
|
13247
|
+
if (recorded.has(minute.key)) continue;
|
|
13248
|
+
debitedMicros += await withRlsContext2(
|
|
13249
|
+
deps.db,
|
|
13250
|
+
{ accountId: facts.accountId, workspaceId: facts.workspaceId },
|
|
13251
|
+
async (tx) => {
|
|
13252
|
+
const sourceId = `${minute.connectionId}:${minute.minute}`;
|
|
13253
|
+
const receipt2 = await recordUsageEvent5(tx, {
|
|
13254
|
+
accountId: facts.accountId,
|
|
13255
|
+
workspaceId: facts.workspaceId,
|
|
13256
|
+
sessionId: facts.sessionId,
|
|
13257
|
+
eventType: "model.cost",
|
|
13258
|
+
quantity: cost.creditCostMicros,
|
|
13259
|
+
unit: "usd_micros",
|
|
13260
|
+
sourceResourceType: REALTIME_VOICE_SOURCE_TYPE,
|
|
13261
|
+
sourceResourceId: sourceId,
|
|
13262
|
+
idempotencyKey: minute.key,
|
|
13263
|
+
occurredAt: minute.startsAt,
|
|
13264
|
+
initiator: { kind: "service", subjectId: "api:voice-realtime" },
|
|
13265
|
+
initiatorContext: { creditDebitAttribution: attribution }
|
|
13266
|
+
});
|
|
13267
|
+
const amount = Number(receipt2.quantity);
|
|
13268
|
+
if (amount <= 0) return 0;
|
|
13269
|
+
const debit = await applyCreditDebitAfterUse4(tx, {
|
|
13270
|
+
accountId: facts.accountId,
|
|
13271
|
+
workspaceId: facts.workspaceId,
|
|
13272
|
+
type: REALTIME_VOICE_DEBIT_TYPE,
|
|
13273
|
+
amountMicros: amount,
|
|
13274
|
+
sourceType: REALTIME_VOICE_SOURCE_TYPE,
|
|
13275
|
+
sourceId,
|
|
13276
|
+
idempotencyKey: `credit:${REALTIME_VOICE_DEBIT_TYPE}:${sourceId}`,
|
|
13277
|
+
occurredAt: minute.startsAt,
|
|
13278
|
+
metadata: {
|
|
13279
|
+
provider: voice.provider,
|
|
13280
|
+
model: facts.model,
|
|
13281
|
+
realtimeId: facts.realtimeId,
|
|
13282
|
+
connectionId: minute.connectionId,
|
|
13283
|
+
minute: minute.minute,
|
|
13284
|
+
basis: "server_observed_started_minute",
|
|
13285
|
+
providerCostMicros: cost.providerCostMicros,
|
|
13286
|
+
...attribution.kind === "unknown" ? {} : creditDebitAttributionMetadata3(attribution)
|
|
13287
|
+
}
|
|
13288
|
+
});
|
|
13289
|
+
return debit.debitedMicros;
|
|
13290
|
+
}
|
|
13291
|
+
);
|
|
13292
|
+
}
|
|
13293
|
+
const stop = facts.state === "active" ? await refusal({
|
|
13294
|
+
accountId: facts.accountId,
|
|
13295
|
+
workspaceId: facts.workspaceId,
|
|
13296
|
+
attribution,
|
|
13297
|
+
now
|
|
13298
|
+
}) : null;
|
|
13299
|
+
return { debitedMicros, stop };
|
|
13300
|
+
}
|
|
13301
|
+
};
|
|
13302
|
+
}
|
|
13303
|
+
|
|
12599
13304
|
// src/workflow-wake-contract.ts
|
|
12600
13305
|
var SESSION_WORKFLOW_WAKE_DISPATCHER_SCHEDULE_ID = "opengeni-session-workflow-wake-dispatcher";
|
|
12601
13306
|
var SESSION_WORKFLOW_WAKE_DISPATCHER_WORKFLOW_TYPE = "sessionWorkflowWakeDispatcherWorkflow";
|
|
@@ -12697,83 +13402,6 @@ function createUserPresenceRecorder(options) {
|
|
|
12697
13402
|
};
|
|
12698
13403
|
}
|
|
12699
13404
|
|
|
12700
|
-
// src/transcription.ts
|
|
12701
|
-
var TRANSCRIPTION_PROVIDER_REQUEST_TIMEOUT_MILLISECONDS = 10 * 60 * 1e3;
|
|
12702
|
-
var TranscriptionServiceError = class extends Error {
|
|
12703
|
-
code;
|
|
12704
|
-
status;
|
|
12705
|
-
retryable;
|
|
12706
|
-
/** Explicit rejection before any transcription result; safe to try another provider. */
|
|
12707
|
-
fallbackSafe;
|
|
12708
|
-
constructor(input) {
|
|
12709
|
-
super(input.message);
|
|
12710
|
-
this.name = "TranscriptionServiceError";
|
|
12711
|
-
this.code = input.code;
|
|
12712
|
-
this.status = input.status ?? statusForVoiceInputError(input.code);
|
|
12713
|
-
this.retryable = input.retryable ?? false;
|
|
12714
|
-
this.fallbackSafe = input.fallbackSafe ?? false;
|
|
12715
|
-
}
|
|
12716
|
-
};
|
|
12717
|
-
function statusForVoiceInputError(code) {
|
|
12718
|
-
switch (code) {
|
|
12719
|
-
case "permission_denied":
|
|
12720
|
-
return 403;
|
|
12721
|
-
case "policy_blocked":
|
|
12722
|
-
return 403;
|
|
12723
|
-
case "not_supported":
|
|
12724
|
-
return 415;
|
|
12725
|
-
case "unavailable":
|
|
12726
|
-
return 503;
|
|
12727
|
-
case "too_large":
|
|
12728
|
-
return 413;
|
|
12729
|
-
case "invalid_audio":
|
|
12730
|
-
return 400;
|
|
12731
|
-
case "timeout":
|
|
12732
|
-
return 504;
|
|
12733
|
-
case "cancelled":
|
|
12734
|
-
return 499;
|
|
12735
|
-
case "network":
|
|
12736
|
-
case "provider":
|
|
12737
|
-
return 502;
|
|
12738
|
-
case "unknown":
|
|
12739
|
-
default:
|
|
12740
|
-
return 500;
|
|
12741
|
-
}
|
|
12742
|
-
}
|
|
12743
|
-
function normalizeMimeType(mimeType) {
|
|
12744
|
-
return mimeType.trim().toLowerCase();
|
|
12745
|
-
}
|
|
12746
|
-
function isAcceptedMimeType(mimeType, accepted) {
|
|
12747
|
-
const normalized = normalizeMimeType(mimeType);
|
|
12748
|
-
if (accepted.some((candidate) => normalizeMimeType(candidate) === normalized)) {
|
|
12749
|
-
return true;
|
|
12750
|
-
}
|
|
12751
|
-
const bare = normalized.split(";")[0]?.trim() ?? normalized;
|
|
12752
|
-
return accepted.some((candidate) => {
|
|
12753
|
-
const allowed = normalizeMimeType(candidate);
|
|
12754
|
-
return allowed === bare || allowed.split(";")[0]?.trim() === bare;
|
|
12755
|
-
});
|
|
12756
|
-
}
|
|
12757
|
-
function filenameForMimeType(mimeType) {
|
|
12758
|
-
const bare = normalizeMimeType(mimeType).split(";")[0] ?? "audio/webm";
|
|
12759
|
-
switch (bare) {
|
|
12760
|
-
case "audio/mp4":
|
|
12761
|
-
case "audio/m4a":
|
|
12762
|
-
return "audio.mp4";
|
|
12763
|
-
case "audio/ogg":
|
|
12764
|
-
return "audio.ogg";
|
|
12765
|
-
case "audio/mpeg":
|
|
12766
|
-
case "audio/mp3":
|
|
12767
|
-
return "audio.mp3";
|
|
12768
|
-
case "audio/wav":
|
|
12769
|
-
case "audio/x-wav":
|
|
12770
|
-
return "audio.wav";
|
|
12771
|
-
case "audio/webm":
|
|
12772
|
-
default:
|
|
12773
|
-
return "audio.webm";
|
|
12774
|
-
}
|
|
12775
|
-
}
|
|
12776
|
-
|
|
12777
13405
|
// src/goal-admission.ts
|
|
12778
13406
|
import {
|
|
12779
13407
|
isModelAvailableForNewSelection as isModelAvailableForNewSelection2,
|
|
@@ -12792,13 +13420,13 @@ import { getWorkspaceModelPolicy as getWorkspaceModelPolicy3 } from "@opengeni/d
|
|
|
12792
13420
|
// src/billing/agent-run-admission.ts
|
|
12793
13421
|
import {
|
|
12794
13422
|
canonicalizeConfiguredModelId as canonicalizeConfiguredModelId4,
|
|
12795
|
-
configuredStaticUsageLimits as
|
|
13423
|
+
configuredStaticUsageLimits as configuredStaticUsageLimits4
|
|
12796
13424
|
} from "@opengeni/config";
|
|
12797
13425
|
import {
|
|
12798
|
-
checkWorkspaceAllowance as
|
|
12799
|
-
getSpendableCreditBalance as
|
|
13426
|
+
checkWorkspaceAllowance as checkWorkspaceAllowance6,
|
|
13427
|
+
getSpendableCreditBalance as getSpendableCreditBalance6,
|
|
12800
13428
|
isCodexBilledTurn as isCodexBilledTurn2,
|
|
12801
|
-
sumUsageQuantity as
|
|
13429
|
+
sumUsageQuantity as sumUsageQuantity5
|
|
12802
13430
|
} from "@opengeni/db";
|
|
12803
13431
|
async function agentRunAdmissionDenial(services, input) {
|
|
12804
13432
|
const codexBilled = await isCodexBilledTurn2({
|
|
@@ -12822,7 +13450,7 @@ async function agentRunAdmissionDenial(services, input) {
|
|
|
12822
13450
|
});
|
|
12823
13451
|
if (!decision.allowed) return "insufficient_credits";
|
|
12824
13452
|
} else {
|
|
12825
|
-
const balance = await
|
|
13453
|
+
const balance = await getSpendableCreditBalance6(
|
|
12826
13454
|
services.db,
|
|
12827
13455
|
input.accountId,
|
|
12828
13456
|
canonicalizeConfiguredModelId4(services.settings, input.model)
|
|
@@ -12831,7 +13459,7 @@ async function agentRunAdmissionDenial(services, input) {
|
|
|
12831
13459
|
}
|
|
12832
13460
|
}
|
|
12833
13461
|
if (!externallyBilled) {
|
|
12834
|
-
const refusal = await
|
|
13462
|
+
const refusal = await checkWorkspaceAllowance6(services.db, {
|
|
12835
13463
|
accountId: input.accountId,
|
|
12836
13464
|
workspaceId: input.workspaceId,
|
|
12837
13465
|
subjectId: input.initiatingHumanSubjectId ?? null
|
|
@@ -12841,22 +13469,22 @@ async function agentRunAdmissionDenial(services, input) {
|
|
|
12841
13469
|
if (services.settings.usageLimitsMode !== "static" && services.settings.usageLimitsMode !== "managed") {
|
|
12842
13470
|
return null;
|
|
12843
13471
|
}
|
|
12844
|
-
const limits =
|
|
13472
|
+
const limits = configuredStaticUsageLimits4(services.settings);
|
|
12845
13473
|
if (!externallyBilled && limits.maxMonthlyCostMicrosPerAccount) {
|
|
12846
|
-
const used = await
|
|
13474
|
+
const used = await sumUsageQuantity5(services.db, {
|
|
12847
13475
|
accountId: input.accountId,
|
|
12848
13476
|
eventType: "model.cost",
|
|
12849
|
-
since:
|
|
13477
|
+
since: startOfUtcMonth4()
|
|
12850
13478
|
});
|
|
12851
13479
|
if (used >= limits.maxMonthlyCostMicrosPerAccount) {
|
|
12852
13480
|
return "monthly_model_cost_limit";
|
|
12853
13481
|
}
|
|
12854
13482
|
}
|
|
12855
13483
|
if (limits.maxMonthlyAgentRunsPerWorkspace) {
|
|
12856
|
-
const used = await
|
|
13484
|
+
const used = await sumUsageQuantity5(services.db, {
|
|
12857
13485
|
workspaceId: input.workspaceId,
|
|
12858
13486
|
eventType: "agent_run.created",
|
|
12859
|
-
since:
|
|
13487
|
+
since: startOfUtcMonth4()
|
|
12860
13488
|
});
|
|
12861
13489
|
if (used + input.requestedAgentRuns > limits.maxMonthlyAgentRunsPerWorkspace) {
|
|
12862
13490
|
return "monthly_agent_run_limit";
|
|
@@ -12864,7 +13492,7 @@ async function agentRunAdmissionDenial(services, input) {
|
|
|
12864
13492
|
}
|
|
12865
13493
|
return null;
|
|
12866
13494
|
}
|
|
12867
|
-
function
|
|
13495
|
+
function startOfUtcMonth4() {
|
|
12868
13496
|
const now = /* @__PURE__ */ new Date();
|
|
12869
13497
|
return new Date(Date.UTC(now.getUTCFullYear(), now.getUTCMonth(), 1));
|
|
12870
13498
|
}
|
|
@@ -13001,7 +13629,7 @@ import {
|
|
|
13001
13629
|
grantWorkspaceAccess,
|
|
13002
13630
|
listWorkspaceMembers,
|
|
13003
13631
|
lockExternalWorkspaceMembershipLifecycle as lockExternalWorkspaceMembershipLifecycle3,
|
|
13004
|
-
requireWorkspace as
|
|
13632
|
+
requireWorkspace as requireWorkspace7,
|
|
13005
13633
|
setRlsContext,
|
|
13006
13634
|
withWorkspaceSubjectRls as withWorkspaceSubjectRls3,
|
|
13007
13635
|
addExternalWorkspaceMemberOperation,
|
|
@@ -13061,7 +13689,7 @@ async function addExternalWorkspaceMemberForRequest(c, deps, workspaceId, input)
|
|
|
13061
13689
|
if (live.accountId !== grant.accountId || live.subjectId !== grant.subjectId || payload.permissions.some((permission) => !hasPermission(live.permissions, permission))) {
|
|
13062
13690
|
throw new HTTPException18(403, { message: "membership authority changed" });
|
|
13063
13691
|
}
|
|
13064
|
-
const workspace = await
|
|
13692
|
+
const workspace = await requireWorkspace7(tx, workspaceId);
|
|
13065
13693
|
if (workspace.kind !== "shared" || workspace.accountId !== authority.accountId)
|
|
13066
13694
|
throw new HTTPException18(403, {
|
|
13067
13695
|
message: "external onboarding requires a shared organization workspace"
|
|
@@ -15574,7 +16202,7 @@ import {
|
|
|
15574
16202
|
SCHEDULED_TASK_OCCURRENCE_PAYLOAD_INGRESS_HEADROOM_BYTES
|
|
15575
16203
|
} from "@opengeni/contracts";
|
|
15576
16204
|
import {
|
|
15577
|
-
allowedFirstPartyMcpToolsForSession as
|
|
16205
|
+
allowedFirstPartyMcpToolsForSession as allowedFirstPartyMcpToolsForSession5,
|
|
15578
16206
|
resolveFirstPartyMcpToolPolicy as resolveFirstPartyMcpToolPolicy2
|
|
15579
16207
|
} from "@opengeni/config";
|
|
15580
16208
|
import {
|
|
@@ -15617,7 +16245,7 @@ import {
|
|
|
15617
16245
|
getWorkspaceDefaultRigId as getWorkspaceDefaultRigId2,
|
|
15618
16246
|
withSessionRlsActorContext as withSessionRlsActorContext5,
|
|
15619
16247
|
nestedPostgresSqlState as nestedPostgresSqlState6,
|
|
15620
|
-
requireWorkspace as
|
|
16248
|
+
requireWorkspace as requireWorkspace8,
|
|
15621
16249
|
scopedKnowledgeScopeKey,
|
|
15622
16250
|
updateScheduledTask,
|
|
15623
16251
|
ScheduledTaskHeadChangedError,
|
|
@@ -15682,7 +16310,7 @@ async function scheduledConnectionTools(db, workspaceId, settings, target, taskT
|
|
|
15682
16310
|
}).toolRefs;
|
|
15683
16311
|
}
|
|
15684
16312
|
function scheduledConnectionSurfaceEligibility(settings, target) {
|
|
15685
|
-
const tools = target?.firstPartyMcpTools
|
|
16313
|
+
const tools = allowedFirstPartyMcpToolsForSession5(settings, target?.firstPartyMcpTools);
|
|
15686
16314
|
const permissions = target?.firstPartyMcpPermissions ?? DEFAULT_FIRST_PARTY_MCP_PERMISSIONS3;
|
|
15687
16315
|
return {
|
|
15688
16316
|
googleDrivePublicationEnabled: tools.includes("editable_artifact_export") && tools.includes("editable_artifact_export_status") && permissions.includes("artifacts:read") && permissions.includes("artifacts:publish"),
|
|
@@ -15793,7 +16421,7 @@ async function createValidatedScheduledTask(input) {
|
|
|
15793
16421
|
message: "Personal source tasks create a private session for each run"
|
|
15794
16422
|
});
|
|
15795
16423
|
if (learning) {
|
|
15796
|
-
const workspace = await
|
|
16424
|
+
const workspace = await requireWorkspace8(input.db, input.grant.workspaceId);
|
|
15797
16425
|
const destination = knowledgeAction?.destination.kind === "personal" || workspace.kind === "personal" || target?.tenancy?.visibility === "private" || target?.memoryScope === "user" ? "personal" : "workspace";
|
|
15798
16426
|
if (learning.scope !== destination)
|
|
15799
16427
|
throw new HTTPException26(422, {
|
|
@@ -16007,7 +16635,7 @@ async function frozenScheduledTaskCreatorPolicy(input) {
|
|
|
16007
16635
|
restricted ||= Boolean(
|
|
16008
16636
|
turnPolicy.kind === "valid" && turnPolicy.policy.credentialRestriction === "developer_setup" || sessionPolicy.kind === "valid" && sessionPolicy.policy.credentialRestriction === "developer_setup"
|
|
16009
16637
|
);
|
|
16010
|
-
const firstPartyMcpTools =
|
|
16638
|
+
const firstPartyMcpTools = allowedFirstPartyMcpToolsForSession5(
|
|
16011
16639
|
input.settings,
|
|
16012
16640
|
session.firstPartyMcpTools
|
|
16013
16641
|
);
|
|
@@ -17149,7 +17777,7 @@ async function validateScheduledTaskAgentConfig(input) {
|
|
|
17149
17777
|
);
|
|
17150
17778
|
const retainTools = unchangedCreationField("tools");
|
|
17151
17779
|
const requestedTools = retainTools ? input.payload.agentConfig.tools : validateToolRefs(input.payload.agentConfig.tools ?? [], runtimeSettings);
|
|
17152
|
-
const workspace = await
|
|
17780
|
+
const workspace = await requireWorkspace8(input.db, input.workspaceId);
|
|
17153
17781
|
if (parent?.tenancy?.visibility === "private" && workspace.kind !== "personal" && input.payload.runMode !== "existing_session" && !input.payload.targetSessionId) {
|
|
17154
17782
|
throw new HTTPException26(422, {
|
|
17155
17783
|
message: "Schedule this private chat as the existing-session target, or create the task in your Personal workspace."
|
|
@@ -17308,7 +17936,7 @@ function trimmedScheduledTaskName(name) {
|
|
|
17308
17936
|
|
|
17309
17937
|
// src/domain/scheduled-task-access.ts
|
|
17310
17938
|
import {
|
|
17311
|
-
allowedFirstPartyMcpToolsForSession as
|
|
17939
|
+
allowedFirstPartyMcpToolsForSession as allowedFirstPartyMcpToolsForSession6,
|
|
17312
17940
|
resolveFirstPartyMcpToolPolicy as resolveFirstPartyMcpToolPolicy3
|
|
17313
17941
|
} from "@opengeni/config";
|
|
17314
17942
|
import {
|
|
@@ -17330,7 +17958,7 @@ import {
|
|
|
17330
17958
|
listScheduledTaskHumanWaitAttention,
|
|
17331
17959
|
listScheduledTaskCreatorPolicies,
|
|
17332
17960
|
listScheduledTaskRunAuthNeededEvents,
|
|
17333
|
-
requireWorkspace as
|
|
17961
|
+
requireWorkspace as requireWorkspace9,
|
|
17334
17962
|
ScheduledTaskHeadChangedError as ScheduledTaskHeadChangedError2
|
|
17335
17963
|
} from "@opengeni/db";
|
|
17336
17964
|
import { HTTPException as HTTPException27 } from "hono/http-exception";
|
|
@@ -17413,7 +18041,7 @@ function sameMembers(left, right) {
|
|
|
17413
18041
|
function planScheduledTaskOpenGeniTools(input) {
|
|
17414
18042
|
const stored = input.creatorPolicy?.firstPartyMcpTools;
|
|
17415
18043
|
if (!stored) return { missing: [], policy: null };
|
|
17416
|
-
const effective = new Set(
|
|
18044
|
+
const effective = new Set(allowedFirstPartyMcpToolsForSession6(input.settings, stored));
|
|
17417
18045
|
const missing = resolveFirstPartyMcpToolPolicy3(input.settings).default.filter(
|
|
17418
18046
|
(tool) => !effective.has(tool) && !input.leaveOut?.has(tool)
|
|
17419
18047
|
);
|
|
@@ -17522,7 +18150,7 @@ async function computeScheduledTaskAccessPlan(input) {
|
|
|
17522
18150
|
const [callerRegistry, ownerRegistry, workspaceSettings] = await Promise.all([
|
|
17523
18151
|
runtimeRegistry(db, task.workspaceId, settings, input.grant.subjectId, cache),
|
|
17524
18152
|
runtimeRegistry(db, task.workspaceId, settings, ownerSubjectId, cache),
|
|
17525
|
-
input.workspaceSettings !== void 0 ? Promise.resolve(input.workspaceSettings) :
|
|
18153
|
+
input.workspaceSettings !== void 0 ? Promise.resolve(input.workspaceSettings) : requireWorkspace9(db, task.workspaceId).then((workspace) => workspace.settings)
|
|
17526
18154
|
]);
|
|
17527
18155
|
const followsTask = scheduledTaskToolsFollowTask(task);
|
|
17528
18156
|
const target = task.runMode === "existing_session" && task.targetSessionId ? await getSession6(db, task.workspaceId, task.targetSessionId) : null;
|
|
@@ -17628,7 +18256,7 @@ async function withScheduledTaskPolicyDrift(input) {
|
|
|
17628
18256
|
workspaceId,
|
|
17629
18257
|
actionable.map((task) => task.id)
|
|
17630
18258
|
),
|
|
17631
|
-
|
|
18259
|
+
requireWorkspace9(input.db, workspaceId).then((workspace) => workspace.settings)
|
|
17632
18260
|
]);
|
|
17633
18261
|
} catch (error) {
|
|
17634
18262
|
input.onError?.(error);
|
|
@@ -17790,7 +18418,7 @@ async function scheduledTasksWithUnavailableAccounts(input) {
|
|
|
17790
18418
|
if (actionable.length === 0) return [];
|
|
17791
18419
|
let workspaceSettings;
|
|
17792
18420
|
try {
|
|
17793
|
-
workspaceSettings = (await
|
|
18421
|
+
workspaceSettings = (await requireWorkspace9(input.db, input.grant.workspaceId)).settings;
|
|
17794
18422
|
} catch (error) {
|
|
17795
18423
|
input.onError?.(error);
|
|
17796
18424
|
return [];
|
|
@@ -17932,7 +18560,7 @@ function orderScheduledTaskAccessAttention(items) {
|
|
|
17932
18560
|
}
|
|
17933
18561
|
|
|
17934
18562
|
// src/domain/insights.ts
|
|
17935
|
-
import { configuredStaticUsageLimits as
|
|
18563
|
+
import { configuredStaticUsageLimits as configuredStaticUsageLimits5 } from "@opengeni/config";
|
|
17936
18564
|
import {
|
|
17937
18565
|
WorkspaceInsightsSnapshot
|
|
17938
18566
|
} from "@opengeni/contracts";
|
|
@@ -17949,7 +18577,7 @@ import {
|
|
|
17949
18577
|
listScheduledTasks,
|
|
17950
18578
|
readWorkspaceInsightsModelBundle,
|
|
17951
18579
|
readWorkspaceInsightsUsageBundle,
|
|
17952
|
-
requireWorkspace as
|
|
18580
|
+
requireWorkspace as requireWorkspace10
|
|
17953
18581
|
} from "@opengeni/db";
|
|
17954
18582
|
|
|
17955
18583
|
// src/domain/insights-timing.ts
|
|
@@ -18063,7 +18691,7 @@ function cacheHitPct(cached2, input) {
|
|
|
18063
18691
|
function startOfUtcDay(date) {
|
|
18064
18692
|
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate()));
|
|
18065
18693
|
}
|
|
18066
|
-
function
|
|
18694
|
+
function startOfUtcMonth5(date) {
|
|
18067
18695
|
return new Date(Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1));
|
|
18068
18696
|
}
|
|
18069
18697
|
function startOfUtcYear(date) {
|
|
@@ -18092,7 +18720,7 @@ function resolveRangeWindow(range, now) {
|
|
|
18092
18720
|
cacheSeriesLabel = "Cache hit % / UTC day";
|
|
18093
18721
|
break;
|
|
18094
18722
|
case "month":
|
|
18095
|
-
since =
|
|
18723
|
+
since = startOfUtcMonth5(now);
|
|
18096
18724
|
rangeLabel = "This month (UTC)";
|
|
18097
18725
|
priorLabel = "Prior equal window";
|
|
18098
18726
|
seriesLabel = "Credit $ / UTC day";
|
|
@@ -18189,7 +18817,7 @@ async function getWorkspaceInsights(db, settings, input, observePhase) {
|
|
|
18189
18817
|
await measureInsightsPhase(
|
|
18190
18818
|
observePhase,
|
|
18191
18819
|
"require_workspace",
|
|
18192
|
-
() =>
|
|
18820
|
+
() => requireWorkspace10(db, input.workspaceId)
|
|
18193
18821
|
);
|
|
18194
18822
|
const [visibleRootScope, visibleSessionScope] = await Promise.all([
|
|
18195
18823
|
rootSessionId ? getSessionAccessProjection(db, input.workspaceId, rootSessionId) : null,
|
|
@@ -18223,7 +18851,7 @@ async function getWorkspaceInsights(db, settings, input, observePhase) {
|
|
|
18223
18851
|
until: window.until,
|
|
18224
18852
|
priorSince: window.priorSince,
|
|
18225
18853
|
priorUntil: window.priorUntil,
|
|
18226
|
-
monthSince:
|
|
18854
|
+
monthSince: startOfUtcMonth5(now),
|
|
18227
18855
|
granularity: input.range === "today" ? "hour" : "day",
|
|
18228
18856
|
warmGroupLimit: 24
|
|
18229
18857
|
})
|
|
@@ -18466,7 +19094,7 @@ async function getWorkspaceInsights(db, settings, input, observePhase) {
|
|
|
18466
19094
|
billing: fact ? billingPathOf(fact.billingPath) : null
|
|
18467
19095
|
};
|
|
18468
19096
|
});
|
|
18469
|
-
const limits =
|
|
19097
|
+
const limits = configuredStaticUsageLimits5(settings);
|
|
18470
19098
|
const floor = floorRows.filter((row) => {
|
|
18471
19099
|
if (!model) return true;
|
|
18472
19100
|
return row.model === model;
|
|
@@ -20714,7 +21342,7 @@ async function submitComposerDraftForRequest(deps, grant, workspaceId, sessionId
|
|
|
20714
21342
|
import { DraftTimelineAnnotations as DraftTimelineAnnotations3 } from "@opengeni/contracts";
|
|
20715
21343
|
import { HTTPException as HTTPException30 } from "hono/http-exception";
|
|
20716
21344
|
import {
|
|
20717
|
-
checkWorkspaceAllowance as
|
|
21345
|
+
checkWorkspaceAllowance as checkWorkspaceAllowance7,
|
|
20718
21346
|
deleteSessionQueueItemInTransaction,
|
|
20719
21347
|
editQueuedTurnInTransaction,
|
|
20720
21348
|
getComposerDraftInTransaction as getComposerDraftInTransaction2,
|
|
@@ -20812,7 +21440,7 @@ async function assertFreshAgentCommandAllowance(tx, deps, context, targetSession
|
|
|
20812
21440
|
}
|
|
20813
21441
|
}
|
|
20814
21442
|
const frozen = await frozenInitiatorForCommandActor2(tx, context.workspaceId, agentActor(context));
|
|
20815
|
-
const refusal = await
|
|
21443
|
+
const refusal = await checkWorkspaceAllowance7(tx, {
|
|
20816
21444
|
accountId: target.accountId,
|
|
20817
21445
|
workspaceId: context.workspaceId,
|
|
20818
21446
|
subjectId: initiatingHumanForAllowance(frozen)
|
|
@@ -21755,6 +22383,7 @@ import {
|
|
|
21755
22383
|
directIntegrationTransport,
|
|
21756
22384
|
IntegrationInvocationError
|
|
21757
22385
|
} from "@opengeni/capabilities";
|
|
22386
|
+
import { apiIntegrationToolEffect } from "@opengeni/db";
|
|
21758
22387
|
function buildApiIntegrationMcpServers(input) {
|
|
21759
22388
|
const transport = createPinnedIntegrationTransport({
|
|
21760
22389
|
network: input.settings,
|
|
@@ -21784,6 +22413,14 @@ function buildApiIntegrationMcpServers(input) {
|
|
|
21784
22413
|
return {
|
|
21785
22414
|
id: integration.serverId,
|
|
21786
22415
|
server,
|
|
22416
|
+
effectAuthority: (toolName) => ({
|
|
22417
|
+
kind: "api_integration",
|
|
22418
|
+
instanceId: integration.instanceId,
|
|
22419
|
+
baseUrl: integration.baseUrl,
|
|
22420
|
+
connectionRef: integration.connectionRef,
|
|
22421
|
+
connectionAuthorityGeneration: integration.connectionAuthorityGeneration,
|
|
22422
|
+
effect: apiIntegrationToolEffect(integration.revision, toolName)
|
|
22423
|
+
}),
|
|
21787
22424
|
approvalAuthority: {
|
|
21788
22425
|
kind: "api_integration",
|
|
21789
22426
|
capabilityId: integration.capabilityId,
|
|
@@ -22113,6 +22750,7 @@ async function retainKnowledgeMessage(db, context, messageId) {
|
|
|
22113
22750
|
|
|
22114
22751
|
// src/domain/connector-tool-permissions.ts
|
|
22115
22752
|
import { slackRestMcpToolsForScopes } from "@opengeni/contracts/slack-rest-mcp";
|
|
22753
|
+
import { connectionAccountIdentityLabel as connectionAccountIdentityLabel2 } from "@opengeni/contracts/connection-account-label";
|
|
22116
22754
|
import { createHash as createHash11 } from "crypto";
|
|
22117
22755
|
import { Client as Client2 } from "@modelcontextprotocol/sdk/client/index.js";
|
|
22118
22756
|
import { StreamableHTTPClientTransport as StreamableHTTPClientTransport2 } from "@modelcontextprotocol/sdk/client/streamableHttp.js";
|
|
@@ -22125,15 +22763,19 @@ import { createPinnedIntegrationTransport as createPinnedIntegrationTransport2 }
|
|
|
22125
22763
|
import {
|
|
22126
22764
|
buildConnectionTokenResolver,
|
|
22127
22765
|
getConnectionMetadata as getConnectionMetadata5,
|
|
22128
|
-
listConnectionsMetadata as listConnectionsMetadata4,
|
|
22129
22766
|
listEnabledMcpCapabilityServers as listEnabledMcpCapabilityServers3,
|
|
22130
22767
|
listConnectorToolPermissionPolicies,
|
|
22768
|
+
listChangedConnectorToolPermissions,
|
|
22131
22769
|
updateConnectorToolPermissionPolicies,
|
|
22132
|
-
|
|
22770
|
+
projectConnectorToolPermission,
|
|
22771
|
+
connectorToolPolicyRevision,
|
|
22772
|
+
ConnectorToolPermissionConflictError,
|
|
22773
|
+
listInstalledApiIntegrations as listInstalledApiIntegrations2
|
|
22133
22774
|
} from "@opengeni/db";
|
|
22134
22775
|
import { HTTPException as HTTPException32 } from "hono/http-exception";
|
|
22135
22776
|
import {
|
|
22136
22777
|
GMAIL_REST_MCP_TOOLS,
|
|
22778
|
+
gmailToolAvailableOnDeployment,
|
|
22137
22779
|
gmailToolSupportsScopes,
|
|
22138
22780
|
isOfficialGmailMcpConfig,
|
|
22139
22781
|
isOfficialSlackMcpConfig
|
|
@@ -22159,9 +22801,50 @@ function connectorToolPermissionReference(ref, connectionId) {
|
|
|
22159
22801
|
}
|
|
22160
22802
|
async function resolveTarget2(input) {
|
|
22161
22803
|
if (input.capabilityId.startsWith("api:")) {
|
|
22162
|
-
|
|
22163
|
-
|
|
22164
|
-
|
|
22804
|
+
const integrations = (await listInstalledApiIntegrations2(
|
|
22805
|
+
input.db,
|
|
22806
|
+
input.workspaceId,
|
|
22807
|
+
input.personalOwnerVerified ? input.grant.subjectId : void 0
|
|
22808
|
+
)).filter((integration2) => integration2.capabilityId === input.capabilityId);
|
|
22809
|
+
const accountId = (integration2) => integration2.connectionRef?.connectionId ?? `session-mcp:${integration2.serverId}:${createHash11("sha256").update(integration2.baseUrl, "utf8").digest("hex")}`;
|
|
22810
|
+
const integration = integrations.find(
|
|
22811
|
+
(candidate) => (!input.instanceKey || candidate.instanceKey === input.instanceKey) && (!input.connectionId || accountId(candidate) === input.connectionId)
|
|
22812
|
+
);
|
|
22813
|
+
if (!integration) throw new HTTPException32(404, { message: "Integration account unavailable" });
|
|
22814
|
+
const server2 = settingsWithApiIntegrationServers({ ...input.settings, mcpServers: [] }, [
|
|
22815
|
+
integration
|
|
22816
|
+
]).mcpServers[0];
|
|
22817
|
+
const connection2 = integration.connectionRef?.connectionId ? await getConnectionMetadata5(
|
|
22818
|
+
input.db,
|
|
22819
|
+
input.workspaceId,
|
|
22820
|
+
integration.connectionRef.connectionId,
|
|
22821
|
+
input.grant.subjectId
|
|
22822
|
+
) : null;
|
|
22823
|
+
const accounts = integrations.map((candidate) => ({
|
|
22824
|
+
connectionId: accountId(candidate),
|
|
22825
|
+
label: candidate.displayName,
|
|
22826
|
+
scope: candidate.connectionRef?.subjectScope === "subject" ? "personal" : candidate.connectionRef ? "workspace" : "none",
|
|
22827
|
+
instanceKey: candidate.instanceKey
|
|
22828
|
+
}));
|
|
22829
|
+
return {
|
|
22830
|
+
server: server2,
|
|
22831
|
+
connection: connection2,
|
|
22832
|
+
connectionId: accountId(integration),
|
|
22833
|
+
accountLabel: connection2 ? connectionAccountIdentityLabel2(connection2.metadata, integration.displayName) : integration.displayName,
|
|
22834
|
+
accounts,
|
|
22835
|
+
instanceKey: integration.instanceKey,
|
|
22836
|
+
listedTools: integration.revision.tools.filter((tool) => integration.allowedTools.includes(tool.id)).map(
|
|
22837
|
+
(tool) => ({
|
|
22838
|
+
name: tool.id,
|
|
22839
|
+
title: tool.name,
|
|
22840
|
+
description: tool.description,
|
|
22841
|
+
annotations: {
|
|
22842
|
+
readOnlyHint: tool.safety === "read",
|
|
22843
|
+
destructiveHint: tool.safety === "destructive"
|
|
22844
|
+
}
|
|
22845
|
+
})
|
|
22846
|
+
)
|
|
22847
|
+
};
|
|
22165
22848
|
}
|
|
22166
22849
|
const catalog = await buildCapabilityCatalog(input);
|
|
22167
22850
|
const item = catalog.items.find((candidate) => candidate.id === input.capabilityId);
|
|
@@ -22174,25 +22857,32 @@ async function resolveTarget2(input) {
|
|
|
22174
22857
|
if (!server || server.url !== item.endpointUrl)
|
|
22175
22858
|
throw new HTTPException32(409, { message: "Connector configuration is unavailable" });
|
|
22176
22859
|
const ref = server.connectionRef;
|
|
22177
|
-
if (ref?.
|
|
22178
|
-
throw new HTTPException32(
|
|
22179
|
-
message: "
|
|
22860
|
+
if (ref?.subjectScope === "subject" && ref.accountSelection !== "all_eligible" && !input.personalOwnerVerified)
|
|
22861
|
+
throw new HTTPException32(403, {
|
|
22862
|
+
message: "Only the authenticated connection owner may manage personal tool permissions"
|
|
22180
22863
|
});
|
|
22181
|
-
|
|
22182
|
-
|
|
22183
|
-
input.
|
|
22184
|
-
|
|
22185
|
-
input.
|
|
22186
|
-
) :
|
|
22187
|
-
|
|
22188
|
-
|
|
22189
|
-
|
|
22190
|
-
|
|
22191
|
-
|
|
22192
|
-
|
|
22193
|
-
|
|
22194
|
-
|
|
22195
|
-
|
|
22864
|
+
const source = personalConnectionDelegationSourceForGrant(input.grant);
|
|
22865
|
+
const visible = ref ? await visibleMcpAccountConnections(input.db, {
|
|
22866
|
+
accountId: input.grant.accountId,
|
|
22867
|
+
workspaceId: input.workspaceId,
|
|
22868
|
+
source: input.personalOwnerVerified && source.kind === "subject" ? source : { kind: "none" }
|
|
22869
|
+
}) : [];
|
|
22870
|
+
const bindings = mcpAccountBindingsFromVisibleConnections({
|
|
22871
|
+
accountId: input.grant.accountId,
|
|
22872
|
+
workspaceId: input.workspaceId,
|
|
22873
|
+
subjectId: input.personalOwnerVerified ? input.grant.subjectId : null,
|
|
22874
|
+
servers: [server],
|
|
22875
|
+
// Runtime admission can enumerate every eligible account. A permission
|
|
22876
|
+
// selector must also preserve the installation's explicit owner scope.
|
|
22877
|
+
connections: ref?.accountSelection === "all_eligible" ? visible : visible.filter(
|
|
22878
|
+
(candidate) => ref?.subjectScope === "subject" ? candidate.subjectId === input.grant.subjectId : candidate.subjectId === null
|
|
22879
|
+
)
|
|
22880
|
+
});
|
|
22881
|
+
const binding = bindings.find(
|
|
22882
|
+
(candidate) => !input.connectionId || candidate.connectionId === input.connectionId
|
|
22883
|
+
);
|
|
22884
|
+
const connection = visible.find((candidate) => candidate.id === binding?.connectionId) ?? null;
|
|
22885
|
+
if (ref && !connection) {
|
|
22196
22886
|
throw new HTTPException32(409, { message: "Reconnect this connector to manage its tools" });
|
|
22197
22887
|
}
|
|
22198
22888
|
if (connection?.subjectId && !input.personalOwnerVerified)
|
|
@@ -22200,16 +22890,38 @@ async function resolveTarget2(input) {
|
|
|
22200
22890
|
message: "Only the authenticated connection owner may manage personal tool permissions"
|
|
22201
22891
|
});
|
|
22202
22892
|
const connectionId = connection?.id ?? `session-mcp:${server.id}:${createHash11("sha256").update(server.url, "utf8").digest("hex")}`;
|
|
22203
|
-
|
|
22893
|
+
if (input.connectionId && input.connectionId !== connectionId)
|
|
22894
|
+
throw new HTTPException32(409, {
|
|
22895
|
+
message: "Connector account unavailable. Reload its permissions."
|
|
22896
|
+
});
|
|
22897
|
+
return {
|
|
22898
|
+
server: binding ? { ...server, connectionRef: binding.connectionRef } : server,
|
|
22899
|
+
connection,
|
|
22900
|
+
connectionId,
|
|
22901
|
+
accountLabel: binding?.accountLabel ?? server.name ?? server.id,
|
|
22902
|
+
accounts: bindings.map((candidate) => ({
|
|
22903
|
+
connectionId: candidate.connectionId,
|
|
22904
|
+
label: candidate.accountLabel,
|
|
22905
|
+
scope: candidate.subjectScope === "subject" ? "personal" : "workspace"
|
|
22906
|
+
})),
|
|
22907
|
+
instanceKey: void 0,
|
|
22908
|
+
listedTools: null
|
|
22909
|
+
};
|
|
22204
22910
|
}
|
|
22205
|
-
function reviewedConnectorToolCatalog(server, grantedScopes) {
|
|
22206
|
-
const tools = isOfficialGmailMcpConfig(server.url, server.connectionRef) ? GMAIL_REST_MCP_TOOLS.filter(
|
|
22911
|
+
function reviewedConnectorToolCatalog(server, grantedScopes, deployment) {
|
|
22912
|
+
const tools = isOfficialGmailMcpConfig(server.url, server.connectionRef) ? GMAIL_REST_MCP_TOOLS.filter(
|
|
22913
|
+
(tool) => gmailToolSupportsScopes(tool.name, grantedScopes) && gmailToolAvailableOnDeployment(tool.name, {
|
|
22914
|
+
watchTopicName: deployment.gmailWatchTopicName
|
|
22915
|
+
})
|
|
22916
|
+
) : isOfficialSlackMcpConfig(server.url, server.connectionRef) ? slackRestMcpToolsForScopes(grantedScopes) : null;
|
|
22207
22917
|
return tools?.filter((tool) => !server.allowedTools || server.allowedTools.includes(tool.name)) ?? null;
|
|
22208
22918
|
}
|
|
22209
22919
|
async function listTools(input, target) {
|
|
22920
|
+
if (target.listedTools !== null) return target.listedTools;
|
|
22210
22921
|
const reviewed = reviewedConnectorToolCatalog(
|
|
22211
22922
|
target.server,
|
|
22212
|
-
target.connection?.grantedScopes ?? []
|
|
22923
|
+
target.connection?.grantedScopes ?? [],
|
|
22924
|
+
input.settings
|
|
22213
22925
|
);
|
|
22214
22926
|
if (reviewed !== null) return reviewed;
|
|
22215
22927
|
let headers = { ...target.server.headers };
|
|
@@ -22218,7 +22930,9 @@ async function listTools(input, target) {
|
|
|
22218
22930
|
input.db,
|
|
22219
22931
|
input.settings
|
|
22220
22932
|
)({
|
|
22221
|
-
|
|
22933
|
+
// The selected account's credentials remain in its origin workspace;
|
|
22934
|
+
// approval preferences remain scoped to the workspace being configured.
|
|
22935
|
+
workspaceId: target.connection?.workspaceId ?? input.workspaceId,
|
|
22222
22936
|
...target.connection?.subjectId ? { subjectId: input.grant.subjectId } : {},
|
|
22223
22937
|
serverId: target.server.id,
|
|
22224
22938
|
toolName: "tools/list",
|
|
@@ -22288,19 +23002,14 @@ async function getConnectorToolPermissions(input) {
|
|
|
22288
23002
|
workspaceId: input.workspaceId,
|
|
22289
23003
|
connectionId: target.connectionId
|
|
22290
23004
|
});
|
|
22291
|
-
const
|
|
22292
|
-
|
|
23005
|
+
const changedTools = new Set(
|
|
23006
|
+
await listChangedConnectorToolPermissions(input.db, {
|
|
23007
|
+
accountId: input.grant.accountId,
|
|
23008
|
+
workspaceId: input.workspaceId,
|
|
22293
23009
|
connectionId: target.connectionId,
|
|
22294
|
-
serverId: target.server.id
|
|
22295
|
-
|
|
22296
|
-
|
|
22297
|
-
});
|
|
22298
|
-
if (!resolved.managed) return { permission: "allow", inherited: true };
|
|
22299
|
-
return {
|
|
22300
|
-
permission: resolved.entry?.policy ?? "block",
|
|
22301
|
-
inherited: resolved.entry?.toolName !== name
|
|
22302
|
-
};
|
|
22303
|
-
};
|
|
23010
|
+
serverId: target.server.id
|
|
23011
|
+
})
|
|
23012
|
+
);
|
|
22304
23013
|
const defaultPolicy = policies.find(
|
|
22305
23014
|
(row) => row.serverId === target.server.id && row.toolName === "*" && row.actionName === "*"
|
|
22306
23015
|
);
|
|
@@ -22322,15 +23031,25 @@ async function getConnectorToolPermissions(input) {
|
|
|
22322
23031
|
tools: tools.map(
|
|
22323
23032
|
(tool) => ({
|
|
22324
23033
|
name: tool.name,
|
|
23034
|
+
...changedTools.has(tool.name) ? { resetReason: "operation_changed" } : {},
|
|
22325
23035
|
...tool.title ?? tool.annotations?.title ? { title: tool.title ?? tool.annotations?.title } : {},
|
|
22326
23036
|
...tool.description ? { description: tool.description } : {},
|
|
22327
23037
|
group: connectorToolGroup(tool),
|
|
22328
|
-
...
|
|
22329
|
-
|
|
23038
|
+
...projectConnectorToolPermission(policies, {
|
|
23039
|
+
connectionId: target.connectionId,
|
|
23040
|
+
serverId: target.server.id,
|
|
23041
|
+
toolName: tool.name,
|
|
23042
|
+
defaultDecision: target.server.requireApproval === true || Array.isArray(target.server.requireApproval) && target.server.requireApproval.includes(tool.name) ? "ask" : "allow"
|
|
23043
|
+
})
|
|
22330
23044
|
})
|
|
22331
23045
|
),
|
|
22332
23046
|
discoveryError,
|
|
22333
|
-
canManage: canManageConnectorPermissions(input.grant)
|
|
23047
|
+
canManage: canManageConnectorPermissions(input.grant),
|
|
23048
|
+
appliesTo: "next_attempt",
|
|
23049
|
+
revision: connectorToolPolicyRevision(policies, target.connectionId, target.server.id),
|
|
23050
|
+
accountLabel: target.accountLabel,
|
|
23051
|
+
accounts: target.accounts,
|
|
23052
|
+
...target.instanceKey ? { instanceKey: target.instanceKey } : {}
|
|
22334
23053
|
};
|
|
22335
23054
|
}
|
|
22336
23055
|
function canManageConnectorPermissions(grant) {
|
|
@@ -22343,20 +23062,32 @@ async function updateConnectorToolPermissions(input) {
|
|
|
22343
23062
|
throw new HTTPException32(400, {
|
|
22344
23063
|
message: "Tool names must be exact and cannot use the connector-default wildcard."
|
|
22345
23064
|
});
|
|
22346
|
-
const target = await resolveTarget2(
|
|
23065
|
+
const target = await resolveTarget2({
|
|
23066
|
+
...input,
|
|
23067
|
+
connectionId: input.payload.connectionId,
|
|
23068
|
+
...input.payload.instanceKey ? { instanceKey: input.payload.instanceKey } : {}
|
|
23069
|
+
});
|
|
22347
23070
|
if (target.connectionId !== input.payload.connectionId)
|
|
22348
23071
|
throw new HTTPException32(409, {
|
|
22349
23072
|
message: "The connector account changed. Reload its permissions."
|
|
22350
23073
|
});
|
|
22351
|
-
|
|
22352
|
-
|
|
22353
|
-
|
|
22354
|
-
|
|
22355
|
-
|
|
22356
|
-
|
|
22357
|
-
|
|
22358
|
-
|
|
22359
|
-
|
|
23074
|
+
try {
|
|
23075
|
+
await updateConnectorToolPermissionPolicies(input.db, {
|
|
23076
|
+
accountId: input.grant.accountId,
|
|
23077
|
+
workspaceId: input.workspaceId,
|
|
23078
|
+
subjectId: input.grant.subjectId,
|
|
23079
|
+
connectionId: target.connectionId,
|
|
23080
|
+
serverId: target.server.id,
|
|
23081
|
+
toolNames: input.payload.target === "default" ? ["*"] : input.payload.target === "action" ? [input.payload.toolName] : input.payload.toolNames,
|
|
23082
|
+
...input.payload.target === "action" ? { actionName: input.payload.actionName } : {},
|
|
23083
|
+
...input.payload.expectedRevision ? { expectedRevision: input.payload.expectedRevision } : {},
|
|
23084
|
+
policy: input.payload.permission
|
|
23085
|
+
});
|
|
23086
|
+
} catch (error) {
|
|
23087
|
+
if (error instanceof ConnectorToolPermissionConflictError)
|
|
23088
|
+
throw new HTTPException32(409, { message: error.message });
|
|
23089
|
+
throw error;
|
|
23090
|
+
}
|
|
22360
23091
|
}
|
|
22361
23092
|
export {
|
|
22362
23093
|
ArchivedSessionImportError2 as ArchivedSessionImportError,
|
|
@@ -22458,7 +23189,11 @@ export {
|
|
|
22458
23189
|
PR_REVIEW_AUTOMATION_SETUP,
|
|
22459
23190
|
ProductionEditableArtifactSnapshotVerifier,
|
|
22460
23191
|
PublicSkillSearchError,
|
|
23192
|
+
REALTIME_VOICE_DEBIT_TYPE,
|
|
23193
|
+
REALTIME_VOICE_INSUFFICIENT_CREDITS_MESSAGE,
|
|
23194
|
+
REALTIME_VOICE_SOURCE_TYPE,
|
|
22461
23195
|
RIG_DEFAULT_VARIABLE_SET_LOAD_CONCURRENCY,
|
|
23196
|
+
RealtimeVoiceUnavailableError,
|
|
22462
23197
|
SESSION_AUTHORIZATION_DEFAULT_REAUTHORIZE_MS,
|
|
22463
23198
|
SESSION_CREATED_BY_KINDS,
|
|
22464
23199
|
SESSION_WORKFLOW_WAKE_DISPATCHER_PERIOD_MS,
|
|
@@ -22477,14 +23212,20 @@ export {
|
|
|
22477
23212
|
SystemEditableArtifactLiveScheduler,
|
|
22478
23213
|
TRANSCRIPTION_PROVIDER_REQUEST_TIMEOUT_MILLISECONDS,
|
|
22479
23214
|
TURN_ACTIVITY_CANCELLATION_HEARTBEAT_INTERVAL_MS,
|
|
23215
|
+
TranscriptionBillingRefusedError,
|
|
22480
23216
|
TranscriptionServiceError,
|
|
22481
23217
|
USER_PRESENCE_FLUSH_DELAY_MS,
|
|
22482
23218
|
USER_PRESENCE_THROTTLE_MS,
|
|
22483
23219
|
VIDEO_GENERATION_ADAPTER_VERSION,
|
|
22484
23220
|
VIDEO_GENERATION_MODEL_CATALOG,
|
|
23221
|
+
VOICE_INPUT_DEBIT_TYPE,
|
|
23222
|
+
VOICE_INPUT_SOURCE_TYPE,
|
|
23223
|
+
WEB_SEARCH_DEBIT_TYPE,
|
|
23224
|
+
WEB_SEARCH_SOURCE_TYPE,
|
|
22485
23225
|
WORKSPACE_INSIGHTS_MODEL_FILTER_MAX_UTF8_BYTES,
|
|
22486
23226
|
WORKSPACE_INSIGHTS_PROVIDER_FILTER_MAX_UTF8_BYTES,
|
|
22487
23227
|
WebCryptoEditableArtifactLiveTokens,
|
|
23228
|
+
WebSearchBillingRefusedError,
|
|
22488
23229
|
WorkspaceInsightsFilterValidationError,
|
|
22489
23230
|
acceptSessionUserMessage,
|
|
22490
23231
|
acceptSessionUserMessageWithOutcome,
|
|
@@ -22577,12 +23318,15 @@ export {
|
|
|
22577
23318
|
createCompanyProfileDurableLearningAdapter,
|
|
22578
23319
|
createGitHubSkillSourceClient,
|
|
22579
23320
|
createPublicSkillSearchClient,
|
|
23321
|
+
createRealtimeVoiceBilling,
|
|
22580
23322
|
createRigForApi,
|
|
22581
23323
|
createRigVersionForApi,
|
|
22582
23324
|
createSessionForRequest,
|
|
22583
23325
|
createSessionForRequestWithOutcome,
|
|
22584
23326
|
createUserPresenceRecorder,
|
|
22585
23327
|
createValidatedScheduledTask,
|
|
23328
|
+
createVoiceInputBilling,
|
|
23329
|
+
createWebSearchBilling,
|
|
22586
23330
|
creationInitiatorForGrant,
|
|
22587
23331
|
creditsDefaultSessionModel,
|
|
22588
23332
|
decodeEditableArtifactBrokerHint,
|
|
@@ -22595,6 +23339,7 @@ export {
|
|
|
22595
23339
|
deleteHumanQueuePrompt,
|
|
22596
23340
|
deleteRigForApi,
|
|
22597
23341
|
deleteScheduledTaskLifecycle,
|
|
23342
|
+
deploymentRealtimeVoice,
|
|
22598
23343
|
describeConfiguredExportFormats,
|
|
22599
23344
|
describeEditableArtifactExportFormats,
|
|
22600
23345
|
directPersonalConnectionSubjectId,
|
|
@@ -22818,6 +23563,9 @@ export {
|
|
|
22818
23563
|
readSessionAttachmentFiles,
|
|
22819
23564
|
readSessionLineage,
|
|
22820
23565
|
readSkill,
|
|
23566
|
+
realtimeVoiceOfferProblem,
|
|
23567
|
+
reconcileUnsettledVoiceInputCharges,
|
|
23568
|
+
recordManagedAuthLoggedFailure,
|
|
22821
23569
|
recordRigAuditEvent,
|
|
22822
23570
|
recordSessionCreated,
|
|
22823
23571
|
recordUserMessageAccepted,
|
|
@@ -22953,6 +23701,7 @@ export {
|
|
|
22953
23701
|
settingsWithRigProviderImage,
|
|
22954
23702
|
settingsWithSessionMcpServerMetadata,
|
|
22955
23703
|
settingsWithWorkspaceSandboxImage,
|
|
23704
|
+
settleVoiceInputUsage,
|
|
22956
23705
|
signedJsonAutomationAdapter,
|
|
22957
23706
|
skillBundleHash,
|
|
22958
23707
|
stableJson,
|
|
@@ -23010,9 +23759,12 @@ export {
|
|
|
23010
23759
|
videoGenerationProviderIdempotencyKey,
|
|
23011
23760
|
videoGenerationRequestDigest,
|
|
23012
23761
|
visibleMcpAccountConnections,
|
|
23762
|
+
voiceInputBillableUsage,
|
|
23763
|
+
webSearchCreditBillingActive,
|
|
23013
23764
|
withAgentConfigHttpErrors,
|
|
23014
23765
|
withDefaultEnabledCapabilityMcpTools,
|
|
23015
23766
|
withFrozenPersonalConnectionDelegations,
|
|
23767
|
+
withManagedAuthSessionLookup,
|
|
23016
23768
|
withResolvedSessionAuthorization,
|
|
23017
23769
|
withSameRequestSessionMcpServerTools,
|
|
23018
23770
|
withScheduledSlackBotPostingTools,
|