@fonoster/common 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 (88) hide show
  1. package/dist/{assistants → agents}/index.d.ts +1 -1
  2. package/dist/{assistants → agents}/index.js +1 -1
  3. package/dist/{assistants/sessionAssistantSchema.d.ts → agents/sessionAgentSchema.d.ts} +20 -6
  4. package/dist/{assistants/sessionAssistantSchema.js → agents/sessionAgentSchema.js} +16 -11
  5. package/dist/cellsecrets/index.d.ts +2 -2
  6. package/dist/cellsecrets/index.js +3 -3
  7. package/dist/config/cli/render.d.ts +1 -1
  8. package/dist/config/cli/render.js +3 -3
  9. package/dist/config/configHints.d.ts +1 -14
  10. package/dist/config/configHints.js +16 -30
  11. package/dist/config/index.d.ts +0 -1
  12. package/dist/config/index.js +0 -1
  13. package/dist/config/interpolateEnv.d.ts +1 -1
  14. package/dist/config/loadServiceConfig.d.ts +0 -5
  15. package/dist/config/loadServiceConfig.js +3 -12
  16. package/dist/constants.d.ts +1 -3
  17. package/dist/constants.js +3 -5
  18. package/dist/errors/handleZodError.js +3 -1
  19. package/dist/filters/index.d.ts +70 -0
  20. package/dist/filters/index.js +101 -0
  21. package/dist/identity/roles.js +11 -1
  22. package/dist/index.d.ts +4 -1
  23. package/dist/index.js +5 -2
  24. package/dist/protos/applications.proto +16 -2
  25. package/dist/protos/authz.proto +3 -0
  26. package/dist/protos/billing.proto +92 -0
  27. package/dist/protos/calls.proto +4 -0
  28. package/dist/protos/capabilities.proto +8 -0
  29. package/dist/protos/providers.proto +6 -2
  30. package/dist/protos/roomr.proto +146 -0
  31. package/dist/protos/session.proto +194 -0
  32. package/dist/protos/usage.proto +59 -0
  33. package/dist/registry/Registry.d.ts +13 -5
  34. package/dist/registry/Registry.js +49 -35
  35. package/dist/registry/cli.js +19 -7
  36. package/dist/registry/features.d.ts +2 -2
  37. package/dist/registry/features.js +7 -5
  38. package/dist/registry/prisma.d.ts +2 -2
  39. package/dist/registry/prisma.js +26 -18
  40. package/dist/registry/types.d.ts +17 -5
  41. package/dist/registry/types.js +2 -0
  42. package/dist/roomr/health.d.ts +9 -0
  43. package/dist/roomr/health.js +75 -0
  44. package/dist/roomr/index.d.ts +75 -0
  45. package/dist/roomr/index.js +146 -0
  46. package/dist/roomr/session.d.ts +133 -0
  47. package/dist/roomr/session.js +132 -0
  48. package/dist/session/schema.d.ts +196 -7
  49. package/dist/session/schema.js +59 -8
  50. package/dist/sessions/index.d.ts +15 -12
  51. package/dist/sessions/index.js +15 -12
  52. package/dist/telemetry.d.ts +1 -1
  53. package/dist/usage/CallUsage.d.ts +38 -0
  54. package/dist/usage/CallUsage.js +76 -0
  55. package/dist/{utils/types.d.ts → usage/index.d.ts} +4 -5
  56. package/dist/usage/index.js +38 -0
  57. package/dist/usage/meters.d.ts +113 -0
  58. package/dist/usage/meters.js +90 -0
  59. package/dist/usage/types.d.ts +159 -0
  60. package/dist/usage/types.js +84 -0
  61. package/dist/usage/usageId.d.ts +6 -0
  62. package/dist/usage/usageId.js +45 -0
  63. package/dist/utils/index.d.ts +0 -2
  64. package/dist/utils/index.js +0 -2
  65. package/dist/utils/withErrorHandling.js +1 -1
  66. package/dist/validators/calls.d.ts +5 -2
  67. package/dist/validators/calls.js +8 -1
  68. package/dist/validators/sip.d.ts +2 -2
  69. package/dist/validators/sip.js +3 -3
  70. package/dist/webhooks/bus.d.ts +29 -10
  71. package/dist/webhooks/bus.js +58 -50
  72. package/dist/webhooks/events.d.ts +1 -1
  73. package/dist/webhooks/events.js +1 -1
  74. package/package.json +9 -8
  75. package/schema/session.v1.json +82 -2
  76. package/dist/config/integrationsSchema.d.ts +0 -32
  77. package/dist/config/integrationsSchema.js +0 -56
  78. package/dist/utils/createFetchSingleCallByCallId.d.ts +0 -22
  79. package/dist/utils/createFetchSingleCallByCallId.js +0 -33
  80. package/dist/utils/types.js +0 -2
  81. /package/dist/{assistants → agents}/testCasesSchema.d.ts +0 -0
  82. /package/dist/{assistants → agents}/testCasesSchema.js +0 -0
  83. /package/dist/{assistants → agents}/tools/index.d.ts +0 -0
  84. /package/dist/{assistants → agents}/tools/index.js +0 -0
  85. /package/dist/{assistants → agents}/tools/propertySchema.d.ts +0 -0
  86. /package/dist/{assistants → agents}/tools/propertySchema.js +0 -0
  87. /package/dist/{assistants → agents}/tools/toolSchema.d.ts +0 -0
  88. /package/dist/{assistants → agents}/tools/toolSchema.js +0 -0
@@ -21,21 +21,24 @@ exports.openSessions = openSessions;
21
21
  exports.watchSessions = watchSessions;
22
22
  exports.getSession = getSession;
23
23
  /**
24
- * The session registry (add-platform 2.3, add-media-node 3.2, decision D3): one NATS JetStream KV
24
+ * The session registry (add-platform 2.3, add-roomr 3.2, decision D3): one NATS JetStream KV
25
25
  * bucket shared by every service. Keys are `<kind>.<id>`:
26
26
  *
27
- * nodes.<nodeId> media node: { nodeId, rooms, draining, at } (written by the node)
28
- * rooms.<roomRef> media node: { roomRef, nodeId, at } (written by the node)
29
- * calls.<callRef> gateway: { callRef, gatewayRef, nodeId, roomRef, direction, at }
30
- * + once answered: { appRef, from, to, startedAt }
31
- * gateways.<gatewayRef> gateway: { gatewayRef, calls, at }
27
+ * calls.<callRef> appbridge: { callRef, bridgeRef, nodeId, roomRef, direction, at }
28
+ * + once answered: { appRef, workspaceRef, from, to, startedAt }
29
+ * appbridges.<bridgeRef> retired: AppBridge no longer writes it (redesign-roomr 15.3)
30
+ * placements.<callRef> apiserver: { callRef, nodeRef, controlAddr, roomRef?, at }
31
+ * while an outbound call is being placed (CreateCall)
32
32
  *
33
- * The control plane reads `calls` and `gateways`: a call whose entry and whose gateway's entry
34
- * both stop being rewritten lost its gateway mid-call, and gets `call.ended` (`appbridge-lost`).
33
+ * Roomr nodes write nothing here (core NATS only: heartbeat and events); the control plane learns
34
+ * nodes from their heartbeats.
35
+ *
36
+ * The control plane reads `calls` (billing counts active calls from them). A call that loses its
37
+ * AppBridge mid-call is reported by its node's `call.ended` with cause `app_gone` (redesign-roomr
38
+ * 15.4), not by expired `appbridges` entries.
35
39
  *
36
40
  * Entries are leases: the bucket keeps a value for SESSIONS_TTL_MS after its last write, owners
37
- * rewrite theirs every SESSIONS_REFRESH_MS, and a crashed owner's entries expire on their own. The
38
- * Go node uses the same bucket, TTL and key rules (go/medianode/internal/registry).
41
+ * rewrite theirs every SESSIONS_REFRESH_MS, and a crashed owner's entries expire on their own.
39
42
  */
40
43
  exports.SESSIONS_BUCKET = "fonoster_sessions";
41
44
  exports.SESSIONS_TTL_MS = 15000;
@@ -53,7 +56,7 @@ function openSessions(nc_1) {
53
56
  return nc.jetstream().views.kv(bucket, {
54
57
  history: 1,
55
58
  ttl: (_a = options.ttlMs) !== null && _a !== void 0 ? _a : exports.SESSIONS_TTL_MS,
56
- description: "Fonoster session registry: nodes, rooms, calls, gateways (leases)"
59
+ description: "Fonoster session registry: nodes, rooms, calls, appbridges (leases)"
57
60
  });
58
61
  };
59
62
  try {
@@ -68,7 +71,7 @@ function openSessions(nc_1) {
68
71
  });
69
72
  }
70
73
  /**
71
- * An owner's entries, kept alive until deleted (the gateway's calls and its own gateway entry).
74
+ * An owner's entries, kept alive until deleted (AppBridge's calls and its own appbridge entry).
72
75
  * Writes never throw: the registry is best effort and entries are rewritten on the next refresh.
73
76
  */
74
77
  class SessionLeases {
@@ -45,7 +45,7 @@ export interface Telemetry {
45
45
  enabled: boolean;
46
46
  /**
47
47
  * Starts the span of one call; the returned handle is a no-op when disabled. `parent` (a W3C
48
- * traceparent from another service, e.g. the media node) makes it a child in that trace.
48
+ * traceparent from another service, e.g. the Roomr node) makes it a child in that trace.
49
49
  */
50
50
  startCall(callRef: string, name: string, attrs?: Attrs, parent?: string): CallSpan;
51
51
  /**
@@ -0,0 +1,38 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { MeterName } from "./meters";
20
+ import { KeySource, UsageLine } from "./types";
21
+ type Key = {
22
+ meter: MeterName;
23
+ provider?: string;
24
+ model?: string;
25
+ keySource?: KeySource;
26
+ };
27
+ /**
28
+ * A call's usage, accumulated in memory while it runs (design D1). One entry per meter, provider,
29
+ * model and key source; seconds are kept exact and rounded up only when lines are taken.
30
+ */
31
+ export declare class CallUsage {
32
+ private readonly entries;
33
+ add(line: UsageLine): void;
34
+ /** Adds seconds of a meter measured as a duration in milliseconds. */
35
+ addMillis(key: Key, ms: number): void;
36
+ lines(): UsageLine[];
37
+ }
38
+ export {};
@@ -0,0 +1,76 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.CallUsage = void 0;
4
+ /**
5
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
6
+ * http://github.com/fonoster/fonoster
7
+ *
8
+ * This file is part of Fonoster
9
+ *
10
+ * Licensed under the MIT License (the "License");
11
+ * you may not use this file except in compliance with
12
+ * the License. You may obtain a copy of the License at
13
+ *
14
+ * https://opensource.org/licenses/MIT
15
+ *
16
+ * Unless required by applicable law or agreed to in writing, software
17
+ * distributed under the License is distributed on an "AS IS" BASIS,
18
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19
+ * See the License for the specific language governing permissions and
20
+ * limitations under the License.
21
+ */
22
+ const meters_1 = require("./meters");
23
+ const types_1 = require("./types");
24
+ /**
25
+ * A call's usage, accumulated in memory while it runs (design D1). One entry per meter, provider,
26
+ * model and key source; seconds are kept exact and rounded up only when lines are taken.
27
+ */
28
+ class CallUsage {
29
+ constructor() {
30
+ this.entries = new Map();
31
+ }
32
+ add(line) {
33
+ var _a, _b, _c;
34
+ const parsed = (0, types_1.parseUsageLine)(line);
35
+ const key = [
36
+ parsed.meter,
37
+ (_a = parsed.provider) !== null && _a !== void 0 ? _a : "",
38
+ (_b = parsed.model) !== null && _b !== void 0 ? _b : "",
39
+ (_c = parsed.keySource) !== null && _c !== void 0 ? _c : ""
40
+ ].join("|");
41
+ const entry = this.entries.get(key);
42
+ if (entry)
43
+ entry.quantity += parsed.quantity;
44
+ else
45
+ this.entries.set(key, {
46
+ meter: parsed.meter,
47
+ provider: parsed.provider,
48
+ model: parsed.model,
49
+ keySource: parsed.keySource,
50
+ quantity: parsed.quantity
51
+ });
52
+ }
53
+ /** Adds seconds of a meter measured as a duration in milliseconds. */
54
+ addMillis(key, ms) {
55
+ if (ms > 0)
56
+ this.add(Object.assign(Object.assign({}, key), { quantity: ms / 1000 }));
57
+ }
58
+ lines() {
59
+ return Array.from(this.entries.values())
60
+ .map((e) => {
61
+ const quantity = (0, meters_1.meterOf)(e.meter).unit === "second"
62
+ ? Math.ceil(e.quantity - 1e-9)
63
+ : Math.round(e.quantity);
64
+ const line = { meter: e.meter, quantity };
65
+ if (e.provider)
66
+ line.provider = e.provider;
67
+ if (e.model)
68
+ line.model = e.model;
69
+ if (e.keySource)
70
+ line.keySource = e.keySource;
71
+ return line;
72
+ })
73
+ .filter((line) => line.quantity > 0);
74
+ }
75
+ }
76
+ exports.CallUsage = CallUsage;
@@ -16,8 +16,7 @@
16
16
  * See the License for the specific language governing permissions and
17
17
  * limitations under the License.
18
18
  */
19
- import { ParameterizedQuery } from "@influxdata/influxdb-client";
20
- type InfluxDBClient = {
21
- collectRows(query: ParameterizedQuery): Promise<unknown[]>;
22
- };
23
- export { InfluxDBClient };
19
+ export * from "./CallUsage";
20
+ export * from "./meters";
21
+ export * from "./types";
22
+ export * from "./usageId";
@@ -0,0 +1,38 @@
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 __exportStar = (this && this.__exportStar) || function(m, exports) {
14
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
15
+ };
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ /**
18
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
19
+ * http://github.com/fonoster/fonoster
20
+ *
21
+ * This file is part of Fonoster
22
+ *
23
+ * Licensed under the MIT License (the "License");
24
+ * you may not use this file except in compliance with
25
+ * the License. You may obtain a copy of the License at
26
+ *
27
+ * https://opensource.org/licenses/MIT
28
+ *
29
+ * Unless required by applicable law or agreed to in writing, software
30
+ * distributed under the License is distributed on an "AS IS" BASIS,
31
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
32
+ * See the License for the specific language governing permissions and
33
+ * limitations under the License.
34
+ */
35
+ __exportStar(require("./CallUsage"), exports);
36
+ __exportStar(require("./meters"), exports);
37
+ __exportStar(require("./types"), exports);
38
+ __exportStar(require("./usageId"), exports);
@@ -0,0 +1,113 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ /** The unit a meter counts in. */
20
+ export type UsageUnit = "second" | "character" | "token" | "count" | "byte";
21
+ /** How a meter's lines combine: added up, or a point-in-time reading (take the latest). */
22
+ export type UsageAggregation = "sum" | "snapshot";
23
+ /** The component that measures a meter. */
24
+ export type UsageReporter = "appbridge" | "autopilot" | "apiserver";
25
+ export type MeterDefinition = {
26
+ unit: UsageUnit;
27
+ aggregation: UsageAggregation;
28
+ reporter: UsageReporter;
29
+ /** A third-party vendor does the work, so every line says whose key was used. */
30
+ vendor: boolean;
31
+ };
32
+ /**
33
+ * The declared meters (add-usage-metering, usage-metering spec). Usage for any other name is
34
+ * rejected. Adding a meter is adding an entry here.
35
+ */
36
+ export declare const METERS: {
37
+ readonly "call.seconds": {
38
+ readonly unit: "second";
39
+ readonly aggregation: "sum";
40
+ readonly reporter: "appbridge";
41
+ readonly vendor: false;
42
+ };
43
+ readonly "stt.seconds": {
44
+ readonly unit: "second";
45
+ readonly aggregation: "sum";
46
+ readonly reporter: "appbridge";
47
+ readonly vendor: true;
48
+ };
49
+ readonly "tts.characters": {
50
+ readonly unit: "character";
51
+ readonly aggregation: "sum";
52
+ readonly reporter: "appbridge";
53
+ readonly vendor: true;
54
+ };
55
+ readonly "llm.tokens.in": {
56
+ readonly unit: "token";
57
+ readonly aggregation: "sum";
58
+ readonly reporter: "autopilot";
59
+ readonly vendor: true;
60
+ };
61
+ readonly "llm.tokens.out": {
62
+ readonly unit: "token";
63
+ readonly aggregation: "sum";
64
+ readonly reporter: "autopilot";
65
+ readonly vendor: true;
66
+ };
67
+ readonly "llm.tokens.cached": {
68
+ readonly unit: "token";
69
+ readonly aggregation: "sum";
70
+ readonly reporter: "autopilot";
71
+ readonly vendor: true;
72
+ };
73
+ readonly "embedding.tokens": {
74
+ readonly unit: "token";
75
+ readonly aggregation: "sum";
76
+ readonly reporter: "autopilot";
77
+ readonly vendor: true;
78
+ };
79
+ readonly "nc.seconds": {
80
+ readonly unit: "second";
81
+ readonly aggregation: "sum";
82
+ readonly reporter: "appbridge";
83
+ readonly vendor: true;
84
+ };
85
+ readonly "amd.detections": {
86
+ readonly unit: "count";
87
+ readonly aggregation: "sum";
88
+ readonly reporter: "appbridge";
89
+ readonly vendor: false;
90
+ };
91
+ readonly "amd.seconds": {
92
+ readonly unit: "second";
93
+ readonly aggregation: "sum";
94
+ readonly reporter: "appbridge";
95
+ readonly vendor: false;
96
+ };
97
+ readonly "recording.seconds": {
98
+ readonly unit: "second";
99
+ readonly aggregation: "sum";
100
+ readonly reporter: "appbridge";
101
+ readonly vendor: false;
102
+ };
103
+ readonly "storage.bytes": {
104
+ readonly unit: "byte";
105
+ readonly aggregation: "snapshot";
106
+ readonly reporter: "apiserver";
107
+ readonly vendor: false;
108
+ };
109
+ };
110
+ export type MeterName = keyof typeof METERS;
111
+ export declare const METER_NAMES: MeterName[];
112
+ export declare function isMeter(name: string): name is MeterName;
113
+ export declare function meterOf(name: MeterName): MeterDefinition;
@@ -0,0 +1,90 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.METER_NAMES = exports.METERS = void 0;
4
+ exports.isMeter = isMeter;
5
+ exports.meterOf = meterOf;
6
+ /**
7
+ * The declared meters (add-usage-metering, usage-metering spec). Usage for any other name is
8
+ * rejected. Adding a meter is adding an entry here.
9
+ */
10
+ exports.METERS = {
11
+ "call.seconds": {
12
+ unit: "second",
13
+ aggregation: "sum",
14
+ reporter: "appbridge",
15
+ vendor: false
16
+ },
17
+ "stt.seconds": {
18
+ unit: "second",
19
+ aggregation: "sum",
20
+ reporter: "appbridge",
21
+ vendor: true
22
+ },
23
+ "tts.characters": {
24
+ unit: "character",
25
+ aggregation: "sum",
26
+ reporter: "appbridge",
27
+ vendor: true
28
+ },
29
+ "llm.tokens.in": {
30
+ unit: "token",
31
+ aggregation: "sum",
32
+ reporter: "autopilot",
33
+ vendor: true
34
+ },
35
+ "llm.tokens.out": {
36
+ unit: "token",
37
+ aggregation: "sum",
38
+ reporter: "autopilot",
39
+ vendor: true
40
+ },
41
+ "llm.tokens.cached": {
42
+ unit: "token",
43
+ aggregation: "sum",
44
+ reporter: "autopilot",
45
+ vendor: true
46
+ },
47
+ "embedding.tokens": {
48
+ unit: "token",
49
+ aggregation: "sum",
50
+ reporter: "autopilot",
51
+ vendor: true
52
+ },
53
+ "nc.seconds": {
54
+ unit: "second",
55
+ aggregation: "sum",
56
+ reporter: "appbridge",
57
+ vendor: true
58
+ },
59
+ "amd.detections": {
60
+ unit: "count",
61
+ aggregation: "sum",
62
+ reporter: "appbridge",
63
+ vendor: false
64
+ },
65
+ "amd.seconds": {
66
+ unit: "second",
67
+ aggregation: "sum",
68
+ reporter: "appbridge",
69
+ vendor: false
70
+ },
71
+ "recording.seconds": {
72
+ unit: "second",
73
+ aggregation: "sum",
74
+ reporter: "appbridge",
75
+ vendor: false
76
+ },
77
+ "storage.bytes": {
78
+ unit: "byte",
79
+ aggregation: "snapshot",
80
+ reporter: "apiserver",
81
+ vendor: false
82
+ }
83
+ };
84
+ exports.METER_NAMES = Object.keys(exports.METERS);
85
+ function isMeter(name) {
86
+ return Object.prototype.hasOwnProperty.call(exports.METERS, name);
87
+ }
88
+ function meterOf(name) {
89
+ return exports.METERS[name];
90
+ }
@@ -0,0 +1,159 @@
1
+ /**
2
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
3
+ * http://github.com/fonoster/fonoster
4
+ *
5
+ * This file is part of Fonoster
6
+ *
7
+ * Licensed under the MIT License (the "License");
8
+ * you may not use this file except in compliance with
9
+ * the License. You may obtain a copy of the License at
10
+ *
11
+ * https://opensource.org/licenses/MIT
12
+ *
13
+ * Unless required by applicable law or agreed to in writing, software
14
+ * distributed under the License is distributed on an "AS IS" BASIS,
15
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16
+ * See the License for the specific language governing permissions and
17
+ * limitations under the License.
18
+ */
19
+ import { z } from "zod";
20
+ import { MeterName } from "./meters";
21
+ export declare const KEY_SOURCES: readonly ["platform", "workspace"];
22
+ export type KeySource = (typeof KEY_SOURCES)[number];
23
+ export declare const ORIGINS: readonly ["call", "browser_test", "eval", "api"];
24
+ export type UsageOrigin = (typeof ORIGINS)[number];
25
+ export declare const REGION_KINDS: readonly ["public", "private"];
26
+ export type RegionKind = (typeof REGION_KINDS)[number];
27
+ /** One quantity of one meter. Facts only: strict, so no price or billable flag can ride along. */
28
+ export declare const usageLineSchema: z.ZodEffects<z.ZodObject<{
29
+ meter: z.ZodEffects<z.ZodString, "llm.tokens.in" | "llm.tokens.out" | "llm.tokens.cached" | "embedding.tokens" | "call.seconds" | "stt.seconds" | "tts.characters" | "nc.seconds" | "amd.detections" | "amd.seconds" | "recording.seconds" | "storage.bytes", string>;
30
+ quantity: z.ZodNumber;
31
+ provider: z.ZodOptional<z.ZodString>;
32
+ model: z.ZodOptional<z.ZodString>;
33
+ keySource: z.ZodOptional<z.ZodEnum<["platform", "workspace"]>>;
34
+ }, "strict", z.ZodTypeAny, {
35
+ model?: string;
36
+ provider?: string;
37
+ meter?: "llm.tokens.in" | "llm.tokens.out" | "llm.tokens.cached" | "embedding.tokens" | "call.seconds" | "stt.seconds" | "tts.characters" | "nc.seconds" | "amd.detections" | "amd.seconds" | "recording.seconds" | "storage.bytes";
38
+ quantity?: number;
39
+ keySource?: "platform" | "workspace";
40
+ }, {
41
+ model?: string;
42
+ provider?: string;
43
+ meter?: string;
44
+ quantity?: number;
45
+ keySource?: "platform" | "workspace";
46
+ }>, {
47
+ model?: string;
48
+ provider?: string;
49
+ meter?: "llm.tokens.in" | "llm.tokens.out" | "llm.tokens.cached" | "embedding.tokens" | "call.seconds" | "stt.seconds" | "tts.characters" | "nc.seconds" | "amd.detections" | "amd.seconds" | "recording.seconds" | "storage.bytes";
50
+ quantity?: number;
51
+ keySource?: "platform" | "workspace";
52
+ }, {
53
+ model?: string;
54
+ provider?: string;
55
+ meter?: string;
56
+ quantity?: number;
57
+ keySource?: "platform" | "workspace";
58
+ }>;
59
+ /** A usage line with its attribution, as stored and as published on `usage.>`. */
60
+ export declare const usageEventSchema: z.ZodEffects<z.ZodObject<{
61
+ id: z.ZodString;
62
+ /** Resolved from the workspace at ingest when the reporter does not know it. */
63
+ ownerRef: z.ZodOptional<z.ZodString>;
64
+ workspaceRef: z.ZodString;
65
+ appRef: z.ZodOptional<z.ZodString>;
66
+ callRef: z.ZodOptional<z.ZodString>;
67
+ region: z.ZodString;
68
+ regionKind: z.ZodEnum<["public", "private"]>;
69
+ origin: z.ZodEnum<["call", "browser_test", "eval", "api"]>;
70
+ occurredAt: z.ZodString;
71
+ meter: z.ZodEffects<z.ZodString, "llm.tokens.in" | "llm.tokens.out" | "llm.tokens.cached" | "embedding.tokens" | "call.seconds" | "stt.seconds" | "tts.characters" | "nc.seconds" | "amd.detections" | "amd.seconds" | "recording.seconds" | "storage.bytes", string>;
72
+ quantity: z.ZodNumber;
73
+ provider: z.ZodOptional<z.ZodString>;
74
+ model: z.ZodOptional<z.ZodString>;
75
+ keySource: z.ZodOptional<z.ZodEnum<["platform", "workspace"]>>;
76
+ }, "strict", z.ZodTypeAny, {
77
+ model?: string;
78
+ provider?: string;
79
+ id?: string;
80
+ appRef?: string;
81
+ region?: string;
82
+ callRef?: string;
83
+ meter?: "llm.tokens.in" | "llm.tokens.out" | "llm.tokens.cached" | "embedding.tokens" | "call.seconds" | "stt.seconds" | "tts.characters" | "nc.seconds" | "amd.detections" | "amd.seconds" | "recording.seconds" | "storage.bytes";
84
+ quantity?: number;
85
+ keySource?: "platform" | "workspace";
86
+ origin?: "call" | "browser_test" | "eval" | "api";
87
+ workspaceRef?: string;
88
+ ownerRef?: string;
89
+ regionKind?: "public" | "private";
90
+ occurredAt?: string;
91
+ }, {
92
+ model?: string;
93
+ provider?: string;
94
+ id?: string;
95
+ appRef?: string;
96
+ region?: string;
97
+ callRef?: string;
98
+ meter?: string;
99
+ quantity?: number;
100
+ keySource?: "platform" | "workspace";
101
+ origin?: "call" | "browser_test" | "eval" | "api";
102
+ workspaceRef?: string;
103
+ ownerRef?: string;
104
+ regionKind?: "public" | "private";
105
+ occurredAt?: string;
106
+ }>, {
107
+ model?: string;
108
+ provider?: string;
109
+ id?: string;
110
+ appRef?: string;
111
+ region?: string;
112
+ callRef?: string;
113
+ meter?: "llm.tokens.in" | "llm.tokens.out" | "llm.tokens.cached" | "embedding.tokens" | "call.seconds" | "stt.seconds" | "tts.characters" | "nc.seconds" | "amd.detections" | "amd.seconds" | "recording.seconds" | "storage.bytes";
114
+ quantity?: number;
115
+ keySource?: "platform" | "workspace";
116
+ origin?: "call" | "browser_test" | "eval" | "api";
117
+ workspaceRef?: string;
118
+ ownerRef?: string;
119
+ regionKind?: "public" | "private";
120
+ occurredAt?: string;
121
+ }, {
122
+ model?: string;
123
+ provider?: string;
124
+ id?: string;
125
+ appRef?: string;
126
+ region?: string;
127
+ callRef?: string;
128
+ meter?: string;
129
+ quantity?: number;
130
+ keySource?: "platform" | "workspace";
131
+ origin?: "call" | "browser_test" | "eval" | "api";
132
+ workspaceRef?: string;
133
+ ownerRef?: string;
134
+ regionKind?: "public" | "private";
135
+ occurredAt?: string;
136
+ }>;
137
+ export type UsageLine = {
138
+ meter: MeterName;
139
+ quantity: number;
140
+ provider?: string;
141
+ model?: string;
142
+ keySource?: KeySource;
143
+ };
144
+ export type UsageEvent = UsageLine & {
145
+ id: string;
146
+ ownerRef?: string;
147
+ workspaceRef: string;
148
+ appRef?: string;
149
+ callRef?: string;
150
+ region: string;
151
+ regionKind: RegionKind;
152
+ origin: UsageOrigin;
153
+ occurredAt: string;
154
+ };
155
+ /** A usage line or event that failed validation; the message names every problem. */
156
+ export declare class InvalidUsageError extends Error {
157
+ }
158
+ export declare function parseUsageLine(input: unknown): UsageLine;
159
+ export declare function parseUsageEvent(input: unknown): UsageEvent;
@@ -0,0 +1,84 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.InvalidUsageError = exports.usageEventSchema = exports.usageLineSchema = exports.REGION_KINDS = exports.ORIGINS = exports.KEY_SOURCES = void 0;
4
+ exports.parseUsageLine = parseUsageLine;
5
+ exports.parseUsageEvent = parseUsageEvent;
6
+ /**
7
+ * Copyright (C) 2025 by Fonoster Inc (https://fonoster.com)
8
+ * http://github.com/fonoster/fonoster
9
+ *
10
+ * This file is part of Fonoster
11
+ *
12
+ * Licensed under the MIT License (the "License");
13
+ * you may not use this file except in compliance with
14
+ * the License. You may obtain a copy of the License at
15
+ *
16
+ * https://opensource.org/licenses/MIT
17
+ *
18
+ * Unless required by applicable law or agreed to in writing, software
19
+ * distributed under the License is distributed on an "AS IS" BASIS,
20
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ * See the License for the specific language governing permissions and
22
+ * limitations under the License.
23
+ */
24
+ const zod_1 = require("zod");
25
+ const meters_1 = require("./meters");
26
+ exports.KEY_SOURCES = ["platform", "workspace"];
27
+ exports.ORIGINS = ["call", "browser_test", "eval", "api"];
28
+ exports.REGION_KINDS = ["public", "private"];
29
+ const lineFields = {
30
+ meter: zod_1.z
31
+ .string()
32
+ .refine(meters_1.isMeter, (m) => ({ message: `undeclared meter "${m}"` })),
33
+ quantity: zod_1.z.number().finite().nonnegative(),
34
+ provider: zod_1.z.string().min(1).optional(),
35
+ model: zod_1.z.string().min(1).optional(),
36
+ keySource: zod_1.z.enum(exports.KEY_SOURCES).optional()
37
+ };
38
+ function checkKeySource(line, ctx) {
39
+ if (!line.meter || !(0, meters_1.isMeter)(line.meter))
40
+ return;
41
+ const vendor = meters_1.METERS[line.meter].vendor;
42
+ if (vendor && !line.keySource)
43
+ ctx.addIssue({
44
+ code: zod_1.z.ZodIssueCode.custom,
45
+ path: ["keySource"],
46
+ message: `${line.meter} needs a keySource`
47
+ });
48
+ if (!vendor && line.keySource)
49
+ ctx.addIssue({
50
+ code: zod_1.z.ZodIssueCode.custom,
51
+ path: ["keySource"],
52
+ message: `${line.meter} is not a vendor meter and takes no keySource`
53
+ });
54
+ }
55
+ /** One quantity of one meter. Facts only: strict, so no price or billable flag can ride along. */
56
+ exports.usageLineSchema = zod_1.z
57
+ .object(lineFields)
58
+ .strict()
59
+ .superRefine(checkKeySource);
60
+ /** A usage line with its attribution, as stored and as published on `usage.>`. */
61
+ exports.usageEventSchema = zod_1.z
62
+ .object(Object.assign(Object.assign({}, lineFields), { id: zod_1.z.string().regex(/^usg_[a-z2-7]{26}$/),
63
+ /** Resolved from the workspace at ingest when the reporter does not know it. */
64
+ ownerRef: zod_1.z.string().min(1).optional(), workspaceRef: zod_1.z.string().min(1), appRef: zod_1.z.string().min(1).optional(), callRef: zod_1.z.string().min(1).optional(), region: zod_1.z.string().min(1), regionKind: zod_1.z.enum(exports.REGION_KINDS), origin: zod_1.z.enum(exports.ORIGINS), occurredAt: zod_1.z.string().datetime() }))
65
+ .strict()
66
+ .superRefine(checkKeySource);
67
+ /** A usage line or event that failed validation; the message names every problem. */
68
+ class InvalidUsageError extends Error {
69
+ }
70
+ exports.InvalidUsageError = InvalidUsageError;
71
+ function parseWith(schema, input) {
72
+ const result = schema.safeParse(input);
73
+ if (result.success)
74
+ return result.data;
75
+ throw new InvalidUsageError(result.error.issues
76
+ .map((i) => i.path.length ? `${i.path.join(".")}: ${i.message}` : i.message)
77
+ .join("; "));
78
+ }
79
+ function parseUsageLine(input) {
80
+ return parseWith(exports.usageLineSchema, input);
81
+ }
82
+ function parseUsageEvent(input) {
83
+ return parseWith(exports.usageEventSchema, input);
84
+ }