dsh-cliproxyapi-pro 1.8.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.
Files changed (81) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.en.md +38 -409
  3. package/README.md +38 -409
  4. package/lib/client.js +131 -28
  5. package/lib/host/accounts.js +176 -0
  6. package/lib/host/apply/agent-tool.js +406 -0
  7. package/lib/host/apply/commands.js +122 -0
  8. package/lib/host/apply/controller.js +105 -0
  9. package/lib/host/apply/http-routes.js +273 -0
  10. package/lib/host/apply/image-jobs.js +171 -0
  11. package/lib/host/apply/index.js +41 -0
  12. package/lib/host/apply/interpret.js +72 -0
  13. package/lib/host/apply/lifecycle.js +34 -0
  14. package/lib/host/apply/media-failures.js +68 -0
  15. package/lib/host/apply/media-service.js +202 -0
  16. package/lib/host/apply/quota-service.js +42 -0
  17. package/lib/host/apply/references.js +43 -0
  18. package/lib/host/apply/session-status.js +104 -0
  19. package/lib/host/apply/state.js +78 -0
  20. package/lib/host/apply/updates.js +55 -0
  21. package/lib/host/apply/video-command.js +152 -0
  22. package/lib/host/apply/video-edit.js +253 -0
  23. package/lib/host/apply/video-jobs.js +206 -0
  24. package/lib/host/apply-utils.js +39 -0
  25. package/lib/host/config.js +205 -0
  26. package/lib/host/controller.js +435 -0
  27. package/lib/host/discovery.js +295 -0
  28. package/lib/host/http-gate.js +144 -0
  29. package/lib/host/models.js +102 -0
  30. package/lib/host/mount-guard.js +56 -0
  31. package/lib/host/routes.js +165 -0
  32. package/lib/host/runtime.js +445 -0
  33. package/lib/host/state-store.js +39 -0
  34. package/lib/host/status-text.js +93 -0
  35. package/lib/index.js +17 -4330
  36. package/lib/media/agent-tool.js +255 -0
  37. package/lib/media/choice.js +83 -0
  38. package/lib/media/classify.js +65 -0
  39. package/lib/media/codec/fit.js +76 -0
  40. package/lib/media/codec/jpeg.js +158 -0
  41. package/lib/media/codec/png.js +102 -0
  42. package/lib/media/commands/parsing.js +269 -0
  43. package/lib/media/constants.js +46 -0
  44. package/lib/media/diagnose.js +134 -0
  45. package/lib/media/images.js +165 -0
  46. package/lib/media/index.js +29 -0
  47. package/lib/media/interpret.js +126 -0
  48. package/lib/media/job-store.js +99 -0
  49. package/lib/media/mp4.js +44 -0
  50. package/lib/media/output-files.js +59 -0
  51. package/lib/media/session-store.js +293 -0
  52. package/lib/media/settings.js +255 -0
  53. package/lib/media/util.js +45 -0
  54. package/lib/media/video.js +326 -0
  55. package/lib/quota/auth-state.js +33 -0
  56. package/lib/quota/constants.js +86 -0
  57. package/lib/quota/controller.js +467 -0
  58. package/lib/quota/helpers.js +325 -0
  59. package/lib/quota/index.js +19 -0
  60. package/lib/quota/management.js +216 -0
  61. package/lib/quota/matching.js +143 -0
  62. package/lib/quota/parsers.js +352 -0
  63. package/lib/quota/probes/billing.js +80 -0
  64. package/lib/quota/probes/google.js +120 -0
  65. package/lib/quota/probes/oauth.js +27 -0
  66. package/lib/quota/probes/plugin.js +18 -0
  67. package/lib/updater/constants.js +23 -0
  68. package/lib/updater/errors.js +8 -0
  69. package/lib/updater/index.js +11 -0
  70. package/lib/updater/registry.js +83 -0
  71. package/lib/updater/settings.js +45 -0
  72. package/lib/updater/store.js +23 -0
  73. package/lib/updater/updater.js +148 -0
  74. package/lib/updater/verify.js +110 -0
  75. package/lib/updater/version.js +31 -0
  76. package/locale/en.json +1 -1
  77. package/locale/zh.json +1 -1
  78. package/package.json +6 -9
  79. package/lib/media.js +0 -2528
  80. package/lib/quota.js +0 -1646
  81. package/lib/updater.js +0 -443
@@ -0,0 +1,293 @@
1
+ // Per-session picks, run records, recent outputs and agent budget policy.
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { randomBytes } from "node:crypto";
4
+ import { dirname, isAbsolute } from "node:path";
5
+ import { MAX_RUNS, VIDEO_MODES, IMAGE_ASPECTS, VIDEO_SECONDS, VIDEO_RESOLUTIONS, CONFIRM_MODES } from "./constants.js";
6
+ import { validBudget, validSelectionRef } from "./settings.js";
7
+ import { MediaError, plain, intIn, clip } from "./util.js";
8
+
9
+ // #region Session store (media-sessions.json)
10
+
11
+ export const MEDIA_SESSIONS_VERSION = 1;
12
+ const MAX_SESSIONS = 500;
13
+ // Enough to keep the images of a session's recent commands visible in chat.
14
+ export const MAX_RECENT = 48;
15
+ const SESSION_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/;
16
+ const COMMAND_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,119}$/;
17
+
18
+ export function validSessionId(value) {
19
+ return typeof value === "string" && SESSION_ID_PATTERN.test(value) ? value : undefined;
20
+ }
21
+
22
+ /** A DSH command run id (`cmd-<token>-<seq>`), or undefined. */
23
+ export function validCommandId(value) {
24
+ return typeof value === "string" && COMMAND_ID_PATTERN.test(value) ? value : undefined;
25
+ }
26
+
27
+ function normalizeRecent(value) {
28
+ if (!Array.isArray(value)) return [];
29
+ const out = [];
30
+ for (const item of value) {
31
+ const entry = plain(item);
32
+ if (entry === undefined) continue;
33
+ const { id, kind, file, model, createdAt, commandId } = entry;
34
+ if (typeof id !== "string" || !/^[a-f0-9]{8,32}$/.test(id)) continue;
35
+ if (!["image", "video"].includes(kind) || typeof file !== "string" || !isAbsolute(file)) continue;
36
+ out.push({
37
+ id,
38
+ kind,
39
+ file,
40
+ model: typeof model === "string" ? model.slice(0, 300) : "",
41
+ createdAt: typeof createdAt === "string" ? createdAt.slice(0, 40) : "",
42
+ ...(validCommandId(commandId) === undefined ? {} : { commandId }),
43
+ });
44
+ if (out.length >= MAX_RECENT) break;
45
+ }
46
+ return out;
47
+ }
48
+
49
+
50
+ const RUN_STATUSES = ["running", "done", "error"];
51
+
52
+ /**
53
+ * One generation run as its chat row shows it: what was asked, by which model,
54
+ * and how it ended. Never paths, keys or upstream bodies; `folder` is a display
55
+ * label (relative to the working directory, or the folder's own name).
56
+ */
57
+ export function normalizeRun(value) {
58
+ const run = plain(value);
59
+ if (run === undefined || validCommandId(run.commandId) === undefined) return undefined;
60
+ if (!["image", "video"].includes(run.kind) || !RUN_STATUSES.includes(run.status)) return undefined;
61
+ const count = Number.isInteger(run.count) && run.count >= 1 && run.count <= 4 ? run.count : 1;
62
+ const references = Number.isInteger(run.references) && run.references >= 0 && run.references <= 14 ? run.references : 0;
63
+ const files = Number.isInteger(run.files) && run.files >= 0 && run.files <= 4 ? run.files : 0;
64
+ return {
65
+ commandId: run.commandId,
66
+ kind: run.kind,
67
+ status: run.status,
68
+ model: clip(run.model, 300),
69
+ modelName: clip(run.modelName, 300),
70
+ accountName: clip(run.accountName, 120),
71
+ prompt: clip(run.prompt, 4000),
72
+ ...(typeof run.aspect === "string" && IMAGE_ASPECTS.includes(run.aspect) ? { aspect: run.aspect } : {}),
73
+ ...(run.kind === "video" && intIn(run.seconds, VIDEO_SECONDS) !== undefined ? { seconds: run.seconds } : {}),
74
+ ...(run.kind === "video" && VIDEO_RESOLUTIONS.includes(run.resolution) ? { resolution: run.resolution } : {}),
75
+ ...(run.kind === "video" && VIDEO_MODES.includes(run.mode) ? { mode: run.mode } : {}),
76
+ ...(run.kind === "video" && validCommandId(run.sourceCommandId) !== undefined ? { sourceCommandId: run.sourceCommandId } : {}),
77
+ // Prompt words the edit / extension route cannot use, taken out of the prompt.
78
+ ...(run.kind === "video" && Array.isArray(run.ignored) && run.ignored.length > 0
79
+ ? { ignored: run.ignored.filter((w) => typeof w === "string" && w !== "").slice(0, 4).map((w) => w.slice(0, 20)) }
80
+ : {}),
81
+ // Parameters the session's chat model read from the prompt (or that it was asked and failed).
82
+ ...(plain(run.interpreted) !== undefined && typeof run.interpreted.by === "string" && run.interpreted.by !== ""
83
+ ? {
84
+ interpreted: {
85
+ by: run.interpreted.by.slice(0, 160),
86
+ items: Array.isArray(run.interpreted.items) ? run.interpreted.items.filter((w) => typeof w === "string" && w !== "").slice(0, 8).map((w) => w.slice(0, 30)) : [],
87
+ ...(run.interpreted.failed === true ? { failed: true } : {}),
88
+ ...(run.interpreted.prompt === true ? { prompt: true } : {}),
89
+ },
90
+ }
91
+ : {}),
92
+ // How an edit / extension got its source: xAI's own result link, an inline upload, or a public URL.
93
+ ...(run.kind === "video" && ["link", "upload", "url"].includes(run.sourceKind) ? { sourceKind: run.sourceKind } : {}),
94
+ // A local file's name or a URL's host, never a path or a full address.
95
+ ...(run.kind === "video" && typeof run.sourceName === "string" && run.sourceName.trim() !== "" ? { sourceName: run.sourceName.trim().slice(0, 200) } : {}),
96
+ ...(run.kind === "video" && typeof run.videoId === "string" && /^[A-Za-z0-9][A-Za-z0-9._:-]{0,199}$/.test(run.videoId) ? { videoId: run.videoId } : {}),
97
+ count,
98
+ references,
99
+ files,
100
+ startedAt: clip(run.startedAt, 40),
101
+ ...(typeof run.finishedAt === "string" ? { finishedAt: run.finishedAt.slice(0, 40) } : {}),
102
+ ...(typeof run.folder === "string" && run.folder !== "" ? { folder: run.folder.slice(0, 300) } : {}),
103
+ ...(typeof run.revisedPrompt === "string" && run.revisedPrompt !== "" ? { revisedPrompt: run.revisedPrompt.slice(0, 4000) } : {}),
104
+ ...(typeof run.errorCode === "string" && /^[a-z][a-z-]{0,59}$/.test(run.errorCode) ? { errorCode: run.errorCode } : {}),
105
+ ...(typeof run.error === "string" && run.error !== "" ? { error: run.error.slice(0, 500) } : {}),
106
+ };
107
+ }
108
+
109
+ function normalizeRuns(value) {
110
+ if (!Array.isArray(value)) return [];
111
+ const out = [];
112
+ const seen = new Set();
113
+ for (const item of value) {
114
+ const run = normalizeRun(item);
115
+ if (run === undefined || seen.has(run.commandId)) continue;
116
+ seen.add(run.commandId);
117
+ out.push(run);
118
+ if (out.length >= MAX_RUNS) break;
119
+ }
120
+ return out;
121
+ }
122
+
123
+ function normalizeSessionEntry(value) {
124
+ const raw = plain(value) ?? {};
125
+ const out = {};
126
+ for (const kind of ["image", "video"]) {
127
+ const ref = validSelectionRef(raw[kind]);
128
+ if (ref !== undefined) out[kind] = ref;
129
+ }
130
+ // Agent-tool overrides for this session (absent = follow the global setting).
131
+ if (CONFIRM_MODES.includes(raw.imageConfirm)) out.imageConfirm = raw.imageConfirm;
132
+ if (CONFIRM_MODES.includes(raw.videoConfirm)) out.videoConfirm = raw.videoConfirm;
133
+ const budget = validBudget(raw.videoBudget);
134
+ if (budget !== undefined) out.videoBudget = budget;
135
+ // Video seconds the agent submitted, against the limit named by `budgetKey`.
136
+ if (Number.isInteger(raw.usedSeconds) && raw.usedSeconds > 0 && raw.usedSeconds <= 1_000_000) out.usedSeconds = raw.usedSeconds;
137
+ if (typeof raw.budgetKey === "string" && /^(unlimited|limited:\d{1,4})$/.test(raw.budgetKey)) out.budgetKey = raw.budgetKey;
138
+ if (CONFIRM_MODES.includes(raw.lastConfirm)) out.lastConfirm = raw.lastConfirm;
139
+ out.recent = normalizeRecent(raw.recent);
140
+ out.runs = normalizeRuns(raw.runs);
141
+ out.updatedAt = typeof raw.updatedAt === "string" ? raw.updatedAt.slice(0, 40) : "";
142
+ return out;
143
+ }
144
+
145
+ /** The identity of a seconds limit: a different limit starts the count again. */
146
+ export function budgetKey(budget) {
147
+ return budget?.mode === "limited" ? `limited:${budget.seconds}` : "unlimited";
148
+ }
149
+
150
+ /**
151
+ * The agent tool's effective rules for one (root) session: confirmation per
152
+ * kind and the video seconds limit, each from the session's override or the
153
+ * global setting, and the seconds already used under that limit. The count
154
+ * starts again when the limit changed or the video confirmation went from
155
+ * `ask` to `auto` since the last charge (design §8).
156
+ */
157
+ export function agentPolicy(settings, entry = {}) {
158
+ const imageConfirm = entry.imageConfirm ?? settings.imageConfirm;
159
+ const videoConfirm = entry.videoConfirm ?? settings.videoConfirm;
160
+ const budget = entry.videoBudget ?? settings.videoBudget;
161
+ const key = budgetKey(budget);
162
+ const stale = (entry.budgetKey !== undefined && entry.budgetKey !== key) || (entry.lastConfirm === "ask" && videoConfirm === "auto");
163
+ const used = stale ? 0 : entry.usedSeconds ?? 0;
164
+ return {
165
+ imageConfirm,
166
+ videoConfirm,
167
+ budget,
168
+ key,
169
+ used,
170
+ limit: budget.mode === "limited" ? budget.seconds : undefined,
171
+ sources: {
172
+ imageConfirm: entry.imageConfirm === undefined ? "global" : "session",
173
+ videoConfirm: entry.videoConfirm === undefined ? "global" : "session",
174
+ videoBudget: entry.videoBudget === undefined ? "global" : "session",
175
+ },
176
+ };
177
+ }
178
+
179
+ /**
180
+ * Apply a session's agent-tool overrides from the composer button:
181
+ * `imageConfirm` / `videoConfirm` `ask` | `auto` | `inherit`, `videoBudget`
182
+ * `{ mode, seconds? }` | `inherit`. The seconds count starts again when the
183
+ * limit changes or video confirmation turns from `ask` to `auto`. Mutates `entry`.
184
+ * @throws MediaError `invalid-confirm-mode` / `invalid-video-budget` / `invalid-request`.
185
+ */
186
+ export function applySessionPolicy(entry, input, settings) {
187
+ const before = agentPolicy(settings, entry);
188
+ let changed = false;
189
+ for (const field of ["imageConfirm", "videoConfirm"]) {
190
+ if (!(field in input)) continue;
191
+ if (input[field] === "inherit") delete entry[field];
192
+ else if (CONFIRM_MODES.includes(input[field])) entry[field] = input[field];
193
+ else throw new MediaError("invalid-confirm-mode");
194
+ changed = true;
195
+ }
196
+ if ("videoBudget" in input) {
197
+ if (input.videoBudget === "inherit") delete entry.videoBudget;
198
+ else {
199
+ const budget = validBudget(input.videoBudget);
200
+ if (budget === undefined) throw new MediaError("invalid-video-budget");
201
+ entry.videoBudget = budget;
202
+ }
203
+ changed = true;
204
+ }
205
+ if (!changed) throw new MediaError("invalid-request");
206
+ const after = agentPolicy(settings, entry);
207
+ if (after.key !== before.key || (before.videoConfirm === "ask" && after.videoConfirm === "auto")) {
208
+ delete entry.usedSeconds;
209
+ delete entry.budgetKey;
210
+ delete entry.lastConfirm;
211
+ }
212
+ }
213
+
214
+ /**
215
+ * Charge (`seconds` > 0) or refund (< 0) agent video seconds on a session
216
+ * entry, under the policy's current limit. Mutates `entry`.
217
+ */
218
+ export function chargeSeconds(entry, policy, seconds) {
219
+ entry.usedSeconds = Math.max(0, policy.used + seconds);
220
+ entry.budgetKey = policy.key;
221
+ entry.lastConfirm = policy.videoConfirm;
222
+ if (entry.usedSeconds === 0) delete entry.usedSeconds;
223
+ }
224
+
225
+ /** Tolerant normalization; keeps the {@link MAX_SESSIONS} most recently updated sessions. */
226
+ export function normalizeMediaSessions(raw) {
227
+ const sessions = Object.entries(plain(plain(raw)?.sessions) ?? {})
228
+ .filter(([id]) => validSessionId(id) !== undefined)
229
+ .map(([id, entry]) => [id, normalizeSessionEntry(entry)])
230
+ .sort((a, b) => String(b[1].updatedAt).localeCompare(String(a[1].updatedAt)))
231
+ .slice(0, MAX_SESSIONS);
232
+ return { version: MEDIA_SESSIONS_VERSION, sessions: Object.fromEntries(sessions) };
233
+ }
234
+
235
+ /**
236
+ * Per-session generation state (model picks, recent outputs) in its own file,
237
+ * re-read on every access. Writes are atomic; a damaged file loads as empty
238
+ * and is kept as `*.corrupt-*.json` by the next write.
239
+ */
240
+ export function createMediaSessionStore(filePath, { now = () => new Date() } = {}) {
241
+ const read = () => {
242
+ if (!existsSync(filePath)) return { data: normalizeMediaSessions({}) };
243
+ try {
244
+ const raw = JSON.parse(readFileSync(filePath, "utf8"));
245
+ if (plain(raw) === undefined) return { data: normalizeMediaSessions({}), damaged: true };
246
+ return { data: normalizeMediaSessions(raw) };
247
+ } catch {
248
+ return { data: normalizeMediaSessions({}), damaged: true };
249
+ }
250
+ };
251
+ return {
252
+ get(sessionId) {
253
+ const id = validSessionId(sessionId);
254
+ return id === undefined ? normalizeSessionEntry({}) : read().data.sessions[id] ?? normalizeSessionEntry({});
255
+ },
256
+ /** Apply `mutate(entry)` to one session's entry and persist it. */
257
+ update(sessionId, mutate) {
258
+ const id = validSessionId(sessionId);
259
+ if (id === undefined) throw new MediaError("invalid-session");
260
+ const { data, damaged } = read();
261
+ const entry = normalizeSessionEntry(data.sessions[id]);
262
+ mutate(entry);
263
+ entry.updatedAt = now().toISOString();
264
+ data.sessions[id] = normalizeSessionEntry(entry);
265
+ const next = normalizeMediaSessions(data);
266
+ mkdirSync(dirname(filePath), { recursive: true });
267
+ if (damaged && existsSync(filePath)) {
268
+ renameSync(filePath, filePath.replace(/\.json$/, `.corrupt-${Date.now().toString(36)}.json`));
269
+ }
270
+ const tmp = `${filePath}.${Date.now().toString(36)}.tmp`;
271
+ writeFileSync(tmp, `${JSON.stringify(next, null, 2)}\n`, "utf8");
272
+ renameSync(tmp, filePath);
273
+ return next.sessions[id];
274
+ },
275
+ };
276
+ }
277
+
278
+ /**
279
+ * A recent-output record for a file this plugin just wrote; `commandId` ties
280
+ * it to the slash-command run that produced it (its chat row shows it).
281
+ */
282
+ export function recentEntry(kind, file, model, createdAt = new Date(), commandId) {
283
+ return {
284
+ id: randomBytes(8).toString("hex"),
285
+ kind,
286
+ file,
287
+ model,
288
+ createdAt: createdAt.toISOString(),
289
+ ...(validCommandId(commandId) === undefined ? {} : { commandId }),
290
+ };
291
+ }
292
+
293
+ // #endregion
@@ -0,0 +1,255 @@
1
+ // Independent media preferences, normalization and validated patches.
2
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
3
+ import { dirname } from "node:path";
4
+ import { MEDIA_SETTINGS_VERSION, VIDEO_SECONDS, VIDEO_RESOLUTIONS, BUDGET_SECONDS, CONFIRM_MODES, MAX_LIST, MAX_OUTPUT_DIR, ACCOUNT_ID_PATTERN } from "./constants.js";
5
+ import { MEDIA_KINDS } from "./classify.js";
6
+ import { MediaError, plain, intIn } from "./util.js";
7
+
8
+ // #region Preferences (media-settings.json)
9
+
10
+ /**
11
+ * Defaults for a profile without `media-settings.json`: generation is off
12
+ * until the user switches it on (an older file without `enabled` reads as on,
13
+ * see {@link normalizeMediaSettings}).
14
+ */
15
+ export function defaultMediaSettings() {
16
+ return {
17
+ version: MEDIA_SETTINGS_VERSION,
18
+ enabled: false,
19
+ agentTool: false,
20
+ outputDir: "generated",
21
+ defaultVideoSeconds: 6,
22
+ defaultVideoResolution: "720p",
23
+ imageConfirm: "auto",
24
+ videoConfirm: "ask",
25
+ videoBudget: { mode: "limited", seconds: 60 },
26
+ lastSelection: {},
27
+ accounts: {},
28
+ };
29
+ }
30
+
31
+ function validOutputDir(value) {
32
+ if (typeof value !== "string") return undefined;
33
+ const trimmed = value.trim();
34
+ if (trimmed === "" || trimmed.length > MAX_OUTPUT_DIR || /[\u0000-\u001f]/.test(trimmed)) return undefined;
35
+ return trimmed;
36
+ }
37
+
38
+ function validBudget(value) {
39
+ const raw = plain(value);
40
+ if (raw?.mode === "unlimited") return { mode: "unlimited" };
41
+ if (raw?.mode === "limited") {
42
+ const seconds = intIn(raw.seconds, BUDGET_SECONDS);
43
+ if (seconds !== undefined) return { mode: "limited", seconds };
44
+ }
45
+ return undefined;
46
+ }
47
+
48
+ function validSelectionRef(value) {
49
+ if (typeof value !== "string") return undefined;
50
+ const trimmed = value.trim();
51
+ const slash = trimmed.indexOf("/");
52
+ if (slash <= 0 || slash === trimmed.length - 1 || trimmed.length > 300) return undefined;
53
+ return ACCOUNT_ID_PATTERN.test(trimmed.slice(0, slash)) ? trimmed : undefined;
54
+ }
55
+
56
+ function validModelList(value) {
57
+ if (!Array.isArray(value)) return undefined;
58
+ const out = [];
59
+ for (const item of value) {
60
+ if (typeof item !== "string") continue;
61
+ const trimmed = item.trim();
62
+ if (trimmed !== "" && trimmed.length <= 200 && !out.includes(trimmed)) out.push(trimmed);
63
+ if (out.length >= MAX_LIST) break;
64
+ }
65
+ return out;
66
+ }
67
+
68
+ function validKindOverrides(value) {
69
+ const raw = plain(value);
70
+ if (raw === undefined) return {};
71
+ const out = {};
72
+ for (const [id, kind] of Object.entries(raw)) {
73
+ const key = id.trim();
74
+ if (key === "" || key.length > 200 || !MEDIA_KINDS.includes(kind)) continue;
75
+ out[key] = kind;
76
+ if (Object.keys(out).length >= MAX_LIST) break;
77
+ }
78
+ return out;
79
+ }
80
+
81
+ // Per account: the media models switched off (new models start switched on)
82
+ // and the user's chat / image / video reclassifications.
83
+ function normalizeAccountMedia(value) {
84
+ const raw = plain(value) ?? {};
85
+ return {
86
+ disabledModels: validModelList(raw.disabledModels) ?? [],
87
+ kindOverrides: validKindOverrides(raw.kindOverrides),
88
+ };
89
+ }
90
+
91
+ /**
92
+ * Tolerant normalization: every invalid or missing field takes its default,
93
+ * unknown fields are dropped. The result always has `version: 1`. A missing
94
+ * `enabled` means a file written before the switch existed (by someone who
95
+ * already used generation), so it reads as on.
96
+ */
97
+ export function normalizeMediaSettings(raw) {
98
+ const input = plain(raw) ?? {};
99
+ const defaults = defaultMediaSettings();
100
+ const accounts = {};
101
+ for (const [id, entry] of Object.entries(plain(input.accounts) ?? {})) {
102
+ if (ACCOUNT_ID_PATTERN.test(id)) accounts[id] = normalizeAccountMedia(entry);
103
+ }
104
+ const selection = plain(input.lastSelection) ?? {};
105
+ const lastSelection = {};
106
+ for (const kind of ["image", "video"]) {
107
+ const ref = validSelectionRef(selection[kind]);
108
+ if (ref !== undefined) lastSelection[kind] = ref;
109
+ }
110
+ return {
111
+ version: MEDIA_SETTINGS_VERSION,
112
+ enabled: typeof input.enabled === "boolean" ? input.enabled : true,
113
+ agentTool: input.agentTool === true,
114
+ outputDir: validOutputDir(input.outputDir) ?? defaults.outputDir,
115
+ defaultVideoSeconds: intIn(input.defaultVideoSeconds, VIDEO_SECONDS) ?? defaults.defaultVideoSeconds,
116
+ defaultVideoResolution: VIDEO_RESOLUTIONS.includes(input.defaultVideoResolution)
117
+ ? input.defaultVideoResolution
118
+ : defaults.defaultVideoResolution,
119
+ imageConfirm: CONFIRM_MODES.includes(input.imageConfirm) ? input.imageConfirm : defaults.imageConfirm,
120
+ videoConfirm: CONFIRM_MODES.includes(input.videoConfirm) ? input.videoConfirm : defaults.videoConfirm,
121
+ videoBudget: validBudget(input.videoBudget) ?? defaults.videoBudget,
122
+ lastSelection,
123
+ accounts,
124
+ };
125
+ }
126
+
127
+ /**
128
+ * Read preferences. A missing file yields defaults; an unreadable or
129
+ * malformed one also yields defaults but reports `error: "invalid-file"` so
130
+ * the caller can log it and the next save keeps a copy of the damaged file.
131
+ */
132
+ export function loadMediaSettings(filePath) {
133
+ if (!existsSync(filePath)) return { settings: defaultMediaSettings() };
134
+ try {
135
+ const raw = JSON.parse(readFileSync(filePath, "utf8"));
136
+ if (plain(raw) === undefined) return { settings: defaultMediaSettings(), error: "invalid-file" };
137
+ return { settings: normalizeMediaSettings(raw) };
138
+ } catch {
139
+ return { settings: defaultMediaSettings(), error: "invalid-file" };
140
+ }
141
+ }
142
+
143
+ /** Atomic write; a damaged existing file is first renamed to `*.corrupt-<time>.json`. */
144
+ export function saveMediaSettings(filePath, settings) {
145
+ mkdirSync(dirname(filePath), { recursive: true });
146
+ if (existsSync(filePath) && loadMediaSettings(filePath).error !== undefined) {
147
+ renameSync(filePath, filePath.replace(/\.json$/, `.corrupt-${Date.now().toString(36)}.json`));
148
+ }
149
+ const tmp = `${filePath}.${Date.now().toString(36)}.tmp`;
150
+ writeFileSync(tmp, `${JSON.stringify(normalizeMediaSettings(settings), null, 2)}\n`, "utf8");
151
+ renameSync(tmp, filePath);
152
+ }
153
+
154
+ const PATCH_FIELDS = [
155
+ "enabled",
156
+ "agentTool",
157
+ "outputDir",
158
+ "defaultVideoSeconds",
159
+ "defaultVideoResolution",
160
+ "imageConfirm",
161
+ "videoConfirm",
162
+ "videoBudget",
163
+ "account",
164
+ ];
165
+
166
+ /**
167
+ * Apply a validated patch. Unlike {@link normalizeMediaSettings}, an invalid
168
+ * value is an error (`MediaError` with a stable code), never a silent default.
169
+ * `account.kindOverrides` merges per model; a `null` value removes an override.
170
+ * `account.disabledModels` replaces the account's list of switched-off models.
171
+ * @returns `{ settings, kindsChanged }` — `kindsChanged` names the account
172
+ * whose model kinds changed (its routes need a re-sync).
173
+ */
174
+ export function applyMediaPatch(current, patch) {
175
+ const input = plain(patch);
176
+ if (input === undefined) throw new MediaError("invalid-request");
177
+ const unknown = Object.keys(input).filter((key) => !PATCH_FIELDS.includes(key) && key !== "accountId");
178
+ if (unknown.length > 0) throw new MediaError("invalid-request", `unknown field(s): ${unknown.join(", ")}`);
179
+ const next = normalizeMediaSettings(current);
180
+ if ("enabled" in input) {
181
+ if (typeof input.enabled !== "boolean") throw new MediaError("invalid-enabled");
182
+ next.enabled = input.enabled;
183
+ }
184
+ if ("agentTool" in input) {
185
+ if (typeof input.agentTool !== "boolean") throw new MediaError("invalid-agent-tool");
186
+ next.agentTool = input.agentTool;
187
+ }
188
+ if ("outputDir" in input) {
189
+ const dir = validOutputDir(input.outputDir);
190
+ if (dir === undefined) throw new MediaError("invalid-output-dir");
191
+ next.outputDir = dir;
192
+ }
193
+ if ("defaultVideoSeconds" in input) {
194
+ const seconds = intIn(input.defaultVideoSeconds, VIDEO_SECONDS);
195
+ if (seconds === undefined) throw new MediaError("invalid-video-seconds");
196
+ next.defaultVideoSeconds = seconds;
197
+ }
198
+ if ("defaultVideoResolution" in input) {
199
+ if (!VIDEO_RESOLUTIONS.includes(input.defaultVideoResolution)) throw new MediaError("invalid-video-resolution");
200
+ next.defaultVideoResolution = input.defaultVideoResolution;
201
+ }
202
+ for (const field of ["imageConfirm", "videoConfirm"]) {
203
+ if (!(field in input)) continue;
204
+ if (!CONFIRM_MODES.includes(input[field])) throw new MediaError("invalid-confirm-mode");
205
+ next[field] = input[field];
206
+ }
207
+ if ("videoBudget" in input) {
208
+ const budget = validBudget(input.videoBudget);
209
+ if (budget === undefined) throw new MediaError("invalid-video-budget");
210
+ next.videoBudget = budget;
211
+ }
212
+ let kindsChanged;
213
+ if ("account" in input) {
214
+ const account = plain(input.account);
215
+ const id = typeof account?.accountId === "string" ? account.accountId.trim() : "";
216
+ if (!ACCOUNT_ID_PATTERN.test(id)) throw new MediaError("invalid-account");
217
+ const entry = normalizeAccountMedia(next.accounts[id]);
218
+ if ("disabledModels" in account) {
219
+ const list = validModelList(account.disabledModels);
220
+ if (list === undefined) throw new MediaError("invalid-model-list");
221
+ entry.disabledModels = list;
222
+ }
223
+ if ("kindOverrides" in account) {
224
+ const raw = plain(account.kindOverrides);
225
+ if (raw === undefined) throw new MediaError("invalid-kind");
226
+ const merged = { ...entry.kindOverrides };
227
+ for (const [modelId, kind] of Object.entries(raw)) {
228
+ const key = modelId.trim();
229
+ if (key === "" || key.length > 200) throw new MediaError("invalid-kind");
230
+ if (kind === null) delete merged[key];
231
+ else if (MEDIA_KINDS.includes(kind)) merged[key] = kind;
232
+ else throw new MediaError("invalid-kind");
233
+ }
234
+ if (JSON.stringify(merged) !== JSON.stringify(entry.kindOverrides)) kindsChanged = id;
235
+ entry.kindOverrides = merged;
236
+ }
237
+ next.accounts[id] = entry;
238
+ }
239
+ return { settings: normalizeMediaSettings(next), kindsChanged };
240
+ }
241
+
242
+ /** Kind overrides of one account (empty when none). */
243
+ export function accountKindOverrides(settings, accountId) {
244
+ return settings?.accounts?.[accountId]?.kindOverrides ?? {};
245
+ }
246
+
247
+ /** Whether a media model is offered for an account (on unless switched off). */
248
+ export function mediaModelEnabled(settings, accountId, modelId) {
249
+ const list = settings?.accounts?.[accountId]?.disabledModels;
250
+ return !Array.isArray(list) || !list.includes(modelId);
251
+ }
252
+
253
+ // #endregion
254
+
255
+ export { validBudget, validSelectionRef };
@@ -0,0 +1,45 @@
1
+ // Shared validation, bounded response reading and safe media errors.
2
+ export class MediaError extends Error {
3
+ constructor(code, detail) {
4
+ super(code);
5
+ this.name = "MediaError";
6
+ this.code = code;
7
+ if (detail !== undefined) this.detail = detail;
8
+ }
9
+ }
10
+
11
+ function plain(value) {
12
+ return typeof value === "object" && value !== null && !Array.isArray(value) ? value : undefined;
13
+ }
14
+
15
+ function intIn(value, range) {
16
+ return Number.isInteger(value) && value >= range.min && value <= range.max ? value : undefined;
17
+ }
18
+
19
+ const DIAG_MAX_BYTES = 8 * 1024 * 1024;
20
+
21
+ async function readBoundedText(response, max = DIAG_MAX_BYTES) {
22
+ const declared = Number(response.headers?.get?.("content-length"));
23
+ const limit = `response is larger than ${Math.round(max / 1024 / 1024)} MiB`;
24
+ if (Number.isFinite(declared) && declared > max) throw new Error(limit);
25
+ const text = await response.text();
26
+ if (new TextEncoder().encode(text).byteLength > max) throw new Error(limit);
27
+ return text;
28
+ }
29
+
30
+ const clip = (value, max) => (typeof value === "string" ? value.slice(0, max) : "");
31
+
32
+ /** A short, URL-free upstream error message (never a body dump). */
33
+ export function upstreamMessage(text, status) {
34
+ let message = "";
35
+ try {
36
+ const payload = JSON.parse(text);
37
+ message = payload?.error?.message ?? payload?.message ?? (typeof payload?.error === "string" ? payload.error : "");
38
+ } catch {
39
+ message = text;
40
+ }
41
+ message = String(message ?? "").replace(/https?:\/\/\S+/g, "[url]").replace(/\s+/g, " ").trim().slice(0, 300);
42
+ return message === "" ? `HTTP ${status}` : `HTTP ${status}: ${message}`;
43
+ }
44
+
45
+ export { plain, intIn, readBoundedText, clip };