dsh-cliproxyapi-pro 1.9.0 → 1.9.1
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/CHANGELOG.md +15 -0
- package/README.en.md +23 -407
- package/README.md +23 -407
- package/lib/client.js +46 -20
- package/lib/host/accounts.js +176 -0
- package/lib/host/apply/agent-tool.js +406 -0
- package/lib/host/apply/commands.js +122 -0
- package/lib/host/apply/controller.js +105 -0
- package/lib/host/apply/http-routes.js +273 -0
- package/lib/host/apply/image-jobs.js +171 -0
- package/lib/host/apply/index.js +41 -0
- package/lib/host/apply/interpret.js +72 -0
- package/lib/host/apply/lifecycle.js +34 -0
- package/lib/host/apply/media-failures.js +68 -0
- package/lib/host/apply/media-service.js +202 -0
- package/lib/host/apply/quota-service.js +42 -0
- package/lib/host/apply/references.js +43 -0
- package/lib/host/apply/session-status.js +104 -0
- package/lib/host/apply/state.js +78 -0
- package/lib/host/apply/updates.js +55 -0
- package/lib/host/apply/video-command.js +152 -0
- package/lib/host/apply/video-edit.js +253 -0
- package/lib/host/apply/video-jobs.js +206 -0
- package/lib/host/apply-utils.js +39 -0
- package/lib/host/config.js +205 -0
- package/lib/host/controller.js +435 -0
- package/lib/host/discovery.js +295 -0
- package/lib/host/http-gate.js +144 -0
- package/lib/host/models.js +102 -0
- package/lib/host/mount-guard.js +56 -0
- package/lib/host/routes.js +165 -0
- package/lib/host/runtime.js +445 -0
- package/lib/host/state-store.js +39 -0
- package/lib/host/status-text.js +93 -0
- package/lib/index.js +17 -4417
- package/lib/media/agent-tool.js +255 -0
- package/lib/media/choice.js +83 -0
- package/lib/media/classify.js +65 -0
- package/lib/media/codec/fit.js +76 -0
- package/lib/media/codec/jpeg.js +158 -0
- package/lib/media/codec/png.js +102 -0
- package/lib/media/commands/parsing.js +269 -0
- package/lib/media/constants.js +46 -0
- package/lib/media/diagnose.js +134 -0
- package/lib/media/images.js +165 -0
- package/lib/media/index.js +29 -0
- package/lib/media/interpret.js +126 -0
- package/lib/media/job-store.js +99 -0
- package/lib/media/mp4.js +44 -0
- package/lib/media/output-files.js +59 -0
- package/lib/media/session-store.js +293 -0
- package/lib/media/settings.js +255 -0
- package/lib/media/util.js +45 -0
- package/lib/media/video.js +326 -0
- package/lib/quota/auth-state.js +33 -0
- package/lib/quota/constants.js +86 -0
- package/lib/quota/controller.js +467 -0
- package/lib/quota/helpers.js +325 -0
- package/lib/quota/index.js +19 -0
- package/lib/quota/management.js +216 -0
- package/lib/quota/matching.js +143 -0
- package/lib/quota/parsers.js +352 -0
- package/lib/quota/probes/billing.js +80 -0
- package/lib/quota/probes/google.js +120 -0
- package/lib/quota/probes/oauth.js +27 -0
- package/lib/quota/probes/plugin.js +18 -0
- package/lib/updater/constants.js +23 -0
- package/lib/updater/errors.js +8 -0
- package/lib/updater/index.js +11 -0
- package/lib/updater/registry.js +83 -0
- package/lib/updater/settings.js +45 -0
- package/lib/updater/store.js +23 -0
- package/lib/updater/updater.js +148 -0
- package/lib/updater/verify.js +110 -0
- package/lib/updater/version.js +31 -0
- package/locale/en.json +1 -1
- package/locale/zh.json +1 -1
- package/package.json +6 -9
- package/lib/media.js +0 -2542
- package/lib/quota.js +0 -1748
- package/lib/updater.js +0 -443
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
// Constants, credential references and account configuration normalization.
|
|
2
|
+
|
|
3
|
+
|
|
4
|
+
|
|
5
|
+
export const PACKAGE_NAME = "dsh-cliproxyapi-pro";
|
|
6
|
+
export const name = "dsh-cliproxyapi-pro";
|
|
7
|
+
export const inject = ["settings"];
|
|
8
|
+
|
|
9
|
+
export const DEFAULT_ACCOUNT_ID = "default";
|
|
10
|
+
export const DEFAULT_PROVIDER = "cli-proxy";
|
|
11
|
+
export const DEFAULT_DISPLAY_NAME = "CLI Proxy API";
|
|
12
|
+
export const DEFAULT_API_KEY_ENV = "CLI_PROXY_API_KEY";
|
|
13
|
+
export const STATE_VERSION = 2;
|
|
14
|
+
export const ACCOUNT_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/;
|
|
15
|
+
/** Per-account settings; everything else in the state file is global. */
|
|
16
|
+
export const ACCOUNT_FIELDS = [
|
|
17
|
+
"enabled",
|
|
18
|
+
"provider",
|
|
19
|
+
"displayName",
|
|
20
|
+
"baseURL",
|
|
21
|
+
"apiKeyEnv",
|
|
22
|
+
"protocol",
|
|
23
|
+
"protocolMode",
|
|
24
|
+
"includePrefix",
|
|
25
|
+
"excludePrefix",
|
|
26
|
+
"selectedModels",
|
|
27
|
+
"modelOverrides",
|
|
28
|
+
];
|
|
29
|
+
export const GLOBAL_FIELDS = ["refreshIntervalSeconds", "probeTimeoutMs"];
|
|
30
|
+
export const DEFAULT_REFRESH_INTERVAL_SECONDS = 300;
|
|
31
|
+
export const DEFAULT_PROBE_TIMEOUT_MS = 5000;
|
|
32
|
+
|
|
33
|
+
export const LOCAL_CANDIDATES = [
|
|
34
|
+
"http://127.0.0.1:8317",
|
|
35
|
+
"http://localhost:8317",
|
|
36
|
+
"http://[::1]:8317",
|
|
37
|
+
];
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Most models {@link recommendModels} picks for an account that has no saved
|
|
41
|
+
* selection yet: one per model family, so the picker starts small.
|
|
42
|
+
*/
|
|
43
|
+
export const MAX_RECOMMENDED_MODELS = 12;
|
|
44
|
+
|
|
45
|
+
export const MAX_CATALOG_BYTES = 8 * 1024 * 1024;
|
|
46
|
+
export const PI_AI_NS = "llm-pi-ai";
|
|
47
|
+
export const REASONING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"];
|
|
48
|
+
/** Wire protocols the DSH llm-pi-ai adapter accepts on a hand-declared route. */
|
|
49
|
+
export const PROTOCOLS = ["openai-completions", "openai-responses", "anthropic-messages"];
|
|
50
|
+
/** Route-key suffix and display-name label of each protocol's route. */
|
|
51
|
+
export const PROTOCOL_ROUTES = {
|
|
52
|
+
"openai-completions": { suffix: "", label: "" },
|
|
53
|
+
"openai-responses": { suffix: "-responses", label: " (OpenAI Responses)" },
|
|
54
|
+
"anthropic-messages": { suffix: "-messages", label: " (Claude Messages)" },
|
|
55
|
+
};
|
|
56
|
+
export const DEFAULT_MODEL_NS = "agent-default-model";
|
|
57
|
+
export const REF_PATTERN = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
58
|
+
|
|
59
|
+
export function toCredentialRef(value) {
|
|
60
|
+
const trimmed = String(value ?? "").trim();
|
|
61
|
+
if (!REF_PATTERN.test(trimmed)) {
|
|
62
|
+
throw new TypeError(`credential ref "${trimmed}" must match ${String(REF_PATTERN)}`);
|
|
63
|
+
}
|
|
64
|
+
return trimmed;
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
export function getEnvValue(ctx, varName) {
|
|
68
|
+
try {
|
|
69
|
+
const launchEnv = ctx.get?.("launchEnvironment");
|
|
70
|
+
if (launchEnv && typeof launchEnv.get === "function") {
|
|
71
|
+
const hit = launchEnv.get(varName);
|
|
72
|
+
if (hit && typeof hit.value === "string" && hit.value.length > 0) {
|
|
73
|
+
return hit.value;
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
} catch {}
|
|
77
|
+
const raw = process.env[varName];
|
|
78
|
+
return typeof raw === "string" && raw.length > 0 ? raw : undefined;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export function readVolatile(field, fallback) {
|
|
82
|
+
if (field !== undefined && field !== null && typeof field.get === "function") {
|
|
83
|
+
const val = field.get();
|
|
84
|
+
return val === undefined || val === null ? fallback : val;
|
|
85
|
+
}
|
|
86
|
+
return field === undefined || field === null ? fallback : field;
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
export function normalizeStringList(value) {
|
|
90
|
+
if (!Array.isArray(value)) return undefined;
|
|
91
|
+
const seen = new Set();
|
|
92
|
+
const out = [];
|
|
93
|
+
for (const item of value) {
|
|
94
|
+
if (typeof item !== "string") continue;
|
|
95
|
+
const trimmed = item.trim();
|
|
96
|
+
if (trimmed !== "" && !seen.has(trimmed)) {
|
|
97
|
+
seen.add(trimmed);
|
|
98
|
+
out.push(trimmed);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
return out;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
export const OVERRIDE_LIMITS = {
|
|
105
|
+
contextWindow: 10_000_000,
|
|
106
|
+
maxTokens: 2_000_000,
|
|
107
|
+
};
|
|
108
|
+
|
|
109
|
+
export function normalizePositiveInteger(value, max) {
|
|
110
|
+
if (typeof value === "string" && value.trim() !== "") {
|
|
111
|
+
if (!/^\d+$/.test(value.trim())) return undefined;
|
|
112
|
+
value = Number(value.trim());
|
|
113
|
+
}
|
|
114
|
+
return typeof value === "number" &&
|
|
115
|
+
Number.isInteger(value) &&
|
|
116
|
+
value > 0 &&
|
|
117
|
+
value <= max
|
|
118
|
+
? value
|
|
119
|
+
: undefined;
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function normalizeModelOverrides(value) {
|
|
123
|
+
const raw = readVolatile(value, undefined);
|
|
124
|
+
if (typeof raw !== "object" || raw === null || Array.isArray(raw)) return {};
|
|
125
|
+
const out = {};
|
|
126
|
+
for (const [id, entry] of Object.entries(raw)) {
|
|
127
|
+
if (typeof id !== "string" || id.trim() === "") continue;
|
|
128
|
+
if (typeof entry !== "object" || entry === null || Array.isArray(entry)) continue;
|
|
129
|
+
const normalized = {};
|
|
130
|
+
const contextWindow = normalizePositiveInteger(entry.contextWindow, OVERRIDE_LIMITS.contextWindow);
|
|
131
|
+
const maxTokens = normalizePositiveInteger(entry.maxTokens, OVERRIDE_LIMITS.maxTokens);
|
|
132
|
+
if (contextWindow !== undefined) normalized.contextWindow = contextWindow;
|
|
133
|
+
if (maxTokens !== undefined) normalized.maxTokens = maxTokens;
|
|
134
|
+
if (entry.image === true || entry.image === false) normalized.image = entry.image;
|
|
135
|
+
if (typeof entry.protocol === "string" && PROTOCOLS.includes(entry.protocol)) {
|
|
136
|
+
normalized.protocol = entry.protocol;
|
|
137
|
+
}
|
|
138
|
+
if (Array.isArray(entry.reasoningLevels)) {
|
|
139
|
+
const levels = [];
|
|
140
|
+
for (const level of entry.reasoningLevels) {
|
|
141
|
+
if (typeof level !== "string") continue;
|
|
142
|
+
const mapped = level.trim().toLowerCase();
|
|
143
|
+
if (REASONING_LEVELS.includes(mapped) && !levels.includes(mapped)) levels.push(mapped);
|
|
144
|
+
}
|
|
145
|
+
normalized.reasoningLevels = levels;
|
|
146
|
+
}
|
|
147
|
+
if (Object.keys(normalized).length > 0) out[id.trim()] = normalized;
|
|
148
|
+
}
|
|
149
|
+
return out;
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
export function resolveConfig(rawConfig = {}) {
|
|
153
|
+
const providerRaw = String(readVolatile(rawConfig?.provider, DEFAULT_PROVIDER)).trim();
|
|
154
|
+
const provider = providerRaw || DEFAULT_PROVIDER;
|
|
155
|
+
const displayNameRaw = String(readVolatile(rawConfig?.displayName, DEFAULT_DISPLAY_NAME)).trim();
|
|
156
|
+
const displayName = displayNameRaw || DEFAULT_DISPLAY_NAME;
|
|
157
|
+
const apiKeyEnvRaw = String(readVolatile(rawConfig?.apiKeyEnv, DEFAULT_API_KEY_ENV)).trim();
|
|
158
|
+
const apiKeyEnv = apiKeyEnvRaw || DEFAULT_API_KEY_ENV;
|
|
159
|
+
const baseURL = String(readVolatile(rawConfig?.baseURL, "")).trim();
|
|
160
|
+
const protocolRaw = String(readVolatile(rawConfig?.protocol, "openai-completions")).trim();
|
|
161
|
+
const protocol =
|
|
162
|
+
protocolRaw === "openai-responses" || protocolRaw === "anthropic-messages"
|
|
163
|
+
? protocolRaw
|
|
164
|
+
: "openai-completions";
|
|
165
|
+
const protocolMode =
|
|
166
|
+
String(readVolatile(rawConfig?.protocolMode, "auto")).trim() === "fixed" ? "fixed" : "auto";
|
|
167
|
+
const refreshRaw = Number(
|
|
168
|
+
readVolatile(rawConfig?.refreshIntervalSeconds, DEFAULT_REFRESH_INTERVAL_SECONDS)
|
|
169
|
+
);
|
|
170
|
+
const refreshIntervalSeconds =
|
|
171
|
+
Number.isFinite(refreshRaw) && refreshRaw >= 15 && refreshRaw <= 86400
|
|
172
|
+
? Math.floor(refreshRaw)
|
|
173
|
+
: DEFAULT_REFRESH_INTERVAL_SECONDS;
|
|
174
|
+
const timeoutRaw = Number(readVolatile(rawConfig?.probeTimeoutMs, DEFAULT_PROBE_TIMEOUT_MS));
|
|
175
|
+
const probeTimeoutMs =
|
|
176
|
+
Number.isFinite(timeoutRaw) && timeoutRaw >= 250 && timeoutRaw <= 60000
|
|
177
|
+
? Math.floor(timeoutRaw)
|
|
178
|
+
: DEFAULT_PROBE_TIMEOUT_MS;
|
|
179
|
+
const includePrefix = String(readVolatile(rawConfig?.includePrefix, "")).trim();
|
|
180
|
+
const excludePrefix = String(readVolatile(rawConfig?.excludePrefix, "")).trim();
|
|
181
|
+
const selectedModels = normalizeStringList(readVolatile(rawConfig?.selectedModels, undefined));
|
|
182
|
+
const modelOverrides = normalizeModelOverrides(rawConfig?.modelOverrides);
|
|
183
|
+
|
|
184
|
+
return {
|
|
185
|
+
id: normalizeAccountId(readVolatile(rawConfig?.id, DEFAULT_ACCOUNT_ID)) ?? DEFAULT_ACCOUNT_ID,
|
|
186
|
+
enabled: readVolatile(rawConfig?.enabled, true) !== false,
|
|
187
|
+
provider,
|
|
188
|
+
displayName,
|
|
189
|
+
baseURL,
|
|
190
|
+
apiKeyEnv,
|
|
191
|
+
protocol,
|
|
192
|
+
protocolMode,
|
|
193
|
+
refreshIntervalSeconds,
|
|
194
|
+
probeTimeoutMs,
|
|
195
|
+
includePrefix,
|
|
196
|
+
excludePrefix,
|
|
197
|
+
...(selectedModels === undefined ? {} : { selectedModels }),
|
|
198
|
+
modelOverrides,
|
|
199
|
+
};
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
export function normalizeAccountId(value) {
|
|
203
|
+
const trimmed = typeof value === "string" ? value.trim() : "";
|
|
204
|
+
return ACCOUNT_ID_PATTERN.test(trimmed) ? trimmed : undefined;
|
|
205
|
+
}
|
|
@@ -0,0 +1,435 @@
|
|
|
1
|
+
// Multi-account operations and serialized writes to the shared settings service.
|
|
2
|
+
|
|
3
|
+
import { diagnoseMedia, mediaAliasTarget, MediaError } from "../media/index.js";
|
|
4
|
+
import { DEFAULT_API_KEY_ENV, GLOBAL_FIELDS, toCredentialRef, resolveConfig } from "./config.js";
|
|
5
|
+
import { recommendModels } from "./models.js";
|
|
6
|
+
import { isChatModel, managedRouteKeys } from "./routes.js";
|
|
7
|
+
import { pickFields, normalizeState, accountConflicts, assertNoConflicts, newAccountDefaults, patchAccount } from "./accounts.js";
|
|
8
|
+
import { normalizeCpaRoot, discoverCpa } from "./discovery.js";
|
|
9
|
+
import { CpaRuntime } from "./runtime.js";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* Queue settings writes so concurrent account syncs never interleave their
|
|
13
|
+
* transactions on the shared `llm-pi-ai` namespace.
|
|
14
|
+
*/
|
|
15
|
+
export function serializeSettings(settings) {
|
|
16
|
+
let tail = Promise.resolve();
|
|
17
|
+
return {
|
|
18
|
+
mutate(ns, ops) {
|
|
19
|
+
const run = tail.then(() => settings.mutate(ns, ops));
|
|
20
|
+
tail = run.catch(() => {});
|
|
21
|
+
return run;
|
|
22
|
+
},
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
|
|
26
|
+
/**
|
|
27
|
+
* Owns one {@link CpaRuntime} per account and the state file they share.
|
|
28
|
+
*
|
|
29
|
+
* @param deps.readState - returns the normalized state (see {@link normalizeState}).
|
|
30
|
+
* @param deps.writeState - persists a normalized state.
|
|
31
|
+
* @param deps.resolveApiKey / deps.describeApiKey - credential lookups by ref.
|
|
32
|
+
* @param deps.setCredential / deps.unsetCredential - credential writes by ref.
|
|
33
|
+
* @param deps.onGlobalsChanged - called after the refresh interval changes.
|
|
34
|
+
*/
|
|
35
|
+
export function createCpaController(deps) {
|
|
36
|
+
const settings = serializeSettings(deps.settings);
|
|
37
|
+
const runtimes = new Map();
|
|
38
|
+
|
|
39
|
+
const accountConfig = (state, id) => {
|
|
40
|
+
const account = state.accounts.find((a) => a.id === id);
|
|
41
|
+
if (account === undefined) return undefined;
|
|
42
|
+
const conflicts = accountConflicts(state.accounts);
|
|
43
|
+
const conflictWith = conflicts.get(id);
|
|
44
|
+
return {
|
|
45
|
+
...resolveConfig({
|
|
46
|
+
...account,
|
|
47
|
+
refreshIntervalSeconds: state.refreshIntervalSeconds,
|
|
48
|
+
probeTimeoutMs: state.probeTimeoutMs,
|
|
49
|
+
}),
|
|
50
|
+
// Route keys of every other (non-conflicting) account: never written or
|
|
51
|
+
// removed here. A conflicting account owns no keys.
|
|
52
|
+
reservedKeys: state.accounts
|
|
53
|
+
.filter((a) => a.id !== id && !conflicts.has(a.id))
|
|
54
|
+
.flatMap((a) => managedRouteKeys(a.provider)),
|
|
55
|
+
...(conflictWith === undefined ? {} : { conflictWith }),
|
|
56
|
+
};
|
|
57
|
+
};
|
|
58
|
+
|
|
59
|
+
const ensureRuntime = (id) => {
|
|
60
|
+
const existing = runtimes.get(id);
|
|
61
|
+
if (existing !== undefined) return existing;
|
|
62
|
+
let last = accountConfig(deps.readState(), id) ?? resolveConfig({ id, enabled: false });
|
|
63
|
+
const runtime = new CpaRuntime({
|
|
64
|
+
settings,
|
|
65
|
+
config: () => {
|
|
66
|
+
const config = accountConfig(deps.readState(), id);
|
|
67
|
+
if (config !== undefined) last = config;
|
|
68
|
+
return last;
|
|
69
|
+
},
|
|
70
|
+
resolveApiKey: deps.resolveApiKey,
|
|
71
|
+
readExistingPiAiRoute: deps.readExistingPiAiRoute,
|
|
72
|
+
readDefaultModel: deps.readDefaultModel,
|
|
73
|
+
// User reclassifications (chat / image / video) from media-settings.json.
|
|
74
|
+
kindOverrides: () => deps.mediaKindOverrides?.(id) ?? {},
|
|
75
|
+
// Persist a first-run selection unless one was saved in the meantime.
|
|
76
|
+
seedSelection: (ids) => {
|
|
77
|
+
const state = deps.readState();
|
|
78
|
+
const account = state.accounts.find((a) => a.id === id);
|
|
79
|
+
if (account === undefined || account.selectedModels !== undefined) return;
|
|
80
|
+
deps.writeState(
|
|
81
|
+
normalizeState({
|
|
82
|
+
...state,
|
|
83
|
+
accounts: state.accounts.map((a) => (a.id === id ? { ...a, selectedModels: ids } : a)),
|
|
84
|
+
})
|
|
85
|
+
);
|
|
86
|
+
},
|
|
87
|
+
...(deps.setTimeout === undefined ? {} : { setTimeout: deps.setTimeout }),
|
|
88
|
+
...(deps.environmentBaseURL === undefined ? {} : { environmentBaseURL: deps.environmentBaseURL }),
|
|
89
|
+
...(deps.fetch === undefined ? {} : { fetch: deps.fetch }),
|
|
90
|
+
logger: deps.logger,
|
|
91
|
+
});
|
|
92
|
+
runtime.lastProvider = () => last.provider;
|
|
93
|
+
runtimes.set(id, runtime);
|
|
94
|
+
return runtime;
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** Create runtimes for new accounts and tear down removed ones. */
|
|
98
|
+
const reconcile = async (state) => {
|
|
99
|
+
for (const account of state.accounts) ensureRuntime(account.id);
|
|
100
|
+
const live = new Set(state.accounts.map((a) => a.id));
|
|
101
|
+
const removed = [...runtimes.entries()].filter(([id]) => !live.has(id));
|
|
102
|
+
for (const [id, runtime] of removed) {
|
|
103
|
+
runtimes.delete(id);
|
|
104
|
+
try {
|
|
105
|
+
await runtime.teardown(runtime.lastProvider());
|
|
106
|
+
} catch (error) {
|
|
107
|
+
deps.logger?.warn?.(
|
|
108
|
+
`dsh-cliproxyapi: could not remove routes of account ${id}: ${error instanceof Error ? error.message : String(error)}`
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
}
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const findAccount = (state, ref) => {
|
|
115
|
+
if (ref === undefined || ref === null || String(ref).trim() === "") {
|
|
116
|
+
if (state.accounts.length === 0) {
|
|
117
|
+
throw new Error("dsh-cliproxyapi: no CLIProxyAPI account is configured; add one first");
|
|
118
|
+
}
|
|
119
|
+
return state.accounts[0];
|
|
120
|
+
}
|
|
121
|
+
const wanted = String(ref).trim();
|
|
122
|
+
const hit =
|
|
123
|
+
state.accounts.find((a) => a.id === wanted) ??
|
|
124
|
+
state.accounts.find((a) => a.provider === wanted) ??
|
|
125
|
+
state.accounts.find((a) => a.displayName === wanted);
|
|
126
|
+
if (hit === undefined) {
|
|
127
|
+
throw new Error(
|
|
128
|
+
`dsh-cliproxyapi: unknown account "${wanted}" (known: ${state.accounts.map((a) => a.id).join(", ") || "none"})`
|
|
129
|
+
);
|
|
130
|
+
}
|
|
131
|
+
return hit;
|
|
132
|
+
};
|
|
133
|
+
|
|
134
|
+
const effectiveKeyEnv = (config) => {
|
|
135
|
+
const route = deps.readExistingPiAiRoute?.(config.provider);
|
|
136
|
+
return config.apiKeyEnv === DEFAULT_API_KEY_ENV && typeof route?.apiKeyEnv === "string"
|
|
137
|
+
? route.apiKeyEnv
|
|
138
|
+
: config.apiKeyEnv;
|
|
139
|
+
};
|
|
140
|
+
|
|
141
|
+
const describeAccount = async (state, account) => {
|
|
142
|
+
const config = accountConfig(state, account.id);
|
|
143
|
+
const runtime = ensureRuntime(account.id);
|
|
144
|
+
const st = runtime.status();
|
|
145
|
+
const existingRoute = deps.readExistingPiAiRoute?.(config.provider);
|
|
146
|
+
const keyEnv = effectiveKeyEnv(config);
|
|
147
|
+
const keyInfo = (await deps.describeApiKey?.(keyEnv)) ?? { configured: false };
|
|
148
|
+
return {
|
|
149
|
+
id: account.id,
|
|
150
|
+
config: {
|
|
151
|
+
...config,
|
|
152
|
+
selectedModels: config.selectedModels ?? [],
|
|
153
|
+
// false until a selection is saved or seeded by the first probe.
|
|
154
|
+
selectionSaved: config.selectedModels !== undefined,
|
|
155
|
+
modelOverrides: config.modelOverrides ?? {},
|
|
156
|
+
effectiveBaseURL: config.baseURL || st.endpoint || existingRoute?.baseURL || "",
|
|
157
|
+
effectiveApiKeyEnv: keyEnv,
|
|
158
|
+
},
|
|
159
|
+
credential: {
|
|
160
|
+
ref: keyEnv,
|
|
161
|
+
configured: keyInfo.configured === true,
|
|
162
|
+
writable: keyInfo.writable !== false,
|
|
163
|
+
source: keyInfo.source ?? null,
|
|
164
|
+
},
|
|
165
|
+
// One model per family from this account's catalog (the panel's reset button).
|
|
166
|
+
recommendedModels: recommendModels(runtime.chatModels()),
|
|
167
|
+
status: st,
|
|
168
|
+
};
|
|
169
|
+
};
|
|
170
|
+
|
|
171
|
+
const statusPayload = async (extra = {}) => {
|
|
172
|
+
const state = deps.readState();
|
|
173
|
+
const accounts = [];
|
|
174
|
+
for (const account of state.accounts) accounts.push(await describeAccount(state, account));
|
|
175
|
+
return {
|
|
176
|
+
ok: true,
|
|
177
|
+
global: {
|
|
178
|
+
refreshIntervalSeconds: state.refreshIntervalSeconds,
|
|
179
|
+
probeTimeoutMs: state.probeTimeoutMs,
|
|
180
|
+
},
|
|
181
|
+
accounts,
|
|
182
|
+
...extra,
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
const applyKeyPatch = async (account, patch) => {
|
|
187
|
+
const ref = toCredentialRef(account.apiKeyEnv);
|
|
188
|
+
if (typeof patch.apiKey === "string" && patch.apiKey.trim() !== "") {
|
|
189
|
+
if (deps.setCredential === undefined) {
|
|
190
|
+
throw new Error("Credentials service is not available on this host");
|
|
191
|
+
}
|
|
192
|
+
await deps.setCredential(ref, patch.apiKey.trim());
|
|
193
|
+
} else if (patch.clearApiKey === true) {
|
|
194
|
+
await deps.unsetCredential?.(ref);
|
|
195
|
+
}
|
|
196
|
+
};
|
|
197
|
+
|
|
198
|
+
const writeAccounts = (state, accounts, patch = {}) => {
|
|
199
|
+
assertNoConflicts(accounts);
|
|
200
|
+
for (const account of accounts) toCredentialRef(account.apiKeyEnv);
|
|
201
|
+
const next = normalizeState({ ...state, ...pickFields(patch, GLOBAL_FIELDS), accounts });
|
|
202
|
+
deps.writeState(next);
|
|
203
|
+
if (next.refreshIntervalSeconds !== state.refreshIntervalSeconds) deps.onGlobalsChanged?.(next);
|
|
204
|
+
return next;
|
|
205
|
+
};
|
|
206
|
+
|
|
207
|
+
const refreshAccount = (id, options) => ensureRuntime(id).refresh(options);
|
|
208
|
+
|
|
209
|
+
return {
|
|
210
|
+
statusPayload,
|
|
211
|
+
findAccount: (ref) => findAccount(deps.readState(), ref),
|
|
212
|
+
|
|
213
|
+
/** Refresh every account (no catalog probe for disabled ones). */
|
|
214
|
+
async refreshAll(options = {}) {
|
|
215
|
+
const state = deps.readState();
|
|
216
|
+
await reconcile(state);
|
|
217
|
+
await Promise.all(state.accounts.map((a) => refreshAccount(a.id, options)));
|
|
218
|
+
},
|
|
219
|
+
|
|
220
|
+
/** Refresh one account, or all of them when `ref` is omitted. */
|
|
221
|
+
async refresh(ref, options = { probe: true }) {
|
|
222
|
+
const state = deps.readState();
|
|
223
|
+
await reconcile(state);
|
|
224
|
+
if (ref === undefined || ref === null || String(ref).trim() === "") {
|
|
225
|
+
await Promise.all(state.accounts.map((a) => refreshAccount(a.id, options)));
|
|
226
|
+
return statusPayload();
|
|
227
|
+
}
|
|
228
|
+
const account = findAccount(state, ref);
|
|
229
|
+
await refreshAccount(account.id, options);
|
|
230
|
+
return statusPayload({ account: account.id });
|
|
231
|
+
},
|
|
232
|
+
|
|
233
|
+
/** Update one account's settings (and globals in the same patch). */
|
|
234
|
+
async updateAccount(ref, patch = {}) {
|
|
235
|
+
const state = deps.readState();
|
|
236
|
+
const account = findAccount(state, ref);
|
|
237
|
+
const updated = patchAccount(account, patch);
|
|
238
|
+
const accounts = state.accounts.map((a) => (a.id === account.id ? updated : a));
|
|
239
|
+
writeAccounts(state, accounts, patch);
|
|
240
|
+
await applyKeyPatch(updated, patch);
|
|
241
|
+
await refreshAccount(account.id, { probe: true });
|
|
242
|
+
return statusPayload({ account: account.id });
|
|
243
|
+
},
|
|
244
|
+
|
|
245
|
+
/** Update only the global settings. */
|
|
246
|
+
async updateGlobals(patch = {}) {
|
|
247
|
+
const state = deps.readState();
|
|
248
|
+
writeAccounts(state, state.accounts, patch);
|
|
249
|
+
return statusPayload();
|
|
250
|
+
},
|
|
251
|
+
|
|
252
|
+
/** Add an account; it starts disabled unless `patch.enabled` is true. */
|
|
253
|
+
async addAccount(patch = {}) {
|
|
254
|
+
const state = deps.readState();
|
|
255
|
+
const defaults = newAccountDefaults(state.accounts);
|
|
256
|
+
const created = patchAccount(defaults, {
|
|
257
|
+
...patch,
|
|
258
|
+
enabled: patch.enabled === true,
|
|
259
|
+
});
|
|
260
|
+
const accounts = [...state.accounts, created];
|
|
261
|
+
const next = writeAccounts(state, accounts, patch);
|
|
262
|
+
await applyKeyPatch(created, patch);
|
|
263
|
+
await reconcile(next);
|
|
264
|
+
await refreshAccount(created.id, { probe: true });
|
|
265
|
+
return statusPayload({ account: created.id, createdId: created.id });
|
|
266
|
+
},
|
|
267
|
+
|
|
268
|
+
/** Remove an account and every route it synchronized. */
|
|
269
|
+
async removeAccount(ref) {
|
|
270
|
+
if (ref === undefined || ref === null || String(ref).trim() === "") {
|
|
271
|
+
throw new Error("dsh-cliproxyapi: removing an account needs its id");
|
|
272
|
+
}
|
|
273
|
+
const state = deps.readState();
|
|
274
|
+
const account = findAccount(state, ref);
|
|
275
|
+
// Capture the account's provider (and reserved keys) before it leaves the state.
|
|
276
|
+
ensureRuntime(account.id).options.config();
|
|
277
|
+
const next = writeAccounts(
|
|
278
|
+
state,
|
|
279
|
+
state.accounts.filter((a) => a.id !== account.id)
|
|
280
|
+
);
|
|
281
|
+
await reconcile(next);
|
|
282
|
+
return statusPayload({ removedId: account.id });
|
|
283
|
+
},
|
|
284
|
+
|
|
285
|
+
/**
|
|
286
|
+
* Probe a CPA address with unsaved form values, without saving or writing
|
|
287
|
+
* routes. A blank `apiKey` uses the account's stored key; a blank
|
|
288
|
+
* `baseURL` follows the usual fallbacks. Never returns the key.
|
|
289
|
+
*/
|
|
290
|
+
async testConnection(ref, input = {}) {
|
|
291
|
+
const state = deps.readState();
|
|
292
|
+
const account = ref === undefined || ref === null || String(ref).trim() === "" ? undefined : findAccount(state, ref);
|
|
293
|
+
const config = account === undefined ? undefined : accountConfig(state, account.id);
|
|
294
|
+
const draftKey = typeof input.apiKey === "string" ? input.apiKey.trim() : "";
|
|
295
|
+
const apiKey = draftKey !== "" ? draftKey : config === undefined ? undefined : await deps.resolveApiKey(effectiveKeyEnv(config));
|
|
296
|
+
const baseURL = typeof input.baseURL === "string" ? input.baseURL.trim() : "";
|
|
297
|
+
try {
|
|
298
|
+
const result = await discoverCpa({
|
|
299
|
+
baseURL,
|
|
300
|
+
autoDiscover: baseURL === "",
|
|
301
|
+
fallbackBaseURL: config === undefined ? undefined : deps.readExistingPiAiRoute?.(config.provider)?.baseURL,
|
|
302
|
+
environmentBaseURL: deps.environmentBaseURL?.(),
|
|
303
|
+
apiKey,
|
|
304
|
+
timeoutMs: state.probeTimeoutMs,
|
|
305
|
+
...(deps.fetch === undefined ? {} : { fetch: deps.fetch }),
|
|
306
|
+
});
|
|
307
|
+
return { ok: true, test: { ok: true, endpoint: result.rootURL, modelCount: result.models.length } };
|
|
308
|
+
} catch (error) {
|
|
309
|
+
return { ok: true, test: { ok: false, error: error instanceof Error ? error.message : String(error) } };
|
|
310
|
+
}
|
|
311
|
+
},
|
|
312
|
+
|
|
313
|
+
/** Accounts whose credential reference is `ref`. */
|
|
314
|
+
accountsUsingKey(ref) {
|
|
315
|
+
const state = deps.readState();
|
|
316
|
+
return state.accounts
|
|
317
|
+
.map((a) => accountConfig(state, a.id))
|
|
318
|
+
.filter((config) => effectiveKeyEnv(config) === ref)
|
|
319
|
+
.map((config) => config.id);
|
|
320
|
+
},
|
|
321
|
+
|
|
322
|
+
refreshAccount,
|
|
323
|
+
|
|
324
|
+
/**
|
|
325
|
+
* Account facts the quota engine needs: the CPA address it talks to and
|
|
326
|
+
* the DSH route keys whose models belong to this account. A conflicting
|
|
327
|
+
* account owns no routes, so none of its models map to quota.
|
|
328
|
+
*/
|
|
329
|
+
quotaAccounts() {
|
|
330
|
+
const state = deps.readState();
|
|
331
|
+
const conflicts = accountConflicts(state.accounts);
|
|
332
|
+
return state.accounts.map((account) => {
|
|
333
|
+
const config = accountConfig(state, account.id);
|
|
334
|
+
const runtime = runtimes.get(account.id);
|
|
335
|
+
const st = runtime?.currentStatus ?? {};
|
|
336
|
+
const existingRoute = deps.readExistingPiAiRoute?.(config.provider);
|
|
337
|
+
const owners = new Map((runtime?.allDiscoveredModels ?? []).map((m) => [m.id, m.ownedBy]));
|
|
338
|
+
return {
|
|
339
|
+
id: account.id,
|
|
340
|
+
displayName: config.displayName,
|
|
341
|
+
provider: config.provider,
|
|
342
|
+
enabled: config.enabled === true,
|
|
343
|
+
baseURL: config.baseURL || "",
|
|
344
|
+
endpoint: st.endpoint || existingRoute?.baseURL || "",
|
|
345
|
+
routes: conflicts.has(account.id) ? [] : managedRouteKeys(config.provider),
|
|
346
|
+
// Models this account currently puts in the DSH picker.
|
|
347
|
+
pickerModels: (runtime?.syncedModels ?? []).map((m) => ({
|
|
348
|
+
id: m.id,
|
|
349
|
+
route: m.route,
|
|
350
|
+
...(typeof owners.get(m.id) === "string" ? { ownedBy: owners.get(m.id) } : {}),
|
|
351
|
+
})),
|
|
352
|
+
};
|
|
353
|
+
});
|
|
354
|
+
},
|
|
355
|
+
|
|
356
|
+
/**
|
|
357
|
+
* Media models per account, from the last catalog each runtime saw, with
|
|
358
|
+
* their effective and detected kind. `chatModelIds` lets the panel mark a
|
|
359
|
+
* chat model as media by hand. No network access.
|
|
360
|
+
*/
|
|
361
|
+
mediaAccounts() {
|
|
362
|
+
const state = deps.readState();
|
|
363
|
+
return state.accounts.map((account) => {
|
|
364
|
+
const config = accountConfig(state, account.id);
|
|
365
|
+
const runtime = ensureRuntime(account.id);
|
|
366
|
+
const st = runtime.currentStatus ?? {};
|
|
367
|
+
const kinded = runtime.withKinds();
|
|
368
|
+
return {
|
|
369
|
+
id: account.id,
|
|
370
|
+
displayName: config.displayName,
|
|
371
|
+
enabled: config.enabled === true,
|
|
372
|
+
state: config.enabled === true ? st.state ?? "idle" : "disabled",
|
|
373
|
+
endpoint: st.endpoint || "",
|
|
374
|
+
discovered: kinded.length,
|
|
375
|
+
listingOk: runtime.listingOk !== false,
|
|
376
|
+
catalogIncomplete: runtime.listingOk === false,
|
|
377
|
+
models: kinded
|
|
378
|
+
.filter((m) => !isChatModel(m))
|
|
379
|
+
.map((m) => ({
|
|
380
|
+
id: m.id,
|
|
381
|
+
...(m.name === undefined ? {} : { name: m.name }),
|
|
382
|
+
kind: m.kind,
|
|
383
|
+
detectedKind: m.detectedKind ?? "chat",
|
|
384
|
+
...(mediaAliasTarget(m.id) === undefined ? {} : { aliasOf: mediaAliasTarget(m.id) }),
|
|
385
|
+
})),
|
|
386
|
+
chatModelIds: kinded.filter(isChatModel).map((m) => m.id),
|
|
387
|
+
};
|
|
388
|
+
});
|
|
389
|
+
},
|
|
390
|
+
|
|
391
|
+
/**
|
|
392
|
+
* Read-only media diagnostic for one account (see diagnoseMedia in
|
|
393
|
+
* lib/media/diagnose.js). Uses the account's key on the host; never returns it.
|
|
394
|
+
*/
|
|
395
|
+
/**
|
|
396
|
+
* The CPA root and key a media request of this account uses: the address
|
|
397
|
+
* the last sync connected to, else the configured or route address.
|
|
398
|
+
* Host-only; the key is never returned to a page.
|
|
399
|
+
* @throws MediaError `no-endpoint`.
|
|
400
|
+
*/
|
|
401
|
+
async mediaEndpoint(accountId) {
|
|
402
|
+
const state = deps.readState();
|
|
403
|
+
const account = state.accounts.find((a) => a.id === accountId);
|
|
404
|
+
if (account === undefined) throw new MediaError("invalid-account");
|
|
405
|
+
const config = accountConfig(state, account.id);
|
|
406
|
+
const runtime = ensureRuntime(account.id);
|
|
407
|
+
const known = runtime.currentStatus?.endpoint || config.baseURL || deps.readExistingPiAiRoute?.(config.provider)?.baseURL || "";
|
|
408
|
+
let rootURL;
|
|
409
|
+
try {
|
|
410
|
+
rootURL = normalizeCpaRoot(known);
|
|
411
|
+
} catch {
|
|
412
|
+
throw new MediaError("no-endpoint");
|
|
413
|
+
}
|
|
414
|
+
return { rootURL, apiKey: await deps.resolveApiKey(effectiveKeyEnv(config)), probeTimeoutMs: state.probeTimeoutMs };
|
|
415
|
+
},
|
|
416
|
+
|
|
417
|
+
async diagnoseMedia(ref) {
|
|
418
|
+
const state = deps.readState();
|
|
419
|
+
const account = findAccount(state, ref);
|
|
420
|
+
const { rootURL, apiKey } = await this.mediaEndpoint(account.id);
|
|
421
|
+
const diagnostic = await diagnoseMedia({
|
|
422
|
+
rootURL,
|
|
423
|
+
apiKey,
|
|
424
|
+
timeoutMs: Math.max(state.probeTimeoutMs, 8000),
|
|
425
|
+
...(deps.fetch === undefined ? {} : { fetch: deps.fetch }),
|
|
426
|
+
});
|
|
427
|
+
return { accountId: account.id, keyConfigured: apiKey !== undefined, ...diagnostic };
|
|
428
|
+
},
|
|
429
|
+
|
|
430
|
+
dispose() {
|
|
431
|
+
for (const runtime of runtimes.values()) runtime.dispose();
|
|
432
|
+
runtimes.clear();
|
|
433
|
+
},
|
|
434
|
+
};
|
|
435
|
+
}
|