dsh-half-page 0.3.38 → 0.3.50

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/notice.js ADDED
@@ -0,0 +1,83 @@
1
+ /**
2
+ * notice —— 造一条「到点了」的用户消息,按系统提示那一排显示,不冒充谁在说话。
3
+ *
4
+ * 优先从宿主那棵树里取官方的 createUserMessage;桌面 profile 用
5
+ * autoInstallPeers:false,裸 import 常常解析不到,所以拿不到就退到等价实现。
6
+ */
7
+ import { randomUUID } from 'node:crypto'
8
+ import { existsSync } from 'node:fs'
9
+ import { join } from 'node:path'
10
+ import { homedir } from 'node:os'
11
+ import { pathToFileURL } from 'node:url'
12
+
13
+ const PKG = 'dsh-llm'
14
+ const SOURCE_KIND = 'dsh-half-page'
15
+
16
+ function candidateFiles() {
17
+ const out = []
18
+ const add = (p) => {
19
+ if (p && existsSync(p) && !out.includes(p)) out.push(p)
20
+ }
21
+ const res = process.resourcesPath
22
+ if (res) {
23
+ add(join(res, 'app.asar', 'dsh', 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'))
24
+ add(join(res, 'app', 'dsh', 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'))
25
+ }
26
+ const appdata = process.env.APPDATA
27
+ if (appdata) {
28
+ add(join(appdata, 'npm', 'node_modules', '@deepseek-ai', 'dsh', 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'))
29
+ }
30
+ const dshHome = process.env.DSH_HOME || join(homedir(), '.dsh')
31
+ for (const profile of ['desktop', 'web']) {
32
+ add(join(dshHome, 'profiles', profile, 'node_modules', '@deepseek-ai', PKG, 'lib', 'index.js'))
33
+ }
34
+ return out
35
+ }
36
+
37
+ function fallback(input) {
38
+ const text = typeof input?.text === 'string'
39
+ ? input.text
40
+ : (Array.isArray(input?.content) ? input.content : [])
41
+ .filter((block) => block?.type === 'text')
42
+ .map((block) => String(block.text ?? ''))
43
+ .join('')
44
+ return Object.freeze({
45
+ id: randomUUID(),
46
+ role: 'user',
47
+ content: Object.freeze([{ type: 'text', text }]),
48
+ source: Object.freeze({ kind: SOURCE_KIND, form: 'notice', summary: input?.summary ?? text.slice(0, 120) }),
49
+ })
50
+ }
51
+
52
+ let cached
53
+
54
+ export async function loadCreateUserMessage(onNote = () => {}) {
55
+ if (cached) return cached
56
+ for (const file of candidateFiles()) {
57
+ try {
58
+ const mod = await import(pathToFileURL(file).href)
59
+ if (typeof mod.createUserMessage === 'function') {
60
+ cached = mod.createUserMessage
61
+ onNote(`createUserMessage:用宿主那份(${file})`)
62
+ return cached
63
+ }
64
+ } catch (error) {
65
+ onNote(`createUserMessage:${file} 取不到(${error?.code || error?.message || error})`)
66
+ }
67
+ }
68
+ try {
69
+ const mod = await import('@deepseek-ai/dsh-llm')
70
+ if (typeof mod?.createUserMessage === 'function') {
71
+ cached = mod.createUserMessage
72
+ onNote('createUserMessage:用裸 import 那份')
73
+ return cached
74
+ }
75
+ } catch {
76
+ // 走兜底
77
+ }
78
+ cached = fallback
79
+ onNote('createUserMessage:官方那份拿不到,用本地等价实现(结构一致)')
80
+ return cached
81
+ }
82
+
83
+ export { SOURCE_KIND }
@@ -0,0 +1,167 @@
1
+ /**
2
+ * session-probe —— 只回答三个时间:他最后说话、我最后回话、最后一条 notice。
3
+ *
4
+ * 为什么不用会话文件的 mtime:日志每轮都在写(系统注入、汇报都算),mtime 永远是新的。
5
+ * 为什么事件里没有 source:真正落盘的 `user/message` 不带 source,来源只活在
6
+ * `agent/inbox/spliced` 的 inserted[].source 里 —— notice 就是靠这个认的。
7
+ */
8
+ import { readdir, readFile, stat } from 'node:fs/promises'
9
+ import { join } from 'node:path'
10
+ import { zstdDecompressSync } from 'node:zlib'
11
+
12
+ const FRAME = [0x28, 0xb5, 0x2f, 0xfd]
13
+ const NOTICE_KINDS = new Set(['heartbeat', 'dsh-half-page', 'schedule', 'dsh-heartbeat'])
14
+
15
+ /** 多帧 zstd:按魔数切开逐帧解,再拼起来。只解第一帧会漏掉 99% 的内容。 */
16
+ export function decodeLog(buffer, options = {}) {
17
+ const frames = []
18
+ let start = -1
19
+ for (let i = 0; i + 3 < buffer.length; i += 1) {
20
+ if (buffer[i] === FRAME[0] && buffer[i + 1] === FRAME[1] && buffer[i + 2] === FRAME[2] && buffer[i + 3] === FRAME[3]) {
21
+ if (start >= 0) frames.push(buffer.subarray(start, i))
22
+ start = i
23
+ }
24
+ }
25
+ if (start >= 0) frames.push(buffer.subarray(start))
26
+ if (frames.length === 0) return ''
27
+ const limit = Number.isInteger(options.maxFrames) && options.maxFrames > 0 ? options.maxFrames : frames.length
28
+ const parts = []
29
+ for (const frame of frames.slice(-limit)) {
30
+ try {
31
+ parts.push(zstdDecompressSync(frame).toString('utf8'))
32
+ } catch {
33
+ // 坏帧跳过,别整份报废
34
+ }
35
+ }
36
+ return parts.join('')
37
+ }
38
+
39
+ export function parseEvents(text) {
40
+ const out = []
41
+ for (const line of text.split('\n')) {
42
+ if (!line.trim()) continue
43
+ try {
44
+ const event = JSON.parse(line)
45
+ if (event && typeof event === 'object') out.push(event)
46
+ } catch {
47
+ // 半行/坏行跳过
48
+ }
49
+ }
50
+ return out
51
+ }
52
+
53
+ export function textOfContent(content) {
54
+ if (typeof content === 'string') return content
55
+ if (!Array.isArray(content)) return ''
56
+ const parts = []
57
+ for (const part of content) {
58
+ if (typeof part === 'string') parts.push(part)
59
+ else if (part && typeof part.text === 'string') parts.push(part.text)
60
+ }
61
+ return parts.join('')
62
+ }
63
+
64
+ /** 会话目录名跟 cwd 编码有关,不猜:直接按 <sid>/session.v4.jsonl.zstd 找。 */
65
+ export async function findSessionLog(sessionsRoot, sessionId) {
66
+ let dirs
67
+ try {
68
+ dirs = await readdir(sessionsRoot, { withFileTypes: true })
69
+ } catch {
70
+ return null
71
+ }
72
+ for (const dirent of dirs) {
73
+ if (!dirent.isDirectory()) continue
74
+ const candidate = join(sessionsRoot, dirent.name, String(sessionId), 'session.v4.jsonl.zstd')
75
+ try {
76
+ await stat(candidate)
77
+ return candidate
78
+ } catch {
79
+ // 下一个
80
+ }
81
+ }
82
+ return null
83
+ }
84
+
85
+ /** 最近被人写过日志的会话(不猜目录名,按文件 mtime 取最新) */
86
+ export async function newestSessionId(sessionsRoot) {
87
+ let dirs
88
+ try {
89
+ dirs = await readdir(sessionsRoot, { withFileTypes: true })
90
+ } catch {
91
+ return ''
92
+ }
93
+ let best = null
94
+ for (const dirent of dirs) {
95
+ if (!dirent.isDirectory()) continue
96
+ const project = join(sessionsRoot, dirent.name)
97
+ let subs
98
+ try {
99
+ subs = await readdir(project, { withFileTypes: true })
100
+ } catch {
101
+ continue
102
+ }
103
+ for (const sub of subs) {
104
+ if (!sub.isDirectory()) continue
105
+ const file = join(project, sub.name, 'session.v4.jsonl.zstd')
106
+ try {
107
+ const info = await stat(file)
108
+ if (!best || info.mtimeMs > best.mtimeMs) best = { sessionId: sub.name, mtimeMs: info.mtimeMs }
109
+ } catch {
110
+ // 没日志的会话跳过
111
+ }
112
+ }
113
+ }
114
+ return best ? best.sessionId : ''
115
+ }
116
+
117
+ function noticeAt(event) {
118
+ if (event?.type !== 'agent/inbox/spliced') return null
119
+ const inserted = event.data?.inserted
120
+ if (!Array.isArray(inserted)) return null
121
+ for (const item of inserted) {
122
+ const source = item?.source
123
+ if (!source) continue
124
+ if (source.form === 'notice') return Number(event.time) || null
125
+ if (typeof source.kind === 'string' && NOTICE_KINDS.has(source.kind)) return Number(event.time) || null
126
+ }
127
+ return null
128
+ }
129
+
130
+ export function pickTimeline(events) {
131
+ let lastUserAt = null
132
+ let lastAssistantAt = null
133
+ let lastNoticeAt = null
134
+ for (let i = events.length - 1; i >= 0; i -= 1) {
135
+ if (lastUserAt !== null && lastAssistantAt !== null && lastNoticeAt !== null) break
136
+ const event = events[i]
137
+ const at = Number(event?.time) || null
138
+ if (!at) continue
139
+ if (lastNoticeAt === null) {
140
+ const notice = noticeAt(event)
141
+ if (notice) lastNoticeAt = notice
142
+ }
143
+ if (lastAssistantAt === null && event.type === 'assistant/message') lastAssistantAt = at
144
+ if (lastUserAt === null && event.type === 'user/message' && textOfContent(event.data?.content).trim()) lastUserAt = at
145
+ }
146
+ return { lastUserAt, lastAssistantAt, lastNoticeAt }
147
+ }
148
+
149
+ /** 大日志先只解最后几百帧;什么都没读到再全量解一次 */
150
+ export async function readTimeline(sessionsRoot, sessionId, options = {}) {
151
+ const file = await findSessionLog(sessionsRoot, sessionId)
152
+ if (!file) return { ok: false, error: 'no_log' }
153
+ let buffer
154
+ try {
155
+ buffer = await readFile(file)
156
+ } catch (error) {
157
+ return { ok: false, error: String(error?.code || error?.message || error) }
158
+ }
159
+ const tail = Number.isInteger(options.tailFrames) ? options.tailFrames : 400
160
+ let events = parseEvents(decodeLog(buffer, { maxFrames: tail }))
161
+ let timeline = pickTimeline(events)
162
+ if (timeline.lastUserAt === null && timeline.lastAssistantAt === null) {
163
+ events = parseEvents(decodeLog(buffer))
164
+ timeline = pickTimeline(events)
165
+ }
166
+ return { ok: true, sessionFile: file, events: events.length, ...timeline }
167
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "dsh-half-page",
3
- "version": "0.3.38",
3
+ "version": "0.3.50",
4
4
  "private": false,
5
5
  "author": "鹿野 <luye@dsh.local>",
6
6
  "license": "MIT",
@@ -15,6 +15,7 @@
15
15
  "files": [
16
16
  "index.js",
17
17
  "client.js",
18
+ "lib",
18
19
  "cordis.patch.yml",
19
20
  "locale/*.json",
20
21
  "icon.svg",
@@ -1,6 +0,0 @@
1
- {
2
- "meta": {
3
- "title": "半页",
4
- "description": "一间会自己读书的书房:一章一章地读,把读到哪儿记下来;读完想说什么,就写在那一章的边上;想写点自己的东西,也放在这儿。打开面板就能看见它今天翻了几页、这次写下了什么。"
5
- }
6
- }