dsh-rest-api 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,803 @@
1
+ /**
2
+ * dsh-rest-api 浏览器侧配置面板插件。
3
+ *
4
+ * 挂载于 dsh Web「插件 -> 已安装插件 -> dsh-rest-api」详情页(plugins.bundle.config)
5
+ * 以及 `rest-api` 组件行配置页(plugins.row.config),通过 dsh 原生 `ctx.configForms`
6
+ * 读写 Host 设置文档,所有修改保存后即时热生效,无需重启 dsh web。
7
+ */
8
+ window.__ModuleLoader__.load({
9
+ id: "dsh-rest-api",
10
+ factory: (require) => {
11
+ const module = { exports: {} };
12
+ const exports = module.exports;
13
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
14
+
15
+ const React = require("react");
16
+ const jsxRuntime = require("react/jsx-runtime");
17
+ const { jsx, jsxs } = jsxRuntime;
18
+
19
+ const NS = "rest-api";
20
+ const BUNDLE_NAME = "dsh-rest-api";
21
+ const ROW_KEY = `${BUNDLE_NAME}#${NS}`;
22
+ const STYLE_ID = "dsh-rest-api/settings-panel.css";
23
+
24
+ const TEXT = {
25
+ zh: {
26
+ summary: "通用 REST API 网关(同步对话、异步长轮询、SSE 进度流、Webhook 回调与任务停止)",
27
+ title: "REST API 配置",
28
+ subtitle: "保存后写入当前 Profile 并立即热生效,无需重启 dsh web。",
29
+ statusRunning: "运行中",
30
+ statusBearerProtected: "运行中(Bearer 鉴权已开启)",
31
+ statusProxyProtected: "受前置反代鉴权保护 (HTTP 401)",
32
+ statusChecking: "检测中…",
33
+ statusOffline: "未响应",
34
+ refresh: "刷新状态",
35
+ copyCurl: "复制健康检查 curl",
36
+ copied: "已复制",
37
+ endpointLabel: "API 基础路径",
38
+ loading: "正在加载配置…",
39
+ unavailable: "插件当前未激活,暂时无法编辑配置。",
40
+ readOnly: "当前 Profile 为只读模式,无法通过页面保存修改。",
41
+ sectionModel: "模型与默认预设",
42
+ sectionWorkspace: "侧边栏分组与工作区",
43
+ sectionAuth: "接入鉴权与安全",
44
+ sectionAdvanced: "Webhook 与运行限制",
45
+ presetId: "默认 Agent 预设 (presetId)",
46
+ presetIdHint: "留空则继承 Host 默认预设;推荐使用 headless-task(非交互式,不阻塞追问)。",
47
+ provider: "默认模型提供商 (provider)",
48
+ providerHint: "例如 openrouter、deepseek;留空则继承 dsh 全局默认模型。",
49
+ model: "默认模型 (model)",
50
+ modelHint: "例如 deepseek/deepseek-v3.2;留空则继承 dsh 全局默认模型。",
51
+ workspaceTitle: "侧边栏分组名称 (workspaceTitle)",
52
+ workspaceTitleHint: "所有通过 API 创建的会话将统一归入此左侧栏分组,避免散落在「未分组」。",
53
+ workspaceDir: "工作区目录 (workspaceDir)",
54
+ workspaceDirHint: "支持 ~ 路径;留空默认 ~/.dsh/rest-api-workspace。",
55
+ sandboxMode: "默认沙箱模式 (sandboxMode)",
56
+ sandboxReadOnly: "read-only(仅读)",
57
+ sandboxWrite: "workspace-write(工作区可写,推荐)",
58
+ sandboxFull: "danger-full-access(完全访问)",
59
+ approvalPolicy: "默认工具审批策略 (approvalPolicy)",
60
+ approvalNever: "never(自动放行,无人值守推荐)",
61
+ approvalAsk: "ask(需要确认)",
62
+ authMode: "访问鉴权模式 (authMode)",
63
+ authLoopback: "loopback(仅本机与反代,推荐配合 Pangolin / Nginx)",
64
+ authBearer: "bearer(校验 Authorization: Bearer Token)",
65
+ authNone: "none(无鉴权,仅限受信任内网)",
66
+ apiKey: "Bearer API Key (apiKey)",
67
+ apiKeyHint: "仅在 authMode=bearer 时生效。出于安全原因不回传明文;留空表示保持当前密钥不变。",
68
+ apiKeyConfigured: "当前状态:已配置密钥",
69
+ apiKeyUnset: "当前状态:未配置密钥(将回退读取环境变量)",
70
+ apiKeyPlaceholderSet: "输入新密钥以覆盖,留空保持不变",
71
+ apiKeyPlaceholderUnset: "输入 Bearer Token",
72
+ clearApiKey: "清空已保存密钥",
73
+ clearApiKeyPending: "保存时将清空密钥",
74
+ apiKeyEnv: "备用密钥环境变量名 (apiKeyEnv)",
75
+ apiKeyEnvHint: "当上方 apiKey 为空且 authMode=bearer 时读取此环境变量。",
76
+ allowRequestOverrides: "允许请求级覆盖参数 (allowRequestOverrides)",
77
+ allowRequestOverridesHint: "允许调用方在单次请求中指定 preset、workspace_title、provider 或 model。",
78
+ allowCustomWorkspaceDir: "允许请求级自定义工作区目录 (allowCustomWorkspaceDir)",
79
+ allowCustomWorkspaceDirHint: "高权限选项:开启后调用方可通过 workspace_dir 指定任意宿主机目录(默认关闭)。",
80
+ defaultWebhookUrl: "全局默认 Webhook URL (defaultWebhookUrl)",
81
+ defaultWebhookUrlHint: "可选。任务进入 completed / cancelled / failed 时自动 POST 回调此地址。",
82
+ webhookTimeoutMs: "Webhook 超时时间 (ms)",
83
+ requestTimeoutMs: "HTTP 长连接超时 (ms)",
84
+ runRetentionMs: "Run 记录内存保留时长 (ms)",
85
+ save: "保存配置",
86
+ saving: "保存中…",
87
+ discard: "撤销修改",
88
+ savedOk: "配置已保存并即时热生效。",
89
+ saveFailed: "保存失败:服务端拒绝了本次修改,请检查参数格式或刷新后重试。",
90
+ invalidNumber: "请输入大于 0 的有效整数。",
91
+ dirtyBadge: (n) => `${n} 项未保存更改`,
92
+ },
93
+ en: {
94
+ summary: "Standard REST API gateway (sync messages, async long-polling runs, SSE streaming, webhooks, and cancellation)",
95
+ title: "REST API Settings",
96
+ subtitle: "Changes are written to the active profile and take effect live without restarting dsh web.",
97
+ statusRunning: "Running",
98
+ statusBearerProtected: "Running (Bearer auth enabled)",
99
+ statusProxyProtected: "Protected by reverse-proxy auth (HTTP 401)",
100
+ statusChecking: "Checking…",
101
+ statusOffline: "Unreachable",
102
+ refresh: "Refresh status",
103
+ copyCurl: "Copy health curl",
104
+ copied: "Copied",
105
+ endpointLabel: "API Base URL",
106
+ loading: "Loading configuration…",
107
+ unavailable: "This plugin is not active right now and cannot be configured.",
108
+ readOnly: "The active profile is read-only; settings cannot be saved here.",
109
+ sectionModel: "Model & Default Preset",
110
+ sectionWorkspace: "Sidebar Group & Workspace",
111
+ sectionAuth: "Authentication & Security",
112
+ sectionAdvanced: "Webhook & Runtime Limits",
113
+ presetId: "Default Agent Preset (presetId)",
114
+ presetIdHint: "Leave empty to use the host default preset. headless-task is recommended for non-interactive runs.",
115
+ provider: "Default Provider (provider)",
116
+ providerHint: "e.g. openrouter, deepseek. Leave empty to inherit the dsh global default.",
117
+ model: "Default Model (model)",
118
+ modelHint: "e.g. deepseek/deepseek-v3.2. Leave empty to inherit the dsh global default.",
119
+ workspaceTitle: "Sidebar Workspace Group (workspaceTitle)",
120
+ workspaceTitleHint: "API-created sessions appear under this sidebar group instead of Ungrouped.",
121
+ workspaceDir: "Workspace Directory (workspaceDir)",
122
+ workspaceDirHint: "Supports ~ expansion. Leave empty for ~/.dsh/rest-api-workspace.",
123
+ sandboxMode: "Default Sandbox Mode (sandboxMode)",
124
+ sandboxReadOnly: "read-only",
125
+ sandboxWrite: "workspace-write (recommended)",
126
+ sandboxFull: "danger-full-access",
127
+ approvalPolicy: "Default Tool Approval Policy (approvalPolicy)",
128
+ approvalNever: "never (recommended for headless runs)",
129
+ approvalAsk: "ask",
130
+ authMode: "Access Control Mode (authMode)",
131
+ authLoopback: "loopback (local & reverse proxy, e.g. Pangolin / Nginx)",
132
+ authBearer: "bearer (require Authorization: Bearer token)",
133
+ authNone: "none (trusted private network only)",
134
+ apiKey: "Bearer API Key (apiKey)",
135
+ apiKeyHint: "Used when authMode=bearer. Never returned in plaintext; leave blank to keep the existing key.",
136
+ apiKeyConfigured: "Status: Secret is configured",
137
+ apiKeyUnset: "Status: Not set (falls back to apiKeyEnv)",
138
+ apiKeyPlaceholderSet: "Enter a new key to replace, or leave blank",
139
+ apiKeyPlaceholderUnset: "Enter Bearer token",
140
+ clearApiKey: "Clear saved key",
141
+ clearApiKeyPending: "Key will be cleared on save",
142
+ apiKeyEnv: "Fallback Env Variable (apiKeyEnv)",
143
+ apiKeyEnvHint: "Environment variable read when apiKey is empty and authMode=bearer.",
144
+ allowRequestOverrides: "Allow Per-Request Overrides (allowRequestOverrides)",
145
+ allowRequestOverridesHint: "Allow callers to override preset, workspace_title, provider, or model per request.",
146
+ allowCustomWorkspaceDir: "Allow Custom workspace_dir (allowCustomWorkspaceDir)",
147
+ allowCustomWorkspaceDirHint: "Privileged option: allow callers to pass arbitrary host directories via workspace_dir.",
148
+ defaultWebhookUrl: "Default Webhook URL (defaultWebhookUrl)",
149
+ defaultWebhookUrlHint: "Optional URL receiving POST callbacks when runs complete, cancel, or fail.",
150
+ webhookTimeoutMs: "Webhook Timeout (ms)",
151
+ requestTimeoutMs: "HTTP Request Timeout (ms)",
152
+ runRetentionMs: "Run Retention in Memory (ms)",
153
+ save: "Save Changes",
154
+ saving: "Saving…",
155
+ discard: "Discard",
156
+ savedOk: "Saved and applied live.",
157
+ saveFailed: "Save failed: the host rejected these values. Please verify and try again.",
158
+ invalidNumber: "Please enter a valid positive integer.",
159
+ dirtyBadge: (n) => `${n} unsaved change${n > 1 ? "s" : ""}`,
160
+ },
161
+ };
162
+
163
+ const CSS = `
164
+ .dshra-wrap{display:flex;flex-direction:column;gap:16px;font-size:13px;line-height:1.5;color:var(--dsw-alias-label-primary,inherit)}
165
+ .dshra-statusCard{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:12px;padding:12px 14px;border-radius:10px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.22));background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.06))}
166
+ .dshra-statusLeft{display:flex;flex-direction:column;gap:4px;min-width:0}
167
+ .dshra-statusRow{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
168
+ .dshra-dot{width:8px;height:8px;border-radius:999px;flex-shrink:0}
169
+ .dshra-dot-ok{background:#22c55e}
170
+ .dshra-dot-warn{background:#f59e0b}
171
+ .dshra-dot-err{background:#ef4444}
172
+ .dshra-statusTitle{font-weight:600;font-size:13px}
173
+ .dshra-endpoint{font-family:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,monospace;font-size:12px;color:var(--dsw-alias-label-secondary,rgba(128,128,128,.9));word-break:break-all}
174
+ .dshra-statusActions{display:flex;align-items:center;gap:8px;flex-wrap:wrap}
175
+ .dshra-section{display:flex;flex-direction:column;gap:12px;padding:14px;border-radius:10px;border:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.2));background:var(--dsw-alias-bg-layer-1,transparent)}
176
+ .dshra-sectionTitle{margin:0;font-size:13px;font-weight:600;color:var(--dsw-alias-label-primary,inherit);padding-bottom:6px;border-bottom:1px solid var(--dsw-alias-border-l2,rgba(128,128,128,.16))}
177
+ .dshra-grid{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px}
178
+ .dshra-field{display:flex;flex-direction:column;gap:5px;min-width:0}
179
+ .dshra-fieldFull{grid-column:1 / -1}
180
+ .dshra-labelRow{display:flex;align-items:center;justify-content:space-between;gap:8px}
181
+ .dshra-label{font-weight:500;font-size:12.5px;color:var(--dsw-alias-label-primary,inherit)}
182
+ .dshra-hint{margin:0;font-size:12px;color:var(--dsw-alias-label-tertiary,rgba(128,128,128,.85))}
183
+ .dshra-input,.dshra-select{width:100%;box-sizing:border-box;padding:7px 10px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.3));background:var(--dsw-alias-bg-layer-1,rgba(128,128,128,.05));color:var(--dsw-alias-label-primary,inherit);font:inherit;font-size:13px;outline:none;transition:border-color 140ms ease}
184
+ .dshra-input:focus,.dshra-select:focus{border-color:var(--dsw-alias-interactive-primary,#3b82f6)}
185
+ .dshra-input:disabled,.dshra-select:disabled{opacity:.6;cursor:not-allowed}
186
+ .dshra-toggleRow{display:flex;align-items:flex-start;justify-content:space-between;gap:12px;padding:6px 0}
187
+ .dshra-toggleText{display:flex;flex-direction:column;gap:2px}
188
+ .dshra-checkbox{width:16px;height:16px;margin-top:2px;accent-color:var(--dsw-alias-interactive-primary,#3b82f6);cursor:pointer;flex-shrink:0}
189
+ .dshra-secretMeta{display:flex;align-items:center;justify-content:space-between;gap:8px;font-size:12px;color:var(--dsw-alias-label-secondary,rgba(128,128,128,.9))}
190
+ .dshra-footer{display:flex;flex-wrap:wrap;align-items:center;justify-content:space-between;gap:10px;padding-top:4px}
191
+ .dshra-footerLeft{display:flex;align-items:center;gap:8px;min-height:24px}
192
+ .dshra-footerRight{display:flex;align-items:center;gap:8px}
193
+ .dshra-btn{padding:6px 12px;border-radius:8px;border:1px solid var(--dsw-alias-border-l1,rgba(128,128,128,.3));background:var(--dsw-alias-bg-layer-2,rgba(128,128,128,.08));color:var(--dsw-alias-label-primary,inherit);font:inherit;font-size:12.5px;font-weight:500;cursor:pointer;transition:opacity 140ms ease,background 140ms ease}
194
+ .dshra-btn:hover:not(:disabled){opacity:.9}
195
+ .dshra-btn:disabled{opacity:.5;cursor:not-allowed}
196
+ .dshra-btnPrimary{background:var(--dsw-alias-interactive-primary,#2563eb);border-color:transparent;color:#fff}
197
+ .dshra-btnLink{padding:2px 6px;border:0;background:transparent;color:var(--dsw-alias-link,#3b82f6);font:inherit;font-size:12px;cursor:pointer}
198
+ .dshra-btnLink:hover{text-decoration:underline}
199
+ .dshra-msgOk{color:#16a34a;font-size:12.5px;font-weight:500}
200
+ .dshra-msgErr{color:#dc2626;font-size:12.5px;font-weight:500}
201
+ .dshra-msgMuted{color:var(--dsw-alias-label-tertiary,rgba(128,128,128,.85));font-size:12.5px}
202
+ `;
203
+
204
+ function injectStyles() {
205
+ if (typeof document === "undefined") return;
206
+ if (document.querySelector(`style[data-plugin-css=${JSON.stringify(STYLE_ID)}]`)) return;
207
+ const tag = document.createElement("style");
208
+ tag.dataset.plugin = BUNDLE_NAME;
209
+ tag.dataset.pluginCss = STYLE_ID;
210
+ tag.textContent = CSS;
211
+ document.head.appendChild(tag);
212
+ }
213
+
214
+ function detectLang(ctx) {
215
+ try {
216
+ const localeSvc = ctx.get?.("locale");
217
+ const raw =
218
+ localeSvc?.current?.() ??
219
+ localeSvc?.language ??
220
+ (typeof document !== "undefined" ? document.documentElement.lang : "") ??
221
+ (typeof navigator !== "undefined" ? navigator.language : "");
222
+ return String(raw || "").toLowerCase().startsWith("zh") ? "zh" : "en";
223
+ } catch {
224
+ return "en";
225
+ }
226
+ }
227
+
228
+ function buildDraftFromValue(val) {
229
+ const v = val && typeof val === "object" ? val : {};
230
+ return {
231
+ presetId: String(v.presetId ?? "headless-task"),
232
+ provider: String(v.provider ?? ""),
233
+ model: String(v.model ?? ""),
234
+ workspaceTitle: String(v.workspaceTitle ?? "API Tasks"),
235
+ workspaceDir: String(v.workspaceDir ?? ""),
236
+ sandboxMode: String(v.sandboxMode ?? "workspace-write"),
237
+ approvalPolicy: String(v.approvalPolicy ?? "never"),
238
+ authMode: String(v.authMode ?? "loopback"),
239
+ apiKeyEnv: String(v.apiKeyEnv ?? "DSH_REST_API_KEY"),
240
+ allowRequestOverrides: v.allowRequestOverrides !== false,
241
+ allowCustomWorkspaceDir: v.allowCustomWorkspaceDir === true,
242
+ defaultWebhookUrl: String(v.defaultWebhookUrl ?? ""),
243
+ webhookTimeoutMs: String(v.webhookTimeoutMs ?? 10000),
244
+ requestTimeoutMs: String(v.requestTimeoutMs ?? 960000),
245
+ runRetentionMs: String(v.runRetentionMs ?? 86400000),
246
+ };
247
+ }
248
+
249
+ const STRING_FIELDS = [
250
+ "presetId",
251
+ "provider",
252
+ "model",
253
+ "workspaceTitle",
254
+ "workspaceDir",
255
+ "sandboxMode",
256
+ "approvalPolicy",
257
+ "authMode",
258
+ "apiKeyEnv",
259
+ "defaultWebhookUrl",
260
+ ];
261
+ const BOOLEAN_FIELDS = ["allowRequestOverrides", "allowCustomWorkspaceDir"];
262
+ const NUMBER_FIELDS = ["webhookTimeoutMs", "requestTimeoutMs", "runRetentionMs"];
263
+
264
+ function readSecretSet(describeFace) {
265
+ try {
266
+ const snap = describeFace?.getSnapshot?.();
267
+ const entry = snap?.namespaces?.find((item) => item.ns === NS);
268
+ const secret = entry?.secrets?.find((s) => Array.isArray(s.path) && s.path[0] === "apiKey");
269
+ return secret?.set === true;
270
+ } catch {
271
+ return false;
272
+ }
273
+ }
274
+
275
+ function createPanelComponent(ctx) {
276
+ const form = ctx.configForms.get(NS);
277
+ const describeFace = ctx.configForms.describe();
278
+
279
+ return function RestApiConfigPanel(slotProps) {
280
+ const lang = detectLang(ctx);
281
+ const t = TEXT[lang] || TEXT.en;
282
+
283
+ if (slotProps && slotProps.view === "summary") {
284
+ return t.summary;
285
+ }
286
+
287
+ const [snapshot, setSnapshot] = React.useState(() => form.getSnapshot());
288
+ const [apiKeySet, setApiKeySet] = React.useState(() => readSecretSet(describeFace));
289
+ const [draft, setDraft] = React.useState(() => buildDraftFromValue(snapshot.value));
290
+ const [apiKeyInput, setApiKeyInput] = React.useState("");
291
+ const [clearApiKey, setClearApiKey] = React.useState(false);
292
+ const [saving, setSaving] = React.useState(false);
293
+ const [feedback, setFeedback] = React.useState(null);
294
+ const [copied, setCopied] = React.useState(false);
295
+ const [health, setHealth] = React.useState({ state: "checking", data: null, detail: "" });
296
+
297
+ const baseUrl = React.useMemo(() => {
298
+ if (typeof window === "undefined" || !window.location?.origin) return "/v1";
299
+ return `${window.location.origin}/v1`;
300
+ }, []);
301
+
302
+ const baseline = React.useMemo(() => buildDraftFromValue(snapshot.value), [snapshot.value]);
303
+
304
+ React.useEffect(() => {
305
+ injectStyles();
306
+ const unsubForm = form.subscribe(() => {
307
+ const next = form.getSnapshot();
308
+ setSnapshot(next);
309
+ });
310
+ const unsubDesc = describeFace?.subscribe?.(() => {
311
+ setApiKeySet(readSecretSet(describeFace));
312
+ });
313
+ return () => {
314
+ unsubForm?.();
315
+ unsubDesc?.();
316
+ };
317
+ }, []);
318
+
319
+ // 仅当后端 revision 变化(初始化加载或保存成功)时重置表单草稿
320
+ React.useEffect(() => {
321
+ setDraft(buildDraftFromValue(snapshot.value));
322
+ setApiKeyInput("");
323
+ setClearApiKey(false);
324
+ }, [snapshot.revision, snapshot.status]);
325
+
326
+ const checkHealth = React.useCallback(async () => {
327
+ setHealth({ state: "checking", data: null, detail: "" });
328
+ try {
329
+ // 携带同源 Cookie,确保在 Pangolin / Nginx 等前置鉴权反代下复用浏览器登录态
330
+ const res = await fetch("/v1/health", {
331
+ credentials: "same-origin",
332
+ headers: { Accept: "application/json" },
333
+ });
334
+ if (res.status === 401) {
335
+ setHealth({
336
+ state: "bearer",
337
+ data: null,
338
+ detail: "HTTP 401",
339
+ });
340
+ return;
341
+ }
342
+ const contentType = res.headers.get("content-type") || "";
343
+ if (!res.ok || !contentType.includes("application/json")) {
344
+ setHealth({
345
+ state: "offline",
346
+ data: null,
347
+ detail: `HTTP ${res.status}`,
348
+ });
349
+ return;
350
+ }
351
+ const data = await res.json();
352
+ setHealth({ state: "ok", data, detail: "" });
353
+ } catch (err) {
354
+ setHealth({
355
+ state: "offline",
356
+ data: null,
357
+ detail: err instanceof Error ? err.message : String(err),
358
+ });
359
+ }
360
+ }, []);
361
+
362
+ React.useEffect(() => {
363
+ void checkHealth();
364
+ }, [checkHealth]);
365
+
366
+ const pendingOps = React.useMemo(() => {
367
+ const ops = [];
368
+ for (const key of STRING_FIELDS) {
369
+ if (draft[key] !== baseline[key]) {
370
+ ops.push({ op: "set", path: [key], value: draft[key].trim() });
371
+ }
372
+ }
373
+ for (const key of BOOLEAN_FIELDS) {
374
+ if (draft[key] !== baseline[key]) {
375
+ ops.push({ op: "set", path: [key], value: Boolean(draft[key]) });
376
+ }
377
+ }
378
+ for (const key of NUMBER_FIELDS) {
379
+ if (draft[key] !== baseline[key]) {
380
+ const num = Number(draft[key]);
381
+ ops.push({ op: "set", path: [key], value: num });
382
+ }
383
+ }
384
+ if (clearApiKey) {
385
+ ops.push({ op: "unset", path: ["apiKey"] });
386
+ } else if (apiKeyInput.trim().length > 0) {
387
+ ops.push({ op: "set", path: ["apiKey"], value: apiKeyInput.trim() });
388
+ }
389
+ return ops;
390
+ }, [draft, baseline, apiKeyInput, clearApiKey]);
391
+
392
+ const invalidNumbers = React.useMemo(() => {
393
+ const bad = {};
394
+ for (const key of NUMBER_FIELDS) {
395
+ const num = Number(draft[key]);
396
+ if (!Number.isInteger(num) || num <= 0) bad[key] = true;
397
+ }
398
+ return bad;
399
+ }, [draft]);
400
+
401
+ const hasValidationError = Object.keys(invalidNumbers).length > 0;
402
+ const dirtyCount = pendingOps.length;
403
+ const disabled = !snapshot.writable || saving || snapshot.status !== "ready";
404
+
405
+ const updateField = (key, val) => {
406
+ setFeedback(null);
407
+ setDraft((prev) => ({ ...prev, [key]: val }));
408
+ };
409
+
410
+ const handleDiscard = () => {
411
+ setDraft(baseline);
412
+ setApiKeyInput("");
413
+ setClearApiKey(false);
414
+ setFeedback(null);
415
+ };
416
+
417
+ const handleSave = async () => {
418
+ if (disabled || dirtyCount === 0 || hasValidationError) return;
419
+ setSaving(true);
420
+ setFeedback(null);
421
+ try {
422
+ const accepted = await form.mutate(pendingOps, snapshot.revision);
423
+ if (accepted) {
424
+ setApiKeyInput("");
425
+ setClearApiKey(false);
426
+ setFeedback({ kind: "ok", text: t.savedOk });
427
+ setTimeout(() => void checkHealth(), 150);
428
+ } else {
429
+ setFeedback({ kind: "err", text: t.saveFailed });
430
+ }
431
+ } catch (err) {
432
+ setFeedback({
433
+ kind: "err",
434
+ text: `${t.saveFailed} (${err instanceof Error ? err.message : String(err)})`,
435
+ });
436
+ } finally {
437
+ setSaving(false);
438
+ }
439
+ };
440
+
441
+ const handleCopyCurl = async () => {
442
+ const cmd =
443
+ draft.authMode === "bearer"
444
+ ? `curl -H "Authorization: Bearer $DSH_REST_API_KEY" ${baseUrl}/health`
445
+ : `curl ${baseUrl}/health`;
446
+ try {
447
+ await navigator.clipboard.writeText(cmd);
448
+ setCopied(true);
449
+ setTimeout(() => setCopied(false), 1800);
450
+ } catch {}
451
+ };
452
+
453
+ const statusDotClass =
454
+ health.state === "ok"
455
+ ? "dshra-dot dshra-dot-ok"
456
+ : health.state === "bearer" || health.state === "checking"
457
+ ? "dshra-dot dshra-dot-warn"
458
+ : "dshra-dot dshra-dot-err";
459
+
460
+ const statusLabel =
461
+ health.state === "ok"
462
+ ? `${t.statusRunning}${health.data ? ` · running ${health.data.running ?? 0} / queued ${health.data.queued ?? 0}` : ""}`
463
+ : health.state === "bearer"
464
+ ? (draft.authMode === "bearer" ? t.statusBearerProtected : t.statusProxyProtected)
465
+ : health.state === "checking"
466
+ ? t.statusChecking
467
+ : `${t.statusOffline}${health.detail ? ` (${health.detail})` : ""}`;
468
+
469
+ const textField = (key, label, hint, placeholder = "", full = false) =>
470
+ jsxs("div", {
471
+ className: full ? "dshra-field dshra-fieldFull" : "dshra-field",
472
+ children: [
473
+ jsx("label", { className: "dshra-label", htmlFor: `dshra-${key}`, children: label }),
474
+ jsx("input", {
475
+ id: `dshra-${key}`,
476
+ className: "dshra-input",
477
+ type: "text",
478
+ disabled,
479
+ value: draft[key],
480
+ placeholder,
481
+ onChange: (e) => updateField(key, e.target.value),
482
+ }),
483
+ hint && jsx("p", { className: "dshra-hint", children: hint }),
484
+ ],
485
+ });
486
+
487
+ const numberField = (key, label) =>
488
+ jsxs("div", {
489
+ className: "dshra-field",
490
+ children: [
491
+ jsx("label", { className: "dshra-label", htmlFor: `dshra-${key}`, children: label }),
492
+ jsx("input", {
493
+ id: `dshra-${key}`,
494
+ className: "dshra-input",
495
+ type: "number",
496
+ min: 1,
497
+ step: 1,
498
+ disabled,
499
+ value: draft[key],
500
+ onChange: (e) => updateField(key, e.target.value),
501
+ }),
502
+ invalidNumbers[key] && jsx("p", { className: "dshra-msgErr", children: t.invalidNumber }),
503
+ ],
504
+ });
505
+
506
+ const selectField = (key, label, options, hint) =>
507
+ jsxs("div", {
508
+ className: "dshra-field",
509
+ children: [
510
+ jsx("label", { className: "dshra-label", htmlFor: `dshra-${key}`, children: label }),
511
+ jsx("select", {
512
+ id: `dshra-${key}`,
513
+ className: "dshra-select",
514
+ disabled,
515
+ value: draft[key],
516
+ onChange: (e) => updateField(key, e.target.value),
517
+ children: options.map((opt) =>
518
+ jsx("option", { value: opt.value, children: opt.label }, opt.value),
519
+ ),
520
+ }),
521
+ hint && jsx("p", { className: "dshra-hint", children: hint }),
522
+ ],
523
+ });
524
+
525
+ const toggleField = (key, label, hint) =>
526
+ jsxs("label", {
527
+ className: "dshra-toggleRow",
528
+ children: [
529
+ jsxs("div", {
530
+ className: "dshra-toggleText",
531
+ children: [
532
+ jsx("span", { className: "dshra-label", children: label }),
533
+ jsx("span", { className: "dshra-hint", children: hint }),
534
+ ],
535
+ }),
536
+ jsx("input", {
537
+ type: "checkbox",
538
+ className: "dshra-checkbox",
539
+ disabled,
540
+ checked: Boolean(draft[key]),
541
+ onChange: (e) => updateField(key, e.target.checked),
542
+ }),
543
+ ],
544
+ });
545
+
546
+ if (snapshot.status === "loading") {
547
+ return jsx("div", { className: "dshra-wrap", children: jsx("p", { className: "dshra-msgMuted", children: t.loading }) });
548
+ }
549
+
550
+ if (snapshot.status === "unavailable") {
551
+ return jsx("div", { className: "dshra-wrap", children: jsx("p", { className: "dshra-msgMuted", children: t.unavailable }) });
552
+ }
553
+
554
+ return jsxs("div", {
555
+ className: "dshra-wrap",
556
+ children: [
557
+ // 顶部状态卡片
558
+ jsxs("div", {
559
+ className: "dshra-statusCard",
560
+ children: [
561
+ jsxs("div", {
562
+ className: "dshra-statusLeft",
563
+ children: [
564
+ jsxs("div", {
565
+ className: "dshra-statusRow",
566
+ children: [
567
+ jsx("span", { className: statusDotClass }),
568
+ jsx("span", { className: "dshra-statusTitle", children: `${t.title} · ${statusLabel}` }),
569
+ ],
570
+ }),
571
+ jsx("div", { className: "dshra-endpoint", children: `${t.endpointLabel}: ${baseUrl}` }),
572
+ jsx("p", { className: "dshra-hint", children: t.subtitle }),
573
+ ],
574
+ }),
575
+ jsxs("div", {
576
+ className: "dshra-statusActions",
577
+ children: [
578
+ jsx("button", {
579
+ type: "button",
580
+ className: "dshra-btn",
581
+ onClick: handleCopyCurl,
582
+ children: copied ? t.copied : t.copyCurl,
583
+ }),
584
+ jsx("button", {
585
+ type: "button",
586
+ className: "dshra-btn",
587
+ onClick: checkHealth,
588
+ children: t.refresh,
589
+ }),
590
+ ],
591
+ }),
592
+ ],
593
+ }),
594
+
595
+ !snapshot.writable && jsx("p", { className: "dshra-msgErr", children: t.readOnly }),
596
+
597
+ // 1. 模型与默认预设
598
+ jsxs("section", {
599
+ className: "dshra-section",
600
+ children: [
601
+ jsx("h4", { className: "dshra-sectionTitle", children: t.sectionModel }),
602
+ jsxs("div", {
603
+ className: "dshra-grid",
604
+ children: [
605
+ textField("presetId", t.presetId, t.presetIdHint, "headless-task"),
606
+ textField("provider", t.provider, t.providerHint, "openrouter"),
607
+ textField("model", t.model, t.modelHint, "deepseek/deepseek-v3.2"),
608
+ ],
609
+ }),
610
+ ],
611
+ }),
612
+
613
+ // 2. 侧边栏分组与工作区
614
+ jsxs("section", {
615
+ className: "dshra-section",
616
+ children: [
617
+ jsx("h4", { className: "dshra-sectionTitle", children: t.sectionWorkspace }),
618
+ jsxs("div", {
619
+ className: "dshra-grid",
620
+ children: [
621
+ textField("workspaceTitle", t.workspaceTitle, t.workspaceTitleHint, "API Tasks"),
622
+ textField("workspaceDir", t.workspaceDir, t.workspaceDirHint, "~/.dsh/rest-api-workspace"),
623
+ selectField("sandboxMode", t.sandboxMode, [
624
+ { value: "read-only", label: t.sandboxReadOnly },
625
+ { value: "workspace-write", label: t.sandboxWrite },
626
+ { value: "danger-full-access", label: t.sandboxFull },
627
+ ]),
628
+ selectField("approvalPolicy", t.approvalPolicy, [
629
+ { value: "never", label: t.approvalNever },
630
+ { value: "ask", label: t.approvalAsk },
631
+ ]),
632
+ ],
633
+ }),
634
+ ],
635
+ }),
636
+
637
+ // 3. 接入鉴权与安全
638
+ jsxs("section", {
639
+ className: "dshra-section",
640
+ children: [
641
+ jsx("h4", { className: "dshra-sectionTitle", children: t.sectionAuth }),
642
+ jsxs("div", {
643
+ className: "dshra-grid",
644
+ children: [
645
+ selectField("authMode", t.authMode, [
646
+ { value: "loopback", label: t.authLoopback },
647
+ { value: "bearer", label: t.authBearer },
648
+ { value: "none", label: t.authNone },
649
+ ]),
650
+ textField("apiKeyEnv", t.apiKeyEnv, t.apiKeyEnvHint, "DSH_REST_API_KEY"),
651
+ jsxs("div", {
652
+ className: "dshra-field dshra-fieldFull",
653
+ children: [
654
+ jsxs("div", {
655
+ className: "dshra-labelRow",
656
+ children: [
657
+ jsx("label", { className: "dshra-label", htmlFor: "dshra-apiKey", children: t.apiKey }),
658
+ apiKeySet &&
659
+ jsx("button", {
660
+ type: "button",
661
+ className: "dshra-btnLink",
662
+ disabled,
663
+ onClick: () => {
664
+ setClearApiKey((prev) => !prev);
665
+ setApiKeyInput("");
666
+ setFeedback(null);
667
+ },
668
+ children: clearApiKey ? t.clearApiKeyPending : t.clearApiKey,
669
+ }),
670
+ ],
671
+ }),
672
+ jsx("input", {
673
+ id: "dshra-apiKey",
674
+ className: "dshra-input",
675
+ type: "password",
676
+ autoComplete: "new-password",
677
+ disabled: disabled || clearApiKey,
678
+ value: apiKeyInput,
679
+ placeholder: apiKeySet ? t.apiKeyPlaceholderSet : t.apiKeyPlaceholderUnset,
680
+ onChange: (e) => {
681
+ setFeedback(null);
682
+ setClearApiKey(false);
683
+ setApiKeyInput(e.target.value);
684
+ },
685
+ }),
686
+ jsxs("div", {
687
+ className: "dshra-secretMeta",
688
+ children: [
689
+ jsx("span", { children: apiKeySet ? t.apiKeyConfigured : t.apiKeyUnset }),
690
+ ],
691
+ }),
692
+ jsx("p", { className: "dshra-hint", children: t.apiKeyHint }),
693
+ ],
694
+ }),
695
+ ],
696
+ }),
697
+ toggleField("allowRequestOverrides", t.allowRequestOverrides, t.allowRequestOverridesHint),
698
+ toggleField("allowCustomWorkspaceDir", t.allowCustomWorkspaceDir, t.allowCustomWorkspaceDirHint),
699
+ ],
700
+ }),
701
+
702
+ // 4. Webhook 与运行限制
703
+ jsxs("section", {
704
+ className: "dshra-section",
705
+ children: [
706
+ jsx("h4", { className: "dshra-sectionTitle", children: t.sectionAdvanced }),
707
+ jsxs("div", {
708
+ className: "dshra-grid",
709
+ children: [
710
+ textField("defaultWebhookUrl", t.defaultWebhookUrl, t.defaultWebhookUrlHint, "https://example.com/webhooks/dsh", true),
711
+ numberField("webhookTimeoutMs", t.webhookTimeoutMs),
712
+ numberField("requestTimeoutMs", t.requestTimeoutMs),
713
+ numberField("runRetentionMs", t.runRetentionMs),
714
+ ],
715
+ }),
716
+ ],
717
+ }),
718
+
719
+ // 底部保存操作栏
720
+ jsxs("div", {
721
+ className: "dshra-footer",
722
+ children: [
723
+ jsx("div", {
724
+ className: "dshra-footerLeft",
725
+ children:
726
+ feedback?.kind === "ok"
727
+ ? jsx("span", { className: "dshra-msgOk", children: feedback.text })
728
+ : feedback?.kind === "err"
729
+ ? jsx("span", { className: "dshra-msgErr", children: feedback.text })
730
+ : dirtyCount > 0
731
+ ? jsx("span", { className: "dshra-msgMuted", children: t.dirtyBadge(dirtyCount) })
732
+ : null,
733
+ }),
734
+ jsxs("div", {
735
+ className: "dshra-footerRight",
736
+ children: [
737
+ dirtyCount > 0 &&
738
+ jsx("button", {
739
+ type: "button",
740
+ className: "dshra-btn",
741
+ disabled: saving,
742
+ onClick: handleDiscard,
743
+ children: t.discard,
744
+ }),
745
+ jsx("button", {
746
+ type: "button",
747
+ className: "dshra-btn dshra-btnPrimary",
748
+ disabled: disabled || dirtyCount === 0 || hasValidationError,
749
+ onClick: handleSave,
750
+ children: saving ? t.saving : t.save,
751
+ }),
752
+ ],
753
+ }),
754
+ ],
755
+ }),
756
+ ],
757
+ });
758
+ };
759
+ }
760
+
761
+ const inject = ["slots", "configForms"];
762
+
763
+ function apply(ctx) {
764
+ const Panel = createPanelComponent(ctx);
765
+
766
+ // 1. 组合包详情页内嵌配置区(插件 -> 已安装插件 -> dsh-rest-api)
767
+ ctx.effect(() =>
768
+ ctx.configForms.whileServed([NS], () =>
769
+ ctx.slots.inject("plugins.bundle.config", () =>
770
+ ctx.slots.register(
771
+ {
772
+ name: "plugins.bundle.config",
773
+ key: BUNDLE_NAME,
774
+ },
775
+ Panel,
776
+ ),
777
+ ),
778
+ ),
779
+ "dsh-rest-api: bundle config slot",
780
+ );
781
+
782
+ // 2. 组件行独立配置页(插件 -> 已安装插件 -> dsh-rest-api -> rest-api -> 配置)
783
+ ctx.effect(() =>
784
+ ctx.configForms.whileServed([NS], () =>
785
+ ctx.slots.inject("plugins.row.config", () =>
786
+ ctx.slots.register(
787
+ {
788
+ name: "plugins.row.config",
789
+ key: ROW_KEY,
790
+ },
791
+ Panel,
792
+ ),
793
+ ),
794
+ ),
795
+ "dsh-rest-api: row config slot",
796
+ );
797
+ }
798
+
799
+ exports.apply = apply;
800
+ exports.inject = inject;
801
+ return module.exports;
802
+ },
803
+ });