dsh-control-mcp 0.0.0-stage → 0.2.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,460 @@
1
+ // Generated by scripts/build-client.mjs; edit client/index.mjs instead.
2
+ window.__ModuleLoader__.load({
3
+ id: 'dsh-control-mcp',
4
+ factory: (function createClientPlugin(require) {
5
+ const React = require('react');
6
+ const { createElement: h, useCallback, useEffect, useMemo, useRef, useState, useSyncExternalStore } = React;
7
+ const PACKAGE = 'dsh-control-mcp';
8
+ const ENTRY_ID = 'dsh-control-mcp';
9
+ const ROUTE = '/dsh-control-mcp';
10
+ const inject = ['slots'];
11
+ const SAVE_ERROR = 'Could not save this setting. It may have changed elsewhere; review the current value and try again.';
12
+ const SWITCHES = [
13
+ { field: 'mcpEnabled', label: 'MCP server', hint: 'Serve the MCP endpoint so MCP clients (Claude, Codex, Cursor, another DSH…) can control this harness.' },
14
+ { field: 'apiEnabled', label: 'HTTP API', hint: 'Serve a JSON and Server-Sent Events API for scripts and other programs.' },
15
+ { field: 'readOnly', label: 'Read-only mode', hint: 'Allow only calls that read. Prompts, creating sessions, plugin changes and every other change are refused.' },
16
+ { field: 'exposeAllEndpoints', label: 'One MCP tool per endpoint', hint: 'Also list every harness endpoint as its own MCP tool (about 200). The curated tools and dsh_call already reach all of them.' },
17
+ ];
18
+
19
+ function isRecord(value) {
20
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
21
+ }
22
+
23
+ /** Settings namespace of this plugin's Host entry among the served ones. */
24
+ function findEntryNamespace(namespaces) {
25
+ const ids = (Array.isArray(namespaces) ? namespaces : []).map(view => view?.ns).filter(id => typeof id === 'string');
26
+ return ids.find(id => id === `include:${ENTRY_ID}`)
27
+ ?? ids.find(id => id === ENTRY_ID)
28
+ ?? ids.find(id => id.endsWith(`:${ENTRY_ID}`));
29
+ }
30
+
31
+ /** Parse the blocked-endpoints textarea: one pattern per line or comma. */
32
+ function parseBlocked(text) {
33
+ const items = String(text ?? '').split(/[\n,]/).map(item => item.trim()).filter(Boolean);
34
+ const invalid = items.filter(item => !/^[A-Za-z0-9_*-]+\/[A-Za-z0-9_*-]+$/.test(item));
35
+ return { items: [...new Set(items)], invalid };
36
+ }
37
+
38
+ function originUrl(path) {
39
+ try {
40
+ return new URL(path, window.location.href).toString();
41
+ } catch {
42
+ return path;
43
+ }
44
+ }
45
+
46
+ function mcpJsonConfig(url, token) {
47
+ return JSON.stringify({ mcpServers: { 'dsh-control': { type: 'http', url, headers: { Authorization: `Bearer ${token}` } } } }, null, 2);
48
+ }
49
+
50
+ function stdioConfig(url, token) {
51
+ return JSON.stringify({ mcpServers: { 'dsh-control': { command: 'npx', args: ['-y', 'dsh-control-mcp'], env: { DSH_CONTROL_URL: url, DSH_CONTROL_TOKEN: token } } } }, null, 2);
52
+ }
53
+
54
+ async function tokenRequest(path, method) {
55
+ const response = await fetch(`${ROUTE}${path}`, { method, credentials: 'same-origin', headers: { accept: 'application/json' } });
56
+ const body = await response.json().catch(() => undefined);
57
+ if (!response.ok || body?.ok !== true || typeof body?.value?.token !== 'string') throw new Error('token request failed');
58
+ return body.value.token;
59
+ }
60
+
61
+ /** Owner-only management call to this plugin's own same-origin routes. */
62
+ async function manage(path, method = 'GET', body) {
63
+ const response = await fetch(`${ROUTE}${path}`, {
64
+ method, credentials: 'same-origin',
65
+ headers: { accept: 'application/json', ...(body === undefined ? {} : { 'content-type': 'application/json' }) },
66
+ ...(body === undefined ? {} : { body: JSON.stringify(body) }),
67
+ });
68
+ const json = await response.json().catch(() => undefined);
69
+ if (!response.ok || json?.ok !== true) throw new Error(typeof json?.error?.message === 'string' ? json.error.message : 'The request failed.');
70
+ return json.value;
71
+ }
72
+
73
+ function scopeSummary(key, options) {
74
+ if (key.mode === 'full') return 'Full access';
75
+ const ws = key.workspaces.map(id => options.workspaces.find(w => w.id === id)?.title ?? 'missing workspace');
76
+ const ss = key.sessions.length;
77
+ const parts = [];
78
+ if (ws.length) parts.push(`${ws.length === 1 ? 'Workspace' : `${ws.length} workspaces`}: ${ws.slice(0, 2).join(', ')}${ws.length > 2 ? '…' : ''}`);
79
+ if (ss) parts.push(`${ss} chat${ss === 1 ? '' : 's'}`);
80
+ return `${key.access === 'prompt' ? 'Read and prompt' : 'Read only'} · ${parts.join(' · ') || 'nothing selected'}`;
81
+ }
82
+
83
+ function relativeTime(iso) {
84
+ if (!iso) return 'never';
85
+ const diff = Date.now() - Date.parse(iso);
86
+ if (!Number.isFinite(diff)) return 'never';
87
+ if (diff < 60000) return 'just now';
88
+ if (diff < 3600000) return `${Math.round(diff / 60000)} min ago`;
89
+ if (diff < 86400000) return `${Math.round(diff / 3600000)} h ago`;
90
+ return `${Math.round(diff / 86400000)} d ago`;
91
+ }
92
+
93
+ const styles = {
94
+ page: { display: 'flex', flexDirection: 'column', gap: '16px', minWidth: 0, fontSize: '13px', lineHeight: '20px', color: 'var(--dsw-alias-label-primary)' },
95
+ head: { display: 'flex', flexDirection: 'column', gap: '4px' },
96
+ title: { margin: 0, fontSize: '14px', fontWeight: 500, lineHeight: '20px' },
97
+ lead: { margin: 0, color: 'var(--dsw-alias-label-secondary)' },
98
+ card: { display: 'flex', flexDirection: 'column', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l3)', background: 'var(--dsw-alias-bg-layer-1)' },
99
+ row: { display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between', gap: '16px', padding: '12px 14px', borderBottom: '.5px solid var(--dsw-alias-border-l2)' },
100
+ rowLast: { borderBottom: 0 },
101
+ rowText: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0 },
102
+ label: { fontSize: '13.5px', fontWeight: 500 },
103
+ hint: { margin: 0, fontSize: '12px', lineHeight: '18px', color: 'var(--dsw-alias-label-tertiary)' },
104
+ section: { display: 'flex', flexDirection: 'column', gap: '8px' },
105
+ sectionTitle: { margin: 0, fontSize: '13px', fontWeight: 500 },
106
+ status: { margin: 0, color: 'var(--dsw-alias-label-tertiary)' },
107
+ error: { margin: 0, color: 'var(--dsw-alias-state-error-primary)', overflowWrap: 'anywhere' },
108
+ ok: { margin: 0, color: 'var(--dsw-alias-state-success-primary, #39a869)' },
109
+ warn: { margin: 0, padding: '8px 12px', borderRadius: 'var(--dsw-radius-md, 8px)', background: 'color-mix(in srgb, var(--dsw-alias-state-warning-primary, #d08a00) 12%, transparent)', color: 'var(--dsw-alias-label-secondary)', fontSize: '12px', lineHeight: '18px' },
110
+ code: { margin: 0, padding: '8px 10px', borderRadius: 'var(--dsw-radius-md, 8px)', background: 'var(--dsw-alias-bg-layer-3)', border: '.5px solid var(--dsw-alias-border-l3)', fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)', fontSize: '12px', lineHeight: '18px', whiteSpace: 'pre-wrap', overflowWrap: 'anywhere' },
111
+ inline: { display: 'flex', alignItems: 'center', gap: '8px', flexWrap: 'wrap' },
112
+ input: { flex: 1, minWidth: '220px', height: '30px', padding: '0 10px', boxSizing: 'border-box', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)', fontSize: '12px' },
113
+ textarea: { width: '100%', minHeight: '64px', padding: '8px 10px', boxSizing: 'border-box', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontFamily: 'var(--dsw-font-mono, ui-monospace, monospace)', fontSize: '12px', resize: 'vertical' },
114
+ button: { height: '28px', padding: '0 12px', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontSize: '12.5px', cursor: 'pointer' },
115
+ primary: { background: 'var(--dsw-alias-brand-primary)', borderColor: 'transparent', color: 'var(--dsw-alias-label-on-brand, #fff)' },
116
+ disabled: { opacity: 0.5, cursor: 'not-allowed' },
117
+ tabs: { display: 'flex', gap: '6px', flexWrap: 'wrap' },
118
+ keyRow: { display: 'flex', alignItems: 'center', gap: '12px', padding: '10px 14px', borderBottom: '.5px solid var(--dsw-alias-border-l2)', minWidth: 0 },
119
+ keyMain: { display: 'flex', flexDirection: 'column', gap: '2px', minWidth: 0, flex: 1 },
120
+ badgeMuted: { flex: 'none', padding: '0 8px', borderRadius: '999px', fontSize: '11px', lineHeight: '18px', background: 'var(--dsw-alias-bg-layer-3)', color: 'var(--dsw-alias-label-secondary)', border: '.5px solid var(--dsw-alias-border-l3)' },
121
+ editor: { display: 'flex', flexDirection: 'column', gap: '12px', padding: '14px', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l3)', background: 'var(--dsw-alias-bg-layer-1)' },
122
+ fieldRow: { display: 'flex', flexDirection: 'column', gap: '4px' },
123
+ radioRow: { display: 'flex', gap: '16px', flexWrap: 'wrap' },
124
+ pick: { display: 'flex', flexDirection: 'column', maxHeight: '220px', overflow: 'auto', border: '.5px solid var(--dsw-alias-border-l3)', borderRadius: 'var(--dsw-radius-md, 8px)', padding: '4px' },
125
+ pickItem: { display: 'flex', alignItems: 'flex-start', gap: '8px', padding: '5px 8px', borderRadius: '6px', cursor: 'pointer', minWidth: 0 },
126
+ textInput: { height: '30px', padding: '0 10px', boxSizing: 'border-box', borderRadius: 'var(--dsw-radius-md, 8px)', border: '.5px solid var(--dsw-alias-border-l4)', background: 'var(--dsw-alias-bg-layer-3)', color: 'inherit', font: 'inherit', fontSize: '12.5px', width: '100%' },
127
+ };
128
+
129
+ function buttonStyle(primary, disabled) {
130
+ return { ...styles.button, ...primary ? styles.primary : {}, ...disabled ? styles.disabled : {} };
131
+ }
132
+
133
+ const emptyMirror = { view: undefined };
134
+ const unavailableSnapshot = { status: 'unavailable', value: undefined, revision: undefined, writable: false };
135
+ const noForm = { getSnapshot: () => unavailableSnapshot, subscribe: () => () => {}, mutate: async () => false };
136
+
137
+ function useStore(store, fallback) {
138
+ const subscribe = useCallback(listener => (store ? store.subscribe(listener) : () => {}), [store]);
139
+ const getSnapshot = useCallback(() => (store ? store.getSnapshot() : fallback), [store, fallback]);
140
+ return useSyncExternalStore(subscribe, getSnapshot, getSnapshot);
141
+ }
142
+
143
+ function Switch({ id, checked, disabled, label, onChange }) {
144
+ return h('input', {
145
+ id, type: 'checkbox', role: 'switch', checked, disabled, 'aria-label': label,
146
+ style: { width: '18px', height: '18px', flex: 'none', marginTop: '2px', cursor: disabled ? 'not-allowed' : 'pointer' },
147
+ onChange: event => onChange(event.target.checked),
148
+ });
149
+ }
150
+
151
+ function CopyButton({ text, label = 'Copy', disabled }) {
152
+ const [copied, setCopied] = useState(false);
153
+ useEffect(() => { if (!copied) return undefined; const timer = setTimeout(() => setCopied(false), 1500); return () => clearTimeout(timer); }, [copied]);
154
+ return h('button', {
155
+ type: 'button', style: buttonStyle(false, disabled), disabled,
156
+ onClick: async () => { try { await navigator.clipboard.writeText(text); setCopied(true); } catch { /* clipboard blocked; text stays selectable */ } },
157
+ }, copied ? 'Copied' : label);
158
+ }
159
+
160
+ function TokenSection({ enabled }) {
161
+ const [token, setToken] = useState('');
162
+ const [state, setState] = useState('idle');
163
+ const [visible, setVisible] = useState(false);
164
+ const [tab, setTab] = useState('http');
165
+ const mounted = useRef(true);
166
+ useEffect(() => () => { mounted.current = false; }, []);
167
+
168
+ const load = useCallback(async () => {
169
+ setState('loading');
170
+ try {
171
+ const value = await tokenRequest('/token', 'GET');
172
+ if (mounted.current) { setToken(value); setState('ready'); }
173
+ } catch {
174
+ if (mounted.current) setState('error');
175
+ }
176
+ }, []);
177
+ useEffect(() => { if (enabled) void load(); }, [enabled, load]);
178
+
179
+ const rotate = async () => {
180
+ if (!window.confirm('Rotate the access token? Every MCP and API client using the current token stops working until you update it.')) return;
181
+ setState('loading');
182
+ try {
183
+ const value = await tokenRequest('/token/rotate', 'POST');
184
+ if (mounted.current) { setToken(value); setVisible(true); setState('rotated'); }
185
+ } catch {
186
+ if (mounted.current) setState('error');
187
+ }
188
+ };
189
+
190
+ if (!enabled) return h('p', { style: styles.status }, 'Turn on the MCP server or the HTTP API to see the access token and client setup.');
191
+ const mcpUrl = originUrl(`${ROUTE}/mcp`);
192
+ const apiUrl = originUrl(`${ROUTE}/api/v1`);
193
+ const shown = visible ? token : token.replace(/^(dshc_.{4}).*$/, '$1••••••••••••••••••••••');
194
+ const snippetsFor = value => ({
195
+ http: { label: 'MCP over HTTP', text: mcpJsonConfig(mcpUrl, value) },
196
+ stdio: { label: 'MCP over stdio', text: stdioConfig(mcpUrl, value) },
197
+ curl: { label: 'HTTP API', text: `curl -s -H 'Authorization: Bearer ${value}' ${apiUrl}/info\ncurl -s -X POST -H 'Authorization: Bearer ${value}' -H 'content-type: application/json' \\\n -d '{"_request":{}}' ${apiUrl}/call/session/list` },
198
+ });
199
+ // Displayed text follows the Show/Hide state; copying always uses the real token.
200
+ const snippets = snippetsFor(token);
201
+ const displayed = snippetsFor(shown);
202
+ return h('div', { style: styles.section },
203
+ h('h5', { style: styles.sectionTitle }, 'Owner token'),
204
+ h('p', { style: styles.hint }, 'The built-in full-access token, sent as "Authorization: Bearer <token>". It controls the whole harness (or reads it in read-only mode). Prefer a named API key per client above, so you can scope and revoke each one.'),
205
+ state === 'error' ? h('p', { role: 'alert', style: styles.error }, 'Could not read the token. Reload this page from the DSH web GUI you are signed in to.') : null,
206
+ h('div', { style: styles.inline },
207
+ h('input', { readOnly: true, value: state === 'loading' && !token ? 'Loading…' : shown, style: styles.input, 'aria-label': 'Access token', onFocus: event => event.target.select() }),
208
+ h('button', { type: 'button', style: buttonStyle(false, !token), disabled: !token, onClick: () => setVisible(!visible) }, visible ? 'Hide' : 'Show'),
209
+ h(CopyButton, { text: token, disabled: !token }),
210
+ h('button', { type: 'button', style: buttonStyle(false, state === 'loading'), disabled: state === 'loading', onClick: () => { void rotate(); } }, 'Rotate')),
211
+ state === 'rotated' ? h('p', { role: 'status', style: styles.ok }, 'New token issued. The old one no longer works.') : null,
212
+ h('h5', { style: { ...styles.sectionTitle, marginTop: '8px' } }, 'Client setup'),
213
+ h('div', { style: styles.tabs, role: 'tablist' }, Object.entries(snippets).map(([key, snippet]) => h('button', {
214
+ key, type: 'button', role: 'tab', 'aria-selected': tab === key, style: buttonStyle(tab === key, false), onClick: () => setTab(key),
215
+ }, snippet.label))),
216
+ h('pre', { style: styles.code, 'data-dsh-control-mcp-snippet': tab }, token ? displayed[tab].text : '…'),
217
+ h('div', { style: styles.inline }, h(CopyButton, { text: snippets[tab].text, label: 'Copy configuration', disabled: !token })),
218
+ h('p', { style: styles.hint }, `MCP endpoint: ${mcpUrl} · API base: ${apiUrl}. DSH listens on this machine only unless you started it with a trusted host; remote clients need a tunnel or a trusted host.`));
219
+ }
220
+
221
+ function Picker({ label, items, selected, onToggle, empty, describe }) {
222
+ const [query, setQuery] = useState('');
223
+ const needle = query.trim().toLowerCase();
224
+ const shown = needle ? items.filter(item => `${item.title} ${describe(item)}`.toLowerCase().includes(needle)) : items;
225
+ return h('div', { style: styles.fieldRow },
226
+ h('span', { style: styles.label }, `${label} (${selected.length} selected)`),
227
+ items.length > 6 ? h('input', { type: 'search', placeholder: `Search ${label.toLowerCase()}…`, value: query, style: styles.textInput, 'aria-label': `Search ${label.toLowerCase()}`, onChange: event => setQuery(event.target.value) }) : null,
228
+ h('div', { style: styles.pick, role: 'group', 'aria-label': label },
229
+ items.length === 0 ? h('p', { style: { ...styles.hint, padding: '6px 8px' } }, empty) : null,
230
+ shown.map(item => h('label', { key: item.id, style: styles.pickItem },
231
+ h('input', { type: 'checkbox', checked: selected.includes(item.id), onChange: () => onToggle(item.id), style: { marginTop: '3px', flex: 'none' } }),
232
+ h('span', { style: { display: 'flex', flexDirection: 'column', minWidth: 0 } },
233
+ h('span', { style: { overflowWrap: 'anywhere' } }, item.title),
234
+ h('span', { style: { ...styles.hint, overflowWrap: 'anywhere' } }, describe(item)))))));
235
+ }
236
+
237
+ const EMPTY_KEY = { name: '', mode: 'scoped', access: 'read', workspaces: [], sessions: [], mcp: true, api: true, expiresAt: null, disabled: false };
238
+
239
+ function KeyEditor({ initial, options, scopedSupported, onCancel, onSave, busy }) {
240
+ const [draft, setDraft] = useState(() => ({ ...EMPTY_KEY, ...initial, expiresAt: initial?.expiresAt ? initial.expiresAt.slice(0, 10) : '' }));
241
+ const set = patch => setDraft(previous => ({ ...previous, ...patch }));
242
+ const toggle = (field, id) => set({ [field]: draft[field].includes(id) ? draft[field].filter(item => item !== id) : [...draft[field], id] });
243
+ const workspaceTitle = id => options.workspaces.find(w => w.id === id)?.title;
244
+ const coveredByWorkspace = session => options.workspaces.some(w => draft.workspaces.includes(w.id) && w.sessionIds.includes(session.id));
245
+ const problems = [];
246
+ if (draft.name.trim() === '') problems.push('Give the key a name.');
247
+ if (!draft.mcp && !draft.api) problems.push('Enable MCP, the HTTP API, or both.');
248
+ if (draft.mode === 'scoped' && draft.workspaces.length === 0 && draft.sessions.length === 0) problems.push('Choose at least one workspace or chat, or make it a full-access key.');
249
+ if (draft.mode === 'scoped' && !scopedSupported) problems.push('Scoped keys need DSH 0.2.1 or later.');
250
+ const submit = () => onSave({
251
+ name: draft.name.trim(), mode: draft.mode, access: draft.access, mcp: draft.mcp, api: draft.api,
252
+ workspaces: draft.mode === 'scoped' ? draft.workspaces : [], sessions: draft.mode === 'scoped' ? draft.sessions : [],
253
+ expiresAt: draft.expiresAt ? new Date(`${draft.expiresAt}T23:59:59`).toISOString() : null,
254
+ });
255
+ return h('div', { style: styles.editor, 'data-dsh-control-mcp-key-editor': '' },
256
+ h('div', { style: styles.fieldRow },
257
+ h('label', { htmlFor: 'dsh-control-mcp-key-name', style: styles.label }, 'Name'),
258
+ h('input', { id: 'dsh-control-mcp-key-name', style: styles.textInput, maxLength: 80, value: draft.name, placeholder: 'e.g. Claude on my phone, CI bot, Release notes chat', onChange: event => set({ name: event.target.value }) })),
259
+ h('div', { style: styles.radioRow },
260
+ h('label', { style: styles.inline }, h('input', { type: 'checkbox', checked: draft.mcp, onChange: event => set({ mcp: event.target.checked }) }), 'MCP'),
261
+ h('label', { style: styles.inline }, h('input', { type: 'checkbox', checked: draft.api, onChange: event => set({ api: event.target.checked }) }), 'HTTP API')),
262
+ h('div', { style: styles.fieldRow, role: 'radiogroup', 'aria-label': 'Access' },
263
+ h('span', { style: styles.label }, 'Access'),
264
+ h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-mode', checked: draft.mode === 'scoped', onChange: () => set({ mode: 'scoped' }) }), 'Only chosen workspaces and chats'),
265
+ h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-mode', checked: draft.mode === 'full', onChange: () => set({ mode: 'full' }) }), 'Full access to this harness'),
266
+ draft.mode === 'full' ? h('p', { style: styles.warn }, 'A full-access key can do anything you can: every chat, plugins, settings and installs.') : null),
267
+ draft.mode === 'scoped' ? h(React.Fragment, null,
268
+ h('div', { style: styles.fieldRow, role: 'radiogroup', 'aria-label': 'Inside its chats' },
269
+ h('span', { style: styles.label }, 'Inside its chats'),
270
+ h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-access', checked: draft.access === 'read', onChange: () => set({ access: 'read' }) }), 'Read only: history, state and replies'),
271
+ h('label', { style: styles.inline }, h('input', { type: 'radio', name: 'dsh-control-mcp-access', checked: draft.access === 'prompt', onChange: () => set({ access: 'prompt' }) }), 'Read and prompt: also send messages, stop, rename, and start chats in its workspaces')),
272
+ h(Picker, {
273
+ label: 'Workspaces', items: options.workspaces, selected: draft.workspaces, onToggle: id => toggle('workspaces', id),
274
+ empty: 'No workspaces yet.', describe: w => `${w.path} · ${w.sessionIds.length} chat${w.sessionIds.length === 1 ? '' : 's'} · includes chats added later`,
275
+ }),
276
+ h(Picker, {
277
+ label: 'Chats', items: options.sessions, selected: draft.sessions, onToggle: id => toggle('sessions', id),
278
+ empty: 'No chats yet.',
279
+ describe: session => [coveredByWorkspace(session) ? 'already covered by a chosen workspace' : null, options.workspaces.find(w => w.sessionIds.includes(session.id)) ? `in ${workspaceTitle(options.workspaces.find(w => w.sessionIds.includes(session.id)).id)}` : session.cwd, session.blank ? 'not started' : session.running ? 'running' : null].filter(Boolean).join(' · '),
280
+ })) : null,
281
+ h('div', { style: styles.fieldRow },
282
+ h('label', { htmlFor: 'dsh-control-mcp-key-expiry', style: styles.label }, 'Expires (optional)'),
283
+ h('input', { id: 'dsh-control-mcp-key-expiry', type: 'date', style: { ...styles.textInput, width: '180px' }, value: draft.expiresAt, onChange: event => set({ expiresAt: event.target.value }) })),
284
+ problems.length ? h('p', { role: 'alert', style: styles.error }, problems[0]) : null,
285
+ h('div', { style: styles.inline },
286
+ h('button', { type: 'button', style: buttonStyle(true, busy || problems.length > 0), disabled: busy || problems.length > 0, onClick: submit }, busy ? 'Saving…' : initial?.id ? 'Save key' : 'Create key'),
287
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: onCancel }, 'Cancel')));
288
+ }
289
+
290
+ function NewToken({ reveal, onDone }) {
291
+ const [tab, setTab] = useState('http');
292
+ const mcpUrl = originUrl(`${ROUTE}/mcp`);
293
+ const apiUrl = originUrl(`${ROUTE}/api/v1`);
294
+ const snippets = {
295
+ http: { label: 'MCP over HTTP', text: mcpJsonConfig(mcpUrl, reveal.token) },
296
+ stdio: { label: 'MCP over stdio', text: stdioConfig(mcpUrl, reveal.token) },
297
+ curl: { label: 'HTTP API', text: `curl -s -X POST -H 'Authorization: Bearer ${reveal.token}' -H 'content-type: application/json' \\\n -d '{"_request":{}}' ${apiUrl}/call/session/list` },
298
+ };
299
+ return h('div', { style: { ...styles.editor, borderColor: 'var(--dsw-alias-brand-primary)' }, role: 'status', 'data-dsh-control-mcp-new-token': '' },
300
+ h('span', { style: styles.label }, `Token for "${reveal.key.name}"`),
301
+ h('p', { style: styles.warn }, 'Copy it now. It is shown only once; the harness keeps only a fingerprint. Rotate the key if you lose it.'),
302
+ h('div', { style: styles.inline },
303
+ h('input', { readOnly: true, value: reveal.token, style: styles.input, 'aria-label': 'New key token', onFocus: event => event.target.select() }),
304
+ h(CopyButton, { text: reveal.token })),
305
+ h('div', { style: styles.tabs, role: 'tablist' }, Object.entries(snippets).map(([key, snippet]) => h('button', { key, type: 'button', role: 'tab', 'aria-selected': tab === key, style: buttonStyle(tab === key, false), onClick: () => setTab(key) }, snippet.label))),
306
+ h('pre', { style: styles.code }, snippets[tab].text),
307
+ h('div', { style: styles.inline }, h(CopyButton, { text: snippets[tab].text, label: 'Copy configuration' }), h('button', { type: 'button', style: buttonStyle(false, false), onClick: onDone }, 'Done')));
308
+ }
309
+
310
+ function KeysSection({ enabled }) {
311
+ const [state, setState] = useState({ status: 'loading', keys: [], options: { workspaces: [], sessions: [] }, scopedSupported: true, error: '' });
312
+ const [editing, setEditing] = useState(undefined);
313
+ const [reveal, setReveal] = useState(undefined);
314
+ const [busy, setBusy] = useState(false);
315
+ const [failure, setFailure] = useState('');
316
+ const mounted = useRef(true);
317
+ useEffect(() => () => { mounted.current = false; }, []);
318
+
319
+ const load = useCallback(async () => {
320
+ try {
321
+ const [list, options] = await Promise.all([manage('/keys'), manage('/scope-options')]);
322
+ if (mounted.current) setState({ status: 'ready', keys: list.keys, options: { workspaces: options.workspaces, sessions: options.sessions }, scopedSupported: list.scopedSupported !== false, error: '' });
323
+ } catch (error) {
324
+ if (mounted.current) setState(previous => ({ ...previous, status: 'error', error: error.message }));
325
+ }
326
+ }, []);
327
+ useEffect(() => { void load(); }, [load]);
328
+
329
+ const run = async (action, after) => {
330
+ setBusy(true); setFailure('');
331
+ try { const value = await action(); after?.(value); await load(); } catch (error) { setFailure(error.message || 'The change was not saved.'); } finally { if (mounted.current) setBusy(false); }
332
+ };
333
+ const save = fields => run(
334
+ () => (editing?.id ? manage(`/keys/${editing.id}`, 'PATCH', fields) : manage('/keys', 'POST', fields)),
335
+ value => { setEditing(undefined); if (value?.token) setReveal(value); },
336
+ );
337
+
338
+ return h('div', { style: styles.section, 'data-dsh-control-mcp-keys': '' },
339
+ h('h5', { style: styles.sectionTitle }, 'API keys'),
340
+ h('p', { style: styles.hint }, 'Give each client its own key. A key can reach the whole harness, or only the workspaces and chats you choose: everything else stays invisible to it, in every list and every call.'),
341
+ !enabled ? h('p', { style: styles.status }, 'Keys work once the MCP server or the HTTP API is on.') : null,
342
+ !state.scopedSupported ? h('p', { style: styles.warn }, 'This DSH version cannot confine keys; scoped keys need DSH 0.2.1 or later. Full-access keys work.') : null,
343
+ state.status === 'error' ? h('div', { style: styles.inline }, h('p', { role: 'alert', style: styles.error }, `Could not load keys: ${state.error}`), h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => { void load(); } }, 'Retry')) : null,
344
+ failure ? h('p', { role: 'alert', style: styles.error }, failure) : null,
345
+ reveal ? h(NewToken, { reveal, onDone: () => setReveal(undefined) }) : null,
346
+ state.status === 'loading' ? h('p', { style: styles.status }, 'Loading keys…') : null,
347
+ state.status === 'ready' && state.keys.length === 0 && editing === undefined ? h('p', { style: styles.status }, 'No keys yet.') : null,
348
+ state.keys.length > 0 ? h('div', { style: styles.card, role: 'list', 'aria-label': 'API keys' }, state.keys.map((key, index) => h('div', { key: key.id, role: 'listitem', style: { ...styles.keyRow, ...index === state.keys.length - 1 ? styles.rowLast : {} }, 'data-key-name': key.name },
349
+ h('div', { style: styles.keyMain },
350
+ h('span', { style: { ...styles.label, overflowWrap: 'anywhere' } }, key.name),
351
+ h('span', { style: { ...styles.hint, overflowWrap: 'anywhere' } }, `${scopeSummary(key, state.options)} · ${[key.mcp ? 'MCP' : null, key.api ? 'API' : null].filter(Boolean).join(' + ')} · ${key.prefix}… · used ${relativeTime(key.lastUsedAt)}${key.expiresAt ? ` · expires ${key.expiresAt.slice(0, 10)}` : ''}`)),
352
+ key.disabled ? h('span', { style: styles.badgeMuted }, 'Disabled') : key.expired ? h('span', { style: styles.badgeMuted }, 'Expired') : null,
353
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => { setReveal(undefined); setEditing(key); } }, 'Edit'),
354
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => run(() => manage(`/keys/${key.id}`, 'PATCH', { disabled: !key.disabled })) }, key.disabled ? 'Enable' : 'Disable'),
355
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => { if (window.confirm(`Rotate "${key.name}"? Clients using its current token stop working.`)) void run(() => manage(`/keys/${key.id}/rotate`, 'POST'), value => setReveal(value)); } }, 'Rotate'),
356
+ h('button', { type: 'button', style: buttonStyle(false, busy), disabled: busy, onClick: () => { if (window.confirm(`Delete "${key.name}"? Clients using it stop working at once.`)) void run(() => manage(`/keys/${key.id}`, 'DELETE')); } }, 'Delete')))) : null,
357
+ editing !== undefined
358
+ ? h(KeyEditor, { key: editing?.id ?? 'new', initial: editing, options: state.options, scopedSupported: state.scopedSupported, busy, onCancel: () => setEditing(undefined), onSave: save })
359
+ : h('div', { style: styles.inline }, h('button', { type: 'button', style: buttonStyle(true, busy || state.status !== 'ready'), disabled: busy || state.status !== 'ready', onClick: () => { setReveal(undefined); setEditing(null); } }, 'New key'), h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => { void load(); } }, 'Refresh chats')));
360
+ }
361
+
362
+ function ControlPage({ source }) {
363
+ const mirrorSnapshot = useStore(source.describe, emptyMirror);
364
+ const namespaces = mirrorSnapshot?.view?.namespaces ?? [];
365
+ const form = source.formFor(namespaces);
366
+ const snapshot = useStore(form ?? noForm, unavailableSnapshot);
367
+ const [pending, setPending] = useState('');
368
+ const [failure, setFailure] = useState('');
369
+ const [blockedDraft, setBlockedDraft] = useState(undefined);
370
+ const busy = useRef(false);
371
+
372
+ useEffect(() => { try { void source.describe?.ensure?.(); } catch { /* the mirror reports its own failure */ } }, [source]);
373
+
374
+ const value = isRecord(snapshot.value) ? snapshot.value : {};
375
+ const writable = snapshot.status === 'ready' && snapshot.writable === true && (snapshot.mode === undefined || snapshot.mode === 'host');
376
+ const storedBlocked = useMemo(() => (Array.isArray(value.blockedEndpoints) ? value.blockedEndpoints : []).join('\n'), [snapshot.value]);
377
+ const blockedText = blockedDraft ?? storedBlocked;
378
+ const blocked = parseBlocked(blockedText);
379
+
380
+ async function write(field, next) {
381
+ if (!writable || busy.current || form === undefined) return;
382
+ busy.current = true;
383
+ setPending(field);
384
+ setFailure('');
385
+ try {
386
+ await form.mutate([{ op: 'set', path: [field], value: next }], snapshot.revision);
387
+ const settled = form.getSnapshot();
388
+ if (settled.status !== 'ready' || JSON.stringify(settled.value?.[field]) !== JSON.stringify(next)) throw new Error('not confirmed');
389
+ if (field === 'blockedEndpoints') setBlockedDraft(undefined);
390
+ } catch {
391
+ setFailure(SAVE_ERROR);
392
+ } finally {
393
+ busy.current = false;
394
+ setPending('');
395
+ }
396
+ }
397
+
398
+ let status = null;
399
+ if (mirrorSnapshot?.view === undefined && form === undefined) status = 'Loading settings…';
400
+ else if (form === undefined || snapshot.status === 'unavailable') status = 'The dsh-control-mcp host plugin is not running, so these settings cannot be changed. Check the dsh startup output.';
401
+ else if (snapshot.status === 'loading') status = 'Loading settings…';
402
+ else if (!writable) status = 'These settings are read-only in this browser.';
403
+
404
+ const anyEnabled = value.mcpEnabled === true || value.apiEnabled === true;
405
+ return h('section', { style: styles.page, 'data-dsh-control-mcp': '' },
406
+ h('div', { style: styles.head },
407
+ h('h4', { style: styles.title }, 'Harness control'),
408
+ h('p', { style: styles.lead }, 'Let MCP clients and programs drive this harness through the same API the web GUI uses: sessions and prompts, workspaces, models, plugins, schedules, goals, terminals and settings. Both surfaces are off until you turn them on.')),
409
+ status === null ? null : h('p', { role: 'status', style: styles.status }, status),
410
+ h('div', { style: styles.card }, SWITCHES.map((item, index) => h('div', { key: item.field, style: { ...styles.row, ...index === SWITCHES.length - 1 ? styles.rowLast : {} } },
411
+ h('label', { htmlFor: `dsh-control-mcp-${item.field}`, style: styles.rowText },
412
+ h('span', { style: styles.label }, item.label),
413
+ h('span', { style: styles.hint }, item.hint)),
414
+ h(Switch, {
415
+ id: `dsh-control-mcp-${item.field}`, label: item.label, checked: value[item.field] === true,
416
+ disabled: !writable || pending !== '',
417
+ onChange: checked => { void write(item.field, checked); },
418
+ })))),
419
+ anyEnabled && value.readOnly !== true ? h('p', { style: styles.warn, role: 'note' }, 'Full control is on: a client with the token can run prompts (which run tools and shell commands), change plugins and settings, and read every session. Use read-only mode or blocked endpoints to narrow it.') : null,
420
+ failure ? h('p', { role: 'alert', style: styles.error }, failure) : null,
421
+ h('div', { style: styles.section },
422
+ h('label', { htmlFor: 'dsh-control-mcp-blocked', style: styles.sectionTitle }, 'Blocked endpoints'),
423
+ h('p', { style: styles.hint }, 'One pattern per line, "*" matches anything: account/*, pluginManager/removeBundle, */delete. Blocked endpoints are hidden and refused.'),
424
+ h('textarea', { id: 'dsh-control-mcp-blocked', style: styles.textarea, value: blockedText, disabled: !writable, spellCheck: false, onChange: event => setBlockedDraft(event.target.value) }),
425
+ blocked.invalid.length > 0 ? h('p', { role: 'alert', style: styles.error }, `Not a "namespace/method" pattern: ${blocked.invalid.join(', ')}`) : null,
426
+ h('div', { style: styles.inline },
427
+ h('button', {
428
+ type: 'button', style: buttonStyle(true, !writable || blockedDraft === undefined || blocked.invalid.length > 0 || pending !== ''),
429
+ disabled: !writable || blockedDraft === undefined || blocked.invalid.length > 0 || pending !== '',
430
+ onClick: () => { void write('blockedEndpoints', blocked.items); },
431
+ }, pending === 'blockedEndpoints' ? 'Saving…' : 'Save'),
432
+ blockedDraft !== undefined ? h('button', { type: 'button', style: buttonStyle(false, false), onClick: () => setBlockedDraft(undefined) }, 'Discard') : null)),
433
+ h(KeysSection, { enabled: anyEnabled }),
434
+ h(TokenSection, { enabled: anyEnabled }));
435
+ }
436
+
437
+ function apply(ctx) {
438
+ ctx.inject(['configForms'], child => {
439
+ const forms = child.configForms;
440
+ let cached;
441
+ const source = {
442
+ describe: forms.describe(),
443
+ formFor(namespaces) {
444
+ const ns = findEntryNamespace(namespaces);
445
+ if (ns === undefined) return undefined;
446
+ if (cached?.ns !== ns) cached = { ns, form: forms.get(ns) };
447
+ return cached.form;
448
+ },
449
+ };
450
+ child.slots.inject('plugins.bundle.config', () => child.slots.register({
451
+ name: 'plugins.bundle.config',
452
+ key: PACKAGE,
453
+ inject: () => ({ source }),
454
+ }, ControlPage));
455
+ });
456
+ }
457
+
458
+ return { inject, apply, findEntryNamespace, parseBlocked, mcpJsonConfig, stdioConfig, scopeSummary };
459
+ })
460
+ });