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.
- package/CHANGELOG.md +23 -0
- package/README.en.md +24 -408
- package/README.md +24 -408
- package/lib/client.js +265 -27
- package/lib/host/accounts.js +178 -0
- package/lib/host/apply/agent-tool.js +406 -0
- package/lib/host/apply/commands.js +122 -0
- package/lib/host/apply/controller.js +121 -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 +50 -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 +210 -0
- package/lib/host/controller.js +464 -0
- package/lib/host/discovery.js +301 -0
- package/lib/host/http-gate.js +144 -0
- package/lib/host/model-info.js +363 -0
- package/lib/host/model-names.js +152 -0
- package/lib/host/models.js +75 -0
- package/lib/host/mount-guard.js +56 -0
- package/lib/host/recommend.js +367 -0
- package/lib/host/routes.js +165 -0
- package/lib/host/runtime.js +471 -0
- package/lib/host/state-store.js +39 -0
- package/lib/host/status-text.js +93 -0
- package/lib/index.js +18 -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,122 @@
|
|
|
1
|
+
// Slash-command registration and ordered command disposal; the generation
|
|
2
|
+
// commands follow the Generation tab's master switch (syncMediaCommands).
|
|
3
|
+
|
|
4
|
+
import { renderQuotaText, renderStatusText } from "../status-text.js";
|
|
5
|
+
|
|
6
|
+
export function createCommands(shared) {
|
|
7
|
+
const { ctx, controller, quota, readMedia, runImageCommand, runVideoCommand, runVideoEditCommand, runVideoStatusCommand, syncAgentTool } = shared;
|
|
8
|
+
// The generation slash commands (registered only while generation is on).
|
|
9
|
+
let commandsCtx;
|
|
10
|
+
let mediaCommandsOff;
|
|
11
|
+
|
|
12
|
+
/**
|
|
13
|
+
* Register or unregister /cpa-image and the /cpa-video* commands to match
|
|
14
|
+
* the Generation tab's master switch. Jobs already submitted keep running.
|
|
15
|
+
*/
|
|
16
|
+
const syncMediaCommands = () => {
|
|
17
|
+
let wanted = false;
|
|
18
|
+
try {
|
|
19
|
+
wanted = readMedia().settings.enabled === true;
|
|
20
|
+
} catch {
|
|
21
|
+
wanted = false;
|
|
22
|
+
}
|
|
23
|
+
if (wanted && mediaCommandsOff === undefined && commandsCtx !== undefined) {
|
|
24
|
+
try {
|
|
25
|
+
mediaCommandsOff = registerMediaCommands(commandsCtx);
|
|
26
|
+
ctx.logger?.info?.("cpa: generation commands registered");
|
|
27
|
+
} catch (error) {
|
|
28
|
+
ctx.logger?.warn?.(`cpa: could not register the generation commands: ${error instanceof Error ? error.message : String(error)}`);
|
|
29
|
+
}
|
|
30
|
+
} else if (!wanted && mediaCommandsOff !== undefined) {
|
|
31
|
+
const off = mediaCommandsOff;
|
|
32
|
+
mediaCommandsOff = undefined;
|
|
33
|
+
try {
|
|
34
|
+
off();
|
|
35
|
+
} catch {
|
|
36
|
+
// already gone with its scope
|
|
37
|
+
}
|
|
38
|
+
ctx.logger?.info?.("cpa: generation commands unregistered");
|
|
39
|
+
}
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
// Register slash commands (/cpa-status, /cpa-refresh)
|
|
43
|
+
ctx.inject(["commands"], (cmdCtx) => {
|
|
44
|
+
cmdCtx.effect(() => {
|
|
45
|
+
const offStatus = cmdCtx.commands.register({
|
|
46
|
+
name: "cpa-status",
|
|
47
|
+
description: "Show CLIProxyAPI discovery and model synchronization status of every account.",
|
|
48
|
+
handler: async () => {
|
|
49
|
+
const payload = await controller.statusPayload();
|
|
50
|
+
const quotaText = renderQuotaText(await quota.snapshot());
|
|
51
|
+
return { kind: "success", text: [renderStatusText(payload), quotaText].filter(Boolean).join("\n\n") };
|
|
52
|
+
},
|
|
53
|
+
});
|
|
54
|
+
const offRefresh = cmdCtx.commands.register({
|
|
55
|
+
name: "cpa-refresh",
|
|
56
|
+
description: "Probe every CLIProxyAPI account now and refresh the synchronized DSH model catalog.",
|
|
57
|
+
handler: async () => {
|
|
58
|
+
const payload = await controller.refresh(undefined);
|
|
59
|
+
syncAgentTool();
|
|
60
|
+
const failed = payload.accounts.some((a) => a.status.state === "error");
|
|
61
|
+
return { kind: failed ? "error" : "success", text: renderStatusText(payload) };
|
|
62
|
+
},
|
|
63
|
+
});
|
|
64
|
+
commandsCtx = cmdCtx;
|
|
65
|
+
syncMediaCommands();
|
|
66
|
+
return () => {
|
|
67
|
+
offStatus?.();
|
|
68
|
+
offRefresh?.();
|
|
69
|
+
commandsCtx = undefined;
|
|
70
|
+
const off = mediaCommandsOff;
|
|
71
|
+
mediaCommandsOff = undefined;
|
|
72
|
+
try {
|
|
73
|
+
off?.();
|
|
74
|
+
} catch {
|
|
75
|
+
// disposed with its scope
|
|
76
|
+
}
|
|
77
|
+
};
|
|
78
|
+
}, "cpa: commands");
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
/** The generation commands, registered only while generation is switched on (see syncMediaCommands). */
|
|
82
|
+
function registerMediaCommands(cmdCtx) {
|
|
83
|
+
const offVideo = cmdCtx.commands.register({
|
|
84
|
+
name: "cpa-video",
|
|
85
|
+
description: "Generate a video with a CLIProxyAPI video model: text only, one image as the first frame, reference images (--ref, or 2+ images), or pinned first / last frames (--first-last, --last). A submitted video cannot be cancelled.",
|
|
86
|
+
input: { hint: "[-m <model>] [--aspect 16:9] [-s 1-15] [-r 480p|720p] [--ref|--first-last|--last] <prompt>", attachments: true },
|
|
87
|
+
handler: runVideoCommand,
|
|
88
|
+
});
|
|
89
|
+
const offVideoEdit = cmdCtx.commands.register({
|
|
90
|
+
name: "cpa-video-edit",
|
|
91
|
+
description: "Edit any MP4 of up to 8.7 s with grok-imagine-video: attach it, or pass --video <path>, --url <public URL> or --from <command id> (default: this session's newest video). A submitted video cannot be cancelled.",
|
|
92
|
+
input: { hint: "[--video <path> | --url <URL> | --from <command id>] [-m <model>] <what to change>", attachments: true },
|
|
93
|
+
handler: runVideoEditCommand("edit"),
|
|
94
|
+
});
|
|
95
|
+
const offVideoExtend = cmdCtx.commands.register({
|
|
96
|
+
name: "cpa-video-extend",
|
|
97
|
+
description: "Continue any MP4 of 2-15 s by 2-10 seconds: attach it, or pass --video <path>, --url <public URL> or --from <command id> (default: this session's newest video). A submitted video cannot be cancelled.",
|
|
98
|
+
input: { hint: "[--video <path> | --url <URL> | --from <command id>] [-m <model>] [-s 2-10] <what happens next>", attachments: true },
|
|
99
|
+
handler: runVideoEditCommand("extend"),
|
|
100
|
+
});
|
|
101
|
+
const offVideoStatus = cmdCtx.commands.register({
|
|
102
|
+
name: "cpa-video-status",
|
|
103
|
+
description: "List this session's CLIProxyAPI video jobs and their state.",
|
|
104
|
+
handler: runVideoStatusCommand,
|
|
105
|
+
});
|
|
106
|
+
const offImage = cmdCtx.commands.register({
|
|
107
|
+
name: "cpa-image",
|
|
108
|
+
description: "Generate an image with a CLIProxyAPI image model; attach images to edit them. Files go to the session's working directory.",
|
|
109
|
+
input: { hint: "[-m <model>] [--aspect 16:9] [-n 1-4] <prompt>", attachments: true },
|
|
110
|
+
handler: runImageCommand,
|
|
111
|
+
});
|
|
112
|
+
return () => {
|
|
113
|
+
offImage?.();
|
|
114
|
+
offVideo?.();
|
|
115
|
+
offVideoStatus?.();
|
|
116
|
+
offVideoEdit?.();
|
|
117
|
+
offVideoExtend?.();
|
|
118
|
+
};
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
return { syncMediaCommands };
|
|
122
|
+
}
|
|
@@ -0,0 +1,121 @@
|
|
|
1
|
+
// Credentials, media preferences, online model info, account controller and refresh scheduling.
|
|
2
|
+
|
|
3
|
+
import { existsSync } from "node:fs";
|
|
4
|
+
import { join } from "node:path";
|
|
5
|
+
import { accountKindOverrides, loadMediaSettings } from "../../media/index.js";
|
|
6
|
+
import { outsideHmrTransaction } from "../apply-utils.js";
|
|
7
|
+
import { toCredentialRef, getEnvValue } from "../config.js";
|
|
8
|
+
import { createCpaController } from "../controller.js";
|
|
9
|
+
import { createModelInfo } from "../model-info.js";
|
|
10
|
+
|
|
11
|
+
export function createController(shared) {
|
|
12
|
+
const { ctx, readExistingPiAiRoute, readDefaultModel, readState, writeState, updateDirectory } = shared;
|
|
13
|
+
shared.timer = undefined;
|
|
14
|
+
shared.startupTimeout = undefined;
|
|
15
|
+
|
|
16
|
+
const resolveApiKey = async (refName) => {
|
|
17
|
+
try {
|
|
18
|
+
const ref = toCredentialRef(refName);
|
|
19
|
+
const credentials = ctx.get("credentials");
|
|
20
|
+
const stored = credentials === undefined ? undefined : await credentials.resolve(ref);
|
|
21
|
+
const raw = stored?.value ?? getEnvValue(ctx, ref);
|
|
22
|
+
const value = raw?.trim();
|
|
23
|
+
return value === undefined || value === "" ? undefined : value;
|
|
24
|
+
} catch {
|
|
25
|
+
return undefined;
|
|
26
|
+
}
|
|
27
|
+
};
|
|
28
|
+
|
|
29
|
+
const describeApiKey = async (refName) => {
|
|
30
|
+
try {
|
|
31
|
+
const ref = toCredentialRef(refName);
|
|
32
|
+
const credentials = ctx.get("credentials");
|
|
33
|
+
if (credentials !== undefined) {
|
|
34
|
+
return await credentials.describe(ref);
|
|
35
|
+
}
|
|
36
|
+
const envVal = getEnvValue(ctx, ref);
|
|
37
|
+
return {
|
|
38
|
+
configured: envVal !== undefined && envVal.length > 0,
|
|
39
|
+
writable: false,
|
|
40
|
+
};
|
|
41
|
+
} catch {
|
|
42
|
+
return { configured: false, writable: true };
|
|
43
|
+
}
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
const reschedule = () => {
|
|
47
|
+
if (shared.timer !== undefined) clearInterval(shared.timer);
|
|
48
|
+
shared.timer = outsideHmrTransaction(ctx, () =>
|
|
49
|
+
setInterval(() => {
|
|
50
|
+
void controller.refreshAll().finally(() => shared.syncAgentTool());
|
|
51
|
+
}, readState().refreshIntervalSeconds * 1000)
|
|
52
|
+
);
|
|
53
|
+
};
|
|
54
|
+
|
|
55
|
+
// Media preferences (lib/media/settings.js) live in their own file next to the
|
|
56
|
+
// account state, never inside it, so no state migration is involved.
|
|
57
|
+
const mediaSettingsPath = join(updateDirectory, "media-settings.json");
|
|
58
|
+
let mediaWarned = false;
|
|
59
|
+
// Generation is off for a new profile; one that already picked a model or
|
|
60
|
+
// generated something before the switch existed (session or job file, no
|
|
61
|
+
// readable settings file) keeps it on.
|
|
62
|
+
const mediaUsedBefore = () =>
|
|
63
|
+
existsSync(join(updateDirectory, "media-sessions.json")) || existsSync(join(updateDirectory, "media-jobs.json"));
|
|
64
|
+
const readMedia = () => {
|
|
65
|
+
const loaded = loadMediaSettings(mediaSettingsPath);
|
|
66
|
+
if ((loaded.error !== undefined || !existsSync(mediaSettingsPath)) && mediaUsedBefore()) {
|
|
67
|
+
loaded.settings = { ...loaded.settings, enabled: true };
|
|
68
|
+
}
|
|
69
|
+
if (loaded.error === undefined) {
|
|
70
|
+
mediaWarned = false;
|
|
71
|
+
} else if (!mediaWarned) {
|
|
72
|
+
mediaWarned = true;
|
|
73
|
+
ctx.logger?.warn?.(
|
|
74
|
+
`dsh-cliproxyapi: ${mediaSettingsPath} is unreadable; default media settings apply until it is saved again (the damaged file is then kept as *.corrupt-*.json)`
|
|
75
|
+
);
|
|
76
|
+
}
|
|
77
|
+
return loaded;
|
|
78
|
+
};
|
|
79
|
+
|
|
80
|
+
// Public model catalogs for recommendations (download only; global switch, default on).
|
|
81
|
+
// Timers live in lifecycle.js; new data re-syncs the accounts once.
|
|
82
|
+
const modelInfo = createModelInfo({
|
|
83
|
+
cachePath: join(updateDirectory, "model-info.json"),
|
|
84
|
+
enabled: () => readState().onlineModelInfo !== false,
|
|
85
|
+
logger: ctx.logger,
|
|
86
|
+
onChange: () => {
|
|
87
|
+
void controller.refreshAll().finally(() => shared.syncAgentTool?.());
|
|
88
|
+
},
|
|
89
|
+
});
|
|
90
|
+
|
|
91
|
+
const controller = createCpaController({
|
|
92
|
+
settings: ctx.settings,
|
|
93
|
+
readState,
|
|
94
|
+
writeState,
|
|
95
|
+
modelInfo,
|
|
96
|
+
onModelInfoToggled: () => {
|
|
97
|
+
void modelInfo.refresh().finally(() => controller.refreshAll().finally(() => shared.syncAgentTool?.()));
|
|
98
|
+
},
|
|
99
|
+
mediaKindOverrides: (id) => accountKindOverrides(readMedia().settings, id),
|
|
100
|
+
resolveApiKey,
|
|
101
|
+
describeApiKey,
|
|
102
|
+
setCredential: async (ref, value) => {
|
|
103
|
+
const credentials = ctx.get("credentials");
|
|
104
|
+
if (credentials === undefined) {
|
|
105
|
+
throw new Error("Credentials service is not available on this host");
|
|
106
|
+
}
|
|
107
|
+
await credentials.set(ref, value);
|
|
108
|
+
},
|
|
109
|
+
unsetCredential: async (ref) => {
|
|
110
|
+
await ctx.get("credentials")?.unset(ref);
|
|
111
|
+
},
|
|
112
|
+
readExistingPiAiRoute,
|
|
113
|
+
readDefaultModel,
|
|
114
|
+
setTimeout: (fn, ms) => outsideHmrTransaction(ctx, () => setTimeout(fn, ms)),
|
|
115
|
+
environmentBaseURL: () => getEnvValue(ctx, "CLIPROXYAPI_BASE_URL"),
|
|
116
|
+
logger: ctx.logger,
|
|
117
|
+
onGlobalsChanged: () => reschedule(),
|
|
118
|
+
});
|
|
119
|
+
|
|
120
|
+
return { resolveApiKey, describeApiKey, reschedule, mediaSettingsPath, readMedia, controller, modelInfo };
|
|
121
|
+
}
|
|
@@ -0,0 +1,273 @@
|
|
|
1
|
+
// Ordered account/update/quota/media HTTP route registration and media file serving.
|
|
2
|
+
|
|
3
|
+
import { createReadStream, existsSync, readFileSync, statSync } from "node:fs";
|
|
4
|
+
import { basename, dirname, extname } from "node:path";
|
|
5
|
+
import { UpdateError } from "../../updater/index.js";
|
|
6
|
+
import { MediaError, validCommandId, validSessionId, EDIT_SOURCE_MAX_SECONDS, EXTEND_SOURCE_SECONDS, VIDEO_UPLOAD_MAX_BYTES } from "../../media/index.js";
|
|
7
|
+
import { plainObject } from "../accounts.js";
|
|
8
|
+
import { accountPatchFromInput } from "../apply-utils.js";
|
|
9
|
+
import { GLOBAL_FIELDS } from "../config.js";
|
|
10
|
+
import { ROUTES, sendJson, admitRequest, admitUpdateRequest, readJsonBody } from "../http-gate.js";
|
|
11
|
+
|
|
12
|
+
export function createHttpRoutes(shared) {
|
|
13
|
+
const { ctx, updater, controller, quota, mediaStatus, saveMedia, mediaSessions, mediaChoicesFor, sessionView, saveSessionPick, MEDIA_FILE_TYPES, byteRange, mediaFailureText, mediaJobs, videoLive, VIDEO_SOURCE_TTL_MS, usableSource, unsupportedRoutes, pendingConfirms, syncAgentTool } = shared;
|
|
14
|
+
// Register HTTP API Routes on webServer for the Web UI
|
|
15
|
+
ctx.inject(["webServer"], (webCtx) => {
|
|
16
|
+
webCtx.effect(() => {
|
|
17
|
+
const route = (path, method, run, errorStatus = 500) =>
|
|
18
|
+
webCtx.webServer.register({
|
|
19
|
+
kind: "exact",
|
|
20
|
+
path,
|
|
21
|
+
handler: async (req, res) => {
|
|
22
|
+
if (!admitRequest(ctx, req, res, method)) return;
|
|
23
|
+
try {
|
|
24
|
+
const body = method === "POST" ? (await readJsonBody(req)) ?? {} : {};
|
|
25
|
+
const result = await run(body, req);
|
|
26
|
+
// Account, model and Generation-tab changes may switch the agent tool on or off.
|
|
27
|
+
if (method === "POST") syncAgentTool();
|
|
28
|
+
sendJson(res, 200, result);
|
|
29
|
+
} catch (error) {
|
|
30
|
+
sendJson(res, errorStatus, {
|
|
31
|
+
ok: false,
|
|
32
|
+
error: error instanceof Error ? error.message : String(error),
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
},
|
|
36
|
+
});
|
|
37
|
+
const updateRoute = (path, method, run) => webCtx.webServer.register({
|
|
38
|
+
kind: "exact", path,
|
|
39
|
+
handler: async (req, res) => {
|
|
40
|
+
if (!admitUpdateRequest(ctx, req, res, method)) return;
|
|
41
|
+
try {
|
|
42
|
+
const body = method === "POST" ? await readJsonBody(req, 8192) : {};
|
|
43
|
+
if (!plainObject(body)) throw new UpdateError("invalid-settings");
|
|
44
|
+
if (path === ROUTES.updateDownload && (Object.keys(body).some((key) => key !== "version") || typeof body.version !== "string")) {
|
|
45
|
+
throw new UpdateError("stale-version");
|
|
46
|
+
}
|
|
47
|
+
if (path === ROUTES.updateCheck && Object.keys(body).length) throw new UpdateError("invalid-settings");
|
|
48
|
+
const update = await run(body);
|
|
49
|
+
sendJson(res, 200, { ok: true, update });
|
|
50
|
+
} catch (error) {
|
|
51
|
+
const errorCode = error instanceof UpdateError ? error.code : "invalid-settings";
|
|
52
|
+
sendJson(res, errorCode === "busy" ? 409 : 400, { ok: false, errorCode, error: errorCode, update: updater.status() });
|
|
53
|
+
}
|
|
54
|
+
},
|
|
55
|
+
});
|
|
56
|
+
const disposers = [
|
|
57
|
+
updateRoute(ROUTES.updateStatus, "GET", () => updater.status()),
|
|
58
|
+
updateRoute(ROUTES.updateCheck, "POST", () => updater.check()),
|
|
59
|
+
updateRoute(ROUTES.updateSave, "POST", (body) => updater.save(body)),
|
|
60
|
+
updateRoute(ROUTES.updateDownload, "POST", (body) => updater.download(body.version)),
|
|
61
|
+
route(ROUTES.status, "GET", () => controller.statusPayload()),
|
|
62
|
+
route(ROUTES.refresh, "POST", (body) => controller.refresh(body.accountId)),
|
|
63
|
+
route(
|
|
64
|
+
ROUTES.save,
|
|
65
|
+
"POST",
|
|
66
|
+
(body) => {
|
|
67
|
+
const patch = accountPatchFromInput(body);
|
|
68
|
+
const hasAccountFields = Object.keys(patch).some((k) => !GLOBAL_FIELDS.includes(k));
|
|
69
|
+
return body.accountId === undefined && !hasAccountFields
|
|
70
|
+
? controller.updateGlobals(patch)
|
|
71
|
+
: controller.updateAccount(body.accountId, patch);
|
|
72
|
+
},
|
|
73
|
+
400
|
|
74
|
+
),
|
|
75
|
+
route(ROUTES.addAccount, "POST", (body) => controller.addAccount(accountPatchFromInput(body)), 400),
|
|
76
|
+
route(ROUTES.removeAccount, "POST", (body) => controller.removeAccount(body.accountId), 400),
|
|
77
|
+
route(ROUTES.testAccount, "POST", (body) => controller.testConnection(body.accountId, { baseURL: body.baseURL, apiKey: body.apiKey }), 400),
|
|
78
|
+
route(ROUTES.quotaStatus, "GET", async () => ({ ok: true, quota: await quota.snapshot() })),
|
|
79
|
+
route(ROUTES.quotaRefresh, "POST", async (body) => ({
|
|
80
|
+
ok: true,
|
|
81
|
+
quota: await quota.refresh(typeof body.accountId === "string" && body.accountId !== "" ? body.accountId : undefined, { wait: false }),
|
|
82
|
+
})),
|
|
83
|
+
route(
|
|
84
|
+
ROUTES.quotaSave,
|
|
85
|
+
"POST",
|
|
86
|
+
async (body) => {
|
|
87
|
+
if (typeof body.accountId !== "string" || body.accountId === "") {
|
|
88
|
+
throw new Error("dsh-cliproxyapi: saving a management key needs accountId");
|
|
89
|
+
}
|
|
90
|
+
const managementKey = typeof body.managementKey === "string" ? body.managementKey.trim() : "";
|
|
91
|
+
return {
|
|
92
|
+
ok: true,
|
|
93
|
+
quota: await quota.saveKey(body.accountId, {
|
|
94
|
+
...(managementKey === "" ? {} : { managementKey }),
|
|
95
|
+
...(body.clear === true ? { clear: true } : {}),
|
|
96
|
+
}, { wait: false }),
|
|
97
|
+
};
|
|
98
|
+
},
|
|
99
|
+
400
|
|
100
|
+
),
|
|
101
|
+
route(ROUTES.mediaStatus, "GET", async () => ({ ok: true, media: mediaStatus() })),
|
|
102
|
+
route(ROUTES.mediaSave, "POST", saveMedia, 400),
|
|
103
|
+
route(
|
|
104
|
+
ROUTES.mediaDiagnose,
|
|
105
|
+
"POST",
|
|
106
|
+
async (body) => {
|
|
107
|
+
if (typeof body.accountId !== "string" || body.accountId === "") throw new MediaError("invalid-account");
|
|
108
|
+
return { ok: true, diagnostic: await controller.diagnoseMedia(body.accountId) };
|
|
109
|
+
},
|
|
110
|
+
400
|
|
111
|
+
),
|
|
112
|
+
route(
|
|
113
|
+
ROUTES.mediaSession,
|
|
114
|
+
"GET",
|
|
115
|
+
async (_body, req) => {
|
|
116
|
+
const raw = new URL(req.url ?? "/", "http://host").searchParams.get("sessionId");
|
|
117
|
+
const sessionId = raw === null || raw === "" ? undefined : validSessionId(raw);
|
|
118
|
+
if (raw !== null && raw !== "" && sessionId === undefined) throw new MediaError("invalid-session");
|
|
119
|
+
// Right after a start the catalogs may not be read yet; sync once
|
|
120
|
+
// instead of letting the composer button wait for its next retry.
|
|
121
|
+
await mediaChoicesFor("any");
|
|
122
|
+
return { ok: true, session: sessionView(sessionId) };
|
|
123
|
+
},
|
|
124
|
+
400
|
|
125
|
+
),
|
|
126
|
+
route(ROUTES.mediaSessionSave, "POST", async (body) => saveSessionPick(body), 400),
|
|
127
|
+
// The user's answer to a generate_media confirmation shown in its chat row.
|
|
128
|
+
route(
|
|
129
|
+
ROUTES.mediaConfirm,
|
|
130
|
+
"POST",
|
|
131
|
+
async (body) => {
|
|
132
|
+
const sessionId = validSessionId(body.sessionId);
|
|
133
|
+
const commandId = validCommandId(body.commandId);
|
|
134
|
+
if (sessionId === undefined || commandId === undefined || typeof body.allow !== "boolean") throw new MediaError("invalid-request");
|
|
135
|
+
const waiting = pendingConfirms.get(commandId);
|
|
136
|
+
if (waiting === undefined || waiting.sessionId !== sessionId) throw new MediaError("confirm-expired");
|
|
137
|
+
waiting.settle(body.allow ? "allowed" : "rejected");
|
|
138
|
+
return { ok: true };
|
|
139
|
+
},
|
|
140
|
+
400
|
|
141
|
+
),
|
|
142
|
+
// One slash-command run's record and files (its chat row shows them).
|
|
143
|
+
// The absolute paths let the page open or reveal a file through DSH's
|
|
144
|
+
// own Session Remote (`session.openWorkspacePath`), which re-verifies
|
|
145
|
+
// them on the Host.
|
|
146
|
+
route(
|
|
147
|
+
ROUTES.mediaCommand,
|
|
148
|
+
"GET",
|
|
149
|
+
async (_body, req) => {
|
|
150
|
+
const params = new URL(req.url ?? "/", "http://host").searchParams;
|
|
151
|
+
const sessionId = validSessionId(params.get("sessionId") ?? "");
|
|
152
|
+
const commandId = validCommandId(params.get("commandId") ?? "");
|
|
153
|
+
if (sessionId === undefined || commandId === undefined) throw new MediaError("invalid-request");
|
|
154
|
+
const entry = mediaSessions.get(sessionId);
|
|
155
|
+
const files = entry.recent
|
|
156
|
+
.filter((r) => r.commandId === commandId && existsSync(r.file))
|
|
157
|
+
.map((r) => ({ id: r.id, kind: r.kind, name: basename(r.file), path: r.file }));
|
|
158
|
+
let run = entry.runs.find((r) => r.commandId === commandId) ?? null;
|
|
159
|
+
// A run recorded as running that no job of this activation owns was
|
|
160
|
+
// cut off by a reload or a restart.
|
|
161
|
+
if (run?.status === "running" && !mediaJobs.has(commandId)) {
|
|
162
|
+
run = { ...run, status: "error", errorCode: "interrupted", error: mediaFailureText(new MediaError("interrupted"), run.kind) };
|
|
163
|
+
} else if (run?.status === "running" && videoLive.has(commandId)) {
|
|
164
|
+
// A video's phase (submitting / queued / running / downloading) and CPA's progress, if it reports one.
|
|
165
|
+
run = { ...run, ...videoLive.get(commandId) };
|
|
166
|
+
}
|
|
167
|
+
// Which file manager "show in folder" opens, to name the menu item.
|
|
168
|
+
const desktop = process.platform === "win32" ? "explorer" : process.platform === "darwin" ? "finder" : "filemanager";
|
|
169
|
+
// Edit / extend this video: by xAI's short-lived link while it is
|
|
170
|
+
// remembered, else by sending its file inline when small enough.
|
|
171
|
+
let actions;
|
|
172
|
+
// Past results stay visible with generation off, without the edit / extend actions.
|
|
173
|
+
if (run?.kind === "video" && run.status === "done" && shared.readMedia().settings.enabled === true) {
|
|
174
|
+
const source = usableSource(commandId);
|
|
175
|
+
const video = files.find((f) => f.kind === "video");
|
|
176
|
+
let size;
|
|
177
|
+
try {
|
|
178
|
+
size = video === undefined ? undefined : statSync(video.path).size;
|
|
179
|
+
} catch {
|
|
180
|
+
size = undefined;
|
|
181
|
+
}
|
|
182
|
+
if (source !== undefined || (size !== undefined && size <= VIDEO_UPLOAD_MAX_BYTES)) {
|
|
183
|
+
const seconds = source?.seconds ?? run.seconds;
|
|
184
|
+
const accountId = source?.accountId ?? String(run.model).split("/", 1)[0];
|
|
185
|
+
actions = {
|
|
186
|
+
edit: seconds === undefined || seconds <= EDIT_SOURCE_MAX_SECONDS,
|
|
187
|
+
extend:
|
|
188
|
+
(seconds === undefined || (seconds >= EXTEND_SOURCE_SECONDS.min && seconds <= EXTEND_SOURCE_SECONDS.max)) &&
|
|
189
|
+
!unsupportedRoutes.has(`${accountId}/extensions`),
|
|
190
|
+
...(source === undefined ? {} : { expiresAt: new Date(source.at + VIDEO_SOURCE_TTL_MS).toISOString() }),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
// A generate_media call waiting for the user's confirmation in this row.
|
|
195
|
+
const waiting = pendingConfirms.get(commandId);
|
|
196
|
+
const confirm = waiting !== undefined && waiting.sessionId === sessionId ? { kind: waiting.kind, en: waiting.en, zh: waiting.zh, expiresAt: waiting.expiresAt } : undefined;
|
|
197
|
+
return {
|
|
198
|
+
ok: true,
|
|
199
|
+
run,
|
|
200
|
+
files,
|
|
201
|
+
desktop,
|
|
202
|
+
...(files.length > 0 ? { folderPath: dirname(files[0].path) } : {}),
|
|
203
|
+
...(actions === undefined ? {} : { actions }),
|
|
204
|
+
...(confirm === undefined ? {} : { confirm }),
|
|
205
|
+
};
|
|
206
|
+
},
|
|
207
|
+
400
|
|
208
|
+
),
|
|
209
|
+
// Serves only files this plugin wrote and recorded for that session.
|
|
210
|
+
webCtx.webServer.register({
|
|
211
|
+
kind: "exact",
|
|
212
|
+
path: ROUTES.mediaFile,
|
|
213
|
+
handler: async (req, res) => {
|
|
214
|
+
if (!admitRequest(ctx, req, res, "GET")) return;
|
|
215
|
+
const params = new URL(req.url ?? "/", "http://host").searchParams;
|
|
216
|
+
const sessionId = validSessionId(params.get("sessionId") ?? "");
|
|
217
|
+
const record = sessionId === undefined ? undefined : mediaSessions.get(sessionId).recent.find((r) => r.id === params.get("id"));
|
|
218
|
+
const type = record === undefined ? undefined : MEDIA_FILE_TYPES[extname(record.file).toLowerCase()];
|
|
219
|
+
if (record === undefined || type === undefined || !existsSync(record.file)) {
|
|
220
|
+
sendJson(res, 404, { ok: false, error: "not-found" });
|
|
221
|
+
return;
|
|
222
|
+
}
|
|
223
|
+
try {
|
|
224
|
+
if (!type.startsWith("video/")) {
|
|
225
|
+
const bytes = readFileSync(record.file);
|
|
226
|
+
res.writeHead(200, {
|
|
227
|
+
"cache-control": "no-store",
|
|
228
|
+
"content-type": type,
|
|
229
|
+
"content-length": String(bytes.byteLength),
|
|
230
|
+
"x-content-type-options": "nosniff",
|
|
231
|
+
});
|
|
232
|
+
res.end(bytes);
|
|
233
|
+
return;
|
|
234
|
+
}
|
|
235
|
+
// Videos are streamed, with single byte ranges so <video> can seek.
|
|
236
|
+
const size = statSync(record.file).size;
|
|
237
|
+
const range = byteRange(req.headers?.range, size);
|
|
238
|
+
if (range === null) {
|
|
239
|
+
res.writeHead(416, { "content-range": `bytes */${size}` });
|
|
240
|
+
res.end();
|
|
241
|
+
return;
|
|
242
|
+
}
|
|
243
|
+
const [start, end] = range ?? [0, size - 1];
|
|
244
|
+
res.writeHead(range === undefined ? 200 : 206, {
|
|
245
|
+
"cache-control": "no-store",
|
|
246
|
+
"content-type": type,
|
|
247
|
+
"accept-ranges": "bytes",
|
|
248
|
+
"content-length": String(size === 0 ? 0 : end - start + 1),
|
|
249
|
+
...(range === undefined ? {} : { "content-range": `bytes ${start}-${end}/${size}` }),
|
|
250
|
+
"x-content-type-options": "nosniff",
|
|
251
|
+
});
|
|
252
|
+
if (size === 0) {
|
|
253
|
+
res.end();
|
|
254
|
+
return;
|
|
255
|
+
}
|
|
256
|
+
const stream = createReadStream(record.file, { start, end });
|
|
257
|
+
stream.on("error", () => res.destroy?.());
|
|
258
|
+
res.on?.("close", () => stream.destroy());
|
|
259
|
+
stream.pipe(res);
|
|
260
|
+
} catch {
|
|
261
|
+
sendJson(res, 404, { ok: false, error: "not-found" });
|
|
262
|
+
}
|
|
263
|
+
},
|
|
264
|
+
}),
|
|
265
|
+
];
|
|
266
|
+
return () => {
|
|
267
|
+
for (const dispose of disposers) dispose?.();
|
|
268
|
+
};
|
|
269
|
+
}, "cpa: webserver routes");
|
|
270
|
+
});
|
|
271
|
+
|
|
272
|
+
return {};
|
|
273
|
+
}
|