@lyra_wang/dsh-quick-commands 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Wang Ying
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,41 @@
1
- # Temporary Holding Version
1
+ # 常用指令(quick-commands)
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 输入框左侧多一个「☆ 常用」按钮:把常说的话(提示词、命令、模板)存起来,点一下就插入输入框,或者直接发出去。
4
+
5
+ ## 和「待发送」的区别
6
+
7
+ - 待发送:**按会话**的草稿队列,写的是「这件事还没发」
8
+ - 常用指令:**全局**的一份清单,写的是「这句话我经常发」
9
+
10
+ 两个插件互不依赖,可以只装一个。
11
+
12
+ ## 用法
13
+
14
+ 1. 输入框左侧点「☆ 常用」→ 面板从输入框上方弹出
15
+ 2. 点「新建」:填标题(可留空)+ 内容 → 保存
16
+ 3. 列表里**点一行 = 插入输入框**(可继续编辑再回车);行右侧小按钮:**发送 / 编辑 / 删除**
17
+ 4. 顶部搜索框按标题或内容过滤
18
+
19
+ 发送 = 把内容设进输入框并提交;agent 正在跑时它会照常排队,不会打断当前任务。
20
+
21
+ ## 存储
22
+
23
+ 全局一份:`<DSH_HOME>/storages/quick-commands/commands.json`。跨会话共享,不按会话拆分;删掉这个文件就是清空。
24
+
25
+ ## 边界
26
+
27
+ - 内容上限 8000 字、最多 300 条(防止一个手滑塞满)
28
+ - 插入是普通文本编辑,可撤销;发送会把当前草稿替换成该条内容
29
+ - 只在本机,不跨设备同步
30
+
31
+ ## 验证
32
+
33
+ ```bash
34
+ node --test test/store.test.mjs
35
+ ```
36
+
37
+ 覆盖:读取空列表、新增(标题去空白)、更新、删除、空内容拒绝、未知 id 拒绝。
38
+
39
+ ## 版本
40
+
41
+ 0.1.0 — 首个版本:全局常用指令清单、输入框按钮、面板搜索、插入 / 发送 / 编辑 / 删除。
package/client.js ADDED
@@ -0,0 +1,410 @@
1
+ /**
2
+ * Client half of the quick-commands plugin.
3
+ *
4
+ * One compact button in the composer tool row (conversation.input.left).
5
+ * Clicking it grows a panel upward out of the composer: your saved snippets, a
6
+ * search box, and a small editor. Clicking a row inserts the snippet through
7
+ * inputActions (undoable text, never a send); the small send action sets the
8
+ * draft and submits it.
9
+ *
10
+ * The list is global - every conversation shows the same one - and lives in the
11
+ * host half's store.
12
+ */
13
+ window.__ModuleLoader__.load({
14
+ id: '@lyra_wang/dsh-quick-commands',
15
+ factory(require) {
16
+ const React = require('react')
17
+ const h = React.createElement
18
+ const { useCallback, useEffect, useRef, useState } = React
19
+
20
+ const NS = 'quickCommands'
21
+ const STATE_URL = '/plugins/quick-commands/state'
22
+ const ACTION_URL = '/plugins/quick-commands/action'
23
+ const ROOT = 'dsh-quick-commands'
24
+
25
+ const ZH = {
26
+ 'button.label': '常用',
27
+ 'button.title': '常用指令',
28
+ 'panel.title': '常用指令',
29
+ 'panel.new': '新建',
30
+ 'panel.search': '搜索标题或内容',
31
+ 'panel.empty': '还没有常用指令。点「新建」把常说的话存下来。',
32
+ 'panel.noMatch': '没有匹配的指令',
33
+ 'panel.loading': '读取中…',
34
+ 'action.send': '发送',
35
+ 'action.edit': '编辑',
36
+ 'action.remove': '删除',
37
+ 'action.save': '保存',
38
+ 'action.cancel': '取消',
39
+ 'editor.newTitle': '新建常用指令',
40
+ 'editor.editTitle': '编辑常用指令',
41
+ 'editor.titlePlaceholder': '标题,例如:周报模板',
42
+ 'editor.textPlaceholder': '内容。发送时会原样进入对话框。',
43
+ 'error.empty': '内容不能为空',
44
+ 'error.noComposer': '拿不到输入框,换个位置再试',
45
+ 'error.remove': '删除失败',
46
+ }
47
+
48
+ const EN = {
49
+ 'button.label': 'Snippets',
50
+ 'button.title': 'Quick commands',
51
+ 'panel.title': 'Quick commands',
52
+ 'panel.new': 'New',
53
+ 'panel.search': 'Search title or content',
54
+ 'panel.empty': 'No snippets yet. Press New to save something you type often.',
55
+ 'panel.noMatch': 'No matching snippets',
56
+ 'panel.loading': 'Loading…',
57
+ 'action.send': 'Send',
58
+ 'action.edit': 'Edit',
59
+ 'action.remove': 'Delete',
60
+ 'action.save': 'Save',
61
+ 'action.cancel': 'Cancel',
62
+ 'editor.newTitle': 'New snippet',
63
+ 'editor.editTitle': 'Edit snippet',
64
+ 'editor.titlePlaceholder': 'Title, e.g. weekly report template',
65
+ 'editor.textPlaceholder': 'Content. Sent to the conversation as-is.',
66
+ 'error.empty': 'Content is required',
67
+ 'error.noComposer': 'The composer is not reachable here',
68
+ 'error.remove': 'Delete failed',
69
+ }
70
+
71
+ function fallbackCopy(key) {
72
+ return ZH[key] !== undefined ? ZH[key] : key
73
+ }
74
+
75
+ function translator(props) {
76
+ return typeof props.t === 'function' ? props.t : fallbackCopy
77
+ }
78
+
79
+ function messageOf(error) {
80
+ return error instanceof Error ? error.message : String(error)
81
+ }
82
+
83
+ async function readJson(response) {
84
+ try {
85
+ return await response.json()
86
+ } catch {
87
+ return {}
88
+ }
89
+ }
90
+
91
+ async function fetchList() {
92
+ const response = await fetch(STATE_URL, { headers: { accept: 'application/json' } })
93
+ const payload = await readJson(response)
94
+ if (!response.ok || payload.ok !== true) throw new Error(payload.message || ('HTTP ' + response.status))
95
+ return payload.list || { commands: [] }
96
+ }
97
+
98
+ async function postAction(body) {
99
+ const response = await fetch(ACTION_URL, {
100
+ method: 'POST',
101
+ headers: { 'content-type': 'application/json' },
102
+ body: JSON.stringify(body),
103
+ })
104
+ const payload = await readJson(response)
105
+ if (!response.ok || payload.ok !== true) throw new Error(payload.message || ('HTTP ' + response.status))
106
+ return payload.list || { commands: [] }
107
+ }
108
+
109
+ const CSS = [
110
+ '.dsh-quick-commands-btn{all:unset;box-sizing:border-box;display:inline-flex;align-items:center;gap:4px;height:26px;',
111
+ ' padding:0 8px;border-radius:var(--dsw-radius-sm,8px);cursor:pointer;font-size:12px;',
112
+ ' color:var(--dsw-alias-label-secondary,#b9b9c0)}',
113
+ '.dsh-quick-commands-btn:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14);color:var(--dsw-alias-label-primary,#e8e8ea)}',
114
+ '.dsh-quick-commands-panel{position:fixed;z-index:60;width:352px;max-height:420px;display:flex;flex-direction:column;',
115
+ ' background:var(--dsw-alias-bg-layer-1,#1f1f22);border:0.5px solid var(--dsw-alias-border-l3,#ffffff1f);',
116
+ ' border-radius:var(--dsw-radius-md,12px);box-shadow:0 12px 32px #00000059;overflow:hidden;',
117
+ ' color:var(--dsw-alias-label-primary,#e8e8ea);font:13px/1.5 -apple-system,BlinkMacSystemFont,"PingFang SC","Segoe UI",sans-serif}',
118
+ '.dsh-quick-commands-head{display:flex;align-items:center;gap:8px;padding:8px 10px;border-bottom:0.5px solid var(--dsw-alias-border-l3,#ffffff14)}',
119
+ '.dsh-quick-commands-title{flex:1;font-weight:600;font-size:13px}',
120
+ '.dsh-quick-commands-ghost{all:unset;cursor:pointer;height:22px;padding:0 8px;border-radius:6px;font-size:12px;',
121
+ ' color:var(--dsw-alias-label-secondary,#b9b9c0)}',
122
+ '.dsh-quick-commands-ghost:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14);color:var(--dsw-alias-label-primary,#e8e8ea)}',
123
+ '.dsh-quick-commands-search{box-sizing:border-box;width:100%;border:0;outline:0;background:transparent;color:inherit;',
124
+ ' font:inherit;padding:8px 10px;border-bottom:0.5px solid var(--dsw-alias-border-l3,#ffffff14)}',
125
+ '.dsh-quick-commands-body{flex:1;min-height:0;overflow:auto;padding:4px 0}',
126
+ '.dsh-quick-commands-hint{padding:18px 12px;text-align:center;font-size:12px;color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
127
+ '.dsh-quick-commands-row{padding:7px 10px;cursor:pointer;border-radius:8px;margin:0 4px}',
128
+ '.dsh-quick-commands-row:hover{background:var(--dsw-alias-interactive-bg-hover,#ffffff14)}',
129
+ '.dsh-quick-commands-rowTitle{font-size:12.5px;font-weight:600;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}',
130
+ '.dsh-quick-commands-rowText{font-size:11.5px;color:var(--dsw-alias-label-tertiary,#9a9aa2);white-space:nowrap;overflow:hidden;text-overflow:ellipsis}',
131
+ '.dsh-quick-commands-rowActs{display:flex;gap:2px;margin-top:2px;opacity:0;transition:opacity .12s}',
132
+ '.dsh-quick-commands-row:hover .dsh-quick-commands-rowActs{opacity:1}',
133
+ '.dsh-quick-commands-act{all:unset;cursor:pointer;height:20px;padding:0 6px;border-radius:5px;font-size:11px;',
134
+ ' color:var(--dsw-alias-label-tertiary,#9a9aa2)}',
135
+ '.dsh-quick-commands-act:hover{background:#ffffff17;color:var(--dsw-alias-label-primary,#e8e8ea)}',
136
+ '.dsh-quick-commands-act[data-tone="send"]{color:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff)}',
137
+ '.dsh-quick-commands-err{padding:6px 10px;font-size:11.5px;color:var(--dsw-alias-state-error-primary,#f56c6c)}',
138
+ '.dsh-quick-commands-editor{display:flex;flex-direction:column;gap:6px;padding:8px 10px}',
139
+ '.dsh-quick-commands-input{box-sizing:border-box;width:100%;border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);',
140
+ ' border-radius:8px;background:transparent;color:inherit;font:inherit;padding:6px 8px;outline:0}',
141
+ '.dsh-quick-commands-text{box-sizing:border-box;width:100%;min-height:96px;max-height:180px;resize:vertical;',
142
+ ' border:0.5px solid var(--dsw-alias-border-l3,#ffffff1a);border-radius:8px;background:transparent;color:inherit;font:inherit;padding:6px 8px;outline:0}',
143
+ '.dsh-quick-commands-editorActs{display:flex;justify-content:flex-end;gap:6px}',
144
+ '.dsh-quick-commands-primary{all:unset;cursor:pointer;height:24px;padding:0 10px;border-radius:8px;font-size:12px;',
145
+ ' background:var(--dsw-alias-brand-primary-new-colorprimary-new-color,#4d8dff);color:#fff}',
146
+ '.dsh-quick-commands-primary[disabled]{opacity:.45;cursor:default}',
147
+ ].join('\n')
148
+
149
+ function StarGlyph(props) {
150
+ const size = props && props.size ? props.size : 14
151
+ return h('svg', { width: size, height: size, viewBox: '0 0 16 16', fill: 'none', 'aria-hidden': 'true' }, [
152
+ h('path', {
153
+ key: 'p',
154
+ d: 'M8 1.8l1.9 3.8 4.2.6-3 3 .7 4.2L8 11.4l-3.8 2 .7-4.2-3-3 4.2-.6z',
155
+ stroke: 'currentColor',
156
+ strokeWidth: 1.2,
157
+ strokeLinejoin: 'round',
158
+ }),
159
+ ])
160
+ }
161
+
162
+ function QuickCommands(props) {
163
+ const t = translator(props)
164
+ const inputActions = props.inputActions
165
+ const [open, setOpen] = useState(false)
166
+ const [list, setList] = useState(null)
167
+ const [query, setQuery] = useState('')
168
+ const [editing, setEditing] = useState(null)
169
+ const [error, setError] = useState('')
170
+ const [busy, setBusy] = useState(false)
171
+ const [anchor, setAnchor] = useState(null)
172
+ const btnRef = useRef(null)
173
+ const panelRef = useRef(null)
174
+
175
+ const load = useCallback(async () => {
176
+ try {
177
+ const next = await fetchList()
178
+ setList(next)
179
+ setError('')
180
+ } catch (failure) {
181
+ setError(messageOf(failure))
182
+ }
183
+ }, [])
184
+
185
+ const place = useCallback(() => {
186
+ const node = btnRef.current
187
+ if (!node) return
188
+ const rect = node.getBoundingClientRect()
189
+ const width = 352
190
+ const left = Math.max(12, Math.min(rect.left, window.innerWidth - width - 12))
191
+ setAnchor({ left, bottom: window.innerHeight - rect.top + 8 })
192
+ }, [])
193
+
194
+ const toggle = useCallback(() => {
195
+ setOpen((current) => {
196
+ const next = !current
197
+ if (next) {
198
+ place()
199
+ setEditing(null)
200
+ setQuery('')
201
+ load()
202
+ }
203
+ return next
204
+ })
205
+ }, [load, place])
206
+
207
+ useEffect(() => {
208
+ if (!open) return undefined
209
+ const onDown = (event) => {
210
+ const panel = panelRef.current
211
+ const button = btnRef.current
212
+ if (panel && panel.contains(event.target)) return
213
+ if (button && button.contains(event.target)) return
214
+ setOpen(false)
215
+ }
216
+ const onKey = (event) => {
217
+ if (event.key === 'Escape') setOpen(false)
218
+ }
219
+ const onResize = () => place()
220
+ document.addEventListener('mousedown', onDown)
221
+ document.addEventListener('keydown', onKey)
222
+ window.addEventListener('resize', onResize)
223
+ return () => {
224
+ document.removeEventListener('mousedown', onDown)
225
+ document.removeEventListener('keydown', onKey)
226
+ window.removeEventListener('resize', onResize)
227
+ }
228
+ }, [open, place])
229
+
230
+ const insert = useCallback((command) => {
231
+ if (!inputActions || typeof inputActions.setDraft !== 'function') {
232
+ setError(t('error.noComposer'))
233
+ return
234
+ }
235
+ const canInsert = typeof inputActions.captureInsertion === 'function' && typeof inputActions.insertText === 'function'
236
+ if (canInsert && inputActions.insertText(command.text, inputActions.captureInsertion())) {
237
+ setOpen(false)
238
+ return
239
+ }
240
+ inputActions.setDraft(command.text)
241
+ setOpen(false)
242
+ }, [inputActions, t])
243
+
244
+ const send = useCallback((command) => {
245
+ if (!inputActions || typeof inputActions.setDraft !== 'function' || typeof inputActions.submit !== 'function') {
246
+ setError(t('error.noComposer'))
247
+ return
248
+ }
249
+ inputActions.setDraft(command.text)
250
+ inputActions.submit()
251
+ setOpen(false)
252
+ }, [inputActions, t])
253
+
254
+ const save = useCallback(async () => {
255
+ if (editing === null) return
256
+ const text = editing.text.trim()
257
+ if (text === '') {
258
+ setError(t('error.empty'))
259
+ return
260
+ }
261
+ setBusy(true)
262
+ try {
263
+ const body = editing.id
264
+ ? { action: 'update', id: editing.id, title: editing.title, text }
265
+ : { action: 'add', title: editing.title, text }
266
+ const next = await postAction(body)
267
+ setList(next)
268
+ setEditing(null)
269
+ setError('')
270
+ } catch (failure) {
271
+ setError(messageOf(failure))
272
+ } finally {
273
+ setBusy(false)
274
+ }
275
+ }, [editing, t])
276
+
277
+ const remove = useCallback(async (command) => {
278
+ setBusy(true)
279
+ try {
280
+ const next = await postAction({ action: 'remove', id: command.id })
281
+ setList(next)
282
+ setError('')
283
+ } catch (failure) {
284
+ setError(messageOf(failure))
285
+ } finally {
286
+ setBusy(false)
287
+ }
288
+ }, [])
289
+
290
+ const commands = list && Array.isArray(list.commands) ? list.commands : []
291
+ const needle = query.trim().toLowerCase()
292
+ const visible = needle === ''
293
+ ? commands
294
+ : commands.filter((command) => (command.title + ' ' + command.text).toLowerCase().includes(needle))
295
+
296
+ const panel = open && anchor
297
+ ? h('div', {
298
+ key: 'panel',
299
+ ref: panelRef,
300
+ className: ROOT + '-panel',
301
+ style: { left: anchor.left + 'px', bottom: anchor.bottom + 'px' },
302
+ }, [
303
+ h('div', { key: 'head', className: ROOT + '-head' }, [
304
+ h('span', { key: 'title', className: ROOT + '-title' }, t('panel.title')),
305
+ h('button', {
306
+ key: 'new', type: 'button', className: ROOT + '-ghost',
307
+ onClick: () => setEditing({ id: '', title: '', text: '' }),
308
+ }, t('panel.new')),
309
+ ]),
310
+ editing === null
311
+ ? h('input', {
312
+ key: 'search',
313
+ className: ROOT + '-search',
314
+ value: query,
315
+ placeholder: t('panel.search'),
316
+ onChange: (event) => setQuery(event.target.value),
317
+ })
318
+ : null,
319
+ editing !== null
320
+ ? h('div', { key: 'editor', className: ROOT + '-editor' }, [
321
+ h('div', { key: 'et', className: ROOT + '-title', style: { fontSize: '12.5px' } }, editing.id ? t('editor.editTitle') : t('editor.newTitle')),
322
+ h('input', {
323
+ key: 'title',
324
+ className: ROOT + '-input',
325
+ value: editing.title,
326
+ placeholder: t('editor.titlePlaceholder'),
327
+ autoFocus: true,
328
+ onChange: (event) => setEditing({ ...editing, title: event.target.value }),
329
+ }),
330
+ h('textarea', {
331
+ key: 'text',
332
+ className: ROOT + '-text',
333
+ value: editing.text,
334
+ placeholder: t('editor.textPlaceholder'),
335
+ onChange: (event) => setEditing({ ...editing, text: event.target.value }),
336
+ }),
337
+ h('div', { key: 'acts', className: ROOT + '-editorActs' }, [
338
+ h('button', { key: 'cancel', type: 'button', className: ROOT + '-ghost', onClick: () => setEditing(null) }, t('action.cancel')),
339
+ h('button', {
340
+ key: 'save', type: 'button', className: ROOT + '-primary',
341
+ disabled: busy || editing.text.trim() === '',
342
+ onClick: () => { void save() },
343
+ }, t('action.save')),
344
+ ]),
345
+ ])
346
+ : h('div', { key: 'body', className: ROOT + '-body' },
347
+ list === null
348
+ ? [h('div', { key: 'loading', className: ROOT + '-hint' }, t('panel.loading'))]
349
+ : visible.length === 0
350
+ ? [h('div', { key: 'empty', className: ROOT + '-hint' }, commands.length === 0 ? t('panel.empty') : t('panel.noMatch'))]
351
+ : visible.map((command) => h('div', {
352
+ key: command.id,
353
+ className: ROOT + '-row',
354
+ role: 'button',
355
+ tabIndex: 0,
356
+ onClick: () => insert(command),
357
+ onKeyDown: (event) => {
358
+ if (event.key === 'Enter') insert(command)
359
+ },
360
+ }, [
361
+ h('div', { key: 'title', className: ROOT + '-rowTitle' }, command.title || command.text.slice(0, 40)),
362
+ h('div', { key: 'text', className: ROOT + '-rowText' }, command.text.replace(/\n/g, ' ').slice(0, 80)),
363
+ h('div', { key: 'acts', className: ROOT + '-rowActs' }, [
364
+ h('button', {
365
+ key: 'send', type: 'button', className: ROOT + '-act', 'data-tone': 'send',
366
+ onClick: (event) => { event.stopPropagation(); send(command) },
367
+ }, t('action.send')),
368
+ h('button', {
369
+ key: 'edit', type: 'button', className: ROOT + '-act',
370
+ onClick: (event) => { event.stopPropagation(); setEditing({ id: command.id, title: command.title, text: command.text }) },
371
+ }, t('action.edit')),
372
+ h('button', {
373
+ key: 'remove', type: 'button', className: ROOT + '-act',
374
+ onClick: (event) => { event.stopPropagation(); void remove(command) },
375
+ }, t('action.remove')),
376
+ ]),
377
+ ])),
378
+ ),
379
+ error !== '' ? h('div', { key: 'err', className: ROOT + '-err', role: 'alert' }, error) : null,
380
+ ])
381
+ : null
382
+
383
+ return h(React.Fragment, null, [
384
+ h('style', { key: 'css' }, CSS),
385
+ h('button', {
386
+ key: 'btn',
387
+ ref: btnRef,
388
+ type: 'button',
389
+ className: ROOT + '-btn',
390
+ title: t('button.title'),
391
+ onClick: toggle,
392
+ }, [h(StarGlyph, { key: 'icon' }), h('span', { key: 'label' }, t('button.label'))]),
393
+ panel,
394
+ ])
395
+ }
396
+
397
+ return {
398
+ inject: ['slots', 'locale'],
399
+ apply(ctx) {
400
+ const tr = ctx.locale.bind(NS)
401
+ ctx.effect(() => ctx.locale.register(NS, { zh: ZH, en: EN }), 'quick-commands: dictionaries')
402
+ ctx.effect(() => ctx.slots.inject('conversation.input.left', () => ctx.slots.register({
403
+ name: 'conversation.input.left',
404
+ id: 'quick-commands',
405
+ order: 3,
406
+ }, (props) => h(QuickCommands, props))), 'quick-commands: composer button')
407
+ },
408
+ }
409
+ },
410
+ })
@@ -0,0 +1,5 @@
1
+ # 常用指令:输入框左侧一个按钮 + 自己的一条宿主路由。
2
+ # 列表是全局的(不分会话),存在 <DSH_HOME>/storages/quick-commands/commands.json。
3
+ - insert:
4
+ - id: dsh-quick-commands
5
+ name: "@lyra_wang/dsh-quick-commands"
package/icon.svg ADDED
@@ -0,0 +1,4 @@
1
+ <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 64 64" width="64" height="64" role="img" aria-label="Quick commands">
2
+ <rect x="5" y="11" width="54" height="42" rx="12" fill="#2f6feb"/>
3
+ <path d="M32 18.5l3.6 7.3 8 1.2-5.8 5.7 1.4 8-7.2-3.8-7.2 3.8 1.4-8-5.8-5.7 8-1.2z" fill="#ffffff" opacity="0.95"/>
4
+ </svg>
package/index.js ADDED
@@ -0,0 +1,237 @@
1
+ /**
2
+ * Host half of the quick-commands plugin.
3
+ *
4
+ * One global list of the operator's reusable snippets — prompts and commands
5
+ * typed often enough that retyping them is waste. It is not session-scoped:
6
+ * the same list shows up in every conversation, and it is stored as one JSON
7
+ * document under <DSH_HOME>/storages/quick-commands/commands.json.
8
+ *
9
+ * Routes (same-origin, behind DSH connection auth):
10
+ * GET /plugins/quick-commands/state -> the whole list
11
+ * POST /plugins/quick-commands/action -> add / update / remove
12
+ */
13
+ import { mkdir, readFile, rename, writeFile } from 'node:fs/promises'
14
+ import { homedir } from 'node:os'
15
+ import { join } from 'node:path'
16
+
17
+ const ROUTE_BASE = '/plugins/quick-commands'
18
+ const STORE_DIR = join(process.env.DSH_HOME || join(homedir(), '.dsh'), 'storages', 'quick-commands')
19
+ const STORE_FILE = join(STORE_DIR, 'commands.json')
20
+
21
+ const MAX_COMMANDS = 300
22
+ const MAX_TITLE = 80
23
+ const MAX_TEXT = 8000
24
+
25
+ function nowIso() {
26
+ return new Date().toISOString()
27
+ }
28
+
29
+ function titleOf(value) {
30
+ if (typeof value !== 'string') return ''
31
+ return value.replace(/\s+/g, ' ').trim().slice(0, MAX_TITLE)
32
+ }
33
+
34
+ function textOf(value) {
35
+ if (typeof value !== 'string') return ''
36
+ return value.replace(/\r\n/g, '\n').trim().slice(0, MAX_TEXT)
37
+ }
38
+
39
+ function createDoc() {
40
+ return { version: 1, seq: 1, commands: [], updatedAt: nowIso() }
41
+ }
42
+
43
+ function normalizeDoc(doc) {
44
+ doc.version = 1
45
+ doc.commands = Array.isArray(doc.commands) ? doc.commands.filter((entry) => entry && typeof entry.id === 'string') : []
46
+ if (!Number.isInteger(doc.seq) || doc.seq < 1) doc.seq = doc.commands.length + 1
47
+ for (const entry of doc.commands) {
48
+ if (typeof entry.title !== 'string') entry.title = ''
49
+ if (typeof entry.text !== 'string') entry.text = ''
50
+ if (typeof entry.createdAt !== 'string') entry.createdAt = nowIso()
51
+ if (typeof entry.updatedAt !== 'string') entry.updatedAt = entry.createdAt
52
+ }
53
+ doc.commands = doc.commands.filter((entry) => entry.text !== '')
54
+ return doc
55
+ }
56
+
57
+ /* ------------------------------- persistence ------------------------------ */
58
+
59
+ let queue = Promise.resolve()
60
+
61
+ function withLock(task) {
62
+ const run = queue.then(() => task(), () => task())
63
+ queue = run.then(() => undefined, () => undefined)
64
+ return run
65
+ }
66
+
67
+ async function readDoc() {
68
+ try {
69
+ const raw = await readFile(STORE_FILE, 'utf8')
70
+ const parsed = JSON.parse(raw)
71
+ if (parsed !== null && typeof parsed === 'object' && Array.isArray(parsed.commands)) return normalizeDoc(parsed)
72
+ return createDoc()
73
+ } catch (error) {
74
+ if (error && (error.code === 'ENOENT' || error instanceof SyntaxError)) return createDoc()
75
+ throw error
76
+ }
77
+ }
78
+
79
+ async function writeDoc(doc) {
80
+ await mkdir(STORE_DIR, { recursive: true })
81
+ const temporary = STORE_FILE + '.' + process.pid + '.tmp'
82
+ await writeFile(temporary, JSON.stringify(doc, null, 2) + '\n', 'utf8')
83
+ await rename(temporary, STORE_FILE)
84
+ }
85
+
86
+ function mutateDoc(change) {
87
+ return withLock(async () => {
88
+ const doc = await readDoc()
89
+ change(doc)
90
+ doc.updatedAt = nowIso()
91
+ await writeDoc(doc)
92
+ return doc
93
+ })
94
+ }
95
+
96
+ /* --------------------------------- the model ------------------------------- */
97
+
98
+ function viewDoc(doc) {
99
+ return {
100
+ updatedAt: doc.updatedAt,
101
+ commands: doc.commands.map((entry) => ({
102
+ id: entry.id,
103
+ title: entry.title,
104
+ text: entry.text,
105
+ createdAt: entry.createdAt,
106
+ updatedAt: entry.updatedAt,
107
+ })),
108
+ }
109
+ }
110
+
111
+ function requireCommand(doc, id) {
112
+ if (typeof id !== 'string' || id.trim() === '') throw new Error('commandId is required')
113
+ const entry = doc.commands.find((candidate) => candidate.id === id.trim())
114
+ if (entry === undefined) throw new Error('unknown command: ' + id.trim())
115
+ return entry
116
+ }
117
+
118
+ function applyAction(doc, body) {
119
+ const action = String((body && body.action) || '')
120
+ if (action === 'add') {
121
+ const text = textOf(body.text)
122
+ if (text === '') throw new Error('text is required')
123
+ if (doc.commands.length >= MAX_COMMANDS) throw new Error('this list already holds ' + MAX_COMMANDS + ' commands')
124
+ const at = nowIso()
125
+ const id = 'c' + doc.seq
126
+ doc.seq += 1
127
+ doc.commands.unshift({ id, title: titleOf(body.title), text, createdAt: at, updatedAt: at })
128
+ return { id }
129
+ }
130
+ if (action === 'update') {
131
+ const entry = requireCommand(doc, body.id)
132
+ const text = textOf(body.text)
133
+ if (text === '') throw new Error('text is required')
134
+ entry.title = titleOf(body.title)
135
+ entry.text = text
136
+ entry.updatedAt = nowIso()
137
+ return { id: entry.id }
138
+ }
139
+ if (action === 'remove') {
140
+ const entry = requireCommand(doc, body.id)
141
+ doc.commands = doc.commands.filter((candidate) => candidate.id !== entry.id)
142
+ return { id: entry.id }
143
+ }
144
+ throw new Error('unknown action: ' + (action || '(none)'))
145
+ }
146
+
147
+ /* ------------------------------ browser API ------------------------------- */
148
+
149
+ function sendJson(res, status, payload) {
150
+ res.setHeader('content-type', 'application/json; charset=utf-8')
151
+ res.writeHead(status)
152
+ res.end(JSON.stringify(payload))
153
+ }
154
+
155
+ function readJsonBody(req, limit = 256 * 1024) {
156
+ return new Promise((resolve, reject) => {
157
+ const chunks = []
158
+ let size = 0
159
+ req.on('data', (chunk) => {
160
+ size += chunk.length
161
+ if (size > limit) {
162
+ reject(new Error('request body too large'))
163
+ req.destroy()
164
+ return
165
+ }
166
+ chunks.push(chunk)
167
+ })
168
+ req.on('end', () => {
169
+ try {
170
+ resolve(JSON.parse(Buffer.concat(chunks).toString('utf8')))
171
+ } catch {
172
+ reject(new Error('invalid JSON body'))
173
+ }
174
+ })
175
+ req.on('error', reject)
176
+ })
177
+ }
178
+
179
+ function connectionRejection(ctx, req) {
180
+ const connection = typeof ctx.get === 'function' ? ctx.get('connection') : undefined
181
+ if (!connection || typeof connection.requestRejection !== 'function') return undefined
182
+ try {
183
+ return connection.requestRejection({ headers: req.headers })
184
+ } catch {
185
+ return undefined
186
+ }
187
+ }
188
+
189
+ /* --------------------------------- plugin --------------------------------- */
190
+
191
+ export const inject = ['webServer']
192
+
193
+ export function apply(ctx) {
194
+ const stateHandler = async (req, res) => {
195
+ if (req.method !== 'GET') {
196
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
197
+ return
198
+ }
199
+ const rejection = connectionRejection(ctx, req)
200
+ if (rejection !== undefined) {
201
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
202
+ return
203
+ }
204
+ try {
205
+ const doc = await readDoc()
206
+ sendJson(res, 200, { ok: true, list: viewDoc(doc) })
207
+ } catch (error) {
208
+ const message = error instanceof Error ? error.message : String(error)
209
+ ctx.logger?.warn?.('quick-commands: read failed: ' + message)
210
+ sendJson(res, 400, { ok: false, message })
211
+ }
212
+ }
213
+
214
+ const actionHandler = async (req, res) => {
215
+ if (req.method !== 'POST') {
216
+ sendJson(res, 405, { ok: false, message: 'method not allowed' })
217
+ return
218
+ }
219
+ const rejection = connectionRejection(ctx, req)
220
+ if (rejection !== undefined) {
221
+ sendJson(res, rejection, { ok: false, message: 'not authorized' })
222
+ return
223
+ }
224
+ try {
225
+ const body = await readJsonBody(req)
226
+ const doc = await mutateDoc((current) => applyAction(current, body))
227
+ sendJson(res, 200, { ok: true, list: viewDoc(doc) })
228
+ } catch (error) {
229
+ const message = error instanceof Error ? error.message : String(error)
230
+ ctx.logger?.warn?.('quick-commands: action failed: ' + message)
231
+ sendJson(res, 400, { ok: false, message })
232
+ }
233
+ }
234
+
235
+ ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/state', handler: stateHandler }), 'quick-commands: state route')
236
+ ctx.effect(() => ctx.webServer.register({ kind: 'exact', path: ROUTE_BASE + '/action', handler: actionHandler }), 'quick-commands: action route')
237
+ }
package/locale/en.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "Quick commands",
4
+ "description": "A Snippets button beside the composer: keep what you type often, insert it as editable text, or send it in one click."
5
+ }
6
+ }
package/locale/zh.json ADDED
@@ -0,0 +1,6 @@
1
+ {
2
+ "meta": {
3
+ "title": "常用指令",
4
+ "description": "输入框左侧的「常用」按钮:把常说的话存起来,一键插入或发送。"
5
+ }
6
+ }
package/package.json CHANGED
@@ -1,6 +1,57 @@
1
1
  {
2
2
  "name": "@lyra_wang/dsh-quick-commands",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0",
4
+ "description": "Quick commands for DeepSeek Harness: one button next to the composer keeps your reusable snippets, inserts them as editable text, or sends one in a click.",
5
+ "license": "MIT",
6
+ "type": "module",
7
+ "main": "index.js",
8
+ "icon": "./icon.svg",
9
+ "keywords": [
10
+ "dsh",
11
+ "dsh-plugin",
12
+ "client-plugin",
13
+ "snippets",
14
+ "prompts"
15
+ ],
16
+ "repository": {
17
+ "type": "git",
18
+ "url": "git+https://github.com/LyraWang6688/ai-capability-store.git",
19
+ "directory": "external-capabilities/plugin/dsh/quick-commands"
20
+ },
21
+ "publishConfig": {
22
+ "access": "public"
23
+ },
24
+ "engines": {
25
+ "node": ">=20"
26
+ },
27
+ "exports": {
28
+ ".": "./index.js",
29
+ "./client": "./client.js",
30
+ "./cordis.patch.yml": "./cordis.patch.yml",
31
+ "./locale/*.json": "./locale/*.json",
32
+ "./icon": "./icon.svg",
33
+ "./package.json": "./package.json"
34
+ },
35
+ "files": [
36
+ "index.js",
37
+ "client.js",
38
+ "cordis.patch.yml",
39
+ "locale/*.json",
40
+ "icon.svg",
41
+ "README.md",
42
+ "LICENSE"
43
+ ],
44
+ "dsh": {
45
+ "manifestVersion": 1,
46
+ "bundle": {
47
+ "patch": "./cordis.patch.yml"
48
+ },
49
+ "client": {
50
+ "platform": "web",
51
+ "immediately": true,
52
+ "inject": [
53
+ "@deepseek-ai/dsh-client-ui-layout"
54
+ ]
55
+ }
56
+ }
57
+ }