@tina_summer/codepocket 2.6.10 → 2.7.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.
@@ -0,0 +1,203 @@
1
+ /**
2
+ * ZCode engine reader — history/messages via the embedded CLI engine
3
+ * (`ZCode.app/Contents/Resources/glm/zcode.cjs app-server`, "ZCode Protocol").
4
+ *
5
+ * Read path verified working (list/resume/messages all fine while the desktop
6
+ * app runs; model CALLS hit 401 in our standalone process, so sending stays
7
+ * on the ws2 relay — this module is read-only by design).
8
+ *
9
+ * Engine sessions share ~/.zcode storage with the desktop app — session IDs
10
+ * are the same sess_* records.
11
+ */
12
+ const { spawn } = require('child_process')
13
+ const fs = require('fs')
14
+ const os = require('os')
15
+ const path = require('path')
16
+
17
+ const ENGINE_CANDIDATES = [
18
+ '/Applications/ZCode.app/Contents/Resources/glm/zcode.cjs',
19
+ ]
20
+ const BUILTIN_CFG = '/Applications/ZCode.app/Contents/Resources/config/provider/zcode-builtin.json'
21
+
22
+ function findEngine() {
23
+ if (process.env.CODEPOCKET_ZCODE_ENGINE) return process.env.CODEPOCKET_ZCODE_ENGINE
24
+ for (const p of ENGINE_CANDIDATES) {
25
+ try { if (fs.existsSync(p)) return p } catch {}
26
+ }
27
+ return null
28
+ }
29
+
30
+ // ── single shared engine process ──
31
+
32
+ let proc = null
33
+ let stdoutBuf = ''
34
+ let nextId = 1
35
+ const pending = new Map()
36
+ let storageReady = false
37
+ let readyWaiters = []
38
+ let starting = null
39
+ let lastActivity = 0
40
+
41
+ function ensureEngine() {
42
+ if (proc && storageReady) return Promise.resolve()
43
+ if (starting) return starting
44
+ starting = (async () => {
45
+ const engine = findEngine()
46
+ if (!engine) throw new Error('未找到 ZCode 引擎(需要安装 ZCode 桌面端)')
47
+ if (!fs.existsSync(BUILTIN_CFG)) throw new Error('未找到 ZCode 内置 provider 配置')
48
+
49
+ const child = proc = spawn('node', [engine, 'app-server'], {
50
+ stdio: ['pipe', 'pipe', 'ignore'],
51
+ env: { ...process.env, ZCODE_BUILTIN_PROVIDER_CONFIG_FILE: BUILTIN_CFG },
52
+ cwd: path.join(os.homedir(), 'work') || os.homedir(),
53
+ })
54
+ storageReady = false
55
+ child.stdout.on('data', (c) => {
56
+ stdoutBuf += c
57
+ let nl
58
+ while ((nl = stdoutBuf.indexOf('\n')) >= 0) {
59
+ const line = stdoutBuf.slice(0, nl).trim()
60
+ stdoutBuf = stdoutBuf.slice(nl + 1)
61
+ if (!line) continue
62
+ let m
63
+ try { m = JSON.parse(line) } catch { continue }
64
+ handleMessage(m)
65
+ }
66
+ })
67
+ child.on('exit', () => {
68
+ proc = null
69
+ storageReady = false
70
+ starting = null
71
+ for (const cb of pending.values()) cb.reject(new Error('ZCode 引擎已退出'))
72
+ pending.clear()
73
+ })
74
+ await new Promise((resolve, reject) => {
75
+ const timer = setTimeout(() => reject(new Error('ZCode 引擎启动超时')), 30000)
76
+ readyWaiters.push(() => { clearTimeout(timer); resolve() })
77
+ })
78
+ starting = null
79
+ })()
80
+ return starting
81
+ }
82
+
83
+ function handleMessage(m) {
84
+ if (m.id !== undefined && (m.result !== undefined || m.error !== undefined)) {
85
+ const cb = pending.get(m.id)
86
+ if (cb) {
87
+ pending.delete(m.id)
88
+ m.error ? cb.reject(Object.assign(new Error((m.error.data && m.error.data.message) || m.error.message || 'ZCode 引擎错误'), m.error.data || {})) : cb.resolve(m.result)
89
+ }
90
+ return
91
+ }
92
+ if (m.method) {
93
+ const p = m.params || {}
94
+ if (m.method === 'startup/storageState' && (p.phase === 'ready' || p.phase === 'succeeded' || p.phase === 'open')) {
95
+ storageReady = true
96
+ const waiters = readyWaiters; readyWaiters = []
97
+ for (const w of waiters) w()
98
+ }
99
+ // server→client requests: use the official compatibility fallback for
100
+ // runtime preferences (-32601 triggers engine-side defaults); ack others empty.
101
+ if (m.id !== undefined) {
102
+ const isPrefs = m.method.includes('RuntimePreferences')
103
+ send({ id: m.id, error: isPrefs ? { code: -32601, message: 'compat fallback' } : undefined, ...(isPrefs ? {} : { result: {} }) })
104
+ }
105
+ }
106
+ }
107
+
108
+ function send(obj) {
109
+ if (!proc) throw new Error('ZCode 引擎未运行')
110
+ proc.stdin.write(JSON.stringify(obj) + '\n')
111
+ }
112
+
113
+ function req(method, params, timeoutMs = 25000) {
114
+ return new Promise((resolve, reject) => {
115
+ const id = nextId++
116
+ const t = setTimeout(() => { pending.delete(id); reject(new Error(`ZCode 引擎请求超时: ${method}`)) }, timeoutMs)
117
+ pending.set(id, { resolve: v => { clearTimeout(t); resolve(v) }, reject: e => { clearTimeout(t); reject(e) } })
118
+ send({ id, method, params: params || {} })
119
+ })
120
+ }
121
+
122
+ // ── public read API ──
123
+
124
+ async function listSessions(limit = 60) {
125
+ await ensureEngine()
126
+ lastActivity = Date.now()
127
+ const r = await req('session/list', { limit })
128
+ return (r && r.sessions) || []
129
+ }
130
+
131
+ async function readMessages(sessionId, limit = 100) {
132
+ await ensureEngine()
133
+ lastActivity = Date.now()
134
+ // resume activates the runtime AND its response carries the full message list
135
+ // (verified shape: { messages: [...] }); session/messages also works once active
136
+ try {
137
+ const rs = await req('session/resume', { sessionId }, 30000)
138
+ const fromResume = rs && rs.messages
139
+ if (Array.isArray(fromResume) && fromResume.length) return normalizeMessages(fromResume)
140
+ } catch (e) { /* fall through */ }
141
+ try {
142
+ const r = await req('session/messages', { sessionId, limit })
143
+ return normalizeMessages(r && r.messages)
144
+ } catch (e) {
145
+ return { messages: [], page: { hasMore: false, nextBeforeSeq: null }, error: e.message }
146
+ }
147
+ }
148
+
149
+ // ── normalization: engine messages → hub envelope (miniprogram parser format) ──
150
+
151
+ function normalizeMessages(raw) {
152
+ const messages = []
153
+ for (const m of raw || []) {
154
+ const hub = normalizeOne(m)
155
+ if (hub) messages.push(hub)
156
+ }
157
+ return { messages, page: { hasMore: false, nextBeforeSeq: null } }
158
+ }
159
+
160
+ function envelope(id, createdAt, role, blocks) {
161
+ return {
162
+ id, createdAt: createdAt || Date.now(), invokedAt: createdAt || null, status: 'completed',
163
+ content: {
164
+ role,
165
+ content: role === 'user'
166
+ ? { type: 'user', message: { content: blocks } }
167
+ : { type: 'output', data: { type: 'assistant', message: { content: blocks } } },
168
+ },
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Engine message shape (verified): { info: { role: 'user'|'assistant', messageId,
174
+ * finish?, model?... }, parts: [{ type: 'text'|'reasoning'|'step-start'|'step-finish',
175
+ * text?, metadata?, synthetic? }] }
176
+ * Map to Anthropic-ish blocks the miniprogram already renders.
177
+ */
178
+ function normalizeOne(m) {
179
+ if (!m || typeof m !== 'object') return null
180
+ const info = m.info || {}
181
+ const parts = Array.isArray(m.parts) ? m.parts : []
182
+ const id = info.messageId || m.messageId || `zm_${Date.now()}_${messages_counter++}`
183
+ const role = info.role === 'user' ? 'user' : 'agent'
184
+
185
+ if (role === 'user') {
186
+ const text = parts.filter(p => p && !p.synthetic && typeof p.text === 'string' && p.text.trim()).map(p => p.text).join('\n')
187
+ if (!text) return null
188
+ return envelope(id, undefined, 'user', [{ type: 'text', text }])
189
+ }
190
+
191
+ const blocks = []
192
+ for (const p of parts) {
193
+ if (!p || typeof p.text !== 'string' || !p.text.trim()) continue
194
+ if (p.type === 'reasoning') blocks.push({ type: 'thinking', text: p.text })
195
+ else if (p.type === 'text') blocks.push({ type: 'text', text: p.text })
196
+ // step-start / step-finish / metadata-only parts carry no display text
197
+ }
198
+ if (!blocks.length) return null
199
+ return envelope(id, undefined, 'agent', blocks)
200
+ }
201
+ let messages_counter = 0
202
+
203
+ module.exports = { findEngine, listSessions, readMessages }
@@ -0,0 +1,113 @@
1
+ /**
2
+ * ZCode (GLM desktop app) — read-only session listing from the local
3
+ * tasks-index.sqlite (schema verified against ~/.zcode/v2 on this machine:
4
+ * tasks(task_id, title, task_status, provider, mode, model, workspace_path,
5
+ * created_at, updated_at, archived, deleted, ...)).
6
+ *
7
+ * Read-only by design: sending/approvals stay in the ZCode desktop app (its
8
+ * official remote-control protocol is a separate future work item). The
9
+ * miniprogram gets the sessions with caps.send=false etc. and hides the
10
+ * corresponding controls automatically.
11
+ *
12
+ * Uses node:sqlite (Node 22.5+); on older runtimes listing degrades to empty.
13
+ */
14
+ const fs = require('fs')
15
+ const path = require('path')
16
+
17
+ const ZCODE_DB = path.join(process.env.ZCODE_HOME || path.join(require('os').homedir(), '.zcode'), 'v2', 'tasks-index.sqlite')
18
+
19
+ const READONLY_CAPS = {
20
+ send: false, stop: false, resume: false, approve: false, question: false,
21
+ attachments: false, permissionMode: false, queue: false, compact: false,
22
+ share: true, spawn: false,
23
+ }
24
+
25
+ let _db = undefined // undefined = not tried, null = unavailable
26
+
27
+ function openDb() {
28
+ if (_db !== undefined) return _db
29
+ _db = null
30
+ try {
31
+ if (!fs.statSync(ZCODE_DB).isFile()) return null
32
+ const { DatabaseSync } = require('node:sqlite')
33
+ _db = new DatabaseSync(ZCODE_DB, { readOnly: true })
34
+ } catch { _db = null }
35
+ return _db
36
+ }
37
+
38
+ function listSessions(limit = 60) {
39
+ const db = openDb()
40
+ if (!db) return []
41
+ try {
42
+ const stmt = db.prepare(
43
+ 'SELECT task_id, title, task_status, provider, model, workspace_path, created_at, updated_at ' +
44
+ 'FROM tasks WHERE deleted = 0 AND host_id = \'local\' AND provider = \'glm\' ' +
45
+ 'ORDER BY updated_at DESC LIMIT ?')
46
+ return stmt.all(limit).map(row => ({
47
+ id: 'zcode:' + row.task_id,
48
+ active: row.task_status === 'running',
49
+ thinking: row.task_status === 'running',
50
+ updatedAt: Number(row.updated_at) || Date.now(),
51
+ pendingRequestsCount: 0,
52
+ metadata: {
53
+ name: row.title || (row.workspace_path ? String(row.workspace_path).split('/').filter(Boolean).pop() : row.task_id),
54
+ path: row.workspace_path || '',
55
+ provider: 'zcode',
56
+ model: row.model || '',
57
+ },
58
+ capabilities: READONLY_CAPS,
59
+ }))
60
+ } catch { return [] }
61
+ }
62
+
63
+ function sessionDetail(sessionId) {
64
+ if (typeof sessionId !== 'string' || !sessionId.startsWith('zcode:')) return null
65
+ const rows = listSessions(200)
66
+ const row = rows.find(r => r.id === sessionId)
67
+ if (!row) return { session: null }
68
+ return {
69
+ session: {
70
+ ...row,
71
+ agentState: { requests: {}, controlledByUser: false },
72
+ },
73
+ }
74
+ }
75
+
76
+ function isZcodeSession(sessionId) {
77
+ return typeof sessionId === 'string' && sessionId.startsWith('zcode:')
78
+ }
79
+
80
+ /**
81
+ * No message history bridge yet — instead of a blank page (which reads as
82
+ * broken), surface one explanatory agent message. History sync is future work.
83
+ */
84
+ function readMessages(sessionId) {
85
+ const detail = sessionDetail(sessionId)
86
+ const name = detail.session && detail.session.metadata && detail.session.metadata.name
87
+ return {
88
+ messages: [{
89
+ id: 'zcode-readonly-notice',
90
+ createdAt: Date.now(),
91
+ invokedAt: Date.now(),
92
+ status: 'completed',
93
+ content: {
94
+ role: 'agent',
95
+ content: {
96
+ type: 'output',
97
+ data: {
98
+ type: 'assistant',
99
+ message: {
100
+ content: [{
101
+ type: 'text',
102
+ text: `「${name || '该会话'}」来自 ZCode 桌面端,当前为只读展示:\n\n- 历史消息同步开发中,暂无法在此查看\n- 发送消息请回到 ZCode 桌面端操作\n- 会话状态(标题/时间/进行中)会实时更新`,
103
+ }],
104
+ },
105
+ },
106
+ },
107
+ },
108
+ }],
109
+ page: { hasMore: false, nextBeforeSeq: null },
110
+ }
111
+ }
112
+
113
+ module.exports = { isZcodeSession, listSessions, sessionDetail, readMessages, READONLY_CAPS }