@alexpeng/dsh-custom-plugin 0.1.2 → 0.1.4
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 +117 -0
- package/README.i18n.yaml +2 -2
- package/README.md +13 -5
- package/README.zh.md +13 -5
- package/lib/client.js +134 -55
- package/lib/client.js.map +1 -1
- package/lib/index.js +312 -115
- package/lib/types/client/api.d.ts +4 -2
- package/lib/types/host-service.d.ts +30 -13
- package/lib/types/pricing.d.ts +37 -0
- package/lib/types/protocol.d.ts +10 -3
- package/lib/types/state.d.ts +6 -2
- package/lib/types/system-credentials.d.ts +25 -0
- package/lib/types/usage.d.ts +8 -4
- package/package.json +93 -88
package/lib/index.js
CHANGED
|
@@ -105,6 +105,100 @@ const DEFAULT_CONFIG = {
|
|
|
105
105
|
formula: true
|
|
106
106
|
};
|
|
107
107
|
//#endregion
|
|
108
|
+
//#region src/usage.ts
|
|
109
|
+
/** China Standard Time offset: UTC+8, no DST, so fixed-offset arithmetic is
|
|
110
|
+
* exact. The published peak/off-peak schedule and the ledger day buckets are
|
|
111
|
+
* both defined on this clock, independent of the host's local timezone. */
|
|
112
|
+
const CST_OFFSET_MS = 8 * 36e5;
|
|
113
|
+
const DAY_MS = 864e5;
|
|
114
|
+
function cstParts(time) {
|
|
115
|
+
const d = new Date(time + CST_OFFSET_MS);
|
|
116
|
+
return {
|
|
117
|
+
year: d.getUTCFullYear(),
|
|
118
|
+
month: d.getUTCMonth() + 1,
|
|
119
|
+
day: d.getUTCDate(),
|
|
120
|
+
hour: d.getUTCHours(),
|
|
121
|
+
minute: d.getUTCMinutes(),
|
|
122
|
+
weekday: d.getUTCDay()
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
/** Beijing-time (UTC+8) day key `YYYY-MM-DD`. */
|
|
126
|
+
function dayKey(time) {
|
|
127
|
+
const p = cstParts(time === void 0 ? Date.now() : time);
|
|
128
|
+
const pad = (n) => String(n).padStart(2, "0");
|
|
129
|
+
return `${p.year}-${pad(p.month)}-${pad(p.day)}`;
|
|
130
|
+
}
|
|
131
|
+
/** DeepSeek peak billing window: Beijing Monday-Friday 09:00-12:00 /
|
|
132
|
+
* 14:00-18:00; all weekend hours are off-peak. Evaluated on China Standard
|
|
133
|
+
* Time so the split matches the published schedule on any host timezone. */
|
|
134
|
+
function isPeakHour(time) {
|
|
135
|
+
const { hour, weekday } = cstParts(time);
|
|
136
|
+
return weekday >= 1 && weekday <= 5 && (hour >= 9 && hour < 12 || hour >= 14 && hour < 18);
|
|
137
|
+
}
|
|
138
|
+
/** Remove malformed or expired day buckets from the persisted usage ledger. */
|
|
139
|
+
function pruneUsage(usage, now = Date.now(), retentionDays = 90) {
|
|
140
|
+
const cutoff = dayKey(now - (Math.max(1, Math.floor(retentionDays)) - 1) * DAY_MS);
|
|
141
|
+
let removed = 0;
|
|
142
|
+
for (const key of Object.keys(usage)) if (!/^\d{4}-\d{2}-\d{2}$/.test(key) || key < cutoff) {
|
|
143
|
+
delete usage[key];
|
|
144
|
+
removed++;
|
|
145
|
+
}
|
|
146
|
+
return removed;
|
|
147
|
+
}
|
|
148
|
+
/** Fold one usage record into a ledger row, tracking the peak-hour portion. */
|
|
149
|
+
function foldUsageRecord(row, usage, peak) {
|
|
150
|
+
row.in += usage.inputTokens ?? 0;
|
|
151
|
+
row.out += usage.outputTokens ?? 0;
|
|
152
|
+
row.cacheIn += usage.cacheReadTokens ?? 0;
|
|
153
|
+
row.cacheW += usage.cacheWriteTokens ?? 0;
|
|
154
|
+
row.reason += usage.reasoningTokens ?? 0;
|
|
155
|
+
row.calls += 1;
|
|
156
|
+
if (peak) {
|
|
157
|
+
row.peakIn = (row.peakIn ?? 0) + (usage.inputTokens ?? 0);
|
|
158
|
+
row.peakCacheIn = (row.peakCacheIn ?? 0) + (usage.cacheReadTokens ?? 0);
|
|
159
|
+
row.peakCacheW = (row.peakCacheW ?? 0) + (usage.cacheWriteTokens ?? 0);
|
|
160
|
+
row.peakOut = (row.peakOut ?? 0) + (usage.outputTokens ?? 0);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
/** Merge one aggregated row into a target row (scan folds per-session rows). */
|
|
164
|
+
function mergeUsageRow(target, source) {
|
|
165
|
+
target.in += source.in;
|
|
166
|
+
target.out += source.out;
|
|
167
|
+
target.cacheIn += source.cacheIn;
|
|
168
|
+
target.cacheW += source.cacheW;
|
|
169
|
+
target.reason += source.reason;
|
|
170
|
+
target.calls += source.calls;
|
|
171
|
+
target.peakIn = (target.peakIn ?? 0) + (source.peakIn ?? 0);
|
|
172
|
+
target.peakCacheIn = (target.peakCacheIn ?? 0) + (source.peakCacheIn ?? 0);
|
|
173
|
+
target.peakCacheW = (target.peakCacheW ?? 0) + (source.peakCacheW ?? 0);
|
|
174
|
+
target.peakOut = (target.peakOut ?? 0) + (source.peakOut ?? 0);
|
|
175
|
+
}
|
|
176
|
+
/** Replay a session log and aggregate one day's per-model usage rows.
|
|
177
|
+
* `request/context` events anywhere in the log keep the model tracking in
|
|
178
|
+
* order; only `assistant/message` usage events whose own timestamp falls on
|
|
179
|
+
* `day` are folded, so a session crossing midnight contributes exactly the
|
|
180
|
+
* events it produced that day. */
|
|
181
|
+
function aggregateDayUsage(events, day) {
|
|
182
|
+
const agg = {};
|
|
183
|
+
let model = null;
|
|
184
|
+
for (const event of events) {
|
|
185
|
+
if (event === void 0 || event === null) continue;
|
|
186
|
+
if (event.type === "request/context") model = event.data.model ?? null;
|
|
187
|
+
else if (event.type === "assistant/message" && event.data.usage !== void 0 && dayKey(event.time) === day) {
|
|
188
|
+
const key = model ?? "unknown";
|
|
189
|
+
foldUsageRecord(agg[key] ?? (agg[key] = {
|
|
190
|
+
in: 0,
|
|
191
|
+
out: 0,
|
|
192
|
+
cacheIn: 0,
|
|
193
|
+
cacheW: 0,
|
|
194
|
+
reason: 0,
|
|
195
|
+
calls: 0
|
|
196
|
+
}), event.data.usage, isPeakHour(event.time));
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
return agg;
|
|
200
|
+
}
|
|
201
|
+
//#endregion
|
|
108
202
|
//#region src/state.ts
|
|
109
203
|
/**
|
|
110
204
|
* Host-owned state store for dsh-custom-plugin.
|
|
@@ -112,7 +206,9 @@ const DEFAULT_CONFIG = {
|
|
|
112
206
|
* One JSON document at `$DSH_HOME/custom-plugin-state.json` holds the
|
|
113
207
|
* appearance configuration, folder tree, prompt library, starred timeline
|
|
114
208
|
* nodes, the balance API key, and the per-day token usage ledger. Writes are
|
|
115
|
-
* atomic (temp file + rename)
|
|
209
|
+
* atomic (temp file + rename) and serialized (one in-flight write per path),
|
|
210
|
+
* so a crash never truncates the document and concurrent saves never race
|
|
211
|
+
* on the temp file.
|
|
116
212
|
* @module @alexpeng/dsh-custom-plugin/state
|
|
117
213
|
*/
|
|
118
214
|
/** State file name of this plugin. */
|
|
@@ -167,15 +263,29 @@ async function loadStateFile(state, home = dshHome()) {
|
|
|
167
263
|
raw = null;
|
|
168
264
|
}
|
|
169
265
|
if (raw !== null) mergeState(state, raw);
|
|
266
|
+
pruneUsage(state.usage);
|
|
170
267
|
return statePath;
|
|
171
268
|
}
|
|
172
|
-
/**
|
|
173
|
-
|
|
269
|
+
/** In-flight save per state path: concurrent saves queue instead of racing
|
|
270
|
+
* on the shared .tmp file. Two writers renaming one temp file is the Windows
|
|
271
|
+
* EPERM/EBUSY source; queuing also coalesces naturally, because each turn
|
|
272
|
+
* serializes the live document when it runs, not when it was requested. */
|
|
273
|
+
const saveQueues = /* @__PURE__ */ new Map();
|
|
274
|
+
/** Atomically persist the state document. Saves to the same path are
|
|
275
|
+
* serialized: a caller awaits its own turn's completion, a failed turn never
|
|
276
|
+
* poisons the queue behind it. */
|
|
277
|
+
function saveStateFile(state, home = dshHome()) {
|
|
174
278
|
const statePath = join(home, STATE_FILE);
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
279
|
+
const turn = (saveQueues.get(statePath) ?? Promise.resolve()).catch(() => {}).then(async () => {
|
|
280
|
+
await mkdir(dirname(statePath), { recursive: true });
|
|
281
|
+
const tmpPath = statePath + ".tmp";
|
|
282
|
+
await writeFile(tmpPath, JSON.stringify(state), "utf8");
|
|
283
|
+
await rename(tmpPath, statePath);
|
|
284
|
+
});
|
|
285
|
+
saveQueues.set(statePath, turn);
|
|
286
|
+
return turn.finally(() => {
|
|
287
|
+
if (saveQueues.get(statePath) === turn) saveQueues.delete(statePath);
|
|
288
|
+
});
|
|
179
289
|
}
|
|
180
290
|
//#endregion
|
|
181
291
|
//#region src/extract.ts
|
|
@@ -449,89 +559,79 @@ async function readDeepSeekCredential(home = dshHome()) {
|
|
|
449
559
|
return "";
|
|
450
560
|
}
|
|
451
561
|
//#endregion
|
|
452
|
-
//#region src/
|
|
453
|
-
/**
|
|
454
|
-
*
|
|
455
|
-
*
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
}
|
|
473
|
-
|
|
474
|
-
* the remainder at half price. Evaluated on China Standard Time so the split
|
|
475
|
-
* matches the published schedule on any host timezone. */
|
|
476
|
-
function isPeakHour(time) {
|
|
477
|
-
const { hour } = cstParts(time);
|
|
478
|
-
return hour >= 9 && hour < 12 || hour >= 14 && hour < 18;
|
|
479
|
-
}
|
|
480
|
-
/** Fold one usage record into a ledger row, tracking the peak-hour portion. */
|
|
481
|
-
function foldUsageRecord(row, usage, peak) {
|
|
482
|
-
row.in += usage.inputTokens ?? 0;
|
|
483
|
-
row.out += usage.outputTokens ?? 0;
|
|
484
|
-
row.cacheIn += usage.cacheReadTokens ?? 0;
|
|
485
|
-
row.cacheW += usage.cacheWriteTokens ?? 0;
|
|
486
|
-
row.reason += usage.reasoningTokens ?? 0;
|
|
487
|
-
row.calls += 1;
|
|
488
|
-
if (peak) {
|
|
489
|
-
row.peakIn = (row.peakIn ?? 0) + (usage.inputTokens ?? 0);
|
|
490
|
-
row.peakCacheIn = (row.peakCacheIn ?? 0) + (usage.cacheReadTokens ?? 0);
|
|
491
|
-
row.peakCacheW = (row.peakCacheW ?? 0) + (usage.cacheWriteTokens ?? 0);
|
|
492
|
-
row.peakOut = (row.peakOut ?? 0) + (usage.outputTokens ?? 0);
|
|
562
|
+
//#region src/system-credentials.ts
|
|
563
|
+
/**
|
|
564
|
+
* Optional OS credential-store adapter.
|
|
565
|
+
*
|
|
566
|
+
* `keytar` is optional so the plugin still works in minimal/headless
|
|
567
|
+
* installations. When present, it delegates storage to the platform keyring
|
|
568
|
+
* (Windows Credential Manager, macOS Keychain, or the Linux Secret Service
|
|
569
|
+
* backend exposed by keytar). The caller owns the legacy state-file fallback.
|
|
570
|
+
* @module @alexpeng/dsh-custom-plugin/system-credentials
|
|
571
|
+
*/
|
|
572
|
+
const CREDENTIAL_SERVICE = "@alexpeng/dsh-custom-plugin";
|
|
573
|
+
const CREDENTIAL_ACCOUNT = "deepseek-api-key";
|
|
574
|
+
function loadKeytar() {
|
|
575
|
+
try {
|
|
576
|
+
const required = createRequire(import.meta.url)("keytar");
|
|
577
|
+
const candidate = required !== null && typeof required === "object" && "default" in required ? required.default : required;
|
|
578
|
+
if (candidate === null || typeof candidate !== "object") return null;
|
|
579
|
+
const module = candidate;
|
|
580
|
+
if (typeof module.getPassword !== "function" || typeof module.setPassword !== "function" || typeof module.deletePassword !== "function") return null;
|
|
581
|
+
return module;
|
|
582
|
+
} catch {
|
|
583
|
+
return null;
|
|
493
584
|
}
|
|
494
585
|
}
|
|
495
|
-
/**
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
}
|
|
508
|
-
/** Replay a session log and aggregate one day's per-model usage rows.
|
|
509
|
-
* `request/context` events anywhere in the log keep the model tracking in
|
|
510
|
-
* order; only `assistant/message` usage events whose own timestamp falls on
|
|
511
|
-
* `day` are folded, so a session crossing midnight contributes exactly the
|
|
512
|
-
* events it produced that day. */
|
|
513
|
-
function aggregateDayUsage(events, day) {
|
|
514
|
-
const agg = {};
|
|
515
|
-
let model = null;
|
|
516
|
-
for (const event of events) {
|
|
517
|
-
if (event === void 0 || event === null) continue;
|
|
518
|
-
if (event.type === "request/context") model = event.data.model ?? null;
|
|
519
|
-
else if (event.type === "assistant/message" && event.data.usage !== void 0 && dayKey(event.time) === day) {
|
|
520
|
-
const key = model ?? "unknown";
|
|
521
|
-
foldUsageRecord(agg[key] ?? (agg[key] = {
|
|
522
|
-
in: 0,
|
|
523
|
-
out: 0,
|
|
524
|
-
cacheIn: 0,
|
|
525
|
-
cacheW: 0,
|
|
526
|
-
reason: 0,
|
|
527
|
-
calls: 0
|
|
528
|
-
}), event.data.usage, isPeakHour(event.time));
|
|
586
|
+
/** Safe wrapper around the optional keytar dependency. */
|
|
587
|
+
var SystemCredentialStore = class {
|
|
588
|
+
keytar = loadKeytar();
|
|
589
|
+
get available() {
|
|
590
|
+
return this.keytar !== null;
|
|
591
|
+
}
|
|
592
|
+
async get() {
|
|
593
|
+
if (this.keytar === null) return "";
|
|
594
|
+
try {
|
|
595
|
+
return (await this.keytar.getPassword("@alexpeng/dsh-custom-plugin", "deepseek-api-key") ?? "").trim();
|
|
596
|
+
} catch {
|
|
597
|
+
return "";
|
|
529
598
|
}
|
|
530
599
|
}
|
|
531
|
-
|
|
532
|
-
|
|
600
|
+
async set(value) {
|
|
601
|
+
if (this.keytar === null) return false;
|
|
602
|
+
try {
|
|
603
|
+
await this.keytar.setPassword(CREDENTIAL_SERVICE, CREDENTIAL_ACCOUNT, value);
|
|
604
|
+
return true;
|
|
605
|
+
} catch {
|
|
606
|
+
return false;
|
|
607
|
+
}
|
|
608
|
+
}
|
|
609
|
+
async clear() {
|
|
610
|
+
if (this.keytar === null) return false;
|
|
611
|
+
try {
|
|
612
|
+
await this.keytar.deletePassword(CREDENTIAL_SERVICE, CREDENTIAL_ACCOUNT);
|
|
613
|
+
return true;
|
|
614
|
+
} catch {
|
|
615
|
+
return false;
|
|
616
|
+
}
|
|
617
|
+
}
|
|
618
|
+
};
|
|
533
619
|
//#endregion
|
|
534
620
|
//#region src/host-service.ts
|
|
621
|
+
const USAGE_SCAN_CONCURRENCY = 4;
|
|
622
|
+
async function mapConcurrent(items, limit, worker) {
|
|
623
|
+
const results = new Array(items.length);
|
|
624
|
+
let next = 0;
|
|
625
|
+
const run = async () => {
|
|
626
|
+
while (true) {
|
|
627
|
+
const index = next++;
|
|
628
|
+
if (index >= items.length) return;
|
|
629
|
+
results[index] = await worker(items[index]);
|
|
630
|
+
}
|
|
631
|
+
};
|
|
632
|
+
await Promise.all(Array.from({ length: Math.min(limit, items.length) }, () => run()));
|
|
633
|
+
return results;
|
|
634
|
+
}
|
|
535
635
|
/** Host capabilities behind the routes and the agent tool. */
|
|
536
636
|
var CustomPluginHost = class {
|
|
537
637
|
sessionQuery;
|
|
@@ -540,11 +640,15 @@ var CustomPluginHost = class {
|
|
|
540
640
|
persistNow;
|
|
541
641
|
diagReports;
|
|
542
642
|
attachments;
|
|
643
|
+
credentialStore;
|
|
543
644
|
sessionModel = /* @__PURE__ */ new Map();
|
|
645
|
+
usageScanPromise = null;
|
|
646
|
+
lastUsagePruneDay = "";
|
|
544
647
|
mermaidBytesValue = 0;
|
|
545
648
|
mermaidJs = "";
|
|
546
649
|
mermaidSource = "";
|
|
547
650
|
localMermaidPath;
|
|
651
|
+
readCredential;
|
|
548
652
|
constructor(options) {
|
|
549
653
|
this.sessionQuery = options.sessionQuery;
|
|
550
654
|
this.state = options.state;
|
|
@@ -552,7 +656,9 @@ var CustomPluginHost = class {
|
|
|
552
656
|
this.persistNow = options.saveNow;
|
|
553
657
|
this.diagReports = options.diagReports;
|
|
554
658
|
this.attachments = options.attachments;
|
|
659
|
+
this.credentialStore = options.credentialStore ?? new SystemCredentialStore();
|
|
555
660
|
this.localMermaidPath = options.localMermaidPath ?? defaultLocalMermaidPath;
|
|
661
|
+
this.readCredential = options.readCredential ?? readDeepSeekCredential;
|
|
556
662
|
}
|
|
557
663
|
/** Persist the state document (debounced by the loader entry). */
|
|
558
664
|
async persist() {
|
|
@@ -574,7 +680,12 @@ var CustomPluginHost = class {
|
|
|
574
680
|
* decides both the day bucket and the peak/off-peak portion. */
|
|
575
681
|
foldUsage(sessionId, usage, time) {
|
|
576
682
|
const at = time ?? Date.now();
|
|
577
|
-
const
|
|
683
|
+
const dayName = dayKey(at);
|
|
684
|
+
const day = this.state.usage[dayName] ?? (this.state.usage[dayName] = {});
|
|
685
|
+
if (this.lastUsagePruneDay !== dayName) {
|
|
686
|
+
pruneUsage(this.state.usage, at);
|
|
687
|
+
this.lastUsagePruneDay = dayName;
|
|
688
|
+
}
|
|
578
689
|
const model = this.sessionModel.get(sessionId) ?? "unknown";
|
|
579
690
|
foldUsageRecord(day[model] ?? (day[model] = {
|
|
580
691
|
in: 0,
|
|
@@ -585,19 +696,20 @@ var CustomPluginHost = class {
|
|
|
585
696
|
calls: 0
|
|
586
697
|
}), usage, isPeakHour(at));
|
|
587
698
|
}
|
|
588
|
-
/** Snapshot of the
|
|
589
|
-
stateView() {
|
|
699
|
+
/** Snapshot of browser-safe state; the API key value never crosses this boundary. */
|
|
700
|
+
async stateView() {
|
|
701
|
+
const credential = await this.credentialStatus();
|
|
590
702
|
return {
|
|
591
703
|
cfg: this.state.cfg,
|
|
592
704
|
folders: this.state.folders,
|
|
593
705
|
prompts: this.state.prompts,
|
|
594
706
|
stars: this.state.stars,
|
|
595
|
-
|
|
596
|
-
|
|
707
|
+
usage: this.state.usage,
|
|
708
|
+
...credential
|
|
597
709
|
};
|
|
598
710
|
}
|
|
599
711
|
/** Apply a browser-side state edit (config, folders, prompts, stars, api key). */
|
|
600
|
-
applyEdit(edit) {
|
|
712
|
+
async applyEdit(edit) {
|
|
601
713
|
if (edit.cfg !== void 0 && edit.cfg !== null && typeof edit.cfg === "object") this.state.cfg = {
|
|
602
714
|
...this.state.cfg,
|
|
603
715
|
...edit.cfg
|
|
@@ -605,7 +717,24 @@ var CustomPluginHost = class {
|
|
|
605
717
|
if (Array.isArray(edit.folders)) this.state.folders = edit.folders;
|
|
606
718
|
if (Array.isArray(edit.prompts)) this.state.prompts = edit.prompts;
|
|
607
719
|
if (edit.stars !== void 0 && edit.stars !== null && typeof edit.stars === "object") this.state.stars = edit.stars;
|
|
608
|
-
if (typeof edit.apiKey === "string")
|
|
720
|
+
if (typeof edit.apiKey === "string") {
|
|
721
|
+
const key = edit.apiKey.trim();
|
|
722
|
+
if (key === "") {
|
|
723
|
+
await this.credentialStore.clear();
|
|
724
|
+
this.state.apiKey = "";
|
|
725
|
+
} else {
|
|
726
|
+
if (!/^sk-/.test(key)) throw new Error("DeepSeek API Key 必须以 sk- 开头");
|
|
727
|
+
this.state.apiKey = await this.credentialStore.set(key) ? "" : key;
|
|
728
|
+
}
|
|
729
|
+
}
|
|
730
|
+
}
|
|
731
|
+
/** Move a legacy plaintext state key into the OS store when available. */
|
|
732
|
+
async migrateLegacyApiKey() {
|
|
733
|
+
const key = (this.state.apiKey ?? "").trim();
|
|
734
|
+
if (!/^sk-/.test(key) || !this.credentialStore.available) return false;
|
|
735
|
+
if (!await this.credentialStore.set(key)) return false;
|
|
736
|
+
this.state.apiKey = "";
|
|
737
|
+
return true;
|
|
609
738
|
}
|
|
610
739
|
/** Timeline nodes for one session, capped to the 400-node tail. The tail cap
|
|
611
740
|
* bounds the payload (each item carries up to 4k of preview text); 400 keeps
|
|
@@ -722,20 +851,56 @@ var CustomPluginHost = class {
|
|
|
722
851
|
};
|
|
723
852
|
}
|
|
724
853
|
}
|
|
725
|
-
/** Resolve the
|
|
726
|
-
async
|
|
854
|
+
/** Resolve the key and its source without returning either value to the browser. */
|
|
855
|
+
async resolveApiKeyWithSource() {
|
|
856
|
+
try {
|
|
857
|
+
const system = (await this.credentialStore.get()).trim();
|
|
858
|
+
if (/^sk-/.test(system)) return {
|
|
859
|
+
key: system,
|
|
860
|
+
source: "system"
|
|
861
|
+
};
|
|
862
|
+
} catch {}
|
|
727
863
|
const key = (this.state.apiKey ?? "").trim();
|
|
728
|
-
if (key
|
|
864
|
+
if (/^sk-/.test(key)) return {
|
|
865
|
+
key,
|
|
866
|
+
source: "legacy-state"
|
|
867
|
+
};
|
|
729
868
|
try {
|
|
730
869
|
const env = globalThis.process?.env;
|
|
731
|
-
const
|
|
732
|
-
|
|
870
|
+
for (const name of [
|
|
871
|
+
"DEEPSEEK_API_KEY",
|
|
872
|
+
"DEEPSEEK_KEY",
|
|
873
|
+
"DEEPSEEK_TOKEN"
|
|
874
|
+
]) {
|
|
875
|
+
const value = env?.[name];
|
|
876
|
+
if (typeof value === "string" && /^sk-/.test(value.trim())) return {
|
|
877
|
+
key: value.trim(),
|
|
878
|
+
source: "environment"
|
|
879
|
+
};
|
|
880
|
+
}
|
|
733
881
|
} catch {}
|
|
734
882
|
try {
|
|
735
|
-
const candidate = await
|
|
736
|
-
if (/^sk-/.test(candidate)) return
|
|
883
|
+
const candidate = await this.readCredential();
|
|
884
|
+
if (/^sk-/.test(candidate)) return {
|
|
885
|
+
key: candidate.trim(),
|
|
886
|
+
source: "dsh"
|
|
887
|
+
};
|
|
737
888
|
} catch {}
|
|
738
|
-
return
|
|
889
|
+
return {
|
|
890
|
+
key: "",
|
|
891
|
+
source: "none"
|
|
892
|
+
};
|
|
893
|
+
}
|
|
894
|
+
async resolveApiKey() {
|
|
895
|
+
return (await this.resolveApiKeyWithSource()).key;
|
|
896
|
+
}
|
|
897
|
+
/** Browser-safe credential status used by state and save responses. */
|
|
898
|
+
async credentialStatus() {
|
|
899
|
+
const resolved = await this.resolveApiKeyWithSource();
|
|
900
|
+
return {
|
|
901
|
+
apiKeyConfigured: resolved.key !== "",
|
|
902
|
+
credentialStorage: resolved.source
|
|
903
|
+
};
|
|
739
904
|
}
|
|
740
905
|
/** Query the DeepSeek balance endpoint (15s timeout). */
|
|
741
906
|
async balanceGet() {
|
|
@@ -789,6 +954,16 @@ var CustomPluginHost = class {
|
|
|
789
954
|
* folded, so sessions created before midnight keep contributing the usage
|
|
790
955
|
* they produced today. */
|
|
791
956
|
async usageScan() {
|
|
957
|
+
if (this.usageScanPromise !== null) return await this.usageScanPromise;
|
|
958
|
+
const run = this.usageScanImpl();
|
|
959
|
+
this.usageScanPromise = run;
|
|
960
|
+
try {
|
|
961
|
+
return await run;
|
|
962
|
+
} finally {
|
|
963
|
+
if (this.usageScanPromise === run) this.usageScanPromise = null;
|
|
964
|
+
}
|
|
965
|
+
}
|
|
966
|
+
async usageScanImpl() {
|
|
792
967
|
let records;
|
|
793
968
|
try {
|
|
794
969
|
records = await this.sessionQuery.listSessions();
|
|
@@ -799,11 +974,27 @@ var CustomPluginHost = class {
|
|
|
799
974
|
};
|
|
800
975
|
}
|
|
801
976
|
const today = dayKey();
|
|
977
|
+
pruneUsage(this.state.usage);
|
|
802
978
|
const agg = {};
|
|
803
979
|
let scanned = 0;
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
980
|
+
const entries = await mapConcurrent(records, USAGE_SCAN_CONCURRENCY, async (record) => {
|
|
981
|
+
try {
|
|
982
|
+
return {
|
|
983
|
+
readable: true,
|
|
984
|
+
usage: aggregateDayUsage((await this.sessionQuery.readSession(record.header.id)).events, today)
|
|
985
|
+
};
|
|
986
|
+
} catch {
|
|
987
|
+
return {
|
|
988
|
+
readable: false,
|
|
989
|
+
usage: {}
|
|
990
|
+
};
|
|
991
|
+
}
|
|
992
|
+
});
|
|
993
|
+
let readableSessions = 0;
|
|
994
|
+
for (const entry of entries) {
|
|
995
|
+
if (!entry.readable) continue;
|
|
996
|
+
readableSessions++;
|
|
997
|
+
const models = Object.keys(entry.usage);
|
|
807
998
|
if (models.length === 0) continue;
|
|
808
999
|
scanned++;
|
|
809
1000
|
for (const model of models) mergeUsageRow(agg[model] ?? (agg[model] = {
|
|
@@ -813,9 +1004,9 @@ var CustomPluginHost = class {
|
|
|
813
1004
|
cacheW: 0,
|
|
814
1005
|
reason: 0,
|
|
815
1006
|
calls: 0
|
|
816
|
-
}),
|
|
817
|
-
}
|
|
818
|
-
if (
|
|
1007
|
+
}), entry.usage[model]);
|
|
1008
|
+
}
|
|
1009
|
+
if (records.length === 0 || readableSessions > 0) this.state.usage[today] = agg;
|
|
819
1010
|
this.persist();
|
|
820
1011
|
return {
|
|
821
1012
|
ok: true,
|
|
@@ -1073,7 +1264,7 @@ function makeCustomPluginRoutes(host) {
|
|
|
1073
1264
|
if (req.method === "GET") {
|
|
1074
1265
|
json(res, 200, {
|
|
1075
1266
|
ok: true,
|
|
1076
|
-
data: host.stateView()
|
|
1267
|
+
data: await host.stateView()
|
|
1077
1268
|
});
|
|
1078
1269
|
return;
|
|
1079
1270
|
}
|
|
@@ -1086,7 +1277,7 @@ function makeCustomPluginRoutes(host) {
|
|
|
1086
1277
|
}
|
|
1087
1278
|
try {
|
|
1088
1279
|
const body = await readBody(req, BODY_LIMIT);
|
|
1089
|
-
host.applyEdit({
|
|
1280
|
+
await host.applyEdit({
|
|
1090
1281
|
cfg: body.cfg,
|
|
1091
1282
|
folders: Array.isArray(body.folders) ? body.folders : void 0,
|
|
1092
1283
|
prompts: Array.isArray(body.prompts) ? body.prompts : void 0,
|
|
@@ -1094,7 +1285,10 @@ function makeCustomPluginRoutes(host) {
|
|
|
1094
1285
|
apiKey: typeof body.apiKey === "string" ? body.apiKey : void 0
|
|
1095
1286
|
});
|
|
1096
1287
|
await host.persist();
|
|
1097
|
-
json(res, 200, {
|
|
1288
|
+
json(res, 200, {
|
|
1289
|
+
ok: true,
|
|
1290
|
+
...await host.credentialStatus()
|
|
1291
|
+
});
|
|
1098
1292
|
} catch (error) {
|
|
1099
1293
|
const message = error instanceof Error ? error.message : String(error);
|
|
1100
1294
|
json(res, message === "body-too-large" ? 413 : 400, {
|
|
@@ -1244,19 +1438,15 @@ function applyImpl(ctx) {
|
|
|
1244
1438
|
diagReports.push(String(message ?? "").slice(0, 400));
|
|
1245
1439
|
if (diagReports.length > 20) diagReports.splice(0, diagReports.length - 20);
|
|
1246
1440
|
};
|
|
1247
|
-
loadStateFile(state).then((path) => {
|
|
1248
|
-
statePath = path;
|
|
1249
|
-
return saveStateFile(state);
|
|
1250
|
-
}).catch((error) => {
|
|
1251
|
-
reportDiag(`state load failed: ${String(error?.message ?? error)}`);
|
|
1252
|
-
});
|
|
1253
1441
|
const saveSoon = (() => {
|
|
1254
1442
|
let timer;
|
|
1255
1443
|
return () => {
|
|
1256
1444
|
if (timer !== void 0) clearTimeout(timer);
|
|
1257
1445
|
timer = setTimeout(() => {
|
|
1258
1446
|
timer = void 0;
|
|
1259
|
-
saveStateFile(state).catch(() => {
|
|
1447
|
+
saveStateFile(state).catch((error) => {
|
|
1448
|
+
reportDiag(`state save failed: ${String(error?.message ?? error)}`);
|
|
1449
|
+
});
|
|
1260
1450
|
}, 500);
|
|
1261
1451
|
};
|
|
1262
1452
|
})();
|
|
@@ -1269,6 +1459,13 @@ function applyImpl(ctx) {
|
|
|
1269
1459
|
diagReports,
|
|
1270
1460
|
attachments: ctx.get("attachments")
|
|
1271
1461
|
});
|
|
1462
|
+
loadStateFile(state).then(async (path) => {
|
|
1463
|
+
statePath = path;
|
|
1464
|
+
if (await host.migrateLegacyApiKey()) reportDiag("legacy API key migrated to system credentials");
|
|
1465
|
+
return saveStateFile(state);
|
|
1466
|
+
}).catch((error) => {
|
|
1467
|
+
reportDiag(`state load failed: ${String(error?.message ?? error)}`);
|
|
1468
|
+
});
|
|
1272
1469
|
ctx.on("session/event", (session, event) => {
|
|
1273
1470
|
try {
|
|
1274
1471
|
if (event === void 0 || event === null) return;
|
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* failures surface as `{ ok: false, error }` instead of throwing.
|
|
5
5
|
* @module @alexpeng/dsh-custom-plugin/client/api
|
|
6
6
|
*/
|
|
7
|
-
import { type CustomPluginConfig, type CustomPluginState, type TimelineItem } from '../protocol.ts';
|
|
7
|
+
import { type CredentialStorage, type CustomPluginConfig, type CustomPluginPublicState, type CustomPluginState, type TimelineItem } from '../protocol.ts';
|
|
8
8
|
/** State edit the browser sends to the host. */
|
|
9
9
|
export interface StateEdit {
|
|
10
10
|
cfg?: Partial<CustomPluginConfig>;
|
|
@@ -29,7 +29,7 @@ export interface BalancePayload {
|
|
|
29
29
|
/** Read the whole state document. */
|
|
30
30
|
export declare function apiStateGet(): Promise<{
|
|
31
31
|
ok: true;
|
|
32
|
-
data:
|
|
32
|
+
data: CustomPluginPublicState;
|
|
33
33
|
} | {
|
|
34
34
|
ok: false;
|
|
35
35
|
error?: string;
|
|
@@ -37,6 +37,8 @@ export declare function apiStateGet(): Promise<{
|
|
|
37
37
|
/** Persist a state edit. */
|
|
38
38
|
export declare function apiStateSave(edit: StateEdit): Promise<{
|
|
39
39
|
ok: true;
|
|
40
|
+
apiKeyConfigured?: boolean;
|
|
41
|
+
credentialStorage?: CredentialStorage;
|
|
40
42
|
} | {
|
|
41
43
|
ok: false;
|
|
42
44
|
error?: string;
|