dsh-cliproxyapi-pro 1.9.0 → 1.10.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 (84) hide show
  1. package/CHANGELOG.md +23 -0
  2. package/README.en.md +24 -408
  3. package/README.md +24 -408
  4. package/lib/client.js +265 -27
  5. package/lib/host/accounts.js +178 -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 +121 -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 +50 -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 +210 -0
  26. package/lib/host/controller.js +464 -0
  27. package/lib/host/discovery.js +301 -0
  28. package/lib/host/http-gate.js +144 -0
  29. package/lib/host/model-info.js +363 -0
  30. package/lib/host/model-names.js +152 -0
  31. package/lib/host/models.js +75 -0
  32. package/lib/host/mount-guard.js +56 -0
  33. package/lib/host/recommend.js +367 -0
  34. package/lib/host/routes.js +165 -0
  35. package/lib/host/runtime.js +471 -0
  36. package/lib/host/state-store.js +39 -0
  37. package/lib/host/status-text.js +93 -0
  38. package/lib/index.js +18 -4417
  39. package/lib/media/agent-tool.js +255 -0
  40. package/lib/media/choice.js +83 -0
  41. package/lib/media/classify.js +65 -0
  42. package/lib/media/codec/fit.js +76 -0
  43. package/lib/media/codec/jpeg.js +158 -0
  44. package/lib/media/codec/png.js +102 -0
  45. package/lib/media/commands/parsing.js +269 -0
  46. package/lib/media/constants.js +46 -0
  47. package/lib/media/diagnose.js +134 -0
  48. package/lib/media/images.js +165 -0
  49. package/lib/media/index.js +29 -0
  50. package/lib/media/interpret.js +126 -0
  51. package/lib/media/job-store.js +99 -0
  52. package/lib/media/mp4.js +44 -0
  53. package/lib/media/output-files.js +59 -0
  54. package/lib/media/session-store.js +293 -0
  55. package/lib/media/settings.js +255 -0
  56. package/lib/media/util.js +45 -0
  57. package/lib/media/video.js +326 -0
  58. package/lib/quota/auth-state.js +33 -0
  59. package/lib/quota/constants.js +86 -0
  60. package/lib/quota/controller.js +467 -0
  61. package/lib/quota/helpers.js +325 -0
  62. package/lib/quota/index.js +19 -0
  63. package/lib/quota/management.js +216 -0
  64. package/lib/quota/matching.js +143 -0
  65. package/lib/quota/parsers.js +352 -0
  66. package/lib/quota/probes/billing.js +80 -0
  67. package/lib/quota/probes/google.js +120 -0
  68. package/lib/quota/probes/oauth.js +27 -0
  69. package/lib/quota/probes/plugin.js +18 -0
  70. package/lib/updater/constants.js +23 -0
  71. package/lib/updater/errors.js +8 -0
  72. package/lib/updater/index.js +11 -0
  73. package/lib/updater/registry.js +83 -0
  74. package/lib/updater/settings.js +45 -0
  75. package/lib/updater/store.js +23 -0
  76. package/lib/updater/updater.js +148 -0
  77. package/lib/updater/verify.js +110 -0
  78. package/lib/updater/version.js +31 -0
  79. package/locale/en.json +1 -1
  80. package/locale/zh.json +1 -1
  81. package/package.json +6 -9
  82. package/lib/media.js +0 -2542
  83. package/lib/quota.js +0 -1748
  84. package/lib/updater.js +0 -443
@@ -0,0 +1,171 @@
1
+ // Image admission and background generation, output persistence and settlement.
2
+
3
+ import { existsSync } from "node:fs";
4
+ import { isAbsolute } from "node:path";
5
+ import { chooseMediaModel, generateImages, MAX_REFERENCE_IMAGES, MediaError, outputDirectory, outputStem, parseImageCommand, recentEntry, validCommandId, validSessionId, writeOutputFiles } from "../../media/index.js";
6
+
7
+ export function createImageJobs(shared) {
8
+ const { ctx, controller, mediaSessions, mediaChoicesFor, mediaAccountsSummary, REFERENCES_MAX_BYTES, readReference, interpretParams, interpretedRecord, mediaFailureText, mediaJobs, settleWith, publishSessionStatus, settleSessionStatus, syncHeartbeat, recordRun, folderLabel } = shared;
9
+ /** Run one admitted image request in the background; resolves when it has settled and been recorded. */
10
+ const startImageJob = ({ sessionId, commandId, option, args: admitted, references, cwd, outputDir, endpoint, interpret }) => {
11
+ const key = commandId ?? `job-${++shared.mediaJobSeq}`;
12
+ const abort = new AbortController();
13
+ mediaJobs.set(key, { sessionId, abort });
14
+ syncHeartbeat();
15
+ if (sessionId !== undefined) publishSessionStatus(sessionId, true);
16
+ const started = Date.now();
17
+ return settleWith(key, (async () => {
18
+ try {
19
+ let args = admitted;
20
+ if (interpret !== undefined) {
21
+ if (commandId !== undefined) shared.videoLive.set(commandId, { phase: "interpreting" });
22
+ const result = await interpret(abort.signal);
23
+ if (commandId !== undefined) shared.videoLive.delete(commandId);
24
+ if (result !== undefined) {
25
+ args = { ...admitted, ...result.values, prompt: result.prompt };
26
+ recordRun(sessionId, commandId, {
27
+ prompt: args.prompt,
28
+ ...(args.aspect === undefined ? {} : { aspect: args.aspect }),
29
+ count: args.count ?? 1,
30
+ ...interpretedRecord(result, admitted.prompt),
31
+ });
32
+ }
33
+ }
34
+ const images = await generateImages({
35
+ rootURL: endpoint.rootURL,
36
+ apiKey: endpoint.apiKey,
37
+ model: option.modelId,
38
+ prompt: args.prompt,
39
+ ...(args.aspect === undefined ? {} : { aspect: args.aspect }),
40
+ count: args.count ?? 1,
41
+ references,
42
+ signal: abort.signal,
43
+ });
44
+ const dir = outputDirectory(cwd, outputDir);
45
+ const paths = writeOutputFiles(dir, outputStem(option.modelId, args.prompt), images);
46
+ const revised = images.find((image) => image.revisedPrompt !== undefined)?.revisedPrompt;
47
+ recordRun(
48
+ sessionId,
49
+ commandId,
50
+ {
51
+ status: "done",
52
+ files: paths.length,
53
+ folder: folderLabel(cwd, dir),
54
+ finishedAt: new Date().toISOString(),
55
+ ...(revised === undefined ? {} : { revisedPrompt: revised }),
56
+ },
57
+ paths.map((p) => recentEntry("image", p, option.ref, new Date(), commandId))
58
+ );
59
+ ctx.logger?.info?.(`cpa: /cpa-image wrote ${paths.length} image(s) with ${option.modelId} in ${Math.round((Date.now() - started) / 1000)} s`);
60
+ } catch (thrown) {
61
+ const error = abort.signal.aborted ? new MediaError("interrupted") : thrown;
62
+ recordRun(sessionId, commandId, {
63
+ status: "error",
64
+ errorCode: error instanceof MediaError ? error.code : "failed",
65
+ error: mediaFailureText(error),
66
+ finishedAt: new Date().toISOString(),
67
+ });
68
+ ctx.logger?.warn?.(`cpa: /cpa-image failed: ${mediaFailureText(error)}`);
69
+ } finally {
70
+ if (commandId !== undefined) shared.videoLive.delete(commandId);
71
+ mediaJobs.delete(key);
72
+ syncHeartbeat();
73
+ settleSessionStatus(sessionId);
74
+ }
75
+ })());
76
+ };
77
+
78
+ // #endregion
79
+
80
+ /**
81
+ * `/cpa-image`: generate or (with attached images) edit, save into the
82
+ * session's folder. Checks everything it can up front (options, model,
83
+ * folder, references, endpoint), then returns while the generation runs as
84
+ * a background job; the chat row shows its progress and result.
85
+ */
86
+ // Internal callers (the agent tool) add: `literal` (no plain-language
87
+ // parsing or interpretation), `pickSession` (whose model pick applies) and
88
+ // `gate(plan)` (confirmation / budget, run after every check and before
89
+ // anything is recorded or sent; a thrown `gateError` passes through).
90
+ const runImageCommand = async ({ agent, rawInput, attachments = [], signal, commandId, literal = false, pickSession, gate }) => {
91
+ try {
92
+ const args = parseImageCommand(rawInput, { literal });
93
+ const blocks = Array.isArray(attachments) ? attachments : [];
94
+ if (blocks.some((block) => block?.type !== "image")) throw new MediaError("unsupported-attachment");
95
+ if (blocks.length > MAX_REFERENCE_IMAGES) throw new MediaError("too-many-references");
96
+ const { settings, options, accounts } = await mediaChoicesFor("image");
97
+ const sessionId = validSessionId(agent?.id);
98
+ const pickId = validSessionId(pickSession) ?? sessionId;
99
+ const entry = pickId === undefined ? {} : mediaSessions.get(pickId);
100
+ let option;
101
+ try {
102
+ ({ option } = chooseMediaModel({
103
+ options: options.image,
104
+ requested: args.model,
105
+ sessionRef: entry.image,
106
+ lastRef: settings.lastSelection.image,
107
+ }));
108
+ } catch (error) {
109
+ if (error instanceof MediaError && error.code === "no-media-model") {
110
+ throw new MediaError("no-media-model", mediaAccountsSummary(accounts, "image"));
111
+ }
112
+ throw error;
113
+ }
114
+ const workingDirectory = ctx.get?.("workingDirectory");
115
+ const cwd = agent !== undefined && workingDirectory !== undefined ? await workingDirectory.ensure(agent, signal) : undefined;
116
+ if (typeof cwd !== "string" || !isAbsolute(cwd) || !existsSync(cwd)) throw new MediaError("workspace-not-local");
117
+ const references = [];
118
+ if (blocks.length > 0) {
119
+ const store = ctx.get?.("attachments");
120
+ if (store === undefined) throw new MediaError("unsupported-attachment");
121
+ const each = Math.floor(REFERENCES_MAX_BYTES / blocks.length);
122
+ for (const block of blocks) references.push(await readReference(store, block, each, signal));
123
+ }
124
+ const endpoint = await controller.mediaEndpoint(option.accountId);
125
+ const id = validCommandId(commandId);
126
+ const count = args.count ?? 1;
127
+ if (gate !== undefined) {
128
+ await gate({ kind: "image", mode: references.length > 0 ? "image-edit" : "image-text", option, prompt: args.prompt, count, references: references.length, aspect: args.aspect, cwd, outputDir: settings.outputDir });
129
+ }
130
+ recordRun(sessionId, id, {
131
+ kind: "image",
132
+ status: "running",
133
+ model: option.ref,
134
+ modelName: option.name || option.modelId,
135
+ accountName: option.accountName,
136
+ prompt: args.prompt,
137
+ ...(args.aspect === undefined ? {} : { aspect: args.aspect }),
138
+ count,
139
+ references: references.length,
140
+ files: 0,
141
+ startedAt: new Date().toISOString(),
142
+ });
143
+ void startImageJob({
144
+ sessionId,
145
+ commandId: id,
146
+ option,
147
+ args,
148
+ references,
149
+ cwd,
150
+ outputDir: settings.outputDir,
151
+ endpoint,
152
+ ...(literal
153
+ ? {}
154
+ : {
155
+ interpret: (jobSignal) =>
156
+ interpretParams({ agent, command: "image", text: args.prompt, images: references.length, fixed: ["aspect", "count"].filter((k) => args[k] !== undefined), signal: jobSignal }),
157
+ }),
158
+ });
159
+ const dir = outputDirectory(cwd, settings.outputDir);
160
+ return {
161
+ kind: "success",
162
+ text: `${references.length > 0 ? "Editing" : "Generating"} ${count} image(s) with ${option.modelId} (${option.accountName}); files go to ${dir}`,
163
+ };
164
+ } catch (error) {
165
+ if (signal?.aborted || error?.gateError === true) throw error;
166
+ return { kind: "error", text: `/cpa-image: ${mediaFailureText(error)}` };
167
+ }
168
+ };
169
+
170
+ return { runImageCommand };
171
+ }
@@ -0,0 +1,41 @@
1
+ // Host apply orchestration: build an explicit activation context and wire factories in original order.
2
+
3
+ import { createState } from "./state.js";
4
+ import { createUpdates } from "./updates.js";
5
+ import { createController } from "./controller.js";
6
+ import { createQuotaService } from "./quota-service.js";
7
+ import { createMediaService } from "./media-service.js";
8
+ import { createReferences } from "./references.js";
9
+ import { createInterpret } from "./interpret.js";
10
+ import { createMediaFailures } from "./media-failures.js";
11
+ import { createSessionStatus } from "./session-status.js";
12
+ import { createImageJobs } from "./image-jobs.js";
13
+ import { createVideoJobs } from "./video-jobs.js";
14
+ import { createVideoCommand } from "./video-command.js";
15
+ import { createVideoEdit } from "./video-edit.js";
16
+ import { createAgentTool } from "./agent-tool.js";
17
+ import { createLifecycle } from "./lifecycle.js";
18
+ import { createCommands } from "./commands.js";
19
+ import { createHttpRoutes } from "./http-routes.js";
20
+
21
+ export function applyImpl(ctx, config) {
22
+ const shared = { ctx, config };
23
+ Object.assign(shared, createState(shared));
24
+ Object.assign(shared, createUpdates(shared));
25
+ Object.assign(shared, createController(shared));
26
+ Object.assign(shared, createQuotaService(shared));
27
+ Object.assign(shared, createMediaService(shared));
28
+ Object.assign(shared, createReferences(shared));
29
+ Object.assign(shared, createInterpret(shared));
30
+ Object.assign(shared, createMediaFailures(shared));
31
+ Object.assign(shared, createSessionStatus(shared));
32
+ Object.assign(shared, createImageJobs(shared));
33
+ Object.assign(shared, createVideoJobs(shared));
34
+ Object.assign(shared, createVideoCommand(shared));
35
+ Object.assign(shared, createVideoEdit(shared));
36
+ Object.assign(shared, createAgentTool(shared));
37
+ Object.assign(shared, createLifecycle(shared));
38
+ Object.assign(shared, createCommands(shared));
39
+ shared.registerAgentTool();
40
+ Object.assign(shared, createHttpRoutes(shared));
41
+ }
@@ -0,0 +1,72 @@
1
+ // Session chat-target lookup and non-blocking generation-parameter interpretation.
2
+
3
+ import { interpretationLabels, interpretationRequest, parseInterpretation } from "../../media/index.js";
4
+
5
+ export function createInterpret(shared) {
6
+ const { ctx } = shared;
7
+ // #region Parameter interpretation (the session's chat model)
8
+ const INTERPRET_TIMEOUT_MS = 30_000;
9
+ const INTERPRET_MAX_TOKENS = 2000;
10
+
11
+ /** The provider / model the session's agent last used (else its options, else the default model). */
12
+ const sessionChatTarget = (agent) => {
13
+ const valid = (t) => (t && typeof t.provider === "string" && t.provider !== "" && typeof t.model === "string" && t.model !== "" ? { provider: t.provider, model: t.model } : undefined);
14
+ try {
15
+ const header = valid(agent?.session?.requestHeader?.()?.config);
16
+ if (header !== undefined) return header;
17
+ } catch {
18
+ // fall through
19
+ }
20
+ return valid(agent?.options) ?? valid(ctx.get?.("agentDefaultModel")?.currentSelection?.());
21
+ };
22
+
23
+ /**
24
+ * Ask the session's chat model which parameters the prompt states.
25
+ * Never throws: without an `llm` service or a model it returns undefined;
26
+ * a failed call returns `{ failed: true, by }`.
27
+ * @param fixed - fields the rule parser already set (they win).
28
+ * @returns `{ by, values, prompt, items, failed? }` or undefined.
29
+ */
30
+ const interpretParams = async ({ agent, command, text, images = 0, fixed = [], signal }) => {
31
+ const llm = ctx.get?.("llm");
32
+ const target = sessionChatTarget(agent);
33
+ if (typeof llm?.stream !== "function" || target === undefined) return undefined;
34
+ const by = `${target.provider}/${target.model}`;
35
+ const request = interpretationRequest({ command, text, images, fixed });
36
+ const timeout = AbortSignal.timeout(INTERPRET_TIMEOUT_MS);
37
+ const combined = signal === undefined ? timeout : AbortSignal.any([signal, timeout]);
38
+ try {
39
+ const parts = new Map();
40
+ for await (const chunk of llm.stream({
41
+ provider: target.provider,
42
+ model: target.model,
43
+ system: request.system,
44
+ messages: [{ role: "user", content: [{ type: "text", text: request.user }] }],
45
+ maxTokens: INTERPRET_MAX_TOKENS,
46
+ ...(agent?.session?.id === undefined ? {} : { sessionId: agent.session.id }),
47
+ purpose: "cpa-media-params",
48
+ signal: combined,
49
+ })) {
50
+ if (chunk?.type === "text-delta") parts.set(chunk.index, (parts.get(chunk.index) ?? "") + chunk.text);
51
+ else if (chunk?.type === "block-end" && chunk.block?.type === "text") parts.set(chunk.index, chunk.block.text);
52
+ }
53
+ const answer = [...parts.values()].join("");
54
+ const parsed = parseInterpretation(answer, { command, text, fields: request.fields, images });
55
+ if (parsed === undefined) throw new Error("no JSON in the answer");
56
+ return { by, ...parsed, items: interpretationLabels(parsed.values) };
57
+ } catch (error) {
58
+ if (signal?.aborted) throw signal.reason;
59
+ ctx.logger?.warn?.(`cpa: parameter interpretation with ${by} failed: ${error instanceof Error ? error.message : String(error)}`);
60
+ return { by, failed: true, values: {}, prompt: text, items: [] };
61
+ }
62
+ };
63
+
64
+ /** The run-record field describing an interpretation. */
65
+ const interpretedRecord = (result, original) =>
66
+ result === undefined
67
+ ? {}
68
+ : { interpreted: { by: result.by, items: result.items, ...(result.failed ? { failed: true } : {}), ...(result.prompt !== original ? { prompt: true } : {}) } };
69
+ // #endregion
70
+
71
+ return { sessionChatTarget, interpretParams, interpretedRecord };
72
+ }
@@ -0,0 +1,50 @@
1
+ // Refresh startup, online model info schedule, video resume, credential listener and refresh-loop disposal.
2
+
3
+ import { outsideHmrTransaction } from "../apply-utils.js";
4
+
5
+ export function createLifecycle(shared) {
6
+ const { ctx, reschedule, controller, quota, resumeVideoJobs, syncAgentTool } = shared;
7
+ reschedule();
8
+ resumeVideoJobs();
9
+ shared.startupTimeout = outsideHmrTransaction(ctx, () =>
10
+ setTimeout(() => {
11
+ shared.startupTimeout = undefined;
12
+ void controller.refreshAll().finally(() => syncAgentTool());
13
+ }, 600)
14
+ );
15
+
16
+ // Online model info: first look ~5 s after start, then hourly checks that
17
+ // download only when a source is a day old (or an hour after a failure).
18
+ const { modelInfo } = shared;
19
+ ctx.effect(() => {
20
+ const run = () => void modelInfo.refresh().catch(() => {});
21
+ const timers = outsideHmrTransaction(ctx, () => ({
22
+ first: setTimeout(run, 5000),
23
+ every: setInterval(run, 60 * 60 * 1000),
24
+ }));
25
+ return () => {
26
+ clearTimeout(timers.first);
27
+ clearInterval(timers.every);
28
+ modelInfo.dispose();
29
+ };
30
+ }, "cpa: online model info");
31
+
32
+ ctx.on("credentials/reference-updated", (ref) => {
33
+ // A management key changed (also from the DSH credentials page): start a new failure count.
34
+ quota.keyChanged(ref);
35
+ for (const id of controller.accountsUsingKey(ref)) {
36
+ void controller.refreshAccount(id);
37
+ }
38
+ });
39
+
40
+ ctx.effect(
41
+ () => () => {
42
+ if (shared.timer !== undefined) clearInterval(shared.timer);
43
+ if (shared.startupTimeout !== undefined) clearTimeout(shared.startupTimeout);
44
+ controller.dispose();
45
+ },
46
+ "cpa: refresh loop"
47
+ );
48
+
49
+ return {};
50
+ }
@@ -0,0 +1,68 @@
1
+ // Plain-English media failure summaries for commands and persisted run records.
2
+
3
+ import { IMAGE_ASPECTS, MAX_REFERENCE_IMAGES, MediaError, MAX_VIDEO_BYTES, VIDEO_ASPECTS, EDIT_SOURCE_MAX_SECONDS, EXTEND_SOURCE_SECONDS, VIDEO_UPLOAD_MAX_BYTES } from "../../media/index.js";
4
+
5
+ export function createMediaFailures(shared) {
6
+ /** Plain-English host text for a media failure (slash command output and run records). */
7
+ const mediaFailureText = (error, kind = "image") => {
8
+ if (!(error instanceof MediaError)) return error instanceof Error ? error.message : String(error);
9
+ const detail = error.detail;
10
+ const video = kind === "video";
11
+ const noun = video ? "video" : "image";
12
+ switch (error.code) {
13
+ case "missing-prompt": return video ? "add a prompt, for example: /cpa-video waves rolling onto a beach at sunset" : "add a prompt, for example: /cpa-image a red fox in the snow";
14
+ case "invalid-option": return video
15
+ ? `unknown option ${detail}; use -m <model>, --aspect <ratio>, -s <1-15>, -r <480p|720p>`
16
+ : `unknown option ${detail}; use -m <model>, --aspect <ratio>, -n <1-4>`;
17
+ case "invalid-aspect": return `--aspect must be one of ${(video ? VIDEO_ASPECTS : IMAGE_ASPECTS).join(", ")}`;
18
+ case "invalid-count": return "-n must be 1 to 4";
19
+ case "invalid-video-seconds": return "-s / --seconds must be a whole number from 1 to 15";
20
+ case "invalid-video-resolution": return "-r / --resolution must be 480p or 720p";
21
+ case "no-media-model": return `no ${noun} model is available (${detail || "no account"}); check Settings → CLIProxyAPI → Generation, or run /cpa-refresh if a catalog has not been read yet`;
22
+ case "choose-model": return `several ${noun} models are available (${detail}); pick one with the button next to the composer or pass -m <model>`;
23
+ case "model-not-found": return `no enabled ${noun} model matches; available: ${detail || "none"}`;
24
+ case "model-ambiguous": return `several ${noun} models match (${detail}); be more specific`;
25
+ case "workspace-not-local": return `the session's working directory is not a local folder, so the ${noun} cannot be saved`;
26
+ case "unsupported-attachment": return detail === "edit"
27
+ ? "attach one MP4 video as the source (images cannot be used here)"
28
+ : video ? "only image attachments can be used for /cpa-video (first frame, references, first / last frames)" : "only image attachments can be used as references";
29
+ case "too-many-references": return video ? `attach at most ${detail ?? "14"} images for this mode (more than 2 images are references)` : `attach at most ${MAX_REFERENCE_IMAGES} reference images`;
30
+ case "frames-need-images": return "--ref / --last / --first-last need attached images: one for a reference or a last frame, two for first and last frame";
31
+ case "needs-video-15": return "pinned first / last frames need grok-imagine-video-1.5; pick it with -m or the model button";
32
+ case "invalid-extend-seconds": return "an extension adds 2 to 10 seconds (-s 2-10)";
33
+ case "no-video-source": return "no source video: attach an MP4, or pass --video <path>, --url <public URL> or --from <command id>";
34
+ case "video-source-expired": return "that video's file is gone and its short-lived xAI link has expired; attach the MP4 or pass --video <path>";
35
+ case "one-video-source": return "use one source video: an attachment, --video, --url or --from";
36
+ case "invalid-video-url": return "--url must be a public http(s) address without a user name or password";
37
+ case "video-not-found": return `no video file at ${detail}`;
38
+ case "video-not-mp4": return "the source video must be an MP4 file (H.264, H.265 or AV1)";
39
+ case "source-too-large": return `the source video is ${detail} MiB; videos up to ${Math.round(VIDEO_UPLOAD_MAX_BYTES / 1024 / 1024)} MiB can be sent inline — shorten or compress it, or pass a public link with --url`;
40
+ case "request-too-large": return video
41
+ ? `the request is too large for this server (${detail ? `${Math.round(Number(detail) / 1024)} KB` : "body limit"}); attach smaller or fewer images`
42
+ : "the request is too large for this server";
43
+ case "route-unsupported": return `this server's upstream does not offer ${detail === "extensions" ? "video extension" : detail === "edits" ? "video editing" : detail} (HTTP 405); CPA may pause the credential for this model for about a minute`;
44
+ case "edit-source-too-long": return `xAI edits videos of at most ${EDIT_SOURCE_MAX_SECONDS} seconds (this one has ${detail} s); extend it instead`;
45
+ case "extend-source-length": return `xAI extends videos of ${EXTEND_SOURCE_SECONDS.min} to ${EXTEND_SOURCE_SECONDS.max} seconds (this one has ${detail} s)`;
46
+ case "reference-too-large": return `an attached image could not be made smaller than ${detail ?? "1000"} KB; attach a smaller image`;
47
+ case "upstream-error": return `CPA rejected the request (${detail})`;
48
+ case "timeout": return video ? "CPA did not answer in time" : "CPA did not answer within 3 minutes";
49
+ case "network": return "could not reach CPA";
50
+ case "no-image": return "CPA returned no image";
51
+ case "invalid-image":
52
+ case "invalid-response": return video ? "CPA returned an answer this plugin does not understand" : "CPA returned data that is not a PNG, JPEG, WebP or GIF image";
53
+ case "image-too-large": return "an image is larger than 32 MiB";
54
+ case "video-too-large": return `the video is larger than ${Math.round(MAX_VIDEO_BYTES / 1024 / 1024)} MiB`;
55
+ case "invalid-video": return "CPA returned data that is not an MP4, MOV or WebM video";
56
+ case "video-failed": return `the video could not be generated${detail ? ` (${detail})` : ""}`;
57
+ case "expired": return "CPA no longer knows this video: more than 3 hours have passed since it was submitted";
58
+ case "download-failed": return `could not download the generated ${noun}`;
59
+ case "write-failed": return `could not write the ${noun} file${detail ? ` (${detail})` : ""}`;
60
+ case "no-endpoint": return "this account has no usable server address yet";
61
+ case "invalid-account": return "the model's account no longer exists";
62
+ case "interrupted": return "stopped because the plugin was reloaded or DSH closed";
63
+ default: return error.code;
64
+ }
65
+ };
66
+
67
+ return { mediaFailureText };
68
+ }
@@ -0,0 +1,202 @@
1
+ // Media settings, catalog choices, session views/picks and file range helpers.
2
+
3
+ import { existsSync } from "node:fs";
4
+ import { basename, join } from "node:path";
5
+ import { accountKindOverrides, applyMediaPatch, chooseMediaModel, createMediaSessionStore, MediaError, mediaModelEnabled, mediaOptions, normalizeMediaSettings, saveMediaSettings, validSessionId, agentPolicy, applySessionPolicy } from "../../media/index.js";
6
+
7
+ export function createMediaService(shared) {
8
+ const { updateDirectory, mediaSettingsPath, readMedia, controller } = shared;
9
+ /** Media page payload: preferences (without per-account maps) and each account's media models. */
10
+ const mediaStatus = () => {
11
+ const { settings, error } = readMedia();
12
+ const { accounts: perAccount, ...global } = settings;
13
+ return {
14
+ settings: global,
15
+ ...(error === undefined ? {} : { settingsError: error }),
16
+ accounts: controller.mediaAccounts().map((account) => {
17
+ const overrides = accountKindOverrides(settings, account.id);
18
+ return {
19
+ ...account,
20
+ disabledModels: perAccount[account.id]?.disabledModels ?? [],
21
+ kindOverrides: overrides,
22
+ models: account.models.map((m) => ({
23
+ ...m,
24
+ enabled: mediaModelEnabled(settings, account.id, m.id),
25
+ overridden: overrides[m.id] !== undefined,
26
+ })),
27
+ };
28
+ }),
29
+ };
30
+ };
31
+
32
+ const saveMedia = async (body) => {
33
+ const accountId = body?.account?.accountId;
34
+ if (accountId !== undefined && !controller.mediaAccounts().some((a) => a.id === accountId)) {
35
+ throw new MediaError("invalid-account");
36
+ }
37
+ const { settings, kindsChanged } = applyMediaPatch(readMedia().settings, body);
38
+ saveMediaSettings(mediaSettingsPath, settings);
39
+ // A reclassified model enters or leaves the chat routes on the next sync.
40
+ if (kindsChanged === undefined) return { ok: true, media: mediaStatus() };
41
+ await controller.refreshAccount(kindsChanged);
42
+ return { ok: true, media: mediaStatus(), status: await controller.statusPayload() };
43
+ };
44
+
45
+ // Per-session model picks and recent outputs, in their own file.
46
+ const mediaSessions = createMediaSessionStore(join(updateDirectory, "media-sessions.json"));
47
+
48
+ // With generation switched off nothing is offered: no composer buttons, no
49
+ // agent tool, and no command can pick a model.
50
+ const mediaChoices = () => {
51
+ const { settings } = readMedia();
52
+ const accounts = controller.mediaAccounts();
53
+ const on = settings.enabled === true;
54
+ return {
55
+ settings,
56
+ accounts,
57
+ options: on
58
+ ? { image: mediaOptions(accounts, settings, "image"), video: mediaOptions(accounts, settings, "video") }
59
+ : { image: [], video: [] },
60
+ };
61
+ };
62
+
63
+ /**
64
+ * Choices for a generation command. When a needed kind is not offered and an
65
+ * enabled account either has not read its catalog yet (just after a start
66
+ * or reload) or reported a failed plain listing, sync once and look again
67
+ * instead of failing on a timing race. An incomplete-catalog retry is
68
+ * limited to once per 30 s so a permanently missing listing is not fetched
69
+ * on every request.
70
+ */
71
+ let catalogRetryAt = 0;
72
+ const mediaChoicesFor = async (kind) => {
73
+ let choices = mediaChoices();
74
+ if (choices.settings.enabled !== true) return choices;
75
+ const missing = (k) => choices.options[k].length === 0;
76
+ const someMissing = kind === "any" ? missing("image") || missing("video") : missing(kind);
77
+ const cold = choices.accounts.some((a) => a.enabled && a.discovered === 0);
78
+ const incomplete = choices.accounts.some((a) => a.enabled && a.catalogIncomplete === true);
79
+ const retryIncomplete = incomplete && Date.now() - catalogRetryAt >= 30_000;
80
+ if (someMissing && (cold || retryIncomplete)) {
81
+ catalogRetryAt = Date.now();
82
+ await controller.refreshAll();
83
+ choices = mediaChoices();
84
+ }
85
+ return choices;
86
+ };
87
+
88
+ /** One line per account for an empty choice: state and catalog counts, never keys or URLs. */
89
+ const mediaAccountsSummary = (accounts, kind) =>
90
+ accounts
91
+ .map((a) => `${a.displayName || a.id}: ${a.enabled ? a.state : "disabled"}, ${a.discovered} model(s), ${a.models.filter((m) => m.kind === kind).length} ${kind}`)
92
+ .join("; ") || "no account";
93
+
94
+ /** What the composer button shows for one session (no network access). */
95
+ const sessionView = (sessionId) => {
96
+ const { settings, options, accounts } = mediaChoices();
97
+ const entry = sessionId === undefined ? { recent: [] } : mediaSessions.get(sessionId);
98
+ const current = {};
99
+ for (const kind of ["image", "video"]) {
100
+ try {
101
+ const { option, source } = chooseMediaModel({
102
+ options: options[kind],
103
+ sessionRef: entry[kind],
104
+ lastRef: settings.lastSelection[kind],
105
+ });
106
+ current[kind] = { ref: option.ref, source };
107
+ } catch {
108
+ current[kind] = null;
109
+ }
110
+ }
111
+ const policy = agentPolicy(settings, entry);
112
+ return {
113
+ sessionId: sessionId ?? null,
114
+ // The Generation tab's master switch; off = the composer shows nothing.
115
+ generation: settings.enabled === true,
116
+ options,
117
+ current,
118
+ // Compatibility composer fallback; native questions never enter this map.
119
+ pendingConfirmations: sessionId === undefined ? [] : [...shared.pendingConfirms.entries()]
120
+ .filter(([, waiting]) => waiting.sessionId === sessionId)
121
+ .map(([commandId, { kind, en, zh, expiresAt }]) => ({ commandId, kind, en, zh, expiresAt })),
122
+ // True while an enabled account's last catalog read missed the plain
123
+ // listing; the composer button retries instead of keeping an old,
124
+ // image-less list.
125
+ catalogIncomplete: settings.enabled === true && accounts.some((a) => a.enabled === true && a.catalogIncomplete === true),
126
+ // The agent tool's rules for this session (shown while the tool is switched on).
127
+ agent: {
128
+ enabled: settings.agentTool === true,
129
+ imageConfirm: policy.imageConfirm,
130
+ videoConfirm: policy.videoConfirm,
131
+ videoBudget: policy.budget,
132
+ used: policy.used,
133
+ sources: policy.sources,
134
+ global: { imageConfirm: settings.imageConfirm, videoConfirm: settings.videoConfirm, videoBudget: settings.videoBudget },
135
+ },
136
+ recent: entry.recent
137
+ .filter((r) => existsSync(r.file))
138
+ .slice(0, 12)
139
+ .map((r) => ({ id: r.id, kind: r.kind, name: basename(r.file), model: r.model, createdAt: r.createdAt })),
140
+ };
141
+ };
142
+
143
+ /** Pick a model for one session (and remember it as the last pick); `ref: null` clears the session's pick. */
144
+ const saveSessionPick = (body) => {
145
+ // Agent-tool overrides for one session (no model pick in the same request).
146
+ if (body?.kind === undefined && ["imageConfirm", "videoConfirm", "videoBudget"].some((k) => k in (body ?? {}))) {
147
+ const sessionId = validSessionId(body.sessionId);
148
+ if (sessionId === undefined) throw new MediaError("invalid-session");
149
+ const { settings } = mediaChoices();
150
+ mediaSessions.update(sessionId, (entry) => applySessionPolicy(entry, body, settings));
151
+ return { ok: true, session: sessionView(sessionId) };
152
+ }
153
+ const kind = body?.kind;
154
+ if (kind !== "image" && kind !== "video") throw new MediaError("invalid-request");
155
+ const sessionId = body.sessionId === undefined || body.sessionId === null ? undefined : validSessionId(body.sessionId);
156
+ if (body.sessionId !== undefined && body.sessionId !== null && sessionId === undefined) throw new MediaError("invalid-session");
157
+ const ref = body.ref === null ? null : typeof body.ref === "string" ? body.ref : undefined;
158
+ if (ref === undefined) throw new MediaError("invalid-model");
159
+ const { settings, options } = mediaChoices();
160
+ if (ref !== null && !options[kind].some((o) => o.ref === ref)) throw new MediaError("invalid-model");
161
+ if (sessionId !== undefined) {
162
+ mediaSessions.update(sessionId, (entry) => {
163
+ if (ref === null) delete entry[kind];
164
+ else entry[kind] = ref;
165
+ });
166
+ }
167
+ if (ref !== null && settings.lastSelection[kind] !== ref) {
168
+ saveMediaSettings(mediaSettingsPath, normalizeMediaSettings({ ...settings, lastSelection: { ...settings.lastSelection, [kind]: ref } }));
169
+ }
170
+ return { ok: true, session: sessionView(sessionId) };
171
+ };
172
+
173
+ const MEDIA_FILE_TYPES = {
174
+ ".png": "image/png", ".jpg": "image/jpeg", ".jpeg": "image/jpeg", ".webp": "image/webp", ".gif": "image/gif",
175
+ ".mp4": "video/mp4", ".webm": "video/webm", ".mov": "video/quicktime",
176
+ };
177
+
178
+ /**
179
+ * One `Range: bytes=a-b` request against a file of `size` bytes: `[start, end]`,
180
+ * `undefined` without a (usable single) range, `null` when unsatisfiable.
181
+ */
182
+ const byteRange = (header, size) => {
183
+ if (typeof header !== "string" || header === "") return undefined;
184
+ const match = /^bytes=(\d*)-(\d*)$/.exec(header.trim());
185
+ if (match === null || (match[1] === "" && match[2] === "")) return undefined;
186
+ let start;
187
+ let end;
188
+ if (match[1] === "") {
189
+ const suffix = Number(match[2]);
190
+ if (suffix === 0) return null;
191
+ start = Math.max(0, size - suffix);
192
+ end = size - 1;
193
+ } else {
194
+ start = Number(match[1]);
195
+ end = match[2] === "" ? size - 1 : Math.min(Number(match[2]), size - 1);
196
+ }
197
+ if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end) || start > end || start >= size) return null;
198
+ return [start, end];
199
+ };
200
+
201
+ return { mediaStatus, saveMedia, mediaSessions, mediaChoices, mediaChoicesFor, mediaAccountsSummary, sessionView, saveSessionPick, MEDIA_FILE_TYPES, byteRange };
202
+ }
@@ -0,0 +1,42 @@
1
+ // Quota controller wiring through account facts and credential references.
2
+
3
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
4
+ import { dirname, join } from "node:path";
5
+ import { createQuotaController } from "../../quota/index.js";
6
+
7
+ export function createQuotaService(shared) {
8
+ const { ctx, resolveApiKey, describeApiKey, controller, updateDirectory } = shared;
9
+ // Quota ("额度" tab + composer badge): management keys live in the
10
+ // credentials service under their own refs, never in account state.
11
+ // Consecutive management-key rejections per account (never the key itself),
12
+ // so a wrong key stays stopped across reloads and restarts.
13
+ const quotaStatePath = join(updateDirectory, "quota-state.json");
14
+ const quota = createQuotaController({
15
+ authStore: {
16
+ read: () => (existsSync(quotaStatePath) ? JSON.parse(readFileSync(quotaStatePath, "utf8")) : undefined),
17
+ write: (value) => {
18
+ mkdirSync(dirname(quotaStatePath), { recursive: true });
19
+ const tmp = `${quotaStatePath}.${Date.now().toString(36)}.tmp`;
20
+ writeFileSync(tmp, `${JSON.stringify(value, null, 2)}\n`, "utf8");
21
+ renameSync(tmp, quotaStatePath);
22
+ },
23
+ },
24
+ listAccounts: () => controller.quotaAccounts(),
25
+ resolveKey: (ref) => resolveApiKey(ref),
26
+ describeKey: (ref) => describeApiKey(ref),
27
+ setKey: async (ref, value) => {
28
+ const credentials = ctx.get("credentials");
29
+ if (credentials === undefined) {
30
+ throw new Error("Credentials service is not available on this host");
31
+ }
32
+ await credentials.set(ref, value);
33
+ },
34
+ unsetKey: async (ref) => {
35
+ await ctx.get("credentials")?.unset(ref);
36
+ },
37
+ logger: ctx.logger,
38
+ });
39
+ ctx.effect(() => () => quota.dispose(), "cpa: quota");
40
+
41
+ return { quota };
42
+ }