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.
- package/CHANGELOG.md +23 -0
- package/README.en.md +38 -409
- package/README.md +38 -409
- package/lib/client.js +131 -28
- package/lib/host/accounts.js +176 -0
- package/lib/host/apply/agent-tool.js +406 -0
- package/lib/host/apply/commands.js +122 -0
- package/lib/host/apply/controller.js +105 -0
- package/lib/host/apply/http-routes.js +273 -0
- package/lib/host/apply/image-jobs.js +171 -0
- package/lib/host/apply/index.js +41 -0
- package/lib/host/apply/interpret.js +72 -0
- package/lib/host/apply/lifecycle.js +34 -0
- package/lib/host/apply/media-failures.js +68 -0
- package/lib/host/apply/media-service.js +202 -0
- package/lib/host/apply/quota-service.js +42 -0
- package/lib/host/apply/references.js +43 -0
- package/lib/host/apply/session-status.js +104 -0
- package/lib/host/apply/state.js +78 -0
- package/lib/host/apply/updates.js +55 -0
- package/lib/host/apply/video-command.js +152 -0
- package/lib/host/apply/video-edit.js +253 -0
- package/lib/host/apply/video-jobs.js +206 -0
- package/lib/host/apply-utils.js +39 -0
- package/lib/host/config.js +205 -0
- package/lib/host/controller.js +435 -0
- package/lib/host/discovery.js +295 -0
- package/lib/host/http-gate.js +144 -0
- package/lib/host/models.js +102 -0
- package/lib/host/mount-guard.js +56 -0
- package/lib/host/routes.js +165 -0
- package/lib/host/runtime.js +445 -0
- package/lib/host/state-store.js +39 -0
- package/lib/host/status-text.js +93 -0
- package/lib/index.js +17 -4330
- 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 -2528
- package/lib/quota.js +0 -1646
- package/lib/updater.js +0 -443
|
@@ -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
|
+
}
|
|
@@ -0,0 +1,43 @@
|
|
|
1
|
+
// Bounded attachment references and optional request-image resizing.
|
|
2
|
+
|
|
3
|
+
import { MediaError, fitReferenceImage, REFERENCE_MAX_EDGE } from "../../media/index.js";
|
|
4
|
+
|
|
5
|
+
export function createReferences(shared) {
|
|
6
|
+
// Request bodies carry references base64-encoded and upstreams cap the body
|
|
7
|
+
// (xAI: "Failed to read request body: length limit exceeded"). Video
|
|
8
|
+
// requests use the measured `videoImageBudget()`; image edits keep this
|
|
9
|
+
// unmeasured share.
|
|
10
|
+
const FIRST_FRAME_MAX_BYTES = 1_000_000;
|
|
11
|
+
const REFERENCES_MAX_BYTES = 1_400_000;
|
|
12
|
+
|
|
13
|
+
/**
|
|
14
|
+
* One attached image within `maxBytes`: as stored when it fits; a PNG is
|
|
15
|
+
* re-encoded here (JPEG on white, long edge ≤ 1280); another format asks
|
|
16
|
+
* DSH's attachment store for a smaller request version.
|
|
17
|
+
* @throws MediaError `reference-too-large`.
|
|
18
|
+
*/
|
|
19
|
+
const readReference = async (store, block, maxBytes, signal) => {
|
|
20
|
+
const stored = await store.readImage(block.attachment, signal);
|
|
21
|
+
const image = { mediaType: stored.ref?.mediaType ?? block.attachment?.mediaType, data: stored.data };
|
|
22
|
+
const fitted = fitReferenceImage(image, maxBytes);
|
|
23
|
+
if (fitted !== undefined) return { mediaType: fitted.mediaType, data: fitted.data };
|
|
24
|
+
const width = Number(stored.ref?.width ?? block.attachment?.width);
|
|
25
|
+
const height = Number(stored.ref?.height ?? block.attachment?.height);
|
|
26
|
+
if (typeof store.readImageRequest === "function" && width > 0 && height > 0) {
|
|
27
|
+
const scale = Math.min(1, REFERENCE_MAX_EDGE / Math.max(width, height));
|
|
28
|
+
try {
|
|
29
|
+
const smaller = await store.readImageRequest(
|
|
30
|
+
block.attachment,
|
|
31
|
+
{ width: Math.max(1, Math.round(width * scale)), height: Math.max(1, Math.round(height * scale)), maxBytes },
|
|
32
|
+
signal
|
|
33
|
+
);
|
|
34
|
+
if (smaller?.data?.byteLength <= maxBytes) return { mediaType: smaller.mediaType, data: smaller.data };
|
|
35
|
+
} catch (error) {
|
|
36
|
+
if (signal?.aborted) throw error;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
throw new MediaError("reference-too-large", String(Math.round(maxBytes / 1000)));
|
|
40
|
+
};
|
|
41
|
+
|
|
42
|
+
return { FIRST_FRAME_MAX_BYTES, REFERENCES_MAX_BYTES, readReference };
|
|
43
|
+
}
|
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
// Activation job tracking, session-status heartbeat and generation run recording.
|
|
2
|
+
|
|
3
|
+
import { basename, isAbsolute, relative, sep } from "node:path";
|
|
4
|
+
import { MediaError } from "../../media/index.js";
|
|
5
|
+
|
|
6
|
+
export function createSessionStatus(shared) {
|
|
7
|
+
const { ctx, mediaSessions } = shared;
|
|
8
|
+
// #region Background generation jobs and the session's "running" state
|
|
9
|
+
//
|
|
10
|
+
// `/cpa-image` returns as soon as the request is admitted, so the composer
|
|
11
|
+
// clears the draft at once; the generation continues here and its chat row
|
|
12
|
+
// follows it through `media/command`. DSH counts only agent turns as
|
|
13
|
+
// running, so while a job runs this plugin publishes the host's own
|
|
14
|
+
// `api-session/status` event for that session (the workspace list shows it
|
|
15
|
+
// as running, then completed). It is republished every few seconds and
|
|
16
|
+
// after the agent itself goes idle, because those reset it to idle.
|
|
17
|
+
|
|
18
|
+
const mediaJobs = new Map(); // job key → { sessionId, abort }
|
|
19
|
+
// job key → the promise of a job of this activation, until it settles (the agent tool waits on it).
|
|
20
|
+
const jobPromises = new Map();
|
|
21
|
+
const settleWith = (key, promise) => {
|
|
22
|
+
jobPromises.set(key, promise);
|
|
23
|
+
void promise.finally(() => {
|
|
24
|
+
if (jobPromises.get(key) === promise) jobPromises.delete(key);
|
|
25
|
+
});
|
|
26
|
+
return promise;
|
|
27
|
+
};
|
|
28
|
+
shared.mediaJobSeq = 0;
|
|
29
|
+
let mediaHeartbeat;
|
|
30
|
+
const MEDIA_HEARTBEAT_MS = 5000;
|
|
31
|
+
const jobSessions = () => new Set([...mediaJobs.values()].map((job) => job.sessionId).filter(Boolean));
|
|
32
|
+
const agentRunning = (sessionId) => {
|
|
33
|
+
try {
|
|
34
|
+
return ctx.get?.("agents")?.get?.(sessionId)?.status === "running";
|
|
35
|
+
} catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
};
|
|
39
|
+
const publishSessionStatus = (sessionId, running) => {
|
|
40
|
+
if (typeof ctx.emit !== "function") return;
|
|
41
|
+
try {
|
|
42
|
+
ctx.emit("api-session/status", sessionId, running);
|
|
43
|
+
} catch (error) {
|
|
44
|
+
ctx.logger?.warn?.(`cpa: could not publish the session status: ${error instanceof Error ? error.message : String(error)}`);
|
|
45
|
+
}
|
|
46
|
+
};
|
|
47
|
+
const settleSessionStatus = (sessionId) => {
|
|
48
|
+
if (sessionId === undefined || jobSessions().has(sessionId) || agentRunning(sessionId)) return;
|
|
49
|
+
publishSessionStatus(sessionId, false);
|
|
50
|
+
};
|
|
51
|
+
const syncHeartbeat = () => {
|
|
52
|
+
if (mediaJobs.size > 0 && mediaHeartbeat === undefined) {
|
|
53
|
+
mediaHeartbeat = setInterval(() => {
|
|
54
|
+
for (const sessionId of jobSessions()) publishSessionStatus(sessionId, true);
|
|
55
|
+
}, MEDIA_HEARTBEAT_MS);
|
|
56
|
+
mediaHeartbeat.unref?.();
|
|
57
|
+
} else if (mediaJobs.size === 0 && mediaHeartbeat !== undefined) {
|
|
58
|
+
clearInterval(mediaHeartbeat);
|
|
59
|
+
mediaHeartbeat = undefined;
|
|
60
|
+
}
|
|
61
|
+
};
|
|
62
|
+
ctx.on?.("agent/status", (event) => {
|
|
63
|
+
const sessionId = event?.agent?.id;
|
|
64
|
+
if (event?.status === "running" || !jobSessions().has(sessionId)) return;
|
|
65
|
+
// After the host's own idle notice for this transition.
|
|
66
|
+
setTimeout(() => {
|
|
67
|
+
if (jobSessions().has(sessionId)) publishSessionStatus(sessionId, true);
|
|
68
|
+
}, 0);
|
|
69
|
+
});
|
|
70
|
+
ctx.effect(
|
|
71
|
+
() => () => {
|
|
72
|
+
const sessions = jobSessions();
|
|
73
|
+
for (const job of mediaJobs.values()) job.abort.abort(new MediaError("interrupted"));
|
|
74
|
+
mediaJobs.clear();
|
|
75
|
+
syncHeartbeat();
|
|
76
|
+
for (const sessionId of sessions) settleSessionStatus(sessionId);
|
|
77
|
+
},
|
|
78
|
+
"cpa: generation jobs"
|
|
79
|
+
);
|
|
80
|
+
|
|
81
|
+
/** Update one run record (and prepend new recent outputs) in the session store; never throws. */
|
|
82
|
+
const recordRun = (sessionId, commandId, patch, recent = []) => {
|
|
83
|
+
if (sessionId === undefined) return;
|
|
84
|
+
try {
|
|
85
|
+
mediaSessions.update(sessionId, (entry) => {
|
|
86
|
+
if (recent.length > 0) entry.recent = [...recent, ...entry.recent];
|
|
87
|
+
if (commandId === undefined) return;
|
|
88
|
+
const index = entry.runs.findIndex((run) => run.commandId === commandId);
|
|
89
|
+
if (index >= 0) entry.runs[index] = { ...entry.runs[index], ...patch };
|
|
90
|
+
else entry.runs = [{ commandId, ...patch }, ...entry.runs];
|
|
91
|
+
});
|
|
92
|
+
} catch (error) {
|
|
93
|
+
ctx.logger?.warn?.(`cpa: could not record a generation result: ${error instanceof Error ? error.message : String(error)}`);
|
|
94
|
+
}
|
|
95
|
+
};
|
|
96
|
+
|
|
97
|
+
/** How the chat row names the save folder: relative to the working directory when inside it. */
|
|
98
|
+
const folderLabel = (cwd, dir) => {
|
|
99
|
+
const rel = relative(cwd, dir);
|
|
100
|
+
return rel !== "" && !rel.startsWith("..") && !isAbsolute(rel) ? rel.split(sep).join("/") : basename(dir);
|
|
101
|
+
};
|
|
102
|
+
|
|
103
|
+
return { mediaJobs, jobPromises, settleWith, publishSessionStatus, settleSessionStatus, syncHeartbeat, recordRun, folderLabel };
|
|
104
|
+
}
|
|
@@ -0,0 +1,78 @@
|
|
|
1
|
+
// Account state migration, curated-route seeding and fresh state access.
|
|
2
|
+
|
|
3
|
+
import { normalizeState, mergeHostConfig } from "../accounts.js";
|
|
4
|
+
import { PI_AI_NS, DEFAULT_MODEL_NS } from "../config.js";
|
|
5
|
+
import { managedRouteKeys } from "../routes.js";
|
|
6
|
+
import { resolveStateFilePath, loadPersistedState, savePersistedState } from "../state-store.js";
|
|
7
|
+
|
|
8
|
+
export function createState(shared) {
|
|
9
|
+
const { ctx, config } = shared;
|
|
10
|
+
const stateFilePath = resolveStateFilePath(ctx);
|
|
11
|
+
const persisted = loadPersistedState(stateFilePath);
|
|
12
|
+
|
|
13
|
+
const readExistingPiAiRoute = (provider) => {
|
|
14
|
+
try {
|
|
15
|
+
const descriptors = ctx.settings.describe();
|
|
16
|
+
const piAi = descriptors.find((d) => d.ns === PI_AI_NS);
|
|
17
|
+
return piAi?.value?.providers?.[provider];
|
|
18
|
+
} catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
const readDefaultModel = () => {
|
|
24
|
+
try {
|
|
25
|
+
const value = ctx.settings.describe().find((d) => d.ns === DEFAULT_MODEL_NS)?.value;
|
|
26
|
+
return typeof value?.provider === "string" && typeof value?.model === "string"
|
|
27
|
+
? { provider: value.provider, model: value.model }
|
|
28
|
+
: undefined;
|
|
29
|
+
} catch {
|
|
30
|
+
return undefined;
|
|
31
|
+
}
|
|
32
|
+
};
|
|
33
|
+
|
|
34
|
+
// Seed a selection from every managed route, not just the base one, so a
|
|
35
|
+
// restart after protocol routing keeps Messages / Responses models checked.
|
|
36
|
+
const existingManagedIds = (provider) =>
|
|
37
|
+
managedRouteKeys(provider).flatMap((key) => {
|
|
38
|
+
const route = readExistingPiAiRoute(key);
|
|
39
|
+
return Array.isArray(route?.models)
|
|
40
|
+
? route.models.map((m) => m?.id).filter((id) => typeof id === "string" && id.trim() !== "")
|
|
41
|
+
: [];
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
// Migrate a legacy single-account file into `accounts[]`, keeping a copy.
|
|
45
|
+
if (Object.keys(persisted).length > 0 && !Array.isArray(persisted.accounts)) {
|
|
46
|
+
savePersistedState(stateFilePath.replace(/\.json$/, ".v1.json"), persisted);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
// An account without a saved selection keeps the models already on its
|
|
50
|
+
// pi-ai routes when that is a curated list (<= 35). Otherwise it stays
|
|
51
|
+
// unset and its first successful probe seeds recommendModels().
|
|
52
|
+
let memState = normalizeState(mergeHostConfig(persisted, config));
|
|
53
|
+
memState = {
|
|
54
|
+
...memState,
|
|
55
|
+
accounts: memState.accounts.map((account) => {
|
|
56
|
+
if (account.selectedModels !== undefined) return account;
|
|
57
|
+
const existingIds = existingManagedIds(account.provider);
|
|
58
|
+
return existingIds.length > 0 && existingIds.length <= 35
|
|
59
|
+
? { ...account, selectedModels: existingIds }
|
|
60
|
+
: account;
|
|
61
|
+
}),
|
|
62
|
+
};
|
|
63
|
+
savePersistedState(stateFilePath, memState);
|
|
64
|
+
|
|
65
|
+
// The state file is re-read on every access so hand edits take effect.
|
|
66
|
+
const readState = () => {
|
|
67
|
+
const fresh = loadPersistedState(stateFilePath);
|
|
68
|
+
if (Object.keys(fresh).length > 0) memState = normalizeState(fresh);
|
|
69
|
+
return memState;
|
|
70
|
+
};
|
|
71
|
+
const writeState = (state) => {
|
|
72
|
+
memState = state;
|
|
73
|
+
savePersistedState(stateFilePath, state);
|
|
74
|
+
};
|
|
75
|
+
|
|
76
|
+
|
|
77
|
+
return { stateFilePath, readExistingPiAiRoute, readDefaultModel, readState, writeState };
|
|
78
|
+
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
// Independent update preferences, updater wiring and disposed startup/periodic checks.
|
|
2
|
+
|
|
3
|
+
import { readFileSync } from "node:fs";
|
|
4
|
+
import { dirname, join } from "node:path";
|
|
5
|
+
import { createPluginUpdater, loadUpdateSettings, saveUpdateSettings, storeUpdatePackage, UPDATE_INTERVAL_MS } from "../../updater/index.js";
|
|
6
|
+
import { outsideHmrTransaction } from "../apply-utils.js";
|
|
7
|
+
import { PACKAGE_NAME, getEnvValue } from "../config.js";
|
|
8
|
+
import { loadPersistedState } from "../state-store.js";
|
|
9
|
+
|
|
10
|
+
export function createUpdates(shared) {
|
|
11
|
+
const { ctx, stateFilePath } = shared;
|
|
12
|
+
// Update preferences and packages never share the account state or credentials.
|
|
13
|
+
const updateDirectory = dirname(stateFilePath);
|
|
14
|
+
const updateSettingsPath = join(updateDirectory, "update-settings.json");
|
|
15
|
+
let profile;
|
|
16
|
+
try { profile = ctx.get?.("profileContext"); } catch {}
|
|
17
|
+
const source = typeof profile?.dir === "string"
|
|
18
|
+
? loadPersistedState(join(profile.dir, "package.json")).dependencies?.[PACKAGE_NAME]
|
|
19
|
+
: undefined;
|
|
20
|
+
const linkedInstall = typeof source === "string" &&
|
|
21
|
+
(/^(?:link:|workspace:)/.test(source) || /^(?:file:)?(?:[A-Za-z]:[\\/]|\/|\.{1,2}[\\/])/.test(source) && !/\.(?:tgz|tar\.gz)$/i.test(source) || source.startsWith("file:") && !/\.(?:tgz|tar\.gz)$/i.test(source));
|
|
22
|
+
const currentVersion = JSON.parse(readFileSync(new URL("../../../package.json", import.meta.url), "utf8")).version;
|
|
23
|
+
let updateTimer;
|
|
24
|
+
let updateStartup;
|
|
25
|
+
const scheduleUpdates = (preferences) => {
|
|
26
|
+
clearInterval(updateTimer);
|
|
27
|
+
clearTimeout(updateStartup);
|
|
28
|
+
if (!preferences.autoCheck) return;
|
|
29
|
+
outsideHmrTransaction(ctx, () => {
|
|
30
|
+
const run = () => { void Promise.resolve().then(() => updater.check({ automatic: true })).catch(() => {}); };
|
|
31
|
+
updateStartup = setTimeout(run, 3000);
|
|
32
|
+
updateTimer = setInterval(run, UPDATE_INTERVAL_MS);
|
|
33
|
+
});
|
|
34
|
+
};
|
|
35
|
+
const updater = createPluginUpdater({
|
|
36
|
+
currentVersion,
|
|
37
|
+
linkedInstall,
|
|
38
|
+
profileName: profile?.name ?? profile?.profile ?? getEnvValue(ctx, "DSH_PROFILE"),
|
|
39
|
+
readSettings: () => loadUpdateSettings(updateSettingsPath),
|
|
40
|
+
writeSettings: (preferences) => saveUpdateSettings(updateSettingsPath, preferences),
|
|
41
|
+
storePackage: (version, bytes) => storeUpdatePackage(join(updateDirectory, "updates"), version, bytes),
|
|
42
|
+
onSettingsChanged: scheduleUpdates,
|
|
43
|
+
logger: ctx.logger,
|
|
44
|
+
});
|
|
45
|
+
ctx.effect(() => {
|
|
46
|
+
scheduleUpdates(updater.status());
|
|
47
|
+
return () => {
|
|
48
|
+
clearInterval(updateTimer);
|
|
49
|
+
clearTimeout(updateStartup);
|
|
50
|
+
updater.dispose();
|
|
51
|
+
};
|
|
52
|
+
}, "cpa: plugin update checks");
|
|
53
|
+
|
|
54
|
+
return { updateDirectory, updater };
|
|
55
|
+
}
|