@fonoster/apiserver 0.30.0 → 0.31.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (159) hide show
  1. package/dist/applications/buildService.d.ts +1 -1
  2. package/dist/applications/buildService.js +4 -3
  3. package/dist/applications/createCreateApplication.js +6 -3
  4. package/dist/applications/createCreateTestToken.d.ts +3 -1
  5. package/dist/applications/createCreateTestToken.js +18 -13
  6. package/dist/applications/createGetFnUtil.d.ts +1 -1
  7. package/dist/applications/createUpdateApplication.js +6 -4
  8. package/dist/applications/evalKeys.d.ts +7 -1
  9. package/dist/applications/evalKeys.js +9 -3
  10. package/dist/applications/session/appModel.d.ts +28 -4
  11. package/dist/applications/session/appModel.js +74 -35
  12. package/dist/billing/buildService.d.ts +24 -0
  13. package/dist/billing/buildService.js +116 -0
  14. package/dist/{migration/cli.js → bin/usage.js} +46 -22
  15. package/dist/calls/buildService.d.ts +1 -20
  16. package/dist/calls/buildService.js +50 -10
  17. package/dist/calls/createCall.d.ts +16 -2
  18. package/dist/calls/createCall.js +29 -6
  19. package/dist/calls/createCallPublisher.d.ts +6 -4
  20. package/dist/calls/createCallPublisher.js +6 -5
  21. package/dist/calls/createTrackCall.d.ts +16 -13
  22. package/dist/calls/createTrackCall.js +78 -55
  23. package/dist/calls/getCall.d.ts +3 -3
  24. package/dist/calls/getCall.js +2 -3
  25. package/dist/calls/listCalls.d.ts +4 -4
  26. package/dist/calls/listCalls.js +2 -3
  27. package/dist/calls/types.d.ts +2 -1
  28. package/dist/capabilities/createGetCapabilities.d.ts +3 -0
  29. package/dist/capabilities/createGetCapabilities.js +2 -1
  30. package/dist/config/index.js +1 -3
  31. package/dist/config/schema.d.ts +106 -102
  32. package/dist/config/schema.js +39 -47
  33. package/dist/core/applyCatalog.d.ts +3 -3
  34. package/dist/core/applyCatalog.js +5 -4
  35. package/dist/core/regionHooks.d.ts +1 -0
  36. package/dist/core/runServices.js +25 -4
  37. package/dist/core/services.d.ts +25 -1
  38. package/dist/core/services.js +35 -11
  39. package/dist/core/testTokenConfig.js +2 -2
  40. package/dist/core/upsertRoomrPeer.d.ts +6 -0
  41. package/dist/core/{upsertMediaNodePeer.js → upsertRoomrPeer.js} +9 -9
  42. package/dist/envs.d.ts +30 -16
  43. package/dist/envs.js +49 -31
  44. package/dist/index.js +23 -22
  45. package/dist/outbound/createNodeDirectory.d.ts +35 -13
  46. package/dist/outbound/createNodeDirectory.js +54 -20
  47. package/dist/outbound/index.d.ts +1 -0
  48. package/dist/outbound/index.js +1 -0
  49. package/dist/outbound/placeOutboundCall.d.ts +53 -13
  50. package/dist/outbound/placeOutboundCall.js +135 -88
  51. package/dist/outbound/placementSweep.d.ts +56 -0
  52. package/dist/outbound/placementSweep.js +127 -0
  53. package/dist/outbound/runOutboundCalls.d.ts +18 -14
  54. package/dist/outbound/runOutboundCalls.js +46 -34
  55. package/dist/providers/createProvidersHandlers.d.ts +1 -10
  56. package/dist/providers/createProvidersHandlers.js +20 -25
  57. package/dist/providers/index.d.ts +2 -2
  58. package/dist/providers/index.js +2 -2
  59. package/dist/providers/registryUsage.d.ts +2 -2
  60. package/dist/providers/registryUsage.js +5 -5
  61. package/dist/records/createIndexRecord.d.ts +26 -3
  62. package/dist/records/createIndexRecord.js +37 -10
  63. package/dist/records/createRecordsRouter.js +4 -2
  64. package/dist/records/createSearchRecords.d.ts +4 -3
  65. package/dist/records/createSearchRecords.js +9 -21
  66. package/dist/records/maintenance.d.ts +1 -1
  67. package/dist/records/maintenance.js +1 -1
  68. package/dist/records/runCallRecords.d.ts +2 -0
  69. package/dist/records/runCallRecords.js +1 -1
  70. package/dist/records/types.d.ts +2 -0
  71. package/dist/regions/configSync.d.ts +5 -5
  72. package/dist/regions/configSync.js +9 -9
  73. package/dist/regions/createRegionsRouter.d.ts +6 -6
  74. package/dist/regions/createRegionsRouter.js +5 -5
  75. package/dist/regions/link.js +1 -1
  76. package/dist/regions/runRegions.d.ts +2 -0
  77. package/dist/regions/runRegions.js +4 -0
  78. package/dist/regions/service.js +4 -4
  79. package/dist/regions/sources.d.ts +1 -1
  80. package/dist/regions/sources.js +4 -4
  81. package/dist/regions/status.js +5 -4
  82. package/dist/regions/types.d.ts +2 -2
  83. package/dist/usage/buildService.d.ts +16 -0
  84. package/dist/{calls/influxdb.js → usage/buildService.js} +16 -9
  85. package/dist/{events/createPerCallCache.d.ts → usage/createGetUsage.d.ts} +7 -7
  86. package/dist/usage/createGetUsage.js +118 -0
  87. package/dist/usage/ingestUsage.d.ts +7 -0
  88. package/dist/usage/ingestUsage.js +87 -0
  89. package/dist/usage/publishRecordedUsage.d.ts +52 -0
  90. package/dist/usage/publishRecordedUsage.js +103 -0
  91. package/dist/usage/publishUsage.d.ts +29 -0
  92. package/dist/usage/publishUsage.js +50 -0
  93. package/dist/usage/rebuildUsage.d.ts +48 -0
  94. package/dist/usage/rebuildUsage.js +104 -0
  95. package/dist/usage/runUsageConsumer.d.ts +22 -0
  96. package/dist/usage/runUsageConsumer.js +78 -0
  97. package/dist/usage/snapshotStorage.d.ts +14 -0
  98. package/dist/usage/snapshotStorage.js +95 -0
  99. package/dist/usage/types.d.ts +36 -0
  100. package/dist/voice/stt/types.js +1 -1
  101. package/dist/webhooks/lostCalls.d.ts +35 -12
  102. package/dist/webhooks/lostCalls.js +86 -48
  103. package/dist/webhooks/nodeCallEvents.d.ts +73 -0
  104. package/dist/webhooks/nodeCallEvents.js +177 -0
  105. package/dist/webhooks/runWebhookFanout.d.ts +10 -4
  106. package/dist/webhooks/runWebhookFanout.js +41 -39
  107. package/package.json +17 -19
  108. package/dist/applications/migration/PrismaApplicationStore.d.ts +0 -55
  109. package/dist/applications/migration/PrismaApplicationStore.js +0 -92
  110. package/dist/applications/migration/convertLegacyApplication.d.ts +0 -11
  111. package/dist/applications/migration/convertLegacyApplication.js +0 -112
  112. package/dist/applications/migration/index.d.ts +0 -22
  113. package/dist/applications/migration/index.js +0 -38
  114. package/dist/applications/migration/migrateApplications.d.ts +0 -43
  115. package/dist/applications/migration/migrateApplications.js +0 -87
  116. package/dist/applications/migration/types.d.ts +0 -92
  117. package/dist/applications/migration/types.js +0 -20
  118. package/dist/calls/createFetchCalls.d.ts +0 -22
  119. package/dist/calls/createFetchCalls.js +0 -88
  120. package/dist/calls/createFetchSingleCall.d.ts +0 -22
  121. package/dist/calls/createFetchSingleCall.js +0 -54
  122. package/dist/calls/influxdb.d.ts +0 -2
  123. package/dist/core/upsertMediaNodePeer.d.ts +0 -6
  124. package/dist/events/callRefs.d.ts +0 -29
  125. package/dist/events/callRefs.js +0 -103
  126. package/dist/events/createCdrWriter.d.ts +0 -25
  127. package/dist/events/createCdrWriter.js +0 -95
  128. package/dist/events/createInfluxDbPub.d.ts +0 -10
  129. package/dist/events/createInfluxDbPub.js +0 -46
  130. package/dist/events/createPerCallCache.js +0 -46
  131. package/dist/events/mapCallDirectionToEnum.d.ts +0 -21
  132. package/dist/events/mapCallDirectionToEnum.js +0 -37
  133. package/dist/events/nats.d.ts +0 -44
  134. package/dist/events/nats.js +0 -93
  135. package/dist/events/transformEvent.d.ts +0 -4
  136. package/dist/events/transformEvent.js +0 -87
  137. package/dist/events/types.d.ts +0 -26
  138. package/dist/migration/argv.d.ts +0 -22
  139. package/dist/migration/argv.js +0 -42
  140. package/dist/migration/catalogMapping.d.ts +0 -30
  141. package/dist/migration/catalogMapping.js +0 -53
  142. package/dist/migration/index.d.ts +0 -27
  143. package/dist/migration/index.js +0 -43
  144. package/dist/migration/migrateAssistants.d.ts +0 -8
  145. package/dist/migration/migrateAssistants.js +0 -169
  146. package/dist/migration/migrateCredentials.d.ts +0 -4
  147. package/dist/migration/migrateCredentials.js +0 -107
  148. package/dist/migration/migrateIntegrations.d.ts +0 -32
  149. package/dist/migration/migrateIntegrations.js +0 -136
  150. package/dist/migration/migrateLegacy.d.ts +0 -41
  151. package/dist/migration/migrateLegacy.js +0 -76
  152. package/dist/migration/providerKeys.d.ts +0 -14
  153. package/dist/migration/providerKeys.js +0 -61
  154. package/dist/migration/seedCatalog.d.ts +0 -2
  155. package/dist/migration/seedCatalog.js +0 -160
  156. package/dist/migration/types.d.ts +0 -42
  157. package/dist/migration/types.js +0 -31
  158. /package/dist/{migration/cli.d.ts → bin/usage.d.ts} +0 -0
  159. /package/dist/{events → usage}/types.js +0 -0
@@ -1,7 +1,7 @@
1
1
  import { Prisma } from "../core/db";
2
2
  import { SessionAppsConfig } from "./session/appModel";
3
3
  import { TestTokenConfiguration } from "./types";
4
- declare function buildService(prisma: Prisma, testTokenConfig: TestTokenConfiguration, config?: SessionAppsConfig): {
4
+ declare function buildService(prisma: Prisma, testTokenConfig: TestTokenConfiguration, config?: SessionAppsConfig, findCallerEmail?: (userRef: string) => Promise<string | undefined>): {
5
5
  definition: {
6
6
  serviceName: string;
7
7
  pckg: string;
@@ -21,6 +21,7 @@ exports.buildService = buildService;
21
21
  */
22
22
  const autopilot_1 = require("@fonoster/autopilot");
23
23
  const envs_1 = require("../envs");
24
+ const publishUsage_1 = require("../usage/publishUsage");
24
25
  const createCreateApplication_1 = require("./createCreateApplication");
25
26
  const createCreateTestToken_1 = require("./createCreateTestToken");
26
27
  const createDeleteApplication_1 = require("./createDeleteApplication");
@@ -29,8 +30,8 @@ const createListApplications_1 = require("./createListApplications");
29
30
  const createRotateSigningSecret_1 = require("./createRotateSigningSecret");
30
31
  const createUpdateApplication_1 = require("./createUpdateApplication");
31
32
  const evalKeys_1 = require("./evalKeys");
32
- function buildService(prisma, testTokenConfig, config = envs_1.SESSION_APPS) {
33
- const evaluateIntelligence = (0, autopilot_1.createEvaluateIntelligence)((0, evalKeys_1.createEvalKeys)(prisma, envs_1.EVALUATIONS.credentials));
33
+ function buildService(prisma, testTokenConfig, config = envs_1.SESSION_APPS, findCallerEmail) {
34
+ const evaluateIntelligence = (0, autopilot_1.createEvaluateIntelligence)((0, evalKeys_1.createEvalKeys)(prisma, envs_1.EVALUATIONS.credentials), publishUsage_1.reportEvalUsage);
34
35
  return {
35
36
  definition: {
36
37
  serviceName: "Applications",
@@ -46,7 +47,7 @@ function buildService(prisma, testTokenConfig, config = envs_1.SESSION_APPS) {
46
47
  updateApplication: (0, createUpdateApplication_1.createUpdateApplication)(prisma, config),
47
48
  rotateSigningSecret: (0, createRotateSigningSecret_1.createRotateSigningSecret)(prisma, config),
48
49
  evaluateIntelligence,
49
- createTestToken: (0, createCreateTestToken_1.createCreateTestToken)(testTokenConfig)
50
+ createTestToken: (0, createCreateTestToken_1.createCreateTestToken)(testTokenConfig, findCallerEmail)
50
51
  }
51
52
  };
52
53
  }
@@ -44,11 +44,14 @@ function createCreateApplication(prisma, config) {
44
44
  accessKeyId,
45
45
  type: request.type
46
46
  });
47
- const { columns, assistant, autopilot } = yield (0, appModel_1.toAppColumns)(prisma, request, { accessKeyId, config });
47
+ const { columns, agent, autopilot } = yield (0, appModel_1.toAppColumns)(prisma, request, {
48
+ accessKeyId,
49
+ config
50
+ });
48
51
  const shared = autopilot ? config.autopilotSigningSecret : undefined;
49
52
  const signingSecret = shared !== null && shared !== void 0 ? shared : (0, appModel_1.newSigningSecret)();
50
- const intelligence = assistant
51
- ? { create: yield (0, appModel_1.assistantRow)(prisma, assistant) }
53
+ const intelligence = agent
54
+ ? { create: yield (0, appModel_1.agentRow)(prisma, agent) }
52
55
  : undefined;
53
56
  const result = yield prisma.application.create({
54
57
  data: Object.assign(Object.assign({}, columns), { signingSecret, accessKeyId, intelligence })
@@ -18,7 +18,9 @@
18
18
  */
19
19
  import { GrpcErrorMessage } from "@fonoster/common";
20
20
  import { TestTokenConfiguration } from "./types";
21
- declare function createCreateTestToken(config: TestTokenConfiguration): (call: {
21
+ /** The email of the user a ref names, for the token's `caller` (#1060). */
22
+ type FindCallerEmail = (userRef: string) => Promise<string | undefined>;
23
+ declare function createCreateTestToken(config: TestTokenConfiguration, findCallerEmail?: FindCallerEmail): (call: {
22
24
  request: unknown;
23
25
  }, callback: (error?: GrpcErrorMessage, response?: unknown) => void) => Promise<void>;
24
26
  export { createCreateTestToken };
@@ -38,25 +38,30 @@ const jsonwebtoken_1 = __importDefault(require("jsonwebtoken"));
38
38
  const uuid_1 = require("uuid");
39
39
  const envs_1 = require("../envs");
40
40
  const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
41
- function createCreateTestToken(config) {
41
+ function createCreateTestToken(config, findCallerEmail) {
42
42
  const createApplication = (call, callback) => __awaiter(this, void 0, void 0, function* () {
43
43
  const accessKeyId = (0, common_1.getAccessKeyIdFromCall)(call);
44
44
  logger.verbose("call to createTestToken", {
45
45
  accessKeyId
46
46
  });
47
+ // Who is testing: the signed-in user behind the access token, recorded as the call's
48
+ // caller instead of the SIP leg's internal name. A lookup failure only leaves it out.
49
+ let caller;
50
+ try {
51
+ const token = (0, common_1.getTokenFromCall)(call);
52
+ const sub = token
53
+ ? (0, common_1.decodeToken)(token).sub
54
+ : undefined;
55
+ caller =
56
+ typeof sub === "string" && findCallerEmail
57
+ ? yield findCallerEmail(sub)
58
+ : undefined;
59
+ }
60
+ catch (err) {
61
+ logger.verbose("test token without a caller", { error: err });
62
+ }
47
63
  // Build payload
48
- const payload = {
49
- ref: (0, uuid_1.v4)(),
50
- domain: config.domain,
51
- displayName: config.displayName,
52
- signalingServer: config.signalingServer,
53
- targetAor: config.targetAor,
54
- username: config.username,
55
- accessKeyId,
56
- aorLink: config.targetAor,
57
- privacy: "NONE",
58
- allowedMethods: ["INVITE"]
59
- };
64
+ const payload = Object.assign(Object.assign({}, (caller ? { caller } : {})), { ref: (0, uuid_1.v4)(), domain: config.domain, displayName: config.displayName, signalingServer: config.signalingServer, targetAor: config.targetAor, username: config.username, accessKeyId, aorLink: config.targetAor, privacy: "NONE", allowedMethods: ["INVITE"] });
60
65
  // Sign JWT
61
66
  let token;
62
67
  try {
@@ -30,10 +30,10 @@ declare function createGetFnUtil(prisma: Prisma): (ref: string) => Promise<{
30
30
  fallbackMessage: string | null;
31
31
  listeners: import("@prisma/client/runtime/library").JsonValue | null;
32
32
  amd: boolean;
33
+ filters: import("@prisma/client/runtime/library").JsonValue | null;
33
34
  signingSecret: string | null;
34
35
  speechLanguage: string | null;
35
36
  amdWindowMs: number | null;
36
37
  speechSettings: import("@prisma/client/runtime/library").JsonValue | null;
37
- filters: import("@prisma/client/runtime/library").JsonValue | null;
38
38
  }>;
39
39
  export { createGetFnUtil };
@@ -46,10 +46,12 @@ function createUpdateApplication(prisma, config) {
46
46
  const existing = (yield getFn(ref));
47
47
  const request = Object.assign(Object.assign({}, call.request), { name: call.request.name || existing.name, type: call.request.type || existing.type });
48
48
  logger.verbose("call to updateApplication", { accessKeyId, ref });
49
- const { columns, assistant, autopilot } = yield (0, appModel_1.toAppColumns)(prisma, request, { accessKeyId, ref, config });
50
- const intelligence = assistant
51
- ? yield (0, appModel_1.assistantRow)(prisma, assistant)
52
- : undefined;
49
+ const { columns, agent, autopilot } = yield (0, appModel_1.toAppColumns)(prisma, request, {
50
+ accessKeyId,
51
+ ref,
52
+ config
53
+ });
54
+ const intelligence = agent ? yield (0, appModel_1.agentRow)(prisma, agent) : undefined;
53
55
  // An app that became an Autopilot app takes the shared secret; one that stopped being one
54
56
  // needs its own.
55
57
  let signingSecret;
@@ -1,3 +1,9 @@
1
1
  type EvalDb = any;
2
- export declare function createEvalKeys(db: EvalDb, platform: Record<string, string>): (providerId: string, workspaceRef: string) => Promise<string>;
2
+ export declare function createEvalKeys(db: EvalDb, platform: Record<string, string>): (providerId: string, workspaceRef: string) => Promise<{
3
+ key: string;
4
+ source: "workspace";
5
+ } | {
6
+ key: string;
7
+ source: "platform";
8
+ }>;
3
9
  export {};
@@ -33,13 +33,19 @@ function createEvalKeys(db, platform) {
33
33
  const workspaceKeys = new common_1.Registry.PrismaWorkspaceKeys(db);
34
34
  return (providerId, workspaceRef) => __awaiter(this, void 0, void 0, function* () {
35
35
  var _a;
36
- const own = yield workspaceKeys.get(workspaceRef, providerId);
36
+ // An unreadable key never falls back to the platform's (remove-platform-key-fallback).
37
+ const own = yield workspaceKeys
38
+ .get(workspaceRef, providerId)
39
+ .catch((e) => {
40
+ throw new Error(`key_unavailable: the workspace's ${providerId} key could not be read (${e.message})`);
41
+ });
37
42
  if (own)
38
- return own;
43
+ return { key: own, source: "workspace" };
39
44
  const provider = yield db.registryProvider.findUnique({
40
45
  where: { id: providerId }
41
46
  });
42
47
  const ref = (_a = provider === null || provider === void 0 ? void 0 : provider.credentialRef) !== null && _a !== void 0 ? _a : `${providerId}-default`;
43
- return platform[ref] || undefined;
48
+ const key = platform[ref];
49
+ return key ? { key, source: "platform" } : undefined;
44
50
  });
45
51
  }
@@ -1,3 +1,4 @@
1
+ import { AudioFilters } from "@fonoster/common";
1
2
  import { z } from "zod";
2
3
  /** The rebuild columns are newer than the shared generated client, so the slice is typed loosely. */
3
4
  export type AppsDb = any;
@@ -97,6 +98,19 @@ export declare const sessionAppInputSchema: z.ZodObject<{
97
98
  enabled?: boolean;
98
99
  windowMs?: number;
99
100
  }, unknown>;
101
+ filters: z.ZodEffects<z.ZodArray<z.ZodObject<{
102
+ name: z.ZodString;
103
+ options: z.ZodOptional<z.ZodUnknown>;
104
+ }, "strip", z.ZodTypeAny, {
105
+ options?: unknown;
106
+ name?: string;
107
+ }, {
108
+ options?: unknown;
109
+ name?: string;
110
+ }>, "many">, {
111
+ options?: unknown;
112
+ name?: string;
113
+ }[], unknown>;
100
114
  }, "strip", z.ZodTypeAny, {
101
115
  type?: "STREAM" | "AUTOPILOT";
102
116
  name?: string;
@@ -125,6 +139,10 @@ export declare const sessionAppInputSchema: z.ZodObject<{
125
139
  enabled?: boolean;
126
140
  windowMs?: number;
127
141
  };
142
+ filters?: {
143
+ options?: unknown;
144
+ name?: string;
145
+ }[];
128
146
  }, {
129
147
  type?: "STREAM" | "AUTOPILOT";
130
148
  name?: string;
@@ -137,6 +155,7 @@ export declare const sessionAppInputSchema: z.ZodObject<{
137
155
  fallbackMessage?: unknown;
138
156
  listeners?: unknown;
139
157
  amd?: unknown;
158
+ filters?: unknown;
140
159
  }>;
141
160
  export type SessionAppInput = z.infer<typeof sessionAppInputSchema>;
142
161
  export declare function newSigningSecret(): string;
@@ -149,7 +168,7 @@ export declare const invalid: (message: string) => BadRequest;
149
168
  /**
150
169
  * Validates the request and returns the columns to write (without the secret). Autopilot apps get
151
170
  * the hosted Autopilot URL and the fonoster protocol; the agent is checked with
152
- * sessionAssistantSchema and kept on the Intelligence row as before.
171
+ * sessionAgentSchema and kept on the Intelligence row as before.
153
172
  */
154
173
  export declare function toAppColumns(db: AppsDb, request: Record<string, unknown>, ctx: {
155
174
  accessKeyId: string;
@@ -181,12 +200,17 @@ export declare function toAppColumns(db: AppsDb, request: Record<string, unknown
181
200
  recording: "on" | "off" | "consent";
182
201
  amd: boolean;
183
202
  amdWindowMs: number;
203
+ filters: AudioFilters.AudioFilterConfig[];
184
204
  };
185
- assistant: Record<string, unknown>;
205
+ agent: Record<string, unknown>;
186
206
  autopilot: boolean;
187
207
  }>;
188
- /** The Intelligence row for an Autopilot app (productRef from the model's provider). */
189
- export declare function assistantRow(db: AppsDb, assistant: Record<string, unknown>): Promise<{
208
+ /**
209
+ * The Intelligence row for an Autopilot app. The model is a catalog id, checked like the app's
210
+ * speech ids; its provider's `llm.<provider>` product row (the legacy table Intelligence points
211
+ * to) is added on first use, so any catalog provider works without a seeded product.
212
+ */
213
+ export declare function agentRow(db: AppsDb, agent: Record<string, unknown>): Promise<{
190
214
  productRef: string;
191
215
  config: Record<string, unknown>;
192
216
  }>;
@@ -13,7 +13,7 @@ exports.invalid = exports.sessionAppInputSchema = exports.DEFAULT_LANGUAGE = exp
13
13
  exports.newSigningSecret = newSigningSecret;
14
14
  exports.secretHint = secretHint;
15
15
  exports.toAppColumns = toAppColumns;
16
- exports.assistantRow = assistantRow;
16
+ exports.agentRow = agentRow;
17
17
  exports.rowToApplication = rowToApplication;
18
18
  /**
19
19
  * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
@@ -38,10 +38,10 @@ const common_1 = require("@fonoster/common");
38
38
  const pb_util_1 = require("pb-util");
39
39
  const zod_1 = require("zod");
40
40
  /**
41
- * App and listener URLs are the tenant's choice and the gateway dials them, so they must not
41
+ * App and listener URLs are the tenant's choice and AppBridge dials them, so they must not
42
42
  * name the platform's own network: no internal names (localhost, *.svc, single labels) and no
43
43
  * private, loopback or metadata IPs, unless allowed by the operator. The hosted Autopilot URL
44
- * comes from configuration and is exempt. The gateway re-checks resolved addresses on connect.
44
+ * comes from configuration and is exempt. AppBridge re-checks resolved addresses on connect.
45
45
  */
46
46
  function checkDestination(value, what, config) {
47
47
  if (value === config.autopilotUrl)
@@ -130,8 +130,31 @@ exports.sessionAppInputSchema = zod_1.z.object({
130
130
  enabled: zod_1.z.boolean().default(false),
131
131
  windowMs: optional(zod_1.z.number().int().min(500).max(15000))
132
132
  })
133
- .optional())
133
+ .optional()),
134
+ // Audio filters (voice-session "An app's audio filters are set through the Applications
135
+ // API"). Update replaces the whole app, and an omitted repeated field is an empty list on
136
+ // the wire, so a request without filters clears them (as listeners). Options arrive as a
137
+ // Struct over gRPC; they are decoded and checked against each filter's public schema below.
138
+ filters: zod_1.z.preprocess((v) => v !== null && v !== void 0 ? v : [], zod_1.z.array(zod_1.z.object({ name: zod_1.z.string(), options: zod_1.z.unknown().optional() })))
134
139
  });
140
+ /** The app's filters as stored: decoded options, known names and public options only. */
141
+ function toFilters(input) {
142
+ const decoded = input.map((f) => {
143
+ const raw = f.options;
144
+ const options = raw && raw.fields !== undefined
145
+ ? pb_util_1.struct.decode(raw)
146
+ : raw;
147
+ return options && Object.keys(options).length
148
+ ? { name: f.name, options }
149
+ : { name: f.name };
150
+ });
151
+ try {
152
+ return common_1.AudioFilters.parseFilters(decoded);
153
+ }
154
+ catch (e) {
155
+ throw (0, exports.invalid)(`filters: ${e.message}`);
156
+ }
157
+ }
135
158
  function newSigningSecret() {
136
159
  return (0, crypto_1.randomBytes)(32).toString("base64url");
137
160
  }
@@ -147,7 +170,7 @@ exports.invalid = invalid;
147
170
  /**
148
171
  * Validates the request and returns the columns to write (without the secret). Autopilot apps get
149
172
  * the hosted Autopilot URL and the fonoster protocol; the agent is checked with
150
- * sessionAssistantSchema and kept on the Intelligence row as before.
173
+ * sessionAgentSchema and kept on the Intelligence row as before.
151
174
  */
152
175
  function toAppColumns(db, request, ctx) {
153
176
  return __awaiter(this, void 0, void 0, function* () {
@@ -165,7 +188,7 @@ function toAppColumns(db, request, ctx) {
165
188
  const protocol = (_b = input.protocol) !== null && _b !== void 0 ? _b : "fonoster";
166
189
  if (autopilot && protocol !== "fonoster")
167
190
  throw (0, exports.invalid)("Autopilot agents use the fonoster protocol");
168
- let assistant;
191
+ let agent;
169
192
  if (autopilot) {
170
193
  const intelligence = request.intelligence;
171
194
  const raw = intelligence === null || intelligence === void 0 ? void 0 : intelligence.config;
@@ -174,12 +197,12 @@ function toAppColumns(db, request, ctx) {
174
197
  const decoded = raw.fields !== undefined
175
198
  ? pb_util_1.struct.decode(raw)
176
199
  : raw;
177
- const parsed = common_1.sessionAssistantSchema.safeParse(decoded);
200
+ const parsed = common_1.sessionAgentSchema.safeParse(decoded);
178
201
  if (!parsed.success)
179
202
  throw (0, exports.invalid)(`invalid agent: ${parsed.error.issues
180
203
  .map((i) => `${i.path.join(".")}: ${i.message}`)
181
204
  .join("; ")}`);
182
- assistant = decoded;
205
+ agent = decoded;
183
206
  }
184
207
  if (input.fallbackAppRef) {
185
208
  if (input.fallbackAppRef === ctx.ref)
@@ -192,6 +215,7 @@ function toAppColumns(db, request, ctx) {
192
215
  throw (0, exports.invalid)("fallbackAppRef: no such app in this workspace");
193
216
  }
194
217
  yield checkCatalogIds(db, input.speech);
218
+ const filters = toFilters(input.filters);
195
219
  const speech = input.speech;
196
220
  const columns = {
197
221
  name: input.name,
@@ -212,49 +236,58 @@ function toAppColumns(db, request, ctx) {
212
236
  fallbackMessage: (_k = input.fallbackMessage) !== null && _k !== void 0 ? _k : null,
213
237
  recording: (_l = input.recording) !== null && _l !== void 0 ? _l : null,
214
238
  amd: (_o = (_m = input.amd) === null || _m === void 0 ? void 0 : _m.enabled) !== null && _o !== void 0 ? _o : false,
215
- amdWindowMs: ((_p = input.amd) === null || _p === void 0 ? void 0 : _p.enabled) ? ((_q = input.amd.windowMs) !== null && _q !== void 0 ? _q : null) : null
239
+ amdWindowMs: ((_p = input.amd) === null || _p === void 0 ? void 0 : _p.enabled) ? ((_q = input.amd.windowMs) !== null && _q !== void 0 ? _q : null) : null,
240
+ filters: filters.length ? filters : null
216
241
  };
217
- return { columns, assistant, autopilot };
242
+ return { columns, agent, autopilot };
218
243
  });
219
244
  }
220
245
  /**
221
246
  * Catalog ids must exist (and not be retired) once the registry has entries of that kind; an
222
247
  * empty registry (a fresh install) accepts any well-formed id.
223
248
  */
224
- function checkCatalogIds(db, speech) {
249
+ function checkCatalogId(db, table, id, what) {
225
250
  return __awaiter(this, void 0, void 0, function* () {
226
- if (!db.registryVoice || !db.registryModel)
251
+ if (!id || !db[table])
227
252
  return;
228
- const check = (table, id, what) => __awaiter(this, void 0, void 0, function* () {
229
- if (!id)
230
- return;
231
- if ((yield db[table].count()) === 0)
232
- return;
233
- const row = yield db[table].findUnique({ where: { id } });
234
- if (!row)
235
- throw (0, exports.invalid)(`${what} ${id} is not in the catalog`);
236
- if (row.state === "RETIRED")
237
- throw (0, exports.invalid)(`${what} ${id} is retired${row.replacement ? `; use ${row.replacement}` : ""}`);
238
- });
239
- yield check("registryVoice", speech.voice, "voice");
240
- yield check("registryModel", speech.sttModel, "speech.sttModel");
241
- yield check("registryModel", speech.ttsModel, "speech.ttsModel");
253
+ if ((yield db[table].count()) === 0)
254
+ return;
255
+ const row = yield db[table].findUnique({ where: { id } });
256
+ if (!row)
257
+ throw (0, exports.invalid)(`${what} ${id} is not in the catalog`);
258
+ if (row.state === "RETIRED")
259
+ throw (0, exports.invalid)(`${what} ${id} is retired${row.replacement ? `; use ${row.replacement}` : ""}`);
260
+ });
261
+ }
262
+ function checkCatalogIds(db, speech) {
263
+ return __awaiter(this, void 0, void 0, function* () {
264
+ yield checkCatalogId(db, "registryVoice", speech.voice, "voice");
265
+ yield checkCatalogId(db, "registryModel", speech.sttModel, "speech.sttModel");
266
+ yield checkCatalogId(db, "registryModel", speech.ttsModel, "speech.ttsModel");
242
267
  });
243
268
  }
244
- /** The Intelligence row for an Autopilot app (productRef from the model's provider). */
245
- function assistantRow(db, assistant) {
269
+ /**
270
+ * The Intelligence row for an Autopilot app. The model is a catalog id, checked like the app's
271
+ * speech ids; its provider's `llm.<provider>` product row (the legacy table Intelligence points
272
+ * to) is added on first use, so any catalog provider works without a seeded product.
273
+ */
274
+ function agentRow(db, agent) {
246
275
  return __awaiter(this, void 0, void 0, function* () {
247
- const model = assistant.languageModel.model;
248
- const productRef = `llm.${model.split("/")[0]}`;
249
- const product = yield db.product.findUnique({ where: { ref: productRef } });
250
- if (!product)
251
- throw (0, exports.invalid)(`languageModel.model: no LLM product ${productRef} for ${model}`);
252
- return { productRef, config: assistant };
276
+ const model = agent.languageModel.model;
277
+ yield checkCatalogId(db, "registryModel", model, "languageModel.model");
278
+ const provider = model.split("/")[0];
279
+ const productRef = `llm.${provider}`;
280
+ yield db.product.upsert({
281
+ where: { ref: productRef },
282
+ create: { ref: productRef, name: provider, vendor: "GENERIC", type: "LLM" },
283
+ update: {}
284
+ });
285
+ return { productRef, config: agent };
253
286
  });
254
287
  }
255
288
  /** An `applications` row as the API's Application (never the secret). */
256
289
  function rowToApplication(row) {
257
- var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p;
290
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j, _k, _l, _m, _o, _p, _q;
258
291
  const listeners = (_a = row.listeners) !== null && _a !== void 0 ? _a : [];
259
292
  const app = {
260
293
  ref: row.ref,
@@ -277,6 +310,12 @@ function rowToApplication(row) {
277
310
  listeners,
278
311
  recording: (_o = row.recording) !== null && _o !== void 0 ? _o : "",
279
312
  amd: { enabled: row.amd === true, windowMs: (_p = row.amdWindowMs) !== null && _p !== void 0 ? _p : 0 },
313
+ filters: ((_q = row.filters) !== null && _q !== void 0 ? _q : []).map((f) => ({
314
+ name: f.name,
315
+ options: f.options
316
+ ? pb_util_1.struct.encode(f.options)
317
+ : undefined
318
+ })),
280
319
  createdAt: row.createdAt,
281
320
  updatedAt: row.updatedAt
282
321
  };
@@ -0,0 +1,24 @@
1
+ import * as grpc from "@grpc/grpc-js";
2
+ /**
3
+ * The owner whose billing a call reads or changes: the caller, who must own the workspace the call
4
+ * is made in (add-billing-service 6.1). Undefined otherwise.
5
+ */
6
+ export declare function ownerOfCall(call: unknown): string | undefined;
7
+ /**
8
+ * The Billing API for the dashboard (billing.proto), when billing is on: each call is passed to
9
+ * the billing service with owner_ref set from the caller, never from the request.
10
+ */
11
+ declare function buildService(address: string, ownerOf?: typeof ownerOfCall): {
12
+ definition: {
13
+ serviceName: string;
14
+ pckg: string;
15
+ version: string;
16
+ proto: string;
17
+ };
18
+ handlers: {
19
+ [k: string]: (call: {
20
+ request: Record<string, unknown>;
21
+ }, callback: (error: grpc.ServiceError | null | Partial<grpc.ServiceError>, response?: unknown) => void) => void;
22
+ };
23
+ };
24
+ export { buildService };
@@ -0,0 +1,116 @@
1
+ "use strict";
2
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
3
+ if (k2 === undefined) k2 = k;
4
+ var desc = Object.getOwnPropertyDescriptor(m, k);
5
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
6
+ desc = { enumerable: true, get: function() { return m[k]; } };
7
+ }
8
+ Object.defineProperty(o, k2, desc);
9
+ }) : (function(o, m, k, k2) {
10
+ if (k2 === undefined) k2 = k;
11
+ o[k2] = m[k];
12
+ }));
13
+ var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
14
+ Object.defineProperty(o, "default", { enumerable: true, value: v });
15
+ }) : function(o, v) {
16
+ o["default"] = v;
17
+ });
18
+ var __importStar = (this && this.__importStar) || (function () {
19
+ var ownKeys = function(o) {
20
+ ownKeys = Object.getOwnPropertyNames || function (o) {
21
+ var ar = [];
22
+ for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
23
+ return ar;
24
+ };
25
+ return ownKeys(o);
26
+ };
27
+ return function (mod) {
28
+ if (mod && mod.__esModule) return mod;
29
+ var result = {};
30
+ if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
31
+ __setModuleDefault(result, mod);
32
+ return result;
33
+ };
34
+ })();
35
+ Object.defineProperty(exports, "__esModule", { value: true });
36
+ exports.ownerOfCall = ownerOfCall;
37
+ exports.buildService = buildService;
38
+ /**
39
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
40
+ * http://github.com/fonoster/fonoster
41
+ *
42
+ * This file is part of Fonoster
43
+ *
44
+ * Licensed under the MIT License (the "License");
45
+ * you may not use this file except in compliance with
46
+ * the License. You may obtain a copy of the License at
47
+ *
48
+ * https://opensource.org/licenses/MIT
49
+ *
50
+ * Unless required by applicable law or agreed to in writing, software
51
+ * distributed under the License is distributed on an "AS IS" BASIS,
52
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
53
+ * See the License for the specific language governing permissions and
54
+ * limitations under the License.
55
+ */
56
+ const common_1 = require("@fonoster/common");
57
+ const logger_1 = require("@fonoster/logger");
58
+ const types_1 = require("@fonoster/types");
59
+ const grpc = __importStar(require("@grpc/grpc-js"));
60
+ const logger = (0, logger_1.getLogger)({ service: "apiserver", filePath: __filename });
61
+ const METHODS = [
62
+ "getBilling",
63
+ "updateAutoRecharge",
64
+ "createTopUp",
65
+ "subscribe",
66
+ "createPortalSession"
67
+ ];
68
+ const definition = () => (0, common_1.createServiceDefinition)({
69
+ serviceName: "Billing",
70
+ pckg: "billing",
71
+ proto: "billing.proto",
72
+ version: "v1beta2"
73
+ });
74
+ /**
75
+ * The owner whose billing a call reads or changes: the caller, who must own the workspace the call
76
+ * is made in (add-billing-service 6.1). Undefined otherwise.
77
+ */
78
+ function ownerOfCall(call) {
79
+ var _a;
80
+ const grpcCall = call;
81
+ const accessKeyId = (0, common_1.getAccessKeyIdFromCall)(grpcCall);
82
+ const token = (0, common_1.decodeToken)((0, common_1.getTokenFromCall)(grpcCall));
83
+ const owns = ((_a = token.access) !== null && _a !== void 0 ? _a : []).some((a) => a.accessKeyId === accessKeyId && a.role === types_1.Role.WORKSPACE_OWNER);
84
+ return owns ? token.sub : undefined;
85
+ }
86
+ /**
87
+ * The Billing API for the dashboard (billing.proto), when billing is on: each call is passed to
88
+ * the billing service with owner_ref set from the caller, never from the request.
89
+ */
90
+ function buildService(address, ownerOf = ownerOfCall) {
91
+ const client = new (grpc.makeGenericClientConstructor(definition(), "Billing", {}))(address, grpc.credentials.createInsecure());
92
+ const forward = (method) => (call, callback) => {
93
+ const ownerRef = ownerOf(call);
94
+ if (!ownerRef) {
95
+ callback({
96
+ code: grpc.status.PERMISSION_DENIED,
97
+ message: "Only the workspace owner manages billing"
98
+ });
99
+ return;
100
+ }
101
+ client[method](Object.assign(Object.assign({}, call.request), { ownerRef }), (error, response) => {
102
+ if (error)
103
+ logger.verbose("billing call refused", { method, code: error.code });
104
+ callback(error ? { code: error.code, message: error.details } : null, response);
105
+ });
106
+ };
107
+ return {
108
+ definition: {
109
+ serviceName: "Billing",
110
+ pckg: "billing",
111
+ version: "v1beta2",
112
+ proto: "billing.proto"
113
+ },
114
+ handlers: Object.fromEntries(METHODS.map((m) => [m, forward(m)]))
115
+ };
116
+ }