@tina_summer/codepocket 2.6.11 → 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.
- package/bin/codepocket.js +69 -10
- package/package.json +5 -5
- package/src/agents/codexLive.js +362 -0
- package/src/agents/codexRollout.js +311 -0
- package/src/agents/index.js +169 -0
- package/src/agents/registry.js +113 -0
- package/src/agents/zcodeEngine.js +203 -0
- package/src/agents/zcodeIndex.js +113 -0
- package/src/agents/zcodeLive.js +476 -0
- package/src/agents/zcodeRpc.js +170 -0
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Codex rollout files — read-only session discovery & message normalization.
|
|
3
|
+
*
|
|
4
|
+
* Format verified against local ~/.codex/sessions data (codex 0.169):
|
|
5
|
+
* session_meta { id, cwd, timestamp, originator }
|
|
6
|
+
* turn_context per-turn model/config
|
|
7
|
+
* response_item Responses-API items:
|
|
8
|
+
* message { role: user|assistant|developer, content: [{type: input_text|output_text, text}] }
|
|
9
|
+
* reasoning { summary: [{type:'summary_text',text}...], encrypted_content }
|
|
10
|
+
* custom_tool_call { call_id, name, input: string, status }
|
|
11
|
+
* custom_tool_call_output { call_id, output }
|
|
12
|
+
* function_call { call_id, name, arguments: json-string }
|
|
13
|
+
* function_call_output { call_id, output: [{type:'input_text',text}] | string }
|
|
14
|
+
* event_msg item_completed / task_started / task_complete / turn_aborted ...
|
|
15
|
+
*
|
|
16
|
+
* Output shape matches the hub REST model the miniprogram already parses
|
|
17
|
+
* (utils/message-parser.js): messages with content:{role, content:{type:'output', data}}.
|
|
18
|
+
*/
|
|
19
|
+
const fs = require('fs')
|
|
20
|
+
const os = require('os')
|
|
21
|
+
const path = require('path')
|
|
22
|
+
|
|
23
|
+
const CODEX_HOME = process.env.CODEX_HOME || path.join(os.homedir(), '.codex')
|
|
24
|
+
const SESSIONS_DIR = path.join(CODEX_HOME, 'sessions')
|
|
25
|
+
const PROVIDER = 'codex'
|
|
26
|
+
|
|
27
|
+
// Reader-side caps when no codex binary is available (live adapter upgrades these)
|
|
28
|
+
const READONLY_CAPS = {
|
|
29
|
+
send: false, stop: false, resume: false, approve: false, question: false,
|
|
30
|
+
attachments: false, permissionMode: false, queue: false, compact: false,
|
|
31
|
+
share: true, spawn: false,
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
function sessionId(id) { return `${PROVIDER}:${id}` }
|
|
35
|
+
function isCodexSession(id) { return typeof id === 'string' && id.startsWith(PROVIDER + ':') }
|
|
36
|
+
function rawId(id) { return String(id).slice(PROVIDER.length + 1) }
|
|
37
|
+
|
|
38
|
+
// ── Discovery ──
|
|
39
|
+
|
|
40
|
+
/** Index all rollout files (newest first). Light: reads only session_meta line. */
|
|
41
|
+
function listSessions(limit = 60) {
|
|
42
|
+
const files = []
|
|
43
|
+
try {
|
|
44
|
+
// sessions/YYYY/MM/DD/rollout-<ts>-<id>.jsonl — walk 2 levels of months/days
|
|
45
|
+
const years = readdirSafe(SESSIONS_DIR)
|
|
46
|
+
for (const y of years) {
|
|
47
|
+
for (const m of readdirSafe(path.join(SESSIONS_DIR, y))) {
|
|
48
|
+
for (const d of readdirSafe(path.join(SESSIONS_DIR, y, m))) {
|
|
49
|
+
const dirPath = path.join(SESSIONS_DIR, y, m, d)
|
|
50
|
+
for (const f of readdirSafe(dirPath)) {
|
|
51
|
+
if (f.startsWith('rollout-') && f.endsWith('.jsonl')) {
|
|
52
|
+
files.push(path.join(dirPath, f))
|
|
53
|
+
}
|
|
54
|
+
}
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
} catch { return [] }
|
|
59
|
+
|
|
60
|
+
const sessions = []
|
|
61
|
+
for (const file of files) {
|
|
62
|
+
const meta = readMeta(file)
|
|
63
|
+
if (!meta) continue
|
|
64
|
+
sessions.push({
|
|
65
|
+
file,
|
|
66
|
+
id: meta.id,
|
|
67
|
+
cwd: meta.cwd || '',
|
|
68
|
+
title: meta.cwd ? meta.cwd.split('/').filter(Boolean).pop() || meta.cwd : meta.id,
|
|
69
|
+
updatedAt: meta.mtimeMs,
|
|
70
|
+
createdAt: meta.timestamp ? Date.parse(meta.timestamp) : meta.mtimeMs,
|
|
71
|
+
originator: meta.originator || '',
|
|
72
|
+
})
|
|
73
|
+
}
|
|
74
|
+
sessions.sort((a, b) => b.updatedAt - a.updatedAt)
|
|
75
|
+
return sessions.slice(0, limit)
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function readdirSafe(dir) {
|
|
79
|
+
try { return fs.readdirSync(dir) } catch { return [] }
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
/** Read only the first line (session_meta) + file mtime — cheap and WAL-free. */
|
|
83
|
+
function readMeta(file) {
|
|
84
|
+
try {
|
|
85
|
+
const fd = fs.openSync(file, 'r')
|
|
86
|
+
try {
|
|
87
|
+
const buf = Buffer.alloc(65536)
|
|
88
|
+
const n = fs.readSync(fd, buf, 0, buf.length, 0)
|
|
89
|
+
const nl = buf.indexOf(0x0a, 0, n)
|
|
90
|
+
const line = buf.slice(0, nl > 0 ? nl : n).toString('utf8')
|
|
91
|
+
const rec = JSON.parse(line)
|
|
92
|
+
if (rec.type !== 'session_meta') return null
|
|
93
|
+
const p = rec.payload || {}
|
|
94
|
+
if (!p.id) return null
|
|
95
|
+
return { ...p, mtimeMs: fs.fstatSync(fd).mtimeMs }
|
|
96
|
+
} finally { fs.closeSync(fd) }
|
|
97
|
+
} catch { return null }
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/** Hub-shaped list rows for the miniprogram (mapSession-compatible). */
|
|
101
|
+
function sessionRows(liveCapsByRawId) {
|
|
102
|
+
return listSessions().map(s => {
|
|
103
|
+
const live = liveCapsByRawId && liveCapsByRawId[s.id]
|
|
104
|
+
return {
|
|
105
|
+
id: sessionId(s.id),
|
|
106
|
+
active: !!live && !!live.active,
|
|
107
|
+
thinking: !!live && !!live.active,
|
|
108
|
+
updatedAt: Math.round(s.updatedAt),
|
|
109
|
+
pendingRequestsCount: live ? live.pendingCount : 0,
|
|
110
|
+
metadata: {
|
|
111
|
+
name: s.title,
|
|
112
|
+
path: s.cwd,
|
|
113
|
+
provider: PROVIDER,
|
|
114
|
+
},
|
|
115
|
+
capabilities: live ? live.caps : READONLY_CAPS,
|
|
116
|
+
}
|
|
117
|
+
})
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
// ── Message normalization ──
|
|
121
|
+
|
|
122
|
+
/**
|
|
123
|
+
* Parse one rollout file into hub-shaped messages (oldest first).
|
|
124
|
+
* Envelope mirrors the hub: { id, createdAt, invokedAt, status, content:{role, content:{type:'output',data}} }
|
|
125
|
+
*/
|
|
126
|
+
function readMessages(sessionIdStr) {
|
|
127
|
+
if (!isCodexSession(sessionIdStr)) return null
|
|
128
|
+
const id = rawId(sessionIdStr)
|
|
129
|
+
const file = findRolloutFile(id)
|
|
130
|
+
if (!file) return { messages: [], page: { hasMore: false, nextBeforeSeq: null } }
|
|
131
|
+
|
|
132
|
+
const lines = fs.readFileSync(file, 'utf8').split('\n')
|
|
133
|
+
const messages = []
|
|
134
|
+
let seq = 0
|
|
135
|
+
|
|
136
|
+
// Accumulator: consecutive agent-ish items merge into one agent message;
|
|
137
|
+
// tool outputs become one user-role message (parser updates tool blocks).
|
|
138
|
+
let agentBlocks = null
|
|
139
|
+
let agentAt = null
|
|
140
|
+
let resultBlocks = null
|
|
141
|
+
let resultAt = null
|
|
142
|
+
|
|
143
|
+
const flushAgent = () => {
|
|
144
|
+
if (agentBlocks && agentBlocks.length) {
|
|
145
|
+
messages.push(envelope(`m${seq++}`, agentAt, 'agent', agentBlocks))
|
|
146
|
+
}
|
|
147
|
+
agentBlocks = null
|
|
148
|
+
}
|
|
149
|
+
const flushResults = () => {
|
|
150
|
+
if (resultBlocks && resultBlocks.length) {
|
|
151
|
+
messages.push(envelope(`m${seq++}`, resultAt, 'user', resultBlocks))
|
|
152
|
+
}
|
|
153
|
+
resultBlocks = null
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
for (const line of lines) {
|
|
157
|
+
if (!line) continue
|
|
158
|
+
let rec
|
|
159
|
+
try { rec = JSON.parse(line) } catch { continue }
|
|
160
|
+
if (rec.type !== 'response_item') continue
|
|
161
|
+
const item = rec.payload
|
|
162
|
+
if (!item || typeof item !== 'object') continue
|
|
163
|
+
const at = rec.timestamp ? Date.parse(rec.timestamp) : undefined
|
|
164
|
+
|
|
165
|
+
switch (item.type) {
|
|
166
|
+
case 'message': {
|
|
167
|
+
const role = item.role
|
|
168
|
+
const texts = (item.content || [])
|
|
169
|
+
.filter(c => c && typeof c.text === 'string')
|
|
170
|
+
.map(c => c.text)
|
|
171
|
+
.join('\n')
|
|
172
|
+
if (!texts) break
|
|
173
|
+
if (role === 'user') {
|
|
174
|
+
flushAgent(); flushResults()
|
|
175
|
+
// Skip codex-injected environment context — display noise on the phone
|
|
176
|
+
if (texts.startsWith('<environment_context>')) break
|
|
177
|
+
messages.push(envelope(`m${seq++}`, at, 'user', [{ type: 'text', text: texts }]))
|
|
178
|
+
} else if (role === 'assistant') {
|
|
179
|
+
flushResults()
|
|
180
|
+
if (!agentBlocks) { agentBlocks = []; agentAt = at }
|
|
181
|
+
agentBlocks.push({ type: 'text', text: texts })
|
|
182
|
+
}
|
|
183
|
+
// developer/system messages are not shown
|
|
184
|
+
break
|
|
185
|
+
}
|
|
186
|
+
case 'reasoning': {
|
|
187
|
+
const text = (item.summary || [])
|
|
188
|
+
.filter(s => s && typeof s.text === 'string')
|
|
189
|
+
.map(s => s.text).join('\n')
|
|
190
|
+
// encrypted_content is opaque; empty summary → nothing to display
|
|
191
|
+
if (text) {
|
|
192
|
+
if (!agentBlocks) { agentBlocks = []; agentAt = at }
|
|
193
|
+
agentBlocks.push({ type: 'thinking', text })
|
|
194
|
+
}
|
|
195
|
+
break
|
|
196
|
+
}
|
|
197
|
+
case 'custom_tool_call':
|
|
198
|
+
case 'function_call': {
|
|
199
|
+
flushResults()
|
|
200
|
+
if (!agentBlocks) { agentBlocks = []; agentAt = at }
|
|
201
|
+
agentBlocks.push(toToolUse(item))
|
|
202
|
+
break
|
|
203
|
+
}
|
|
204
|
+
case 'custom_tool_call_output':
|
|
205
|
+
case 'function_call_output': {
|
|
206
|
+
flushAgent()
|
|
207
|
+
if (!resultBlocks) { resultBlocks = []; resultAt = at }
|
|
208
|
+
resultBlocks.push(toToolResult(item))
|
|
209
|
+
break
|
|
210
|
+
}
|
|
211
|
+
default:
|
|
212
|
+
break
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
flushAgent(); flushResults()
|
|
216
|
+
|
|
217
|
+
// Newest-last; hub pagination fields (page) — rollouts are small, return all
|
|
218
|
+
return { messages, page: { hasMore: false, nextBeforeSeq: null } }
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
function envelope(id, createdAt, role, blocks) {
|
|
222
|
+
const data = role === 'user'
|
|
223
|
+
? { type: 'user', message: { content: blocks } }
|
|
224
|
+
: { type: 'assistant', message: { content: blocks } }
|
|
225
|
+
return {
|
|
226
|
+
id,
|
|
227
|
+
createdAt: createdAt || Date.now(),
|
|
228
|
+
invokedAt: createdAt || null,
|
|
229
|
+
status: 'completed',
|
|
230
|
+
content: { role, content: { type: 'output', data } },
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
function toToolUse(item) {
|
|
235
|
+
const name = item.name || 'tool'
|
|
236
|
+
let input = {}
|
|
237
|
+
if (item.type === 'function_call') {
|
|
238
|
+
try { input = JSON.parse(item.arguments || '{}') } catch { input = { command: item.arguments } }
|
|
239
|
+
} else {
|
|
240
|
+
// custom_tool_call: input is a raw string (often a JS-style expression) —
|
|
241
|
+
// show it verbatim as the command summary
|
|
242
|
+
input = { command: typeof item.input === 'string' ? item.input : JSON.stringify(item.input) }
|
|
243
|
+
}
|
|
244
|
+
return { type: 'tool_use', id: item.call_id || item.id || undefined, name, input }
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
function toToolResult(item) {
|
|
248
|
+
let text = ''
|
|
249
|
+
const out = item.output
|
|
250
|
+
if (typeof out === 'string') text = out
|
|
251
|
+
else if (Array.isArray(out)) {
|
|
252
|
+
text = out.map(c => (c && typeof c.text === 'string') ? c.text : '').join('\n')
|
|
253
|
+
} else if (out && typeof out === 'object') text = JSON.stringify(out)
|
|
254
|
+
return { type: 'tool_result', tool_use_id: item.call_id, content: text, is_error: false }
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
function findRolloutFile(id) {
|
|
258
|
+
// Sessions are nested by date; matching by filename suffix avoids a full walk
|
|
259
|
+
// when possible: rollout-<timestamp>-<id>.jsonl
|
|
260
|
+
const years = readdirSafe(SESSIONS_DIR)
|
|
261
|
+
for (const y of years) {
|
|
262
|
+
for (const m of readdirSafe(path.join(SESSIONS_DIR, y))) {
|
|
263
|
+
for (const d of readdirSafe(path.join(SESSIONS_DIR, y, m))) {
|
|
264
|
+
const dirPath = path.join(SESSIONS_DIR, y, m, d)
|
|
265
|
+
for (const f of readdirSafe(dirPath)) {
|
|
266
|
+
if (f.endsWith('-' + id + '.jsonl')) return path.join(dirPath, f)
|
|
267
|
+
}
|
|
268
|
+
}
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
return null
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
/** Session detail (hub shape) — read-only unless the live adapter enriches it. */
|
|
275
|
+
function sessionDetail(sessionIdStr, live) {
|
|
276
|
+
if (!isCodexSession(sessionIdStr)) return null
|
|
277
|
+
const id = rawId(sessionIdStr)
|
|
278
|
+
const file = findRolloutFile(id)
|
|
279
|
+
const meta = file ? readMeta(file) : null
|
|
280
|
+
const requests = live && live.pending ? live.pending : {}
|
|
281
|
+
return {
|
|
282
|
+
session: {
|
|
283
|
+
id: sessionIdStr,
|
|
284
|
+
active: !!(live && live.active),
|
|
285
|
+
thinking: !!(live && live.active),
|
|
286
|
+
updatedAt: live && live.updatedAt ? live.updatedAt : (meta ? Math.round(meta.mtimeMs) : Date.now()),
|
|
287
|
+
metadata: {
|
|
288
|
+
name: meta && meta.cwd ? meta.cwd.split('/').filter(Boolean).pop() : id,
|
|
289
|
+
path: meta ? meta.cwd : '',
|
|
290
|
+
provider: PROVIDER,
|
|
291
|
+
},
|
|
292
|
+
capabilities: live ? live.caps : READONLY_CAPS,
|
|
293
|
+
agentState: {
|
|
294
|
+
requests,
|
|
295
|
+
controlledByUser: false,
|
|
296
|
+
},
|
|
297
|
+
},
|
|
298
|
+
}
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
module.exports = {
|
|
302
|
+
isCodexSession,
|
|
303
|
+
sessionId,
|
|
304
|
+
rawId,
|
|
305
|
+
listSessions,
|
|
306
|
+
sessionRows,
|
|
307
|
+
readMessages,
|
|
308
|
+
sessionDetail,
|
|
309
|
+
READONLY_CAPS,
|
|
310
|
+
CODEX_HOME,
|
|
311
|
+
}
|
|
@@ -0,0 +1,169 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent router — single interception surface between the relay pipe and the
|
|
3
|
+
* hub binary. Session IDs are namespaced: 'codex:<threadId>' / 'zcode:<taskId>'.
|
|
4
|
+
* Anything without a known prefix falls through to the hub (claude) unchanged.
|
|
5
|
+
*
|
|
6
|
+
* Rendering paths (list/detail/messages) read local files (verified formats);
|
|
7
|
+
* control paths (send/stop/approve) go through codexLive and require the
|
|
8
|
+
* codex CLI on the machine — honest errors otherwise.
|
|
9
|
+
*/
|
|
10
|
+
const rollout = require('./codexRollout')
|
|
11
|
+
const live = require('./codexLive')
|
|
12
|
+
const zcode = require('./zcodeIndex')
|
|
13
|
+
const zcodeLive = require('./zcodeLive')
|
|
14
|
+
const zcodeEngine = require('./zcodeEngine')
|
|
15
|
+
const registry = require('./registry')
|
|
16
|
+
|
|
17
|
+
function ok(data) { return { status: 200, data } }
|
|
18
|
+
function err(status, message) { return { status, data: { error: message } } }
|
|
19
|
+
|
|
20
|
+
function providers() {
|
|
21
|
+
return registry.listProviders()
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
/** Agent-side session rows (codex + zcode) for merging into GET /api/sessions. */
|
|
25
|
+
function agentSessions() {
|
|
26
|
+
const discovered = live.discoveredCaps() // null without codex CLI
|
|
27
|
+
const rows = rollout.sessionRows(_liveMapWithDiscovered(discovered))
|
|
28
|
+
const zRows = zcode.listSessions().map(r => ({
|
|
29
|
+
...r,
|
|
30
|
+
// 发送能力取决于 ws2 中继是否已连接(连接会占用官方手机端位)
|
|
31
|
+
capabilities: zcodeLive.isReady() ? zcodeLive.LIVE_CAPS : { ...zcode.READONLY_CAPS, resume: true, share: true },
|
|
32
|
+
}))
|
|
33
|
+
return rows.concat(zRows)
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function _liveMapWithDiscovered(discoveredCaps) {
|
|
37
|
+
const map = live.liveInfoMap() || {}
|
|
38
|
+
if (discoveredCaps) {
|
|
39
|
+
// With the CLI installed, discovered (non-live) codex sessions become
|
|
40
|
+
// resumable-by-sending; live sessions keep LIVE_CAPS via liveInfo.
|
|
41
|
+
for (const row of rollout.listSessions()) {
|
|
42
|
+
if (!map[row.id]) map[row.id] = { active: false, pendingCount: 0, caps: discoveredCaps, updatedAt: row.updatedAt }
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
return map
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
function mergeSessionLists(hubData) {
|
|
49
|
+
const hubSessions = (hubData && Array.isArray(hubData.sessions)) ? hubData.sessions : []
|
|
50
|
+
const merged = hubSessions.concat(agentSessions())
|
|
51
|
+
merged.sort((a, b) => (b.updatedAt || 0) - (a.updatedAt || 0))
|
|
52
|
+
return { ...hubData, sessions: merged }
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function _codexDetail(sessionId) {
|
|
56
|
+
const info = live.liveInfo(String(sessionId).slice('codex:'.length))
|
|
57
|
+
const pending = live.pendingRequests(sessionId)
|
|
58
|
+
const caps = info ? info.caps : (live.discoveredCaps() || rollout.READONLY_CAPS)
|
|
59
|
+
const detail = rollout.sessionDetail(sessionId, {
|
|
60
|
+
active: info ? info.active : false,
|
|
61
|
+
pending,
|
|
62
|
+
caps,
|
|
63
|
+
updatedAt: info ? info.updatedAt : undefined,
|
|
64
|
+
})
|
|
65
|
+
return detail
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
function zcodeDetail(sessionId) {
|
|
69
|
+
const detail = zcode.sessionDetail(sessionId)
|
|
70
|
+
if (detail.session) {
|
|
71
|
+
detail.session.capabilities = zcodeLive.isReady() ? zcodeLive.LIVE_CAPS : { ...zcode.READONLY_CAPS, resume: true, share: true }
|
|
72
|
+
}
|
|
73
|
+
return detail
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Handle an agent-namespaced REST call. Returns {status, data} or null when
|
|
78
|
+
* the path belongs to the hub. `p` is the request path without query string.
|
|
79
|
+
*/
|
|
80
|
+
function handleRest(method, p, body) {
|
|
81
|
+
if (p === '/api/providers') {
|
|
82
|
+
if (method !== 'GET') return err(405, 'method not allowed')
|
|
83
|
+
return ok(providers())
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
const m = /^\/api\/sessions\/([^/]+)(\/.*)?$/.exec(p)
|
|
87
|
+
if (!m) return null
|
|
88
|
+
const id = decodeURIComponent(m[1])
|
|
89
|
+
const action = (m[2] || '').replace(/^\//, '').split('?')[0]
|
|
90
|
+
|
|
91
|
+
if (rollout.isCodexSession(id)) {
|
|
92
|
+
switch (action) {
|
|
93
|
+
case '': return method === 'GET' ? ok(_codexDetail(id)) : err(405, 'method not allowed')
|
|
94
|
+
case 'messages':
|
|
95
|
+
if (method === 'GET') return ok(rollout.readMessages(id))
|
|
96
|
+
if (method === 'POST') {
|
|
97
|
+
const text = body && body.text
|
|
98
|
+
if (!text || typeof text !== 'string') return err(400, 'text is required')
|
|
99
|
+
return live.sendMessage(id, text)
|
|
100
|
+
.then(() => ok({ ok: true }))
|
|
101
|
+
.catch(e => err(502, e.message))
|
|
102
|
+
}
|
|
103
|
+
return err(405, 'method not allowed')
|
|
104
|
+
case 'abort':
|
|
105
|
+
return live.stop(id)
|
|
106
|
+
.then(r => ok(r))
|
|
107
|
+
.catch(e => err(502, e.message))
|
|
108
|
+
case 'archive':
|
|
109
|
+
return err(400, 'Codex 会话保存在 ~/.codex,暂不支持归档')
|
|
110
|
+
default:
|
|
111
|
+
break
|
|
112
|
+
}
|
|
113
|
+
const perm = /^permissions\/([^/]+)\/(approve|deny)$/.exec(action)
|
|
114
|
+
if (perm) {
|
|
115
|
+
const decision = perm[2] === 'approve' ? 'approved' : 'denied'
|
|
116
|
+
return live.approve(id, perm[1], decision)
|
|
117
|
+
.then(() => ok({ ok: true }))
|
|
118
|
+
.catch(e => err(502, e.message))
|
|
119
|
+
}
|
|
120
|
+
const unsupported = ['permission-mode', 'upload', 'file', 'resume', 'compact']
|
|
121
|
+
if (unsupported.includes(action)) {
|
|
122
|
+
return err(400, `Codex 会话暂不支持该操作: ${action}`)
|
|
123
|
+
}
|
|
124
|
+
return err(404, 'not found')
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
if (zcode.isZcodeSession(id)) {
|
|
128
|
+
switch (action) {
|
|
129
|
+
case '': return method === 'GET' ? ok(zcodeDetail(id)) : err(405, 'method not allowed')
|
|
130
|
+
case 'messages':
|
|
131
|
+
if (method === 'GET') {
|
|
132
|
+
// 历史经引擎读取(与桌面会话互通);引擎不可用时回落到只读提示
|
|
133
|
+
return zcodeEngine.readMessages(id)
|
|
134
|
+
.then(r => ok(r))
|
|
135
|
+
.catch(e => ok(zcode.readMessages(id)))
|
|
136
|
+
}
|
|
137
|
+
if (method === 'POST') {
|
|
138
|
+
const text = body && body.text
|
|
139
|
+
if (!text || typeof text !== 'string') return err(400, 'text is required')
|
|
140
|
+
return zcodeLive.sendMessage(id, text)
|
|
141
|
+
.then(r => ok(r))
|
|
142
|
+
.catch(e => err(502, e.message))
|
|
143
|
+
}
|
|
144
|
+
return err(405, 'method not allowed')
|
|
145
|
+
default:
|
|
146
|
+
return err(400, '该操作暂不支持 ZCode 会话(引擎读 + 中继发之外的能力开发中)')
|
|
147
|
+
}
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
return null // hub session — caller proxies unchanged
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** spawn-session routing; returns a promise of {sessionId} or throws. */
|
|
154
|
+
function spawn(provider, dir) {
|
|
155
|
+
if (provider === 'codex') return live.spawnSession(dir)
|
|
156
|
+
throw new Error(`agent ${provider} 暂不支持从手机创建会话`)
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
/** Wire the live adapter's change notifications into the SSE broadcast. */
|
|
160
|
+
function onSessionEvent(cb) { live.onSessionEvent(cb) }
|
|
161
|
+
|
|
162
|
+
module.exports = {
|
|
163
|
+
providers,
|
|
164
|
+
agentSessions,
|
|
165
|
+
mergeSessionLists,
|
|
166
|
+
handleRest,
|
|
167
|
+
spawn,
|
|
168
|
+
onSessionEvent,
|
|
169
|
+
}
|
|
@@ -0,0 +1,113 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Agent registry — connector-side provider detection & /api/providers shape.
|
|
3
|
+
*
|
|
4
|
+
* The hub binary owns claude sessions; this registry reports what the
|
|
5
|
+
* connector itself can serve (codex/zcode/dsh) plus the hub-backed claude.
|
|
6
|
+
* Detection is presence-based and cached; nothing here starts processes.
|
|
7
|
+
*/
|
|
8
|
+
const { execSync } = require('child_process')
|
|
9
|
+
const fs = require('fs')
|
|
10
|
+
const os = require('os')
|
|
11
|
+
const path = require('path')
|
|
12
|
+
|
|
13
|
+
const CODEX_HOME = process.env.CODEX_HOME || path.join(os.homedir(), '.codex')
|
|
14
|
+
const ZCODE_HOME = path.join(os.homedir(), '.zcode')
|
|
15
|
+
const DSH_HOME = process.env.DSH_HOME || path.join(os.homedir(), '.dsh')
|
|
16
|
+
|
|
17
|
+
let _codexBinCache = null
|
|
18
|
+
let _codexBinChecked = 0
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Locate the codex CLI binary. Cached for 10 minutes. Precedence:
|
|
22
|
+
* env override → PATH → common install locations. Returns path or null.
|
|
23
|
+
*/
|
|
24
|
+
function findCodexBin() {
|
|
25
|
+
const now = Date.now()
|
|
26
|
+
if (_codexBinCache !== null && now - _codexBinChecked < 10 * 60 * 1000) return _codexBinCache
|
|
27
|
+
_codexBinChecked = now
|
|
28
|
+
_codexBinCache = _detectCodexBin()
|
|
29
|
+
return _codexBinCache
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
function _detectCodexBin() {
|
|
33
|
+
const candidates = []
|
|
34
|
+
if (process.env.CODEPOCKET_CODEX_BIN) candidates.push(process.env.CODEPOCKET_CODEX_BIN)
|
|
35
|
+
candidates.push('codex')
|
|
36
|
+
const home = os.homedir()
|
|
37
|
+
candidates.push(
|
|
38
|
+
path.join(home, '.local', 'bin', 'codex'),
|
|
39
|
+
path.join(home, '.npm-global', 'bin', 'codex'),
|
|
40
|
+
'/opt/homebrew/bin/codex',
|
|
41
|
+
'/usr/local/bin/codex',
|
|
42
|
+
)
|
|
43
|
+
for (const cand of candidates) {
|
|
44
|
+
if (cand === 'codex') {
|
|
45
|
+
try {
|
|
46
|
+
const out = execSync('command -v codex', { stdio: ['ignore', 'pipe', 'ignore'], timeout: 3000 }).toString().trim()
|
|
47
|
+
if (out) return out
|
|
48
|
+
} catch {}
|
|
49
|
+
continue
|
|
50
|
+
}
|
|
51
|
+
try { if (fs.existsSync(cand)) return cand } catch {}
|
|
52
|
+
}
|
|
53
|
+
return null
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function codexHomeExists() {
|
|
57
|
+
try { return fs.statSync(path.join(CODEX_HOME, 'sessions')).isDirectory() } catch { return false }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function zcodeIndexExists() {
|
|
61
|
+
try { return fs.statSync(path.join(ZCODE_HOME, 'v2', 'tasks-index.sqlite')).isFile() } catch { return false }
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function dshHomeExists() {
|
|
65
|
+
try { return fs.statSync(DSH_HOME).isDirectory() } catch { return false }
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* /api/providers payload — consumed by the miniprogram's normalizeProviders.
|
|
70
|
+
* Semantics:
|
|
71
|
+
* spawn:true — new sessions can be created from the phone
|
|
72
|
+
* reason — human-readable why-not string for non-spawn/disabled agents
|
|
73
|
+
*/
|
|
74
|
+
function listProviders() {
|
|
75
|
+
const codexBin = findCodexBin()
|
|
76
|
+
const codexData = codexHomeExists()
|
|
77
|
+
const zcodeData = zcodeIndexExists()
|
|
78
|
+
const dshData = dshHomeExists()
|
|
79
|
+
const providers = []
|
|
80
|
+
|
|
81
|
+
providers.push({ key: 'claude', label: 'Claude', spawn: true, cwdRequired: true, available: true })
|
|
82
|
+
|
|
83
|
+
providers.push({
|
|
84
|
+
key: 'codex', label: 'Codex',
|
|
85
|
+
spawn: !!codexBin, cwdRequired: true, available: !!codexBin || codexData,
|
|
86
|
+
reason: codexBin ? '' : (codexData
|
|
87
|
+
? '检测到 Codex 会话记录(只读)。安装 codex CLI 后可发消息: npm i -g @openai/codex'
|
|
88
|
+
: '未检测到 codex CLI(npm i -g @openai/codex)'),
|
|
89
|
+
})
|
|
90
|
+
|
|
91
|
+
providers.push({
|
|
92
|
+
key: 'zcode', label: 'GLM', spawn: false, cwdRequired: false, available: zcodeData,
|
|
93
|
+
reason: zcodeData
|
|
94
|
+
? 'ZCode 会话:可查看历史并发送消息(需要 ZCode 桌面端在线并开启手机远控)'
|
|
95
|
+
: '未检测到 ZCode 桌面端',
|
|
96
|
+
})
|
|
97
|
+
|
|
98
|
+
providers.push({
|
|
99
|
+
key: 'dsh', label: 'DSH', spawn: false, cwdRequired: false, available: dshData,
|
|
100
|
+
reason: dshData
|
|
101
|
+
? 'DeepSeek Harness 接入插件开发中'
|
|
102
|
+
: '未检测到 DeepSeek Harness(~/.dsh)',
|
|
103
|
+
})
|
|
104
|
+
|
|
105
|
+
return { providers }
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
module.exports = {
|
|
109
|
+
findCodexBin,
|
|
110
|
+
listProviders,
|
|
111
|
+
CODEX_HOME,
|
|
112
|
+
ZCODE_HOME,
|
|
113
|
+
}
|