dsh-aurorix-agentbook 1.4.2 → 1.5.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/abook.js CHANGED
@@ -246,6 +246,21 @@ export function createBackend(options = {}) {
246
246
  },
247
247
 
248
248
  /** 软删一条(测试清理用;面板不暴露删除,删除是维护动作)。 */
249
+ /** 改已有记录:标题、正文、读时机。带上读到的 revision,别人抢先改了就不会被静默覆盖。 */
250
+ async update({ id, title, body, readWhen, revision }) {
251
+ const args = ['memory', 'update', '--id', id]
252
+ if (typeof title === 'string' && title !== '') args.push('--title', title)
253
+ if (typeof body === 'string') args.push('--body-file', '-')
254
+ if (typeof readWhen === 'string') args.push('--read-when', readWhen)
255
+ if (revision !== undefined && revision !== null && String(revision) !== '') {
256
+ args.push('--expect-revision', String(revision))
257
+ }
258
+ args.push('--json')
259
+ const r = await call(args, typeof body === 'string' ? body : undefined)
260
+ if (!r.ok || r.json === undefined) return { ok: false, reason: reasonOf(r) }
261
+ return { ok: true, record: r.json }
262
+ },
263
+
249
264
  async remove(id, revision) {
250
265
  const r = await call(['memory', 'delete', '--id', id, '--expect-revision', String(revision), '--json'])
251
266
  if (!r.ok) return { ok: false, reason: reasonOf(r) }
package/lib/index.js CHANGED
@@ -6,6 +6,7 @@
6
6
  // - 回调 3 秒内返回;查库、写库、解密单条凭据都放延后结果里。
7
7
  // - 不在没有点按时做有副作用的事;insert 永远不自动发送。
8
8
  import { createBackend, PLANES } from './abook.js'
9
+ import { attachWeb } from './web.js'
9
10
  import { attachHost } from './host.js'
10
11
  import { memoryData, memoryView, splitBody, stripData } from './view.js'
11
12
  import { planeLabel, words } from './words.js'
@@ -43,6 +44,9 @@ export function apply(ctx, config) {
43
44
  })
44
45
  const w = (locale) => words(locale)
45
46
 
47
+ // 网页版:在 dsh web 里挂一条「记忆库」入口。手机上拿不到 webServer,会自动跳过。
48
+ attachWeb(ctx, { backend, root: settings.root || undefined })
49
+
46
50
  // 宿主层(提示词注入、工具、斜杠命令)和界面层共用这一个 backend。
47
51
  attachHost(ctx, {
48
52
  backend,
@@ -70,8 +74,32 @@ export function apply(ctx, config) {
70
74
  vaultDraft: { ident: '', purpose: '', body: '' },
71
75
  vaultDraftNote: '',
72
76
  detail: undefined,
77
+ detailEditing: false,
78
+ detailDraft: { title: '', body: '', readWhen: '', purpose: '' },
73
79
  })
74
80
 
81
+ // 详情缓存:abook 每次调用要起子进程(实测 230ms),反复进出同一条记录没必要重读。
82
+ // 写操作后整份清掉,不做细粒度失效——条目少,清干净比算得准更省心。
83
+ const detailCache = new Map()
84
+ const DETAIL_TTL_MS = 30_000
85
+ const DETAIL_CACHE_MAX = 40
86
+ function cacheDetail(id, record) {
87
+ detailCache.set(id, { at: Date.now(), record })
88
+ if (detailCache.size > DETAIL_CACHE_MAX) {
89
+ const oldest = [...detailCache.entries()].sort((a, b) => a[1].at - b[1].at)[0]
90
+ if (oldest !== undefined) detailCache.delete(oldest[0])
91
+ }
92
+ }
93
+ function cachedDetail(id) {
94
+ const hit = detailCache.get(id)
95
+ if (hit === undefined) return undefined
96
+ if (Date.now() - hit.at > DETAIL_TTL_MS) {
97
+ detailCache.delete(id)
98
+ return undefined
99
+ }
100
+ return hit.record
101
+ }
102
+
75
103
  /** 按会话各存一份,两个对话不会互相覆盖。 */
76
104
  const states = new Map()
77
105
  const listeners = new Set()
@@ -153,9 +181,11 @@ export function apply(ctx, config) {
153
181
  /** 打开一条普通记忆:读正文、切到详情页。 */
154
182
  async function openMemory(scope, id) {
155
183
  if (backend === undefined) return { ok: false, reason: 'abook' }
156
- const read = await backend.read(id)
184
+ const cached = cachedDetail(id)
185
+ const read = cached !== undefined ? { ok: true, record: cached } : await backend.read(id)
157
186
  if (!read.ok) return { ok: false, reason: read.reason }
158
187
  const record = read.record ?? {}
188
+ if (cached === undefined) cacheDetail(id, record)
159
189
  const body = splitBody(record.content)
160
190
  update(scope, {
161
191
  detail: {
@@ -166,6 +196,7 @@ export function apply(ctx, config) {
166
196
  readWhen: String(record.read_when ?? ''),
167
197
  updated: record.updated_at === undefined ? '' : formatTime(record.updated_at),
168
198
  body: String(record.content ?? ''),
199
+ revision: record.revision,
169
200
  blocks: body.blocks,
170
201
  shown: body.shown,
171
202
  total: body.total,
@@ -283,6 +314,67 @@ export function apply(ctx, config) {
283
314
  }
284
315
  },
285
316
 
317
+ // 详情页 → 编辑态。字段的初值从当前详情页带过去,不用重新读库。
318
+ 'detail-edit': (scope) => {
319
+ const current = stateOf(scope)
320
+ const d = current.detail
321
+ if (d === undefined || d === null) return { toast: '没有可编辑的详情' }
322
+ update(scope, {
323
+ detailEditing: true,
324
+ detailDraft: {
325
+ title: String(d.title ?? ''),
326
+ body: String(d.body ?? ''),
327
+ readWhen: String(d.readWhen ?? ''),
328
+ purpose: String(d.purpose ?? ''),
329
+ },
330
+ })
331
+ return { refresh: 'memory-home' }
332
+ },
333
+
334
+ 'detail-cancel': (scope) => {
335
+ update(scope, { detailEditing: false })
336
+ return { refresh: 'memory-home' }
337
+ },
338
+
339
+ // 保存:记忆走 memory update(带 revision 防覆盖),保险箱走 vault put 覆盖写。
340
+ 'detail-save': async (scope, event) => {
341
+ const odd = w(event?.locale)
342
+ const current = stateOf(scope)
343
+ const d = current.detail
344
+ if (d === undefined || d === null) return { toast: odd.editFailed + '无详情' }
345
+ const values = event?.value?.values ?? {}
346
+ const field = (path) => (typeof values[path] === 'string' ? values[path] : '')
347
+ const isVault = d.kind === 'vault'
348
+
349
+ if (isVault) {
350
+ const purpose = field('data.detailDraft.purpose').trim()
351
+ const body = field('data.detailDraft.body')
352
+ if (body === '') return { toast: odd.editFailed + '正文不能为空' }
353
+ const r = await backend.vaultPut({ ident: String(d.id ?? ''), purpose, body })
354
+ if (!r.ok) return { toast: `${odd.editFailed}${r.reason}`.slice(0, 60) }
355
+ const reopened = await openVault(scope, String(d.id ?? ''))
356
+ update(scope, { detailEditing: false })
357
+ if (!reopened.ok) return { toast: odd.editedOk }
358
+ return { refresh: 'memory-home' }
359
+ }
360
+
361
+ const title = field('data.detailDraft.title').trim()
362
+ if (title === '') return { toast: odd.editFailed + '标题不能为空' }
363
+ const r = await backend.update({
364
+ id: String(d.id ?? ''),
365
+ title,
366
+ body: field('data.detailDraft.body'),
367
+ readWhen: field('data.detailDraft.readWhen').trim(),
368
+ revision: d.revision,
369
+ })
370
+ if (!r.ok) return { toast: `${odd.editFailed}${r.reason}`.slice(0, 60) }
371
+ detailCache.clear()
372
+ const reopened = await openMemory(scope, String(d.id ?? ''))
373
+ update(scope, { detailEditing: false })
374
+ if (!reopened.ok) return { toast: odd.editedOk }
375
+ return { refresh: 'memory-home' }
376
+ },
377
+
286
378
  // 点召回结果的一行:读出正文,切到详情页。
287
379
  // 详情页要换掉整棵视图,只能用 refresh;而 refresh 不在延后结果允许的效果里,
288
380
  // 所以这里是当场做的:读一条本地记录实测 0.25 秒,3 秒的处理器窗口够用。
package/lib/view.js CHANGED
@@ -157,6 +157,35 @@ function detailView(state, caps) {
157
157
  [w.detailUpdated, d.updated === '' ? '—' : d.updated],
158
158
  ]
159
159
 
160
+ // 编辑态:把只读的字段换成可改的表单,并在底部给保存与取消。
161
+ if (state.detailEditing === true && (caps?.components === undefined || caps.components.includes('form'))) {
162
+ const dft = state.detailDraft ?? {}
163
+ const fields = isVault
164
+ ? [
165
+ { type: 'textField', label: w.editPurpose, bind: 'data.detailDraft.purpose', placeholder: w.detailPurpose, maxLength: 200, value: dft.purpose ?? '' },
166
+ { type: 'textField', label: w.editBody, bind: 'data.detailDraft.body', multiline: true, maxLines: 10, maxLength: 20000, value: dft.body ?? '' },
167
+ ]
168
+ : [
169
+ { type: 'textField', label: w.editTitle, bind: 'data.detailDraft.title', maxLength: 160, required: true, minLength: 1, value: dft.title ?? '' },
170
+ { type: 'textField', label: w.editBody, bind: 'data.detailDraft.body', multiline: true, maxLines: 10, maxLength: 20000, value: dft.body ?? '' },
171
+ { type: 'textField', label: w.editReadWhen, bind: 'data.detailDraft.readWhen', maxLength: 200, value: dft.readWhen ?? '' },
172
+ ]
173
+ return {
174
+ v: 2,
175
+ type: 'stack',
176
+ title: w.detailTitle,
177
+ accent: 'teal',
178
+ style: { gap: 'M' },
179
+ children: [
180
+ { type: 'text', text: isVault ? w.detailVaultKind : w.detailMemoryKind, tone: 'muted' },
181
+ { type: 'form', submit: 'detail-save', submitLabel: w.detailSave, children: fields },
182
+ { type: 'actions', items: [
183
+ { label: w.detailCancel, action: 'detail-cancel', style: 'plain' },
184
+ ] },
185
+ ],
186
+ }
187
+ }
188
+
160
189
  const children = [
161
190
  { type: 'text', text: isVault ? w.detailVaultKind : w.detailMemoryKind, tone: 'muted' },
162
191
  { type: 'text', text: clip(d.title === '' ? '—' : d.title, 200), style: { size: 'title', weight: 'semibold' } },
@@ -168,6 +197,10 @@ function detailView(state, caps) {
168
197
  if (d.shown < d.total) children.push({ type: 'callout', text: w.detailTruncated(d.shown, d.total), tone: 'info' })
169
198
  children.push({ type: 'actions', items: [
170
199
  { label: w.detailBack, action: 'detail-back', style: 'plain' },
200
+ // 既然已经点进详情页,就该能就地改——不用退回去重写一条。
201
+ ...(caps?.components === undefined || caps.components.includes('form')
202
+ ? [{ label: w.detailEdit, icon: 'pencil', action: 'detail-edit', style: 'plain' }]
203
+ : []),
171
204
  { label: w.detailCopy, icon: 'copy', action: 'detail-copy', style: 'primary' },
172
205
  ] })
173
206
 
@@ -235,6 +268,13 @@ export function memoryData(state, caps = {}) {
235
268
  query: state.query ?? '',
236
269
  hits,
237
270
  resultNote,
271
+ detailEditing: state.detailEditing === true,
272
+ detailDraft: {
273
+ title: state.detailDraft?.title ?? '',
274
+ body: state.detailDraft?.body ?? '',
275
+ readWhen: state.detailDraft?.readWhen ?? '',
276
+ purpose: state.detailDraft?.purpose ?? '',
277
+ },
238
278
  draft: {
239
279
  plane: state.draft?.plane ?? 'explicit',
240
280
  title: state.draft?.title ?? '',
package/lib/web.js ADDED
@@ -0,0 +1,308 @@
1
+ // Web 面板:在 dsh 的网页版里加一条「记忆库」入口,点开是独立页面。
2
+ //
3
+ // 两条挂载方式(都来自 @deepseek-ai/dsh-host-webserver):
4
+ // webServer.register({ kind:'prefix', path, handler }) 自己拥有 HTTP 响应
5
+ // ctx.on('webserver/index-inject', table => table.push({ kind:'script', ... }))
6
+ // 往 index.html 里塞一段脚本——侧边栏按钮就是这么加进去的
7
+ //
8
+ // 页面本身是一份自带样式的 HTML,数据和 dsh-go 原生面板同源(同一个 backend)。
9
+ import { existsSync } from 'node:fs'
10
+
11
+ const PAGE_TITLE = '记忆库'
12
+
13
+ /** 页面 HTML。样式跟 dsh-go 原生面板对齐:青绿主色、卡片、等宽数字。 */
14
+ export function pageHtml(locale = 'zh-CN') {
15
+ const zh = !String(locale).toLowerCase().startsWith('en')
16
+ const t = zh
17
+ ? { title: '记忆库', all: '全部', search: '搜一条', detail: '详情', edit: '编辑', save: '保存', cancel: '取消', back: '返回', vault: '保险箱', empty: '这里还没有记录', loading: '读取中…', ok: '已保存', fail: '操作失败:', titleField: '标题', bodyField: '正文', readWhen: '读时机', purpose: '用途', newRec: '写一条' }
18
+ : { title: 'Memory', all: 'All', search: 'Search', detail: 'Detail', edit: 'Edit', save: 'Save', cancel: 'Cancel', back: 'Back', vault: 'Vault', empty: 'Nothing here yet', loading: 'Loading…', ok: 'Saved', fail: 'Failed: ', titleField: 'Title', bodyField: 'Body', readWhen: 'Read when', purpose: 'Purpose', newRec: 'Write' }
19
+
20
+ return `<!doctype html>
21
+ <html lang="${zh ? 'zh-CN' : 'en'}"><head>
22
+ <meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1">
23
+ <title>${t.title}</title>
24
+ <style>
25
+ :root{--bg:#f7f8f8;--card:#fff;--ink:#1b1f1e;--muted:#6b7674;--line:#e3e7e6;--accent:#0f766e;--accent-weak:#e6f4f1}
26
+ @media (prefers-color-scheme:dark){:root{--bg:#141817;--card:#1b201f;--ink:#e8eceb;--muted:#98a3a1;--line:#2a3130;--accent:#4fd1c5;--accent-weak:#17302d}}
27
+ *{box-sizing:border-box}
28
+ body{margin:0;background:var(--bg);color:var(--ink);font:15px/1.55 -apple-system,system-ui,"PingFang SC","Noto Sans CJK SC",sans-serif}
29
+ .wrap{max-width:860px;margin:0 auto;padding:24px 18px 64px}
30
+ h1{font-size:19px;margin:0 0 4px;font-weight:600}
31
+ .sub{color:var(--muted);font-size:13px;margin-bottom:18px}
32
+ .card{background:var(--card);border:1px solid var(--line);border-radius:12px;padding:14px 16px;margin-bottom:12px}
33
+ .planes{display:flex;flex-wrap:wrap;gap:8px}
34
+ .pill{background:var(--accent-weak);color:var(--accent);border-radius:999px;padding:4px 10px;font-size:13px;font-variant-numeric:tabular-nums}
35
+ .row{display:flex;gap:10px;align-items:center}
36
+ input,textarea,select{width:100%;background:var(--card);border:1px solid var(--line);border-radius:10px;padding:9px 11px;color:var(--ink);font:inherit}
37
+ textarea{min-height:160px;resize:vertical;font-family:ui-monospace,SFMono-Regular,Menlo,monospace;font-size:13px}
38
+ button{background:var(--accent);color:#fff;border:0;border-radius:10px;padding:9px 16px;font:inherit;cursor:pointer}
39
+ button.plain{background:transparent;color:var(--accent);border:1px solid var(--line)}
40
+ button:disabled{opacity:.5;cursor:default}
41
+ .item{padding:11px 0;border-bottom:1px solid var(--line);cursor:pointer}
42
+ .item:last-child{border-bottom:0}
43
+ .item:hover{background:var(--accent-weak)}
44
+ .item .t{font-weight:500}
45
+ .item .m{color:var(--muted);font-size:13px}
46
+ .meta{display:grid;grid-template-columns:auto 1fr;gap:4px 14px;font-size:13px;color:var(--muted);margin:10px 0 14px}
47
+ .meta b{font-weight:500;color:var(--muted)}
48
+ .body{white-space:pre-wrap;word-break:break-word;font-size:14px;line-height:1.7;margin-bottom:16px}
49
+ .acts{display:flex;gap:8px;flex-wrap:wrap}
50
+ .err{color:#b42318}
51
+ .hide{display:none}
52
+ </style></head><body><div class="wrap">
53
+ <h1>${t.title}</h1>
54
+ <div class="sub" id="sub"></div>
55
+
56
+ <div class="card"><div class="planes" id="planes"></div></div>
57
+
58
+ <div class="card">
59
+ <div class="row"><input id="q" placeholder="${t.search}" autocomplete="off"><button id="go">${t.search}</button></div>
60
+ </div>
61
+
62
+ <div class="card" id="listCard"><div id="list"></div></div>
63
+
64
+ <div class="card hide" id="detailCard">
65
+ <div id="detailView"></div>
66
+ <div id="detailEdit" class="hide"></div>
67
+ <div class="acts" style="margin-top:14px">
68
+ <button class="plain" id="back">${t.back}</button>
69
+ <button class="plain" id="edit">${t.edit}</button>
70
+ <button class="hide" id="save">${t.save}</button>
71
+ <button class="hide" id="cancel">${t.cancel}</button>
72
+ </div>
73
+ <div class="err" id="err"></div>
74
+ </div>
75
+ </div>
76
+ <script>
77
+ const T = ${JSON.stringify(t)};
78
+ let S = { planes:{}, total:0, hits:[], detail:null, editing:false, draft:{} };
79
+
80
+ const $ = (id) => document.getElementById(id);
81
+ const esc = (s) => String(s == null ? '' : s).replace(/[&<>"]/g, (c) => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]));
82
+
83
+ async function api(path, body) {
84
+ const r = await fetch('aurorix/api/' + path, body === undefined ? {} : {
85
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body),
86
+ });
87
+ if (!r.ok) throw new Error('HTTP ' + r.status + ' ' + (await r.text()).slice(0, 120));
88
+ return await r.json();
89
+ }
90
+
91
+ function renderPlanes() {
92
+ const rows = Object.entries(S.planes || {}).map(([k, v]) => '<span class="pill">' + esc(k) + ' ' + esc(v) + '</span>');
93
+ $('planes').innerHTML = rows.join('') || '<span class="pill">0</span>';
94
+ $('sub').textContent = '共 ' + (S.total || 0) + ' 条';
95
+ }
96
+
97
+ function renderList() {
98
+ const items = S.hits || [];
99
+ if (items.length === 0) { $('list').innerHTML = '<div class="m" style="color:var(--muted)">' + T.empty + '</div>'; return; }
100
+ $('list').innerHTML = items.map((h, i) =>
101
+ '<div class="item" data-i="' + i + '"><div class="t">' + esc(h.title || '(无标题)') + '</div>' +
102
+ '<div class="m">' + esc(h.plane || '') + ' · ' + esc((h.preview || '').slice(0, 80)) + '</div></div>').join('');
103
+ [...document.querySelectorAll('.item')].forEach((el) => {
104
+ el.onclick = () => openDetail((S.hits || [])[Number(el.dataset.i)]);
105
+ });
106
+ }
107
+
108
+ function renderDetail() {
109
+ const d = S.detail; if (!d) return;
110
+ $('listCard').classList.add('hide');
111
+ $('detailCard').classList.remove('hide');
112
+ $('err').textContent = '';
113
+ const isVault = d.kind === 'vault';
114
+ const meta = isVault
115
+ ? [['标识', d.id], [T.purpose, d.purpose || '—']]
116
+ : [['平面', d.plane || '—'], ['更新时间', d.updated || '—'], ['ID', d.id]];
117
+ const body = (d.blocks && d.blocks.length ? d.blocks.join('\\n\\n') : d.body) || '';
118
+ $('detailView').innerHTML =
119
+ '<div class="t" style="font-weight:600;font-size:17px">' + esc(d.title || '—') + '</div>' +
120
+ '<div class="meta">' + meta.map(([k, v]) => '<b>' + esc(k) + '</b><span>' + esc(v) + '</span>').join('') + '</div>' +
121
+ '<div class="body">' + esc(body) + '</div>';
122
+
123
+ const fields = isVault
124
+ ? '<div style="margin-bottom:10px"><div class="m">' + T.purpose + '</div><input id="f-purpose" value="' + esc(S.draft.purpose || '') + '"></div>' +
125
+ '<div><div class="m">' + T.bodyField + '</div><textarea id="f-body">' + esc(S.draft.body || '') + '</textarea></div>'
126
+ : '<div style="margin-bottom:10px"><div class="m">' + T.titleField + '</div><input id="f-title" value="' + esc(S.draft.title || '') + '"></div>' +
127
+ '<div style="margin-bottom:10px"><div class="m">' + T.readWhen + '</div><input id="f-read" value="' + esc(S.draft.readWhen || '') + '"></div>' +
128
+ '<div><div class="m">' + T.bodyField + '</div><textarea id="f-body">' + esc(S.draft.body || '') + '</textarea></div>';
129
+ $('detailEdit').innerHTML = fields;
130
+ $('detailEdit').classList.toggle('hide', !S.editing);
131
+ $('detailView').classList.toggle('hide', S.editing);
132
+ $('edit').classList.toggle('hide', S.editing);
133
+ $('save').classList.toggle('hide', !S.editing);
134
+ $('cancel').classList.toggle('hide', !S.editing);
135
+ }
136
+
137
+ async function openDetail(hit) {
138
+ try {
139
+ const d = await api('detail', { id: hit.id, kind: hit.kind || 'memory' });
140
+ S.detail = d.detail; S.draft = d.draft; S.editing = false; renderDetail();
141
+ } catch (e) { $('err').textContent = T.fail + e.message; }
142
+ }
143
+
144
+ function back() {
145
+ S.detail = null; S.editing = false;
146
+ $('detailCard').classList.add('hide'); $('listCard').classList.remove('hide');
147
+ }
148
+
149
+ $('back').onclick = back;
150
+ $('edit').onclick = () => { S.editing = true; renderDetail(); };
151
+ $('cancel').onclick = () => { S.editing = false; renderDetail(); };
152
+ $('save').onclick = async () => {
153
+ const isVault = S.detail.kind === 'vault';
154
+ const payload = isVault
155
+ ? { ident: S.detail.id, purpose: $('f-purpose').value, body: $('f-body').value }
156
+ : { id: S.detail.id, title: $('f-title').value, readWhen: $('f-read').value, body: $('f-body').value };
157
+ try {
158
+ const r = await api(isVault ? 'vault-save' : 'save', payload);
159
+ if (!r.ok) { $('err').textContent = T.fail + (r.reason || ''); return; }
160
+ S.detail = r.detail; S.draft = r.draft; S.editing = false; renderDetail(); reload();
161
+ } catch (e) { $('err').textContent = T.fail + e.message; }
162
+ };
163
+
164
+ async function reload() {
165
+ const s = await api('state');
166
+ S.planes = s.planes; S.total = s.total; S.hits = s.hits;
167
+ renderPlanes(); renderList();
168
+ }
169
+ $('go').onclick = async () => {
170
+ const q = $('q').value.trim();
171
+ try {
172
+ const s = await api('search', { query: q });
173
+ S.planes = s.planes; S.total = s.total; S.hits = s.hits;
174
+ renderPlanes(); renderList();
175
+ $('listCard').classList.remove('hide'); $('detailCard').classList.add('hide');
176
+ } catch (e) { $('err').textContent = T.fail + e.message; }
177
+ };
178
+ $('q').addEventListener('keydown', (e) => { if (e.key === 'Enter') $('go').click(); });
179
+
180
+ reload().catch((e) => { $('sub').textContent = T.fail + e.message; });
181
+ </script></body></html>`
182
+ }
183
+
184
+ /** 往页面里塞一个侧边栏入口。等 SPA 把导航渲染出来再插,避免插到还没生成的容器里。 */
185
+ export function sidebarScript(prefix, title) {
186
+ return `(function(){
187
+ if (window.__AURORIX_ENTRY__) return; window.__AURORIX_ENTRY__ = true;
188
+ var HREF = ${JSON.stringify(prefix)}, NAME = ${JSON.stringify(title)};
189
+ function insert(){
190
+ var nav = document.querySelector('nav[aria-label],aside nav,nav');
191
+ if (!nav || nav.querySelector('[data-aurorix-entry]')) return false;
192
+ var a = document.createElement('a');
193
+ a.setAttribute('data-aurorix-entry','');
194
+ a.href = HREF; a.target = '_blank'; a.rel = 'noopener';
195
+ a.textContent = NAME;
196
+ a.style.cssText = 'display:block;padding:8px 12px;margin:4px 8px;border-radius:8px;text-decoration:none;color:inherit;font-size:14px;opacity:.85';
197
+ nav.appendChild(a);
198
+ return true;
199
+ }
200
+ var tries = 0;
201
+ var t = setInterval(function(){
202
+ if (insert() || ++tries > 40) clearInterval(t);
203
+ }, 500);
204
+ })();`
205
+ }
206
+
207
+ /**
208
+ * 把 Web 面板挂进 web 载体。拿不到 webServer 就安静跳过——dsh-go 手机上本来就没有它。
209
+ */
210
+ export function attachWeb(ctx, { backend, root }) {
211
+ const prefix = '/aurorix/'
212
+ ctx.inject(['webServer'], (webCtx) => {
213
+ const json = (res, code, value) => {
214
+ res.writeHead(code, { 'content-type': 'application/json; charset=utf-8', 'cache-control': 'no-store' })
215
+ res.end(JSON.stringify(value))
216
+ }
217
+ const readBody = (req) =>
218
+ new Promise((resolve) => {
219
+ let raw = ''
220
+ req.on('data', (c) => {
221
+ raw += c
222
+ if (raw.length > 2 * 1024 * 1024) req.destroy()
223
+ })
224
+ req.on('end', () => {
225
+ try { resolve(JSON.parse(raw === '' ? '{}' : raw)) } catch { resolve({}) }
226
+ })
227
+ })
228
+
229
+ const handler = async (req, res) => {
230
+ const url = new URL(req.url ?? '/', 'http://localhost')
231
+ const path = url.pathname
232
+
233
+ if (path === prefix || path === prefix.slice(0, -1)) {
234
+ res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' })
235
+ res.end(pageHtml(url.searchParams.get('lang') ?? 'zh-CN'))
236
+ return
237
+ }
238
+ if (!path.startsWith(prefix + 'api/')) { json(res, 404, { ok: false, reason: 'not found' }); return }
239
+
240
+ const action = path.slice((prefix + 'api/').length)
241
+ const ok = (value) => json(res, 200, value)
242
+ try {
243
+ if (action === 'state' && req.method === 'GET') {
244
+ const c = await backend.context()
245
+ const list = await backend.list('long_term', { limit: 20 })
246
+ ok({ planes: c.planes ?? {}, total: c.total ?? 0, hits: (list.items ?? []).map((x) => ({ id: x.id, title: x.title, plane: x.plane, preview: x.preview ?? '' })) })
247
+ return
248
+ }
249
+ if (req.method !== 'POST') { json(res, 405, { ok: false, reason: 'method' }); return }
250
+ const body = await readBody(req)
251
+
252
+ if (action === 'search') {
253
+ const q = String(body.query ?? '').trim()
254
+ const c = await backend.context()
255
+ const list = q === ''
256
+ ? await backend.list('long_term', { limit: 20 })
257
+ : await backend.search(q, 20)
258
+ ok({ planes: c.planes ?? {}, total: c.total ?? 0, hits: (list.items ?? []).map((x) => ({ id: x.id, title: x.title, plane: x.plane, preview: x.preview ?? '' })) })
259
+ return
260
+ }
261
+ if (action === 'detail') {
262
+ const isVault = String(body.kind ?? '') === 'vault'
263
+ if (isVault) {
264
+ const r = await backend.vaultGet(String(body.id ?? ''))
265
+ if (!r.ok) { ok({ ok: false, reason: r.reason }); return }
266
+ ok({ ok: true, detail: { kind: 'vault', id: r.record.ident, title: r.record.ident, purpose: r.record.purpose, body: r.record.body, blocks: [] }, draft: { purpose: r.record.purpose, body: r.record.body } })
267
+ return
268
+ }
269
+ const r = await backend.read(String(body.id ?? ''))
270
+ if (!r.ok) { ok({ ok: false, reason: r.reason }); return }
271
+ const rec = r.record ?? {}
272
+ ok({ ok: true, detail: { kind: 'memory', id: rec.id, title: rec.title, plane: rec.plane, readWhen: rec.read_when ?? '', updated: '', body: rec.content ?? '', revision: rec.revision, blocks: [] }, draft: { title: rec.title, readWhen: rec.read_when ?? '', body: rec.content ?? '' } })
273
+ return
274
+ }
275
+ if (action === 'save') {
276
+ const r = await backend.update({ id: String(body.id ?? ''), title: String(body.title ?? ''), body: String(body.body ?? ''), readWhen: String(body.readWhen ?? ''), revision: body.revision })
277
+ if (!r.ok) { ok({ ok: false, reason: r.reason }); return }
278
+ const rec = r.record ?? {}
279
+ ok({ ok: true, detail: { kind: 'memory', id: rec.id, title: rec.title, plane: rec.plane, readWhen: rec.read_when ?? '', updated: '', body: rec.content ?? '', blocks: [] }, draft: { title: rec.title, readWhen: rec.read_when ?? '', body: rec.content ?? '' } })
280
+ return
281
+ }
282
+ if (action === 'vault-save') {
283
+ const r = await backend.vaultPut({ ident: String(body.ident ?? ''), purpose: String(body.purpose ?? ''), body: String(body.body ?? '') })
284
+ if (!r.ok) { ok({ ok: false, reason: r.reason }); return }
285
+ const g = await backend.vaultGet(String(body.ident ?? ''))
286
+ const rec = g.ok ? g.record : { ident: body.ident, purpose: body.purpose, body: body.body }
287
+ ok({ ok: true, detail: { kind: 'vault', id: rec.ident, title: rec.ident, purpose: rec.purpose, body: rec.body, blocks: [] }, draft: { purpose: rec.purpose, body: rec.body } })
288
+ return
289
+ }
290
+ json(res, 404, { ok: false, reason: 'unknown action' })
291
+ } catch (err) {
292
+ json(res, 500, { ok: false, reason: String(err?.message ?? err) })
293
+ }
294
+ }
295
+
296
+ const dispose = webCtx.webServer.register({ kind: 'prefix', path: prefix, handler })
297
+
298
+ // 侧边栏入口:只注入一段脚本,等前端导航出现再插链接。
299
+ const off = ctx.on('webserver/index-inject', (table) => {
300
+ table.push({ kind: 'script', placement: 'body-end', text: sidebarScript(prefix, PAGE_TITLE) })
301
+ })
302
+
303
+ return () => {
304
+ try { dispose() } catch {}
305
+ try { off() } catch {}
306
+ }
307
+ })
308
+ }
package/lib/words.js CHANGED
@@ -72,6 +72,15 @@ export const WORDS = {
72
72
  detailVaultKind: '保险箱凭据',
73
73
  detailEmptyTitle: '还没打开任何一条',
74
74
  detailEmptyMessage: '在上一个页面点一条记录,这里会显示完整正文。',
75
+ detailEdit: '编辑',
76
+ detailSave: '保存修改',
77
+ detailCancel: '取消编辑',
78
+ editTitle: '标题',
79
+ editBody: '正文',
80
+ editReadWhen: '读时机',
81
+ editPurpose: '用途',
82
+ editedOk: '已保存',
83
+ editFailed: '保存失败:',
75
84
  detailBack: '返回',
76
85
  detailCopy: '复制正文',
77
86
  detailLoading: '正在读这一条',
@@ -157,6 +166,15 @@ export const WORDS = {
157
166
  detailVaultKind: 'Vault credential',
158
167
  detailEmptyTitle: 'Nothing opened yet',
159
168
  detailEmptyMessage: 'Tap a row on the previous page and the full text shows up here.',
169
+ detailEdit: 'Edit',
170
+ detailSave: 'Save',
171
+ detailCancel: 'Cancel',
172
+ editTitle: 'Title',
173
+ editBody: 'Body',
174
+ editReadWhen: 'Read when',
175
+ editPurpose: 'Purpose',
176
+ editedOk: 'Saved',
177
+ editFailed: 'Save failed: ',
160
178
  detailBack: 'Back',
161
179
  detailCopy: 'Copy body',
162
180
  detailLoading: 'Reading this one',
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-aurorix-agentbook",
3
- "version": "1.4.2",
3
+ "version": "1.5.0",
4
4
  "description": "dsh-aurorix-agentbook:给 dsh-go 接通 Aurorix 记忆库——原生界面(状态条/胶囊/菜单/面板/保险箱)加宿主侧提示词注入、分层快照与四个工具。",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",