@liyang8246/dsh-accounts 0.0.0-stage → 0.1.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/lib/client.js ADDED
@@ -0,0 +1,663 @@
1
+ (function() {
2
+ // src/shared/channels.ts
3
+ const channels = [
4
+ {
5
+ id: "openai-codex",
6
+ name: "OpenAI Codex",
7
+ source: "openai",
8
+ auth: ["oauth"],
9
+ consoleURL: "https://chatgpt.com/codex/settings/usage"
10
+ },
11
+ {
12
+ id: "opencode-go",
13
+ name: "OpenCode Go",
14
+ source: "opencode-go",
15
+ auth: ["oauth"],
16
+ consoleURL: "https://opencode.ai/console"
17
+ },
18
+ {
19
+ id: "commandcode-go",
20
+ name: "CommandCode Go",
21
+ source: "commandcode",
22
+ auth: ["api-key"],
23
+ consoleURL: "https://commandcode.ai/dashboard"
24
+ }
25
+ ];
26
+ // src/client/constants.ts
27
+ const en = {
28
+ title: "Model Accounts",
29
+ refresh: "Refresh quota",
30
+ refreshAll: "Refresh all quotas",
31
+ add: "Add account",
32
+ label: "Account label",
33
+ key: "API key",
34
+ save: "Save API key",
35
+ login: "Sign in with browser",
36
+ empty: "No accounts yet",
37
+ remove: "Remove",
38
+ confirmRemove: "Remove this saved login and its local credentials?",
39
+ cancel: "Cancel",
40
+ open: "Open authorization page",
41
+ code: "Authorization code",
42
+ reply: "Continue",
43
+ pending: "Waiting for browser authorization…",
44
+ paste: "Callback blocked? Paste the redirect URL",
45
+ loading: "Loading…",
46
+ unavailable: "Unavailable",
47
+ notFetched: "Not fetched",
48
+ failed: "Account operation failed",
49
+ used: "used",
50
+ left: "left",
51
+ week: "Week",
52
+ month: "Month",
53
+ other: "Other window"
54
+ };
55
+ const zh = {
56
+ title: "模型账号",
57
+ refresh: "刷新额度",
58
+ refreshAll: "刷新全部额度",
59
+ add: "添加账号",
60
+ label: "账号名称",
61
+ key: "API Key",
62
+ save: "保存 API Key",
63
+ login: "浏览器登录",
64
+ empty: "暂无账号",
65
+ remove: "删除",
66
+ confirmRemove: "删除此登录账号及其本地凭据?",
67
+ cancel: "取消",
68
+ open: "打开授权页面",
69
+ code: "授权码",
70
+ reply: "继续",
71
+ pending: "等待浏览器授权…",
72
+ paste: "无法自动回调?粘贴跳转地址",
73
+ loading: "加载中…",
74
+ unavailable: "不可用",
75
+ notFetched: "未查询",
76
+ failed: "账号操作失败",
77
+ used: "已用",
78
+ left: "剩余",
79
+ week: "周",
80
+ month: "月",
81
+ other: "其他窗口"
82
+ };
83
+ const quotaPeriods = [
84
+ "5h",
85
+ "week",
86
+ "month"
87
+ ];
88
+ const authorizationHosts = {
89
+ "openai-codex": ["auth.openai.com", "chatgpt.com"],
90
+ "opencode-go": ["opencode.ai"],
91
+ "commandcode-go": []
92
+ };
93
+ const css = `
94
+ .zph-accounts{display:flex;flex-direction:column;gap:16px;color:var(--dsw-alias-label-primary);font-size:13px;line-height:1.5}
95
+ .zph-accounts h2,.zph-accounts h3,.zph-accounts p{margin:0}.zph-accounts h2{font-size:16px;font-weight:600}.zph-accounts h3{font-size:14px;font-weight:600}
96
+ .zph-accounts .zph-muted{color:var(--dsw-alias-label-secondary);font-size:11px}.zph-accounts .zph-row{display:flex;align-items:center;gap:8px;flex-wrap:wrap}.zph-accounts .zph-between{justify-content:space-between}
97
+ .zph-accounts .zph-channel{border:1px solid var(--dsw-alias-border-l1);border-radius:12px;overflow:hidden}.zph-accounts .zph-head{padding:16px;background:var(--dsw-alias-bg-layer-1)}
98
+ .zph-accounts .zph-account{padding:16px;border-top:1px solid var(--dsw-alias-border-l1);display:flex;flex-direction:column;gap:4px}.zph-accounts .zph-account label{display:flex;align-items:center;gap:8px;cursor:pointer;overflow-wrap:anywhere}
99
+ .zph-accounts button,.zph-accounts input{font:inherit;box-sizing:border-box;min-height:32px;border:1px solid var(--dsw-alias-border-l2);border-radius:8px;background:var(--dsw-alias-bg-layer-1);color:var(--dsw-alias-label-primary);padding:5px 10px}
100
+ .zph-accounts button{cursor:pointer}.zph-accounts button:hover{background:var(--dsw-alias-bg-layer-2)}.zph-accounts button:disabled{opacity:.5;cursor:default}.zph-accounts button.zph-link{border:0;background:none;min-height:0;padding:0;color:var(--dsw-alias-brand-primary);text-decoration:underline}.zph-accounts input{max-width:100%;min-width:0}.zph-accounts input[type=radio]{accent-color:var(--dsw-alias-brand-primary);min-height:0;padding:0}
101
+ .zph-accounts button:focus-visible,.zph-accounts input:focus-visible,.zph-accounts a:focus-visible{outline:2px solid var(--dsw-alias-brand-primary);outline-offset:2px}.zph-accounts a{color:var(--dsw-alias-brand-primary)}
102
+ .zph-accounts .zph-quota{display:grid;grid-template-columns:repeat(auto-fit,minmax(150px,1fr));gap:8px}.zph-accounts .zph-window{padding:8px 10px;border-radius:8px;background:var(--dsw-alias-bg-layer-2);font-size:11px;overflow-wrap:anywhere}.zph-accounts .zph-window-head{display:flex;align-items:baseline;justify-content:space-between;gap:8px}
103
+ .zph-accounts .zph-track{margin:6px 0 0;width:100%}.zph-accounts .zph-error{color:var(--dsw-alias-state-error-primary);overflow-wrap:anywhere}
104
+ .zph-accounts .zph-add{padding:12px 16px;border-top:1px solid var(--dsw-alias-border-l1)}.zph-accounts .zph-form{display:flex;flex-direction:column;gap:10px;margin-top:10px}.zph-accounts .zph-form label{display:flex;flex-direction:column;gap:4px}.zph-accounts .zph-grow{flex:1 1 180px;min-width:0}.zph-accounts .zph-align-end{align-items:flex-end}
105
+ .zph-accounts .zph-switch{display:flex;align-items:center;cursor:pointer}.zph-accounts .zph-switch input{appearance:none;-webkit-appearance:none;position:relative;width:36px;height:20px;min-height:0;padding:0;border:0;border-radius:10px;background:var(--dsw-alias-bg-layer-2);cursor:pointer;transition:background .15s}
106
+ .zph-accounts .zph-switch input::after{content:'';position:absolute;top:2px;left:2px;width:16px;height:16px;border-radius:50%;background:var(--dsw-alias-label-secondary);transition:transform .15s,background .15s}
107
+ .zph-accounts .zph-switch input:checked{background:var(--dsw-alias-label-primary)}.zph-accounts .zph-switch input:checked::after{transform:translateX(16px);background:var(--dsw-alias-bg-base)}.zph-accounts .zph-switch input:disabled{opacity:.5;cursor:default}
108
+ .zph-accounts .zph-pill{font-size:10px;line-height:1.4;padding:1px 6px;border-radius:999px;border:1px solid var(--dsw-alias-border-l2);color:var(--dsw-alias-label-secondary)}
109
+ .zph-composer-quota{display:flex;flex-direction:column;gap:3px;width:128px;flex:none}.zph-composer-quota[data-count="3"] .zph-track{height:3px}
110
+ .zph-track{display:block;height:4px;border-radius:2px;background:var(--dsw-alias-border-l2);overflow:hidden}
111
+ .zph-track b{display:block;height:100%;border-radius:2px;background:var(--dsw-alias-brand-primary)}
112
+ .zph-track[data-level=high] b{background:var(--dsw-alias-state-warn-primary)}
113
+ .zph-track[data-level=full] b{background:var(--dsw-alias-state-error-primary)}
114
+ .zph-accounts .zph-login{padding:8px 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l2);display:flex;align-items:center;gap:8px;flex-wrap:wrap;align-self:stretch}.zph-accounts code{font-family:monospace;user-select:all}.zph-accounts .zph-actions{margin-left:auto;display:flex;gap:6px;flex-wrap:wrap}
115
+ @media(max-width:520px){.zph-accounts .zph-actions{margin-left:0}}
116
+ `;
117
+ // src/client/data.ts
118
+ function isObject(value) {
119
+ return typeof value === "object" && value !== null && !Array.isArray(value);
120
+ }
121
+ function optionalString(value) {
122
+ return value === void 0 || typeof value === "string";
123
+ }
124
+ function optionalNumber(value) {
125
+ return value === void 0 || typeof value === "number" && Number.isFinite(value);
126
+ }
127
+ function isChannelId(value) {
128
+ return channels.some((channel) => channel.id === value);
129
+ }
130
+ function isChannel(value) {
131
+ return isObject(value) && isChannelId(value.id) && typeof value.name === "string" && (value.source === "openai" || value.source === "opencode-go" || value.source === "commandcode") && Array.isArray(value.auth) && value.auth.every((item) => item === "api-key" || item === "oauth") && typeof value.consoleURL === "string";
132
+ }
133
+ function isQuotaWindow(value) {
134
+ return isObject(value) && (value.period === "5h" || value.period === "week" || value.period === "month" || value.period === "other") && optionalString(value.label) && optionalString(value.unit) && optionalString(value.resetsAt) && optionalNumber(value.usedPercent) && optionalNumber(value.used) && optionalNumber(value.limit) && (value.exhausted === void 0 || typeof value.exhausted === "boolean");
135
+ }
136
+ function isQuota(value) {
137
+ return isObject(value) && (value.status === "ok" || value.status === "unavailable" || value.status === "error") && typeof value.fetchedAt === "string" && Array.isArray(value.windows) && value.windows.every(isQuotaWindow) && optionalString(value.reason) && optionalString(value.plan);
138
+ }
139
+ function isAccount(value) {
140
+ return isObject(value) && typeof value.id === "string" && isChannelId(value.channel) && typeof value.label === "string" && typeof value.createdAt === "string" && (value.auth === "api-key" || value.auth === "oauth") && typeof value.active === "boolean" && optionalString(value.email) && optionalString(value.orgName) && (value.quota === void 0 || isQuota(value.quota));
141
+ }
142
+ function isNotice(value) {
143
+ return isObject(value) && optionalString(value.url) && optionalString(value.code) && optionalString(value.message);
144
+ }
145
+ function isLogin(value) {
146
+ return isObject(value) && typeof value.id === "string" && isChannelId(value.channel) && (value.status === "pending" || value.status === "authorized" || value.status === "cancelled" || value.status === "error") && optionalString(value.prompt) && optionalString(value.error) && (value.notice === void 0 || isNotice(value.notice));
147
+ }
148
+ function isSnapshot(value) {
149
+ return isObject(value) && Array.isArray(value.channels) && value.channels.every(isChannel) && Array.isArray(value.accounts) && value.accounts.every(isAccount) && isObject(value.catalog) && typeof value.catalog.source === "string" && typeof value.catalog.generatedAt === "string" && typeof value.catalog.sha256 === "string" && (value.login === void 0 || isLogin(value.login));
150
+ }
151
+ function readSnapshot(value) {
152
+ if (!isSnapshot(value)) throw new Error("Invalid account response");
153
+ return value;
154
+ }
155
+ function readLogin(value) {
156
+ if (!isLogin(value)) throw new Error("Invalid login response");
157
+ return value;
158
+ }
159
+ function isLoginRequest(request) {
160
+ return request.action === "login_start" || request.action === "login_status" || request.action === "login_reply" || request.action === "login_cancel";
161
+ }
162
+ function channelOf(provider) {
163
+ return channels.find((channel) => provider === `zephyr-${channel.id}`)?.id;
164
+ }
165
+ function measuredWindows(windows) {
166
+ return quotaPeriods.flatMap((period) => {
167
+ const window = windows.find((item) => item.period === period);
168
+ return window && typeof window.usedPercent === "number" && Number.isFinite(window.usedPercent) ? [{
169
+ ...window,
170
+ usedPercent: window.usedPercent
171
+ }] : [];
172
+ });
173
+ }
174
+ function activeQuota(snapshot, channel) {
175
+ const quota = snapshot?.accounts.find((account) => account.channel === channel && account.active)?.quota;
176
+ return quota?.status === "ok" ? measuredWindows(quota.windows) : [];
177
+ }
178
+ function leftOf(window) {
179
+ return window.exhausted ? 0 : Math.min(100, Math.max(0, 100 - window.usedPercent));
180
+ }
181
+ function levelOf(window) {
182
+ const left = leftOf(window);
183
+ return left <= 0 ? "full" : left <= 20 ? "high" : "ok";
184
+ }
185
+ function authorizationURL(login) {
186
+ if (!login.notice?.url) return void 0;
187
+ try {
188
+ const url = new URL(login.notice.url);
189
+ return url.protocol === "https:" && !url.username && !url.password && !url.port && authorizationHosts[login.channel].includes(url.hostname) ? url.href : void 0;
190
+ } catch {
191
+ return;
192
+ }
193
+ }
194
+ function resetTime(value, countdown = false, now = Date.now()) {
195
+ if (!value || !Number.isFinite(Date.parse(value))) return "";
196
+ if (!countdown) return new Date(value).toLocaleString(void 0, {
197
+ month: "numeric",
198
+ day: "numeric",
199
+ hour: "2-digit",
200
+ minute: "2-digit"
201
+ });
202
+ const minutes = Math.round((Date.parse(value) - now) / 6e4);
203
+ if (minutes <= 0) return "";
204
+ const hours = Math.floor(minutes / 60);
205
+ return hours ? `${hours}h${minutes % 60}min` : `${minutes}min`;
206
+ }
207
+ // src/client/api.ts
208
+ async function call(request, signal) {
209
+ const response = await fetch(new URL("api/zephyr-models", document.baseURI), {
210
+ method: "POST",
211
+ credentials: "same-origin",
212
+ redirect: "error",
213
+ headers: { "Content-Type": "application/json" },
214
+ body: JSON.stringify(request),
215
+ signal
216
+ });
217
+ const value = await response.json();
218
+ signal?.throwIfAborted();
219
+ const error = isObject(value) && typeof value.error === "string" ? value.error : void 0;
220
+ if (!response.ok || error && isObject(value) && !("status" in value)) throw new Error(error || `HTTP ${response.status}`);
221
+ return isLoginRequest(request) ? readLogin(value) : readSnapshot(value);
222
+ }
223
+ // src/client/accounts-page.tsx
224
+ function createAccountsPage(React, ctx, store, t, Quota) {
225
+ const errorMessage = (error) => error instanceof Error ? error.message : t("failed");
226
+ return function AccountsPage() {
227
+ React.useSyncExternalStore((fn) => ctx.locale.subscribe(fn), () => ctx.locale.getSnapshot());
228
+ const data = React.useSyncExternalStore(store.subscribe, store.getSnapshot);
229
+ const [busy, setBusy] = React.useState(false);
230
+ const [error, setError] = React.useState("");
231
+ const [form, setForm] = React.useState(null);
232
+ const [label, setLabel] = React.useState("");
233
+ const [apiKey, setApiKey] = React.useState("");
234
+ const [login, setLogin] = React.useState(null);
235
+ const [answer, setAnswer] = React.useState("");
236
+ const [paste, setPaste] = React.useState(false);
237
+ const [removing, setRemoving] = React.useState(null);
238
+ const mounted = React.useRef(true);
239
+ React.useEffect(() => {
240
+ mounted.current = true;
241
+ store.reload().then((value) => {
242
+ if (!mounted.current) return;
243
+ setLogin(value.login ?? null);
244
+ if (value.login?.status === "pending") setForm(value.login.channel);
245
+ }).catch((error) => {
246
+ if (mounted.current) setError(errorMessage(error));
247
+ });
248
+ return () => {
249
+ mounted.current = false;
250
+ };
251
+ }, []);
252
+ const finishLogin = React.useCallback(async (value, signal) => {
253
+ if (value.status === "authorized") await store.update(() => call({ action: "refresh_quota" }, signal).catch((error) => {
254
+ if (signal?.aborted) throw error;
255
+ return call({ action: "list" }, signal);
256
+ }));
257
+ if (!mounted.current || signal?.aborted) return;
258
+ if (value.error) setError(value.error);
259
+ setLogin(null);
260
+ setForm(null);
261
+ setAnswer("");
262
+ setPaste(false);
263
+ }, []);
264
+ React.useEffect(() => {
265
+ if (login?.status !== "pending") return;
266
+ const attemptId = login.id;
267
+ const controller = new AbortController();
268
+ let timer;
269
+ async function poll() {
270
+ try {
271
+ const value = await call({
272
+ action: "login_status",
273
+ attemptId
274
+ }, controller.signal);
275
+ if (controller.signal.aborted) return;
276
+ if (value.status === "pending") {
277
+ setLogin(value);
278
+ timer = setTimeout(() => {
279
+ poll();
280
+ }, 1e3);
281
+ return;
282
+ }
283
+ await finishLogin(value, controller.signal);
284
+ } catch (error) {
285
+ if (!controller.signal.aborted) {
286
+ setError(errorMessage(error));
287
+ setLogin(null);
288
+ }
289
+ }
290
+ }
291
+ timer = setTimeout(() => {
292
+ poll();
293
+ }, 500);
294
+ return () => {
295
+ clearTimeout(timer);
296
+ controller.abort();
297
+ };
298
+ }, [
299
+ login?.id,
300
+ login?.status,
301
+ finishLogin
302
+ ]);
303
+ async function run(request) {
304
+ setBusy(true);
305
+ setError("");
306
+ try {
307
+ const value = isLoginRequest(request) ? await call(request) : await store.update(() => call(request));
308
+ if ("accounts" in value) {
309
+ if (mounted.current && request.action === "remove") setRemoving(null);
310
+ if (mounted.current && request.action === "add_key") {
311
+ setApiKey("");
312
+ setForm(null);
313
+ }
314
+ } else if (mounted.current) {
315
+ if (request.action === "login_cancel") {
316
+ setLogin(null);
317
+ setForm(null);
318
+ setAnswer("");
319
+ setPaste(false);
320
+ } else if (value.status === "pending") {
321
+ setLogin(value);
322
+ if (request.action === "login_start") {
323
+ setPaste(false);
324
+ setAnswer("");
325
+ }
326
+ if (request.action === "login_reply") {
327
+ setAnswer("");
328
+ setPaste(false);
329
+ }
330
+ } else await finishLogin(value);
331
+ }
332
+ } catch (error) {
333
+ if (mounted.current) setError(errorMessage(error));
334
+ } finally {
335
+ if (mounted.current) setBusy(false);
336
+ }
337
+ }
338
+ function button(caption, request, disabled = busy) {
339
+ return /* @__PURE__ */ React.createElement("button", {
340
+ type: "button",
341
+ disabled,
342
+ onClick: () => {
343
+ run(request);
344
+ }
345
+ }, caption);
346
+ }
347
+ function loginPanel(value) {
348
+ const url = authorizationURL(value);
349
+ return /* @__PURE__ */ React.createElement("div", {
350
+ className: "zph-login",
351
+ role: "status"
352
+ }, /* @__PURE__ */ React.createElement("strong", null, t("pending")), url && /* @__PURE__ */ React.createElement("a", {
353
+ href: url,
354
+ target: "_blank",
355
+ rel: "noreferrer noopener"
356
+ }, t("open")), value.notice?.code && /* @__PURE__ */ React.createElement("span", null, `${t("code")}: `, /* @__PURE__ */ React.createElement("code", null, value.notice.code)), value.prompt && !paste && /* @__PURE__ */ React.createElement("button", {
357
+ type: "button",
358
+ className: "zph-link",
359
+ onClick: () => setPaste(true)
360
+ }, t("paste")), value.prompt && paste && /* @__PURE__ */ React.createElement("form", {
361
+ className: "zph-row",
362
+ onSubmit: (event) => {
363
+ event.preventDefault();
364
+ run({
365
+ action: "login_reply",
366
+ attemptId: value.id,
367
+ answer
368
+ });
369
+ }
370
+ }, /* @__PURE__ */ React.createElement("input", {
371
+ value: answer,
372
+ required: true,
373
+ maxLength: 8192,
374
+ autoComplete: "off",
375
+ placeholder: value.prompt,
376
+ "aria-label": value.prompt,
377
+ onChange: (event) => setAnswer(event.currentTarget.value)
378
+ }), /* @__PURE__ */ React.createElement("button", {
379
+ type: "submit",
380
+ disabled: busy || !answer.trim()
381
+ }, t("reply"))), button(t("cancel"), {
382
+ action: "login_cancel",
383
+ attemptId: value.id
384
+ }));
385
+ }
386
+ return /* @__PURE__ */ React.createElement("section", {
387
+ className: "zph-accounts",
388
+ "aria-label": t("title"),
389
+ "aria-busy": busy
390
+ }, /* @__PURE__ */ React.createElement("style", null, css), /* @__PURE__ */ React.createElement("div", { className: "zph-row zph-between" }, /* @__PURE__ */ React.createElement("h2", null, t("title")), button(t("refreshAll"), { action: "refresh_quota" })), error && /* @__PURE__ */ React.createElement("p", {
391
+ role: "alert",
392
+ className: "zph-error"
393
+ }, error), !data ? /* @__PURE__ */ React.createElement("p", { role: "status" }, t("loading")) : data.channels.map((channel) => {
394
+ const accounts = data.accounts.filter((account) => account.channel === channel.id);
395
+ const active = accounts.find((account) => account.active);
396
+ const first = accounts[0];
397
+ return /* @__PURE__ */ React.createElement("div", {
398
+ key: channel.id,
399
+ className: "zph-channel"
400
+ }, /* @__PURE__ */ React.createElement("div", { className: "zph-head zph-row zph-between" }, /* @__PURE__ */ React.createElement("h3", null, channel.name), /* @__PURE__ */ React.createElement("label", { className: "zph-switch" }, /* @__PURE__ */ React.createElement("input", {
401
+ type: "checkbox",
402
+ role: "switch",
403
+ "aria-label": channel.name,
404
+ checked: Boolean(active),
405
+ disabled: busy || !first,
406
+ onChange: () => {
407
+ if (active) run({
408
+ action: "deactivate",
409
+ channel: channel.id
410
+ });
411
+ else if (first) run({
412
+ action: "activate",
413
+ channel: channel.id,
414
+ id: first.id
415
+ });
416
+ }
417
+ }))), accounts.map((account) => /* @__PURE__ */ React.createElement("article", {
418
+ key: account.id,
419
+ className: "zph-account"
420
+ }, /* @__PURE__ */ React.createElement("div", { className: "zph-row" }, /* @__PURE__ */ React.createElement("label", null, /* @__PURE__ */ React.createElement("input", {
421
+ type: "radio",
422
+ name: `zph-${channel.id}`,
423
+ checked: account.active,
424
+ disabled: busy,
425
+ onChange: () => {
426
+ run({
427
+ action: "activate",
428
+ channel: channel.id,
429
+ id: account.id
430
+ });
431
+ }
432
+ }), /* @__PURE__ */ React.createElement("strong", null, account.label)), account.quota?.plan && /* @__PURE__ */ React.createElement("span", { className: "zph-pill" }, account.quota.plan), /* @__PURE__ */ React.createElement("div", { className: "zph-actions" }, button(t("refresh"), {
433
+ action: "refresh_quota",
434
+ id: account.id
435
+ }), /* @__PURE__ */ React.createElement("button", {
436
+ type: "button",
437
+ disabled: busy,
438
+ "aria-expanded": removing === account.id,
439
+ "aria-controls": `zph-remove-${account.id}`,
440
+ onClick: () => setRemoving(account.id)
441
+ }, t("remove")))), removing === account.id && /* @__PURE__ */ React.createElement("div", {
442
+ id: `zph-remove-${account.id}`,
443
+ className: "zph-row",
444
+ role: "group",
445
+ "aria-label": t("confirmRemove")
446
+ }, /* @__PURE__ */ React.createElement("span", null, t("confirmRemove")), button(t("remove"), {
447
+ action: "remove",
448
+ id: account.id
449
+ }), /* @__PURE__ */ React.createElement("button", {
450
+ type: "button",
451
+ disabled: busy,
452
+ onClick: () => setRemoving(null)
453
+ }, t("cancel"))), /* @__PURE__ */ React.createElement(Quota, { quota: account.quota }))), !accounts.length && /* @__PURE__ */ React.createElement("p", { className: "zph-account zph-muted" }, t("empty")), /* @__PURE__ */ React.createElement("div", { className: "zph-add" }, /* @__PURE__ */ React.createElement("button", {
454
+ type: "button",
455
+ disabled: busy || login?.status === "pending" && login.channel !== channel.id,
456
+ onClick: () => {
457
+ if (form === channel.id && login?.channel === channel.id && login.status === "pending") {
458
+ run({
459
+ action: "login_cancel",
460
+ attemptId: login.id
461
+ });
462
+ return;
463
+ }
464
+ setForm(form === channel.id ? null : channel.id);
465
+ setLabel("");
466
+ setApiKey("");
467
+ setAnswer("");
468
+ setPaste(false);
469
+ }
470
+ }, form === channel.id ? t("cancel") : t("add")), form === channel.id && /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("form", {
471
+ className: "zph-form",
472
+ onSubmit: (event) => {
473
+ event.preventDefault();
474
+ if (channel.auth.includes("api-key")) run({
475
+ action: "add_key",
476
+ channel: channel.id,
477
+ label,
478
+ key: apiKey
479
+ });
480
+ }
481
+ }, /* @__PURE__ */ React.createElement("div", { className: "zph-row zph-align-end" }, /* @__PURE__ */ React.createElement("label", { className: "zph-grow" }, t("label"), /* @__PURE__ */ React.createElement("input", {
482
+ value: label,
483
+ maxLength: 160,
484
+ required: true,
485
+ autoComplete: "off",
486
+ onChange: (event) => setLabel(event.currentTarget.value)
487
+ })), channel.auth.includes("oauth") && button(t("login"), {
488
+ action: "login_start",
489
+ channel: channel.id,
490
+ label
491
+ }, busy || !label.trim() || login?.status === "pending")), channel.auth.includes("api-key") && /* @__PURE__ */ React.createElement("div", { className: "zph-row zph-align-end" }, /* @__PURE__ */ React.createElement("label", { className: "zph-grow" }, t("key"), /* @__PURE__ */ React.createElement("input", {
492
+ type: "password",
493
+ value: apiKey,
494
+ required: true,
495
+ maxLength: 32768,
496
+ autoComplete: "off",
497
+ spellCheck: false,
498
+ onChange: (event) => setApiKey(event.currentTarget.value)
499
+ })), /* @__PURE__ */ React.createElement("button", {
500
+ type: "submit",
501
+ disabled: busy || !label.trim() || !apiKey.trim()
502
+ }, t("save")))), login?.channel === channel.id && loginPanel(login))));
503
+ }));
504
+ };
505
+ }
506
+ // src/client/composer-quota.tsx
507
+ function createComposerQuota(React, ctx, store, QuotaBars) {
508
+ return function ComposerQuota({ sessionId }) {
509
+ React.useSyncExternalStore((fn) => ctx.locale.subscribe(fn), () => ctx.locale.getSnapshot());
510
+ const models = ctx.get("modelDirectories");
511
+ const modelStore = React.useMemo(() => {
512
+ try {
513
+ return models?.directoryFor(sessionId).store;
514
+ } catch {
515
+ return;
516
+ }
517
+ }, [models, sessionId]);
518
+ const state = React.useSyncExternalStore(React.useCallback((listener) => modelStore ? modelStore.subscribe(listener) : () => {}, [modelStore]), React.useCallback(() => modelStore?.getSnapshot(), [modelStore]));
519
+ const data = React.useSyncExternalStore(store.subscribe, store.getSnapshot);
520
+ const channel = channelOf(state?.current?.provider);
521
+ React.useEffect(() => {
522
+ if (channel) store.reload().catch(() => {});
523
+ }, [channel]);
524
+ return /* @__PURE__ */ React.createElement(QuotaBars, { windows: activeQuota(data, channel) });
525
+ };
526
+ }
527
+ // src/client/quota.tsx
528
+ function createQuotaComponents(React, t) {
529
+ function Quota({ quota }) {
530
+ const windows = quota?.status === "ok" ? measuredWindows(quota.windows) : [];
531
+ return /* @__PURE__ */ React.createElement("div", null, windows.length ? /* @__PURE__ */ React.createElement("div", { className: "zph-quota" }, windows.map((window) => /* @__PURE__ */ React.createElement("div", {
532
+ key: window.period,
533
+ className: "zph-window"
534
+ }, /* @__PURE__ */ React.createElement("div", { className: "zph-window-head" }, /* @__PURE__ */ React.createElement("span", null, /* @__PURE__ */ React.createElement("strong", null, window.period === "5h" ? "5h" : t(window.period)), ` · ${Math.round(leftOf(window))}%`), /* @__PURE__ */ React.createElement("span", { className: "zph-muted" }, resetTime(window.resetsAt, window.period === "5h"))), /* @__PURE__ */ React.createElement("span", {
535
+ className: "zph-track",
536
+ "data-level": levelOf(window),
537
+ role: "img",
538
+ "aria-label": `${window.period} ${t("left")} ${Math.round(leftOf(window))}%`
539
+ }, /* @__PURE__ */ React.createElement("b", { style: { width: `${leftOf(window)}%` } })), window.used !== void 0 && window.limit !== void 0 && /* @__PURE__ */ React.createElement("div", { className: "zph-muted" }, `${window.used} / ${window.limit} ${window.unit || ""}`)))) : /* @__PURE__ */ React.createElement("p", { className: "zph-muted" }, t(quota ? "unavailable" : "notFetched")), quota?.status === "ok" && quota.windows.filter((window) => window.period === "other").map((window, index) => /* @__PURE__ */ React.createElement("div", {
540
+ className: "zph-muted",
541
+ key: index
542
+ }, `${window.label || t("other")}: ${window.usedPercent?.toFixed(1) ?? "—"}% ${t("used")}`)), quota?.reason && /* @__PURE__ */ React.createElement("p", { className: quota.status === "error" ? "zph-error" : "zph-muted" }, quota.reason));
543
+ }
544
+ function QuotaBars({ windows }) {
545
+ if (!windows.length) return null;
546
+ const labels = windows.map((window) => `${window.period === "5h" ? "5h" : t(window.period)} ${t("left")} ${Math.round(leftOf(window))}%`);
547
+ return /* @__PURE__ */ React.createElement("span", {
548
+ className: "zph-composer-quota",
549
+ role: "img",
550
+ "data-count": windows.length,
551
+ title: labels.join(" · "),
552
+ "aria-label": labels.join(", ")
553
+ }, /* @__PURE__ */ React.createElement("style", null, css), windows.map((window) => /* @__PURE__ */ React.createElement("span", {
554
+ key: window.period,
555
+ className: "zph-track",
556
+ "data-level": levelOf(window)
557
+ }, /* @__PURE__ */ React.createElement("b", { style: { width: `${leftOf(window)}%` } }))));
558
+ }
559
+ return {
560
+ Quota,
561
+ QuotaBars
562
+ };
563
+ }
564
+ // src/client/store.ts
565
+ function createAccountStore(load) {
566
+ let snapshot;
567
+ let pending;
568
+ let revision = 0;
569
+ let disposed = false;
570
+ let timer;
571
+ const listeners = /* @__PURE__ */ new Set();
572
+ const stopPolling = () => {
573
+ if (timer !== void 0) clearInterval(timer);
574
+ timer = void 0;
575
+ };
576
+ const notify = (value) => {
577
+ if (disposed) return;
578
+ snapshot = value;
579
+ for (const listener of listeners) listener();
580
+ };
581
+ const publish = (value) => {
582
+ revision++;
583
+ notify(value);
584
+ };
585
+ const store = {
586
+ getSnapshot: () => snapshot,
587
+ subscribe(listener) {
588
+ if (disposed) return () => {};
589
+ listeners.add(listener);
590
+ timer ??= setInterval(() => {
591
+ store.reload().catch(() => {});
592
+ }, 6e4);
593
+ return () => {
594
+ listeners.delete(listener);
595
+ if (!listeners.size) stopPolling();
596
+ };
597
+ },
598
+ publish,
599
+ async update(operation) {
600
+ if (disposed) throw new Error("Model Accounts is unloading");
601
+ const started = ++revision;
602
+ const value = await operation();
603
+ if (revision === started) publish(value);
604
+ return snapshot ?? value;
605
+ },
606
+ reload() {
607
+ if (disposed) return Promise.reject(/* @__PURE__ */ new Error("Model Accounts is unloading"));
608
+ if (pending) return pending;
609
+ const started = revision;
610
+ pending = load().then((value) => {
611
+ if (revision === started) notify(value);
612
+ return snapshot ?? value;
613
+ }).finally(() => {
614
+ pending = void 0;
615
+ });
616
+ return pending;
617
+ },
618
+ dispose() {
619
+ disposed = true;
620
+ revision++;
621
+ stopPolling();
622
+ listeners.clear();
623
+ }
624
+ };
625
+ return store;
626
+ }
627
+ // src/client.tsx
628
+ const loader = window.__ModuleLoader__;
629
+ if (!loader || typeof loader.load !== "function") throw new Error("Harness module loader is unavailable");
630
+ loader.load({
631
+ id: "@liyang8246/dsh-accounts",
632
+ factory(require) {
633
+ const React = require("react");
634
+ return {
635
+ inject: [
636
+ "slots",
637
+ "locale",
638
+ "modelDirectories"
639
+ ],
640
+ apply(ctx) {
641
+ ctx.effect(() => ctx.locale.register("zephyr-accounts", "en", en));
642
+ ctx.effect(() => ctx.locale.register("zephyr-accounts", "zh", zh));
643
+ const t = ctx.locale.bind("zephyr-accounts");
644
+ const store = createAccountStore(() => call({ action: "list" }));
645
+ ctx.effect(() => () => store.dispose());
646
+ const { Quota, QuotaBars } = createQuotaComponents(React, t);
647
+ const ComposerQuota = createComposerQuota(React, ctx, store, QuotaBars);
648
+ const AccountsPage = createAccountsPage(React, ctx, store, t, Quota);
649
+ ctx.slots.inject("settings.section", () => ctx.slots.register({
650
+ name: "settings.section",
651
+ id: "zephyr-accounts",
652
+ order: 12,
653
+ label: () => t("title")
654
+ }, AccountsPage));
655
+ ctx.slots.inject("conversation.input.right", () => ctx.slots.register({
656
+ name: "conversation.input.right",
657
+ id: "zephyr-quota"
658
+ }, ComposerQuota));
659
+ }
660
+ };
661
+ }
662
+ });
663
+ })();