@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 CHANGED
@@ -18,6 +18,13 @@ const crypto = require('crypto')
18
18
  const nacl = require('tweetnacl')
19
19
  const { HttpsProxyAgent } = require('https-proxy-agent')
20
20
  const { startMcpServer, handlePhoneActionResponse: onPhoneActionResponse } = require('../src/mcp-server')
21
+ const agents = require('../src/agents')
22
+
23
+ // Agent (codex/zcode) state changes surface as SSE events so the phone
24
+ // refreshes — sendToRelay fans out one encrypted copy per paired device.
25
+ agents.onSessionEvent(() => {
26
+ sendToRelay({ type: 'sse-event', event: { type: 'session-updated' } })
27
+ })
21
28
 
22
29
  // ── Proxy detection ──
23
30
 
@@ -768,8 +775,8 @@ function connectRelay() {
768
775
  break
769
776
  }
770
777
  case 'spawn-session': {
771
- log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}`)
772
- handleSpawnSession(msg.requestId, msg.directory)
778
+ log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}, provider=${msg.provider || 'claude'}`)
779
+ handleSpawnSession(msg.requestId, msg.directory, msg.provider)
773
780
  break
774
781
  }
775
782
  case 'resume-session': {
@@ -860,6 +867,40 @@ async function forwardToHub(requestId, method, p, body) {
860
867
  sendToRelay({ type: 'rest-response', requestId, status: 403, data: { error: 'Forbidden path' } }, peer)
861
868
  return
862
869
  }
870
+
871
+ // ── Agent routes: provider registry, codex/zcode namespaced sessions ──
872
+ // These are served by the connector itself (local files + codex app-server)
873
+ // and never reach the hub binary.
874
+ const pathOnly = p.split('?')[0]
875
+ try {
876
+ if (method === 'GET' && pathOnly === '/api/sessions') {
877
+ // Merge hub (claude) + agent sessions; agent sessions stay readable
878
+ // even when the hub is unreachable.
879
+ let hubData = {}
880
+ try {
881
+ let res = await doForwardToHub(requestId, method, p, body)
882
+ if (res.status === 401) {
883
+ try {
884
+ const token = await findHubToken()
885
+ jwt = await authenticateHub(token)
886
+ res = await doForwardToHub(requestId, method, p, body)
887
+ } catch {}
888
+ }
889
+ hubData = await res.json().catch(() => ({}))
890
+ } catch {}
891
+ sendToRelay({ type: 'rest-response', requestId, status: 200, data: agents.mergeSessionLists(hubData) }, peer)
892
+ return
893
+ }
894
+ const agentRes = await agents.handleRest(method, pathOnly, body)
895
+ if (agentRes) {
896
+ sendToRelay({ type: 'rest-response', requestId, status: agentRes.status, data: agentRes.data }, peer)
897
+ return
898
+ }
899
+ } catch (agentErr) {
900
+ sendToRelay({ type: 'rest-response', requestId, status: 500, data: { error: agentErr.message } }, peer)
901
+ return
902
+ }
903
+
863
904
  try {
864
905
  let res = await doForwardToHub(requestId, method, p, body)
865
906
  if (res.status === 401) {
@@ -890,27 +931,28 @@ async function handleAuthRequest(requestId, accessToken) {
890
931
  }
891
932
  }
892
933
 
893
- async function handleSpawnSession(requestId, directory) {
934
+ async function handleSpawnSession(requestId, directory, provider) {
894
935
  log(`[DEBUG:spawn] === START spawn-session ===`)
895
- log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}`)
936
+ log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}, provider=${provider || 'claude'}`)
896
937
  log(`[DEBUG:spawn] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
897
938
 
898
- if (!hubBin) {
899
- log(`[DEBUG:spawn] FAIL: hubBin is null`)
900
- sendSpawnResult(requestId, null, 'Hub binary not found')
939
+ // Agent selection: 'claude' (default, omit-safe for older miniprogram
940
+ // versions) or a connector-side agent backend.
941
+ const agentKey = (typeof provider === 'string' && provider) ? provider : 'claude'
942
+ if (!['claude', 'codex'].includes(agentKey)) {
943
+ sendSpawnResult(requestId, null, `${agentKey} 会话不能从手机创建(在对应客户端内新建)`)
901
944
  return
902
945
  }
946
+
903
947
  if (!directory || typeof directory !== 'string') {
904
948
  log(`[DEBUG:spawn] FAIL: directory invalid`)
905
949
  sendSpawnResult(requestId, null, 'Directory is required')
906
950
  return
907
951
  }
908
952
 
909
- // Expand ~ to home directory
953
+ // Expand ~ and enforce the same home-only boundary for every agent
910
954
  directory = directory.replace(/^~/, os.homedir())
911
955
  const absDir = path.resolve(directory)
912
-
913
- // Only allow spawning in home directory
914
956
  const home = os.homedir()
915
957
  if (!absDir.startsWith(home)) {
916
958
  log(`[DEBUG:spawn] FAIL: directory outside home: ${absDir}`)
@@ -923,6 +965,23 @@ async function handleSpawnSession(requestId, directory) {
923
965
  return
924
966
  }
925
967
 
968
+ // Codex: connector-side adapter (codex app-server) — no hub involved
969
+ if (agentKey === 'codex') {
970
+ try {
971
+ const sessionId = await agents.spawn('codex', absDir)
972
+ sendSpawnResult(requestId, sessionId)
973
+ } catch (e) {
974
+ sendSpawnResult(requestId, null, e.message || 'Codex 会话启动失败')
975
+ }
976
+ return
977
+ }
978
+
979
+ if (!hubBin) {
980
+ log(`[DEBUG:spawn] FAIL: hubBin is null`)
981
+ sendSpawnResult(requestId, null, 'Hub binary not found')
982
+ return
983
+ }
984
+
926
985
  log(`[DEBUG:spawn] Expanded directory: ${absDir}`)
927
986
 
928
987
  try {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.6.11",
3
+ "version": "2.7.0",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",
@@ -20,10 +20,10 @@
20
20
  "ws": "^8.18.0"
21
21
  },
22
22
  "optionalDependencies": {
23
- "@tina_summer/codepocket-darwin-arm64": "2.6.11",
24
- "@tina_summer/codepocket-darwin-x64": "2.6.11",
25
- "@tina_summer/codepocket-linux-x64": "2.6.11",
26
- "@tina_summer/codepocket-win32-x64": "2.6.11"
23
+ "@tina_summer/codepocket-darwin-arm64": "2.7.0",
24
+ "@tina_summer/codepocket-darwin-x64": "2.7.0",
25
+ "@tina_summer/codepocket-linux-x64": "2.7.0",
26
+ "@tina_summer/codepocket-win32-x64": "2.7.0"
27
27
  },
28
28
  "engines": {
29
29
  "node": ">=18"
@@ -0,0 +1,362 @@
1
+ /**
2
+ * Codex live control via `codex app-server` (JSON-RPC 2.0 over stdio).
3
+ *
4
+ * One child process per active session, mirroring the hub's per-session claude
5
+ * process model. Message RENDERING never goes through this module — the
6
+ * miniprogram reads rollout files (verified format) via codexRollout; this
7
+ * module is control-plane only: spawn/resume, turn/start, turn/interrupt and
8
+ * approval decisions.
9
+ *
10
+ * Protocol method names follow the codex app-server surface as implemented by
11
+ * the cankao reference (initialize / thread/start / thread/resume / thread/read /
12
+ * turn/start / turn/interrupt; approvals arrive as server→client requests and
13
+ * are answered with client.respond(id, {decision})). Requires a codex CLI on
14
+ * the machine — without it every entry point fails with an install hint.
15
+ */
16
+ const { spawn } = require('child_process')
17
+ const crypto = require('crypto')
18
+
19
+ const { findCodexBin } = require('./registry')
20
+
21
+ const LIVE_CAPS = {
22
+ send: true, stop: true, resume: true, approve: true, question: false,
23
+ attachments: false, permissionMode: false, queue: false, compact: false,
24
+ share: true, spawn: false,
25
+ }
26
+
27
+ const INIT_TIMEOUT = 20000
28
+ const RPC_TIMEOUT = 30000
29
+ const POLL_INTERVAL = 1500
30
+
31
+ // sessionId('codex:<raw>') → live state
32
+ const live = new Map()
33
+ // nativeRequestId → { sessionId, kind, tool, arguments }
34
+ const pending = new Map()
35
+
36
+ let notify = () => {} // wired by connector: broadcast SSE session-updated
37
+ function onSessionEvent(cb) { notify = cb }
38
+
39
+ function state(rawId) {
40
+ if (!live.has(rawId)) {
41
+ live.set(rawId, {
42
+ proc: null, nextId: 1, callbacks: new Map(),
43
+ threadId: null, turnId: null, cwd: '', active: false, updatedAt: Date.now(),
44
+ pendingCount: 0, poller: null, starting: null,
45
+ })
46
+ }
47
+ return live.get(rawId)
48
+ }
49
+
50
+ // ── JSON-RPC stdio transport ──
51
+
52
+ function rpc(st, method, params, timeout = RPC_TIMEOUT) {
53
+ return new Promise((resolve, reject) => {
54
+ if (!st.proc || st.proc.exitCode !== null) return reject(new Error('Codex app-server 已退出'))
55
+ const id = st.nextId++
56
+ const timer = setTimeout(() => {
57
+ st.callbacks.delete(id)
58
+ reject(new Error('Codex 请求超时'))
59
+ }, timeout)
60
+ st.callbacks.set(id, { resolve: (v) => { clearTimeout(timer); resolve(v) },
61
+ reject: (e) => { clearTimeout(timer); reject(e) } })
62
+ write(st, { id, method, params: params || {} })
63
+ })
64
+ }
65
+
66
+ function write(st, msg) {
67
+ try { st.proc.stdin.write(JSON.stringify(msg) + '\n') }
68
+ catch (e) { throw new Error('Codex app-server 连接已断开') }
69
+ }
70
+
71
+ function respond(st, requestId, result) {
72
+ write(st, { id: requestId, result })
73
+ }
74
+
75
+ function startServer(st) {
76
+ return new Promise((resolve, reject) => {
77
+ const bin = findCodexBin()
78
+ if (!bin) return reject(new Error('未找到 codex CLI,请先安装: npm i -g @openai/codex'))
79
+ const proc = spawn(bin, ['app-server'], {
80
+ stdio: ['pipe', 'pipe', 'ignore'],
81
+ env: { ...process.env },
82
+ })
83
+ st.proc = proc
84
+ let buf = ''
85
+ proc.stdout.on('data', (chunk) => {
86
+ buf += chunk.toString('utf8')
87
+ let nl
88
+ while ((nl = buf.indexOf('\n')) >= 0) {
89
+ const line = buf.slice(0, nl).trim()
90
+ buf = buf.slice(nl + 1)
91
+ if (!line) continue
92
+ let msg
93
+ try { msg = JSON.parse(line) } catch { continue }
94
+ handleServerMessage(st, msg)
95
+ }
96
+ })
97
+ proc.on('exit', () => {
98
+ for (const cb of st.callbacks.values()) cb.reject(new Error('Codex app-server 已退出'))
99
+ st.callbacks.clear()
100
+ st.proc = null
101
+ st.active = false
102
+ st.pendingCount = 0
103
+ if (st.poller) { clearInterval(st.poller); st.poller = null }
104
+ notify()
105
+ })
106
+ proc.on('error', (err) => reject(new Error(`无法启动 codex app-server: ${err.message}`)))
107
+
108
+ rpc(st, 'initialize', {
109
+ clientInfo: { name: 'codepocket', version: '1' },
110
+ capabilities: { experimentalApi: true },
111
+ }, INIT_TIMEOUT)
112
+ .then((info) => {
113
+ write(st, { method: 'initialized', params: {} })
114
+ resolve(info)
115
+ })
116
+ .catch(reject)
117
+ })
118
+ }
119
+
120
+ function handleServerMessage(st, msg) {
121
+ if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
122
+ const cb = st.callbacks.get(msg.id)
123
+ if (cb) {
124
+ st.callbacks.delete(msg.id)
125
+ if (msg.error) cb.reject(new Error(msg.error.message || 'Codex 请求失败'))
126
+ else cb.resolve(msg.result)
127
+ }
128
+ return
129
+ }
130
+ // Server→client request: approvals / user input.
131
+ if (msg.id !== undefined && msg.method) {
132
+ const kind = approvalKind(msg.method)
133
+ if (kind) {
134
+ const p = msg.params || {}
135
+ pending.set(String(msg.id), {
136
+ sessionId: 'codex:' + st.threadId,
137
+ nativeId: msg.id,
138
+ kind,
139
+ tool: kind === 'command' ? 'shell' : (kind === 'file' ? 'apply_patch' : 'permissions'),
140
+ arguments: summarizeRequest(kind, p),
141
+ // Verified enum (cankao + 0.171): accept / decline / cancel (+accept_once)
142
+ availableDecisions: Array.isArray(p.availableDecisions) ? p.availableDecisions : null,
143
+ })
144
+ st.pendingCount = countPending('codex:' + st.threadId)
145
+ st.active = true
146
+ notify()
147
+ } else {
148
+ // Unknown server request — decline explicitly so the turn doesn't hang forever
149
+ try { write(st, { id: msg.id, error: { code: -32601, message: 'codepocket: unsupported request' } }) } catch {}
150
+ }
151
+ return
152
+ }
153
+ // Notifications: thread/status/changed is the authoritative activity signal
154
+ // (verified 0.171: params {threadId, status:{type:'active'|'idle'|...}}).
155
+ if (msg.method === 'thread/status/changed') {
156
+ const p = msg.params || {}
157
+ if (p.threadId && p.threadId === st.threadId) {
158
+ st.active = !!(p.status && p.status.type === 'active')
159
+ st.updatedAt = Date.now()
160
+ notify()
161
+ }
162
+ return
163
+ }
164
+ // Other notifications (item updates etc.) — rendering reads rollout files,
165
+ // only refresh activity state occasionally via the poller
166
+ if (msg.method && st.threadId) {
167
+ st.updatedAt = Date.now()
168
+ }
169
+ }
170
+
171
+ function approvalKind(method) {
172
+ if (typeof method !== 'string') return null
173
+ if (method.includes('commandExecution') && method.includes('requestApproval')) return 'command'
174
+ if (method.includes('fileChange') && method.includes('requestApproval')) return 'file'
175
+ if (method.includes('permissions') && method.includes('requestApproval')) return 'permission'
176
+ return null
177
+ }
178
+
179
+ function summarizeRequest(kind, p) {
180
+ try {
181
+ if (kind === 'command' && typeof (p.command || (p.item && p.item.command)) === 'string') {
182
+ return p.command || p.item.command
183
+ }
184
+ if (kind === 'file' && Array.isArray(p.changes || (p.item && p.item.changes))) {
185
+ const changes = p.changes || p.item.changes
186
+ return changes.map(c => c.path || c.file || '').filter(Boolean).join(', ') || '文件修改'
187
+ }
188
+ return JSON.stringify(p).slice(0, 400)
189
+ } catch { return '' }
190
+ }
191
+
192
+ // ── Status polling (rendering stays on rollout files) ──
193
+
194
+ /**
195
+ * Verified against codex 0.171: thread/read WITHOUT includeTurns returns
196
+ * thread.status = {type: 'active'|'idle'|'notLoaded'|...}. The includeTurns
197
+ * form is deprecated (deprecationNotice) in favor of thread/turns/list.
198
+ */
199
+ async function refresh(st) {
200
+ if (!st.proc || !st.threadId) return
201
+ try {
202
+ const result = await rpc(st, 'thread/read', { threadId: st.threadId }, 10000)
203
+ st.updatedAt = Date.now()
204
+ const type = result && result.thread && result.thread.status && result.thread.status.type
205
+ const isActive = type === 'active'
206
+ if (isActive !== st.active) {
207
+ st.active = isActive
208
+ if (!isActive && st.poller) { clearInterval(st.poller); st.poller = null }
209
+ }
210
+ notify()
211
+ } catch { /* transient read failure — keep last known state */ }
212
+ }
213
+
214
+ function ensurePolling(st) {
215
+ if (st.poller) return
216
+ st.poller = setInterval(() => {
217
+ const s = live.get(st.threadId)
218
+ if (!s || !s.proc) { clearInterval(st.poller); st.poller = null; return }
219
+ refresh(s)
220
+ }, POLL_INTERVAL)
221
+ }
222
+
223
+ // ── Public API (sessionId = 'codex:<threadId>') ──
224
+
225
+ async function spawnSession(dir) {
226
+ // Temp state — keyed in `live` only after thread/start returns the id
227
+ const st = {
228
+ proc: null, nextId: 1, callbacks: new Map(),
229
+ threadId: null, turnId: null, cwd: dir, active: false, updatedAt: Date.now(),
230
+ pendingCount: 0, poller: null,
231
+ }
232
+ await startServer(st)
233
+ const result = await rpc(st, 'thread/start', { cwd: dir })
234
+ // 0.171 shape: { thread: { id, ... }, sessionId, cwd, ... }
235
+ const threadId = result && result.thread && (result.thread.id || result.thread.threadId)
236
+ if (!threadId) throw new Error('Codex thread/start 未返回 threadId')
237
+ st.threadId = threadId
238
+ live.set(threadId, st)
239
+ return 'codex:' + threadId
240
+ }
241
+
242
+ async function ensureLive(sessionId) {
243
+ const threadId = String(sessionId).slice('codex:'.length)
244
+ let st = live.get(threadId)
245
+ if (st && st.proc) return st
246
+ // Cold resume: CLI installed → spawn + thread/resume the same conversation
247
+ st = state(threadId)
248
+ st.threadId = threadId
249
+ await startServer(st)
250
+ await rpc(st, 'thread/resume', { threadId })
251
+ return st
252
+ }
253
+
254
+ async function sendMessage(sessionId, text) {
255
+ const st = await ensureLive(sessionId)
256
+ if (st.active) throw new Error('当前 Codex 任务仍在进行,请先停止或等待完成')
257
+ // Verified 0.171: result = {turn: {id, status: 'inProgress', ...}}
258
+ const result = await rpc(st, 'turn/start', {
259
+ threadId: st.threadId,
260
+ input: [{ type: 'text', text }],
261
+ clientUserMessageId: crypto.randomUUID(),
262
+ })
263
+ st.turnId = (result && result.turn && result.turn.id) || st.turnId || null
264
+ st.active = true
265
+ st.updatedAt = Date.now()
266
+ ensurePolling(st)
267
+ refresh(st)
268
+ return result
269
+ }
270
+
271
+ async function stop(sessionId) {
272
+ const threadId = String(sessionId).slice('codex:'.length)
273
+ const st = live.get(threadId)
274
+ if (!st || !st.proc) throw new Error('该 Codex 会话未在运行')
275
+ let turnId = st.turnId || null
276
+ if (!turnId) {
277
+ // Fallback: newest inProgress turn via the non-deprecated paging call
278
+ try {
279
+ const result = await rpc(st, 'thread/turns/list', { threadId, limit: 20 }, 10000)
280
+ const turns = (result && Array.isArray(result.data)) ? result.data : []
281
+ const activeTurn = turns.find(t => t && t.status === 'inProgress')
282
+ turnId = activeTurn && activeTurn.id
283
+ } catch {}
284
+ }
285
+ if (!turnId) { st.active = false; notify(); return { stopped: false, reason: '没有进行中的任务' } }
286
+ await rpc(st, 'turn/interrupt', { threadId, turnId })
287
+ st.active = false
288
+ refresh(st)
289
+ return { stopped: true }
290
+ }
291
+
292
+ function pendingRequests(sessionId) {
293
+ const out = {}
294
+ for (const [reqId, p] of pending) {
295
+ if (p.sessionId === sessionId) out[reqId] = { tool: p.tool, arguments: p.arguments, kind: p.kind }
296
+ }
297
+ return out
298
+ }
299
+
300
+ function countPending(sessionId) {
301
+ let n = 0
302
+ for (const p of pending.values()) if (p.sessionId === sessionId) n++
303
+ return n
304
+ }
305
+
306
+ async function approve(sessionId, reqId, decision) {
307
+ const p = pending.get(reqId)
308
+ if (!p || p.sessionId !== sessionId) throw new Error('该审批请求已不存在')
309
+ pending.delete(reqId)
310
+ const threadId = String(sessionId).slice('codex:'.length)
311
+ const st = live.get(threadId)
312
+ if (!st || !st.proc) throw new Error('Codex app-server 已断开,无法提交审批')
313
+ // Native enum is accept/decline(/cancel, accept_once). Map the phone's
314
+ // approve/deny onto it, honoring availableDecisions when the server sent it.
315
+ let native
316
+ if (decision === 'denied') native = 'decline'
317
+ else native = 'accept'
318
+ if (p.availableDecisions && p.availableDecisions.length && !p.availableDecisions.includes(native)) {
319
+ const alt = decision === 'denied' ? 'cancel' : 'accept_once'
320
+ if (p.availableDecisions.includes(alt)) native = alt
321
+ }
322
+ respond(st, p.nativeId, { decision: native })
323
+ st.pendingCount = countPending(sessionId)
324
+ notify()
325
+ return { submitted: true, decision: native }
326
+ }
327
+
328
+ /** Live-enrichment for codexRollout.sessionRows/sessionDetail. */
329
+ function liveInfo(rawId) {
330
+ const st = live.get(rawId)
331
+ if (!st) return null
332
+ const sessionId = 'codex:' + rawId
333
+ return { active: st.active, pendingCount: countPending(sessionId), caps: LIVE_CAPS, updatedAt: st.updatedAt }
334
+ }
335
+
336
+ function liveInfoMap() {
337
+ const out = {}
338
+ for (const key of live.keys()) out[key] = liveInfo(key)
339
+ return out
340
+ }
341
+
342
+ function isLiveCapable() { return !!findCodexBin() }
343
+
344
+ /** Caps reported for discovered (non-live) sessions: read-only, or resumable when CLI exists. */
345
+ function discoveredCaps() {
346
+ if (!isLiveCapable()) return null // → codexRollout.READONLY_CAPS
347
+ return { ...LIVE_CAPS, stop: false } // can send/resume/approve, but no stop until a live turn
348
+ }
349
+
350
+ module.exports = {
351
+ LIVE_CAPS,
352
+ onSessionEvent,
353
+ spawnSession,
354
+ sendMessage,
355
+ stop,
356
+ approve,
357
+ pendingRequests,
358
+ liveInfo,
359
+ liveInfoMap,
360
+ discoveredCaps,
361
+ isLiveCapable,
362
+ }