@celljs/ta-gateway 4.15.1 → 4.16.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/esm/node/command-sandbox.d.ts +6 -2
- package/esm/node/command-sandbox.js +26 -4
- package/esm/node/docker-engine.d.ts +50 -0
- package/esm/node/docker-engine.js +98 -11
- package/esm/node/docker-sandbox.d.ts +6 -1
- package/esm/node/docker-sandbox.js +23 -3
- package/esm/node/environments.d.ts +36 -2
- package/esm/node/environments.js +192 -14
- package/esm/node/gateway-audit.d.ts +12 -0
- package/esm/node/gateway-audit.js +47 -0
- package/esm/node/gateway-cli.d.ts +2 -0
- package/esm/node/gateway-cli.js +1 -0
- package/esm/node/gateway-exec.d.ts +19 -0
- package/esm/node/gateway-exec.js +65 -0
- package/esm/node/gateway-policy.d.ts +47 -0
- package/esm/node/gateway-policy.js +152 -0
- package/esm/node/gateway-quotas.d.ts +40 -0
- package/esm/node/gateway-quotas.js +135 -0
- package/esm/node/gateway-server.d.ts +28 -2
- package/esm/node/gateway-server.js +112 -9
- package/esm/node/gateway-service.d.ts +99 -16
- package/esm/node/gateway-service.js +385 -45
- package/esm/node/gateway-socket.d.ts +7 -1
- package/esm/node/gateway-socket.js +40 -1
- package/esm/node/gateway-usage.d.ts +37 -0
- package/esm/node/gateway-usage.js +137 -0
- package/esm/node/local-sandbox.d.ts +13 -0
- package/esm/node/local-sandbox.js +38 -2
- package/esm/node/model-proxy.d.ts +105 -0
- package/esm/node/model-proxy.js +435 -0
- package/esm/node/sandbox-provider.d.ts +17 -0
- package/esm/node/tenant-store.d.ts +19 -1
- package/esm/node/tenant-store.js +10 -0
- package/lib/node/command-sandbox.d.ts +6 -2
- package/lib/node/command-sandbox.js +26 -4
- package/lib/node/docker-engine.d.ts +50 -0
- package/lib/node/docker-engine.js +98 -11
- package/lib/node/docker-sandbox.d.ts +6 -1
- package/lib/node/docker-sandbox.js +23 -3
- package/lib/node/environments.d.ts +36 -2
- package/lib/node/environments.js +191 -13
- package/lib/node/gateway-audit.d.ts +13 -0
- package/lib/node/gateway-audit.js +51 -0
- package/lib/node/gateway-cli.d.ts +2 -0
- package/lib/node/gateway-cli.js +1 -0
- package/lib/node/gateway-exec.d.ts +20 -0
- package/lib/node/gateway-exec.js +69 -0
- package/lib/node/gateway-policy.d.ts +48 -0
- package/lib/node/gateway-policy.js +157 -0
- package/lib/node/gateway-quotas.d.ts +41 -0
- package/lib/node/gateway-quotas.js +139 -0
- package/lib/node/gateway-server.d.ts +28 -2
- package/lib/node/gateway-server.js +112 -9
- package/lib/node/gateway-service.d.ts +99 -16
- package/lib/node/gateway-service.js +384 -44
- package/lib/node/gateway-socket.d.ts +7 -1
- package/lib/node/gateway-socket.js +40 -1
- package/lib/node/gateway-usage.d.ts +38 -0
- package/lib/node/gateway-usage.js +141 -0
- package/lib/node/local-sandbox.d.ts +13 -0
- package/lib/node/local-sandbox.js +40 -3
- package/lib/node/model-proxy.d.ts +106 -0
- package/lib/node/model-proxy.js +440 -0
- package/lib/node/sandbox-provider.d.ts +17 -0
- package/lib/node/tenant-store.d.ts +19 -1
- package/lib/node/tenant-store.js +10 -0
- package/package.json +4 -4
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import type { TaUsageBucket, TaUsageTrend } from '@celljs/ta-protocol';
|
|
2
|
+
interface Kept {
|
|
3
|
+
readAt: number;
|
|
4
|
+
buckets: TaUsageBucket[];
|
|
5
|
+
}
|
|
6
|
+
export declare namespace GatewayUsageUtil {
|
|
7
|
+
const KEEP_MS: number;
|
|
8
|
+
/** The start of the month of UTC of `now`, and of the next. */
|
|
9
|
+
function month(now: number): {
|
|
10
|
+
key: string;
|
|
11
|
+
start: number;
|
|
12
|
+
next: number;
|
|
13
|
+
};
|
|
14
|
+
function tokens(bucket: TaUsageBucket): number;
|
|
15
|
+
/** The buckets of tenants since `since`: by hour, by model and by tenant. */
|
|
16
|
+
function trend(byTenant: Map<string, TaUsageBucket[]>, since: number, stale: string[], now: number): TaUsageTrend;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* What the agents of each tenant took, by hour, as its Ta said last (TaUsageServer): asked of a running sandbox
|
|
20
|
+
* at most once a minute, kept in `usage/<tenant>.json` so that one stopped still counts.
|
|
21
|
+
*/
|
|
22
|
+
export declare class GatewayUsage {
|
|
23
|
+
protected readonly dir: string;
|
|
24
|
+
protected readonly kept: Map<string, Kept>;
|
|
25
|
+
protected readonly reading: Map<string, Promise<void>>;
|
|
26
|
+
constructor(root: string);
|
|
27
|
+
/** What is kept of the tenant. */
|
|
28
|
+
get(tenantId: string): Kept | undefined;
|
|
29
|
+
/** Asks the tenant's Ta again, unless it was asked within `maxAge` (a minute); `read` undefined: it does not run. */
|
|
30
|
+
refresh(tenantId: string, read: ((since: number) => Promise<TaUsageBucket[]>) | undefined, now?: number, maxAge?: number): Promise<boolean>;
|
|
31
|
+
/** Tokens and dollars of the month of `now`. */
|
|
32
|
+
month(tenantId: string, now?: number): {
|
|
33
|
+
tokens: number;
|
|
34
|
+
cost: number;
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
export {};
|
|
38
|
+
//# sourceMappingURL=gateway-usage.d.ts.map
|
|
@@ -0,0 +1,141 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
+
exports.GatewayUsage = exports.GatewayUsageUtil = void 0;
|
|
4
|
+
const node_fs_1 = require("node:fs");
|
|
5
|
+
const node_path_1 = require("node:path");
|
|
6
|
+
const tenant_store_1 = require("./tenant-store");
|
|
7
|
+
const HOUR = 3600000;
|
|
8
|
+
const DAY = 24 * HOUR;
|
|
9
|
+
/** Kept of each tenant: a month, whatever day of it. */
|
|
10
|
+
const KEPT_DAYS = 32;
|
|
11
|
+
/** A tenant's usage is asked again at most this often. */
|
|
12
|
+
const FRESH_MS = 60000;
|
|
13
|
+
var GatewayUsageUtil;
|
|
14
|
+
(function (GatewayUsageUtil) {
|
|
15
|
+
GatewayUsageUtil.KEEP_MS = KEPT_DAYS * DAY;
|
|
16
|
+
/** The start of the month of UTC of `now`, and of the next. */
|
|
17
|
+
function month(now) {
|
|
18
|
+
const date = new Date(now);
|
|
19
|
+
const start = Date.UTC(date.getUTCFullYear(), date.getUTCMonth(), 1);
|
|
20
|
+
const next = Date.UTC(date.getUTCFullYear(), date.getUTCMonth() + 1, 1);
|
|
21
|
+
return { key: new Date(start).toISOString().slice(0, 7), start, next };
|
|
22
|
+
}
|
|
23
|
+
GatewayUsageUtil.month = month;
|
|
24
|
+
function tokens(bucket) {
|
|
25
|
+
return bucket.input + bucket.output + bucket.cacheRead + bucket.cacheWrite;
|
|
26
|
+
}
|
|
27
|
+
GatewayUsageUtil.tokens = tokens;
|
|
28
|
+
/** The buckets of tenants since `since`: by hour, by model and by tenant. */
|
|
29
|
+
function trend(byTenant, since, stale, now) {
|
|
30
|
+
var _a, _b;
|
|
31
|
+
const hours = new Map();
|
|
32
|
+
const models = new Map();
|
|
33
|
+
const tenants = [];
|
|
34
|
+
for (const [tenantId, buckets] of byTenant) {
|
|
35
|
+
const share = { tenantId, tokens: 0, cost: 0, turns: 0 };
|
|
36
|
+
for (const bucket of buckets) {
|
|
37
|
+
if (bucket.at + HOUR <= since) {
|
|
38
|
+
continue;
|
|
39
|
+
}
|
|
40
|
+
const count = tokens(bucket);
|
|
41
|
+
const hour = (_a = hours.get(bucket.at)) !== null && _a !== void 0 ? _a : { at: bucket.at, input: 0, output: 0, tokens: 0, cost: 0, turns: 0 };
|
|
42
|
+
hour.input += bucket.input;
|
|
43
|
+
hour.output += bucket.output;
|
|
44
|
+
hour.tokens += count;
|
|
45
|
+
hour.cost += bucket.cost;
|
|
46
|
+
hour.turns += bucket.turns;
|
|
47
|
+
hours.set(bucket.at, hour);
|
|
48
|
+
const model = (_b = models.get(bucket.model)) !== null && _b !== void 0 ? _b : { model: bucket.model, tokens: 0, cost: 0, turns: 0 };
|
|
49
|
+
model.tokens += count;
|
|
50
|
+
model.cost += bucket.cost;
|
|
51
|
+
model.turns += bucket.turns;
|
|
52
|
+
models.set(bucket.model, model);
|
|
53
|
+
share.tokens += count;
|
|
54
|
+
share.cost += bucket.cost;
|
|
55
|
+
share.turns += bucket.turns;
|
|
56
|
+
}
|
|
57
|
+
if (share.turns > 0) {
|
|
58
|
+
tenants.push(share);
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
return {
|
|
62
|
+
since,
|
|
63
|
+
hours: [...hours.values()].sort((a, b) => a.at - b.at),
|
|
64
|
+
byModel: [...models.values()].sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
|
|
65
|
+
byTenant: tenants.sort((a, b) => b.cost - a.cost || b.tokens - a.tokens),
|
|
66
|
+
stale,
|
|
67
|
+
readAt: now,
|
|
68
|
+
};
|
|
69
|
+
}
|
|
70
|
+
GatewayUsageUtil.trend = trend;
|
|
71
|
+
})(GatewayUsageUtil || (exports.GatewayUsageUtil = GatewayUsageUtil = {}));
|
|
72
|
+
/**
|
|
73
|
+
* What the agents of each tenant took, by hour, as its Ta said last (TaUsageServer): asked of a running sandbox
|
|
74
|
+
* at most once a minute, kept in `usage/<tenant>.json` so that one stopped still counts.
|
|
75
|
+
*/
|
|
76
|
+
class GatewayUsage {
|
|
77
|
+
constructor(root) {
|
|
78
|
+
this.kept = new Map();
|
|
79
|
+
this.reading = new Map();
|
|
80
|
+
this.dir = (0, node_path_1.join)(root, 'usage');
|
|
81
|
+
(0, node_fs_1.mkdirSync)(this.dir, { recursive: true, mode: 0o700 });
|
|
82
|
+
}
|
|
83
|
+
/** What is kept of the tenant. */
|
|
84
|
+
get(tenantId) {
|
|
85
|
+
let kept = this.kept.get(tenantId);
|
|
86
|
+
if (!kept && /^[0-9a-f]{16}$/.test(tenantId)) {
|
|
87
|
+
try {
|
|
88
|
+
kept = JSON.parse((0, node_fs_1.readFileSync)((0, node_path_1.join)(this.dir, `${tenantId}.json`), 'utf8'));
|
|
89
|
+
this.kept.set(tenantId, kept);
|
|
90
|
+
}
|
|
91
|
+
catch (_a) {
|
|
92
|
+
return undefined;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return kept;
|
|
96
|
+
}
|
|
97
|
+
/** Asks the tenant's Ta again, unless it was asked within `maxAge` (a minute); `read` undefined: it does not run. */
|
|
98
|
+
async refresh(tenantId, read, now = Date.now(), maxAge = FRESH_MS) {
|
|
99
|
+
const kept = this.get(tenantId);
|
|
100
|
+
if (!read) {
|
|
101
|
+
return false;
|
|
102
|
+
}
|
|
103
|
+
if (kept && now - kept.readAt < maxAge) {
|
|
104
|
+
return true;
|
|
105
|
+
}
|
|
106
|
+
let reading = this.reading.get(tenantId);
|
|
107
|
+
if (!reading) {
|
|
108
|
+
reading = read(now - GatewayUsageUtil.KEEP_MS).then(buckets => {
|
|
109
|
+
const next = { readAt: now, buckets };
|
|
110
|
+
this.kept.set(tenantId, next);
|
|
111
|
+
(0, tenant_store_1.writePrivate)((0, node_path_1.join)(this.dir, `${tenantId}.json`), next);
|
|
112
|
+
});
|
|
113
|
+
this.reading.set(tenantId, reading);
|
|
114
|
+
void reading.finally(() => this.reading.delete(tenantId)).catch(() => undefined);
|
|
115
|
+
}
|
|
116
|
+
try {
|
|
117
|
+
await reading;
|
|
118
|
+
return true;
|
|
119
|
+
}
|
|
120
|
+
catch (_a) {
|
|
121
|
+
return false;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
/** Tokens and dollars of the month of `now`. */
|
|
125
|
+
month(tenantId, now = Date.now()) {
|
|
126
|
+
var _a;
|
|
127
|
+
var _b;
|
|
128
|
+
const { start } = GatewayUsageUtil.month(now);
|
|
129
|
+
let tokens = 0;
|
|
130
|
+
let cost = 0;
|
|
131
|
+
for (const bucket of (_b = (_a = this.get(tenantId)) === null || _a === void 0 ? void 0 : _a.buckets) !== null && _b !== void 0 ? _b : []) {
|
|
132
|
+
if (bucket.at >= start) {
|
|
133
|
+
tokens += GatewayUsageUtil.tokens(bucket);
|
|
134
|
+
cost += bucket.cost;
|
|
135
|
+
}
|
|
136
|
+
}
|
|
137
|
+
return { tokens, cost };
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
exports.GatewayUsage = GatewayUsage;
|
|
141
|
+
//# sourceMappingURL=gateway-usage.js.map
|
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
import { type ChildProcess } from 'node:child_process';
|
|
2
2
|
import type { SandboxContext, SandboxEndpoint, SandboxProvider, SandboxProviderConfig, SandboxState, SandboxTenant } from './sandbox-provider';
|
|
3
|
+
/** The last lines written to it, whole lines only but the one being written. */
|
|
4
|
+
export declare class LineTail {
|
|
5
|
+
protected readonly max: number;
|
|
6
|
+
protected readonly lines: string[];
|
|
7
|
+
protected partial: string;
|
|
8
|
+
constructor(max?: number);
|
|
9
|
+
write(chunk: string): void;
|
|
10
|
+
last(count: number): string;
|
|
11
|
+
}
|
|
3
12
|
/**
|
|
4
13
|
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
5
14
|
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
@@ -10,14 +19,18 @@ export declare class LocalSandbox implements SandboxProvider {
|
|
|
10
19
|
protected readonly context: SandboxContext;
|
|
11
20
|
readonly type = "local";
|
|
12
21
|
readonly name: string;
|
|
22
|
+
readonly gatewayUrl?: string;
|
|
13
23
|
protected readonly running: Map<string, {
|
|
14
24
|
child: ChildProcess;
|
|
15
25
|
url: string;
|
|
16
26
|
}>;
|
|
27
|
+
/** Kept past a stop, so that the console shows why one ended. */
|
|
28
|
+
protected readonly output: Map<string, LineTail>;
|
|
17
29
|
constructor(id: string, config: SandboxProviderConfig, context: SandboxContext);
|
|
18
30
|
start(tenant: SandboxTenant): Promise<SandboxEndpoint>;
|
|
19
31
|
stop(tenant: SandboxTenant): Promise<void>;
|
|
20
32
|
state(tenant: SandboxTenant): Promise<SandboxState>;
|
|
33
|
+
logs(tenant: SandboxTenant, lines: number): Promise<string>;
|
|
21
34
|
dispose(): Promise<void>;
|
|
22
35
|
static freePort(): Promise<number>;
|
|
23
36
|
}
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
"use strict";
|
|
2
2
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.LocalSandbox = void 0;
|
|
3
|
+
exports.LocalSandbox = exports.LineTail = void 0;
|
|
4
4
|
const node_child_process_1 = require("node:child_process");
|
|
5
5
|
const node_fs_1 = require("node:fs");
|
|
6
6
|
const node_net_1 = require("node:net");
|
|
@@ -8,6 +8,30 @@ const node_path_1 = require("node:path");
|
|
|
8
8
|
const sandbox_provider_1 = require("./sandbox-provider");
|
|
9
9
|
/** How long a ta serve has to end on SIGTERM before it is killed. */
|
|
10
10
|
const STOP_TIMEOUT_MS = 10000;
|
|
11
|
+
/** The lines of output of each tenant's ta serve kept for the console. */
|
|
12
|
+
const KEPT_LINES = 2000;
|
|
13
|
+
/** The last lines written to it, whole lines only but the one being written. */
|
|
14
|
+
class LineTail {
|
|
15
|
+
constructor(max = KEPT_LINES) {
|
|
16
|
+
this.max = max;
|
|
17
|
+
this.lines = [];
|
|
18
|
+
this.partial = '';
|
|
19
|
+
}
|
|
20
|
+
write(chunk) {
|
|
21
|
+
var _a;
|
|
22
|
+
const parts = (this.partial + chunk).split('\n');
|
|
23
|
+
this.partial = (_a = parts.pop()) !== null && _a !== void 0 ? _a : '';
|
|
24
|
+
this.lines.push(...parts);
|
|
25
|
+
if (this.lines.length > this.max) {
|
|
26
|
+
this.lines.splice(0, this.lines.length - this.max);
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
last(count) {
|
|
30
|
+
const lines = this.partial ? [...this.lines, this.partial] : this.lines;
|
|
31
|
+
return lines.slice(-count).join('\n');
|
|
32
|
+
}
|
|
33
|
+
}
|
|
34
|
+
exports.LineTail = LineTail;
|
|
11
35
|
/**
|
|
12
36
|
* `local`: a `ta serve` process per tenant on the machine of the gateway, its agent directory and workspace
|
|
13
37
|
* under `<gateway>/local/<tenant>`. Not a sandbox: every tenant runs as the user of the gateway and can read
|
|
@@ -19,9 +43,13 @@ class LocalSandbox {
|
|
|
19
43
|
this.context = context;
|
|
20
44
|
this.type = 'local';
|
|
21
45
|
this.running = new Map();
|
|
46
|
+
/** Kept past a stop, so that the console shows why one ended. */
|
|
47
|
+
this.output = new Map();
|
|
22
48
|
this.name = sandbox_provider_1.SandboxProviders.string(config, 'name', 'Local');
|
|
49
|
+
this.gatewayUrl = sandbox_provider_1.SandboxProviders.string(config, 'gatewayUrl');
|
|
23
50
|
}
|
|
24
51
|
async start(tenant) {
|
|
52
|
+
var _a, _b;
|
|
25
53
|
const running = this.running.get(tenant.id);
|
|
26
54
|
if (running && running.child.exitCode === null) {
|
|
27
55
|
return { url: running.url, token: tenant.token };
|
|
@@ -35,9 +63,13 @@ class LocalSandbox {
|
|
|
35
63
|
const [command, ...args] = this.context.taCommand;
|
|
36
64
|
const child = (0, node_child_process_1.spawn)(command, [...args, 'serve', '--port', String(port)], {
|
|
37
65
|
cwd,
|
|
38
|
-
env: { ...process.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
39
|
-
stdio: 'ignore',
|
|
66
|
+
env: { ...process.env, ...tenant.env, TA_CODING_AGENT_DIR: agentDir, TA_SERVE_TOKEN: tenant.token, CELL_SERVER__HOST: '127.0.0.1' },
|
|
67
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
40
68
|
});
|
|
69
|
+
const tail = new LineTail();
|
|
70
|
+
this.output.set(tenant.id, tail);
|
|
71
|
+
(_a = child.stdout) === null || _a === void 0 ? void 0 : _a.setEncoding('utf8').on('data', (data) => tail.write(data));
|
|
72
|
+
(_b = child.stderr) === null || _b === void 0 ? void 0 : _b.setEncoding('utf8').on('data', (data) => tail.write(data));
|
|
41
73
|
const url = `http://127.0.0.1:${port}`;
|
|
42
74
|
// A command that cannot start fails this tenant's start (nothing answers), not the gateway.
|
|
43
75
|
const gone = () => {
|
|
@@ -72,6 +104,11 @@ class LocalSandbox {
|
|
|
72
104
|
async state(tenant) {
|
|
73
105
|
return this.running.has(tenant.id) ? 'running' : 'stopped';
|
|
74
106
|
}
|
|
107
|
+
async logs(tenant, lines) {
|
|
108
|
+
var _a;
|
|
109
|
+
var _b;
|
|
110
|
+
return (_b = (_a = this.output.get(tenant.id)) === null || _a === void 0 ? void 0 : _a.last(lines)) !== null && _b !== void 0 ? _b : '';
|
|
111
|
+
}
|
|
75
112
|
async dispose() {
|
|
76
113
|
await Promise.all([...this.running.keys()].map(id => this.stop({ id, account: '', token: '' })));
|
|
77
114
|
}
|
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import type { IncomingMessage, ServerResponse } from 'node:http';
|
|
2
|
+
/** What a model costs, in dollars per million tokens, as pi's models.json says it. */
|
|
3
|
+
export interface ModelCost {
|
|
4
|
+
input?: number;
|
|
5
|
+
output?: number;
|
|
6
|
+
cacheRead?: number;
|
|
7
|
+
cacheWrite?: number;
|
|
8
|
+
}
|
|
9
|
+
/** A provider of models of the gateway: an entry of pi's models.json, its key kept by the gateway alone. */
|
|
10
|
+
export interface GatewayModelProvider {
|
|
11
|
+
name?: string;
|
|
12
|
+
baseUrl: string;
|
|
13
|
+
/** pi's `api`: openai-completions, openai-responses, anthropic-messages, google-generative-ai, … */
|
|
14
|
+
api: string;
|
|
15
|
+
/** The key, or the name of a variable of the environment of the gateway that holds it. */
|
|
16
|
+
apiKey?: string;
|
|
17
|
+
/** Headers sent upstream, never to sandboxes. */
|
|
18
|
+
headers?: Record<string, string>;
|
|
19
|
+
models: ({
|
|
20
|
+
id: string;
|
|
21
|
+
cost?: ModelCost;
|
|
22
|
+
} & Record<string, unknown>)[];
|
|
23
|
+
}
|
|
24
|
+
/** `models.json` of the directory of the gateway. */
|
|
25
|
+
export interface GatewayModelsConfig {
|
|
26
|
+
providers?: Record<string, GatewayModelProvider>;
|
|
27
|
+
}
|
|
28
|
+
/** Tokens of one call, as the gateway counts them. */
|
|
29
|
+
export interface ModelUsage {
|
|
30
|
+
input: number;
|
|
31
|
+
output: number;
|
|
32
|
+
cacheRead: number;
|
|
33
|
+
cacheWrite: number;
|
|
34
|
+
}
|
|
35
|
+
/** What sandboxes are told of the providers: everything but where they are and their keys. */
|
|
36
|
+
export interface ModelCatalog {
|
|
37
|
+
providers: {
|
|
38
|
+
id: string;
|
|
39
|
+
name?: string;
|
|
40
|
+
api: string;
|
|
41
|
+
models: Record<string, unknown>[];
|
|
42
|
+
}[];
|
|
43
|
+
}
|
|
44
|
+
/** Who a model key is, whether they may call now, and what a call took. */
|
|
45
|
+
export interface ModelProxyHooks {
|
|
46
|
+
tenantOfKey(key: string): {
|
|
47
|
+
id: string;
|
|
48
|
+
account: string;
|
|
49
|
+
} | undefined;
|
|
50
|
+
/** Why the tenant may not call a model now (out of tokens, suspended), as the message a model would give. */
|
|
51
|
+
refuse(tenantId: string): string | undefined;
|
|
52
|
+
record(tenantId: string, usage: ModelUsage, cost: number): void;
|
|
53
|
+
}
|
|
54
|
+
export declare class ModelConfigError extends Error {
|
|
55
|
+
}
|
|
56
|
+
export declare namespace ModelProxyUtil {
|
|
57
|
+
const PATH = "/api/models";
|
|
58
|
+
function read(dir: string): GatewayModelsConfig;
|
|
59
|
+
/** The key: the variable of the environment it names, else itself. */
|
|
60
|
+
function key(value: string | undefined, env?: Record<string, string | undefined>): string | undefined;
|
|
61
|
+
function catalog(config: GatewayModelsConfig): ModelCatalog;
|
|
62
|
+
/** The key a sandbox sent, however its API sends one. */
|
|
63
|
+
function presented(request: IncomingMessage): string | undefined;
|
|
64
|
+
/** How the provider takes its key. */
|
|
65
|
+
function authHeaders(api: string, key: string | undefined): Record<string, string>;
|
|
66
|
+
/** Where a call goes: the rest of its path on the provider's base, its query without a key. */
|
|
67
|
+
function target(baseUrl: string, rest: string, query: URLSearchParams): string;
|
|
68
|
+
/**
|
|
69
|
+
* The tokens an object of an answer tells (OpenAI chat or responses, Anthropic, Google), cached input apart;
|
|
70
|
+
* undefined for one that tells none.
|
|
71
|
+
*/
|
|
72
|
+
function usageOf(value: unknown): ModelUsage | undefined;
|
|
73
|
+
/** Events of a stream tell them as they go, each so far: the most of each. */
|
|
74
|
+
function merge(into: ModelUsage | undefined, next: ModelUsage | undefined): ModelUsage | undefined;
|
|
75
|
+
function total(usage: ModelUsage): number;
|
|
76
|
+
function cost(usage: ModelUsage, price: ModelCost | undefined): number;
|
|
77
|
+
/**
|
|
78
|
+
* The body of an OpenAI chat stream asking for its usage too: without stream_options.include_usage the stream
|
|
79
|
+
* tells none, and a call would go uncounted past every limit. Other bodies are sent as they came.
|
|
80
|
+
*/
|
|
81
|
+
function metered(api: string, body: Buffer): Buffer;
|
|
82
|
+
/** The model a call names: in its path (Google), else in its body. */
|
|
83
|
+
function modelOf(body: Buffer, rest: string): string | undefined;
|
|
84
|
+
/** An error as a model service gives one, so that the clients of every API read its message. */
|
|
85
|
+
function error(response: ServerResponse, status: number, message: string, type?: string): void;
|
|
86
|
+
function sameKey(given: string, known: string): boolean;
|
|
87
|
+
}
|
|
88
|
+
/**
|
|
89
|
+
* The models of the gateway, for its sandboxes: a call of a sandbox with the model key of its tenant goes to the
|
|
90
|
+
* provider with the gateway's key, which no sandbox has, and what it took is counted for the tenant, from the usage
|
|
91
|
+
* of the answer (a stream's too). A tenant out of its tokens of the month gets an error instead of a call.
|
|
92
|
+
*/
|
|
93
|
+
export declare class ModelProxy {
|
|
94
|
+
readonly config: GatewayModelsConfig;
|
|
95
|
+
protected readonly hooks: ModelProxyHooks;
|
|
96
|
+
protected readonly env: Record<string, string | undefined>;
|
|
97
|
+
constructor(config: GatewayModelsConfig, hooks: ModelProxyHooks, env?: Record<string, string | undefined>);
|
|
98
|
+
get enabled(): boolean;
|
|
99
|
+
protected provider(id: string): GatewayModelProvider | undefined;
|
|
100
|
+
handle(request: IncomingMessage, response: ServerResponse): Promise<void>;
|
|
101
|
+
/** Whether the response drained, false once it closed instead (its drain never comes then). */
|
|
102
|
+
protected drained(response: ServerResponse): Promise<boolean>;
|
|
103
|
+
protected event(line: string): ModelUsage | undefined;
|
|
104
|
+
protected body(request: IncomingMessage): Promise<Buffer | undefined>;
|
|
105
|
+
}
|
|
106
|
+
//# sourceMappingURL=model-proxy.d.ts.map
|