@tina_summer/codepocket 2.6.11 → 2.7.1
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 +94 -10
- package/package.json +5 -5
- package/src/agents/codexLive.js +368 -0
- package/src/agents/codexRollout.js +311 -0
- package/src/agents/index.js +170 -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 +526 -0
- package/src/agents/zcodeRpc.js +170 -0
package/bin/codepocket.js
CHANGED
|
@@ -18,6 +18,19 @@ 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
|
+
// Throttled: bursts (poll loops, reconnect churn) must not flood the phone
|
|
26
|
+
// with reload-triggering events (observed WeChat service-thread timeouts).
|
|
27
|
+
let _lastAgentBroadcast = 0
|
|
28
|
+
agents.onSessionEvent(() => {
|
|
29
|
+
const now = Date.now()
|
|
30
|
+
if (now - _lastAgentBroadcast < 3000) return
|
|
31
|
+
_lastAgentBroadcast = now
|
|
32
|
+
sendToRelay({ type: 'sse-event', event: { type: 'session-updated' } })
|
|
33
|
+
})
|
|
21
34
|
|
|
22
35
|
// ── Proxy detection ──
|
|
23
36
|
|
|
@@ -768,8 +781,8 @@ function connectRelay() {
|
|
|
768
781
|
break
|
|
769
782
|
}
|
|
770
783
|
case 'spawn-session': {
|
|
771
|
-
log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}`)
|
|
772
|
-
handleSpawnSession(msg.requestId, msg.directory)
|
|
784
|
+
log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}, provider=${msg.provider || 'claude'}`)
|
|
785
|
+
handleSpawnSession(msg.requestId, msg.directory, msg.provider)
|
|
773
786
|
break
|
|
774
787
|
}
|
|
775
788
|
case 'resume-session': {
|
|
@@ -860,6 +873,40 @@ async function forwardToHub(requestId, method, p, body) {
|
|
|
860
873
|
sendToRelay({ type: 'rest-response', requestId, status: 403, data: { error: 'Forbidden path' } }, peer)
|
|
861
874
|
return
|
|
862
875
|
}
|
|
876
|
+
|
|
877
|
+
// ── Agent routes: provider registry, codex/zcode namespaced sessions ──
|
|
878
|
+
// These are served by the connector itself (local files + codex app-server)
|
|
879
|
+
// and never reach the hub binary.
|
|
880
|
+
const pathOnly = p.split('?')[0]
|
|
881
|
+
try {
|
|
882
|
+
if (method === 'GET' && pathOnly === '/api/sessions') {
|
|
883
|
+
// Merge hub (claude) + agent sessions; agent sessions stay readable
|
|
884
|
+
// even when the hub is unreachable.
|
|
885
|
+
let hubData = {}
|
|
886
|
+
try {
|
|
887
|
+
let res = await doForwardToHub(requestId, method, p, body)
|
|
888
|
+
if (res.status === 401) {
|
|
889
|
+
try {
|
|
890
|
+
const token = await findHubToken()
|
|
891
|
+
jwt = await authenticateHub(token)
|
|
892
|
+
res = await doForwardToHub(requestId, method, p, body)
|
|
893
|
+
} catch {}
|
|
894
|
+
}
|
|
895
|
+
hubData = await res.json().catch(() => ({}))
|
|
896
|
+
} catch {}
|
|
897
|
+
sendToRelay({ type: 'rest-response', requestId, status: 200, data: agents.mergeSessionLists(hubData) }, peer)
|
|
898
|
+
return
|
|
899
|
+
}
|
|
900
|
+
const agentRes = await agents.handleRest(method, pathOnly, body)
|
|
901
|
+
if (agentRes) {
|
|
902
|
+
sendToRelay({ type: 'rest-response', requestId, status: agentRes.status, data: agentRes.data }, peer)
|
|
903
|
+
return
|
|
904
|
+
}
|
|
905
|
+
} catch (agentErr) {
|
|
906
|
+
sendToRelay({ type: 'rest-response', requestId, status: 500, data: { error: agentErr.message } }, peer)
|
|
907
|
+
return
|
|
908
|
+
}
|
|
909
|
+
|
|
863
910
|
try {
|
|
864
911
|
let res = await doForwardToHub(requestId, method, p, body)
|
|
865
912
|
if (res.status === 401) {
|
|
@@ -890,27 +937,28 @@ async function handleAuthRequest(requestId, accessToken) {
|
|
|
890
937
|
}
|
|
891
938
|
}
|
|
892
939
|
|
|
893
|
-
async function handleSpawnSession(requestId, directory) {
|
|
940
|
+
async function handleSpawnSession(requestId, directory, provider) {
|
|
894
941
|
log(`[DEBUG:spawn] === START spawn-session ===`)
|
|
895
|
-
log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}`)
|
|
942
|
+
log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}, provider=${provider || 'claude'}`)
|
|
896
943
|
log(`[DEBUG:spawn] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
|
|
897
944
|
|
|
898
|
-
|
|
899
|
-
|
|
900
|
-
|
|
945
|
+
// Agent selection: 'claude' (default, omit-safe for older miniprogram
|
|
946
|
+
// versions) or a connector-side agent backend.
|
|
947
|
+
const agentKey = (typeof provider === 'string' && provider) ? provider : 'claude'
|
|
948
|
+
if (!['claude', 'codex', 'zcode'].includes(agentKey)) {
|
|
949
|
+
sendSpawnResult(requestId, null, `${agentKey} 会话不能从手机创建(在对应客户端内新建)`)
|
|
901
950
|
return
|
|
902
951
|
}
|
|
952
|
+
|
|
903
953
|
if (!directory || typeof directory !== 'string') {
|
|
904
954
|
log(`[DEBUG:spawn] FAIL: directory invalid`)
|
|
905
955
|
sendSpawnResult(requestId, null, 'Directory is required')
|
|
906
956
|
return
|
|
907
957
|
}
|
|
908
958
|
|
|
909
|
-
// Expand ~
|
|
959
|
+
// Expand ~ and enforce the same home-only boundary for every agent
|
|
910
960
|
directory = directory.replace(/^~/, os.homedir())
|
|
911
961
|
const absDir = path.resolve(directory)
|
|
912
|
-
|
|
913
|
-
// Only allow spawning in home directory
|
|
914
962
|
const home = os.homedir()
|
|
915
963
|
if (!absDir.startsWith(home)) {
|
|
916
964
|
log(`[DEBUG:spawn] FAIL: directory outside home: ${absDir}`)
|
|
@@ -923,6 +971,35 @@ async function handleSpawnSession(requestId, directory) {
|
|
|
923
971
|
return
|
|
924
972
|
}
|
|
925
973
|
|
|
974
|
+
// Codex: connector-side adapter (codex app-server) — no hub involved
|
|
975
|
+
if (agentKey === 'codex') {
|
|
976
|
+
try {
|
|
977
|
+
const sessionId = await agents.spawn('codex', absDir)
|
|
978
|
+
sendSpawnResult(requestId, sessionId)
|
|
979
|
+
} catch (e) {
|
|
980
|
+
sendSpawnResult(requestId, null, e.message || 'Codex 会话启动失败')
|
|
981
|
+
}
|
|
982
|
+
return
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
// ZCode/GLM: created on the desktop via the ws2 relay (createSession command).
|
|
986
|
+
// The desktop's active workspace is used — dir selection is advisory only.
|
|
987
|
+
if (agentKey === 'zcode') {
|
|
988
|
+
try {
|
|
989
|
+
const sessionId = await agents.spawn('zcode', absDir)
|
|
990
|
+
sendSpawnResult(requestId, sessionId)
|
|
991
|
+
} catch (e) {
|
|
992
|
+
sendSpawnResult(requestId, null, e.message || 'GLM 会话创建失败(需 ZCode 桌面端在线并开启远控)')
|
|
993
|
+
}
|
|
994
|
+
return
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
if (!hubBin) {
|
|
998
|
+
log(`[DEBUG:spawn] FAIL: hubBin is null`)
|
|
999
|
+
sendSpawnResult(requestId, null, 'Hub binary not found')
|
|
1000
|
+
return
|
|
1001
|
+
}
|
|
1002
|
+
|
|
926
1003
|
log(`[DEBUG:spawn] Expanded directory: ${absDir}`)
|
|
927
1004
|
|
|
928
1005
|
try {
|
|
@@ -1028,6 +1105,13 @@ async function handleResumeSession(requestId, sessionId) {
|
|
|
1028
1105
|
log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
|
|
1029
1106
|
const peer = takePeer(requestId)
|
|
1030
1107
|
|
|
1108
|
+
// Agent-namespaced sessions are persistent (codex rollout / zcode desktop) —
|
|
1109
|
+
// "resume" is a no-op that returns the same id; the chat page opens directly.
|
|
1110
|
+
if (typeof sessionId === 'string' && (sessionId.startsWith('codex:') || sessionId.startsWith('zcode:'))) {
|
|
1111
|
+
sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId }, peer)
|
|
1112
|
+
return
|
|
1113
|
+
}
|
|
1114
|
+
|
|
1031
1115
|
if (!hubBin) {
|
|
1032
1116
|
sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' }, peer)
|
|
1033
1117
|
return
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tina_summer/codepocket",
|
|
3
|
-
"version": "2.
|
|
3
|
+
"version": "2.7.1",
|
|
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.
|
|
24
|
-
"@tina_summer/codepocket-darwin-x64": "2.
|
|
25
|
-
"@tina_summer/codepocket-linux-x64": "2.
|
|
26
|
-
"@tina_summer/codepocket-win32-x64": "2.
|
|
23
|
+
"@tina_summer/codepocket-darwin-arm64": "2.7.1",
|
|
24
|
+
"@tina_summer/codepocket-darwin-x64": "2.7.1",
|
|
25
|
+
"@tina_summer/codepocket-linux-x64": "2.7.1",
|
|
26
|
+
"@tina_summer/codepocket-win32-x64": "2.7.1"
|
|
27
27
|
},
|
|
28
28
|
"engines": {
|
|
29
29
|
"node": ">=18"
|
|
@@ -0,0 +1,368 @@
|
|
|
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 becomes the session originator — matching the TUI's
|
|
110
|
+
// own value ("codex_cli_rs") makes phone-created sessions appear in the
|
|
111
|
+
// terminal's /resume picker. Override-able via env for debugging.
|
|
112
|
+
clientInfo: { name: process.env.CODEPOCKET_CODEX_ORIGINATOR || 'codex_cli_rs', version: '1' },
|
|
113
|
+
capabilities: { experimentalApi: true },
|
|
114
|
+
}, INIT_TIMEOUT)
|
|
115
|
+
.then((info) => {
|
|
116
|
+
write(st, { method: 'initialized', params: {} })
|
|
117
|
+
resolve(info)
|
|
118
|
+
})
|
|
119
|
+
.catch(reject)
|
|
120
|
+
})
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
function handleServerMessage(st, msg) {
|
|
124
|
+
if (msg.id !== undefined && (msg.result !== undefined || msg.error !== undefined)) {
|
|
125
|
+
const cb = st.callbacks.get(msg.id)
|
|
126
|
+
if (cb) {
|
|
127
|
+
st.callbacks.delete(msg.id)
|
|
128
|
+
if (msg.error) cb.reject(new Error(msg.error.message || 'Codex 请求失败'))
|
|
129
|
+
else cb.resolve(msg.result)
|
|
130
|
+
}
|
|
131
|
+
return
|
|
132
|
+
}
|
|
133
|
+
// Server→client request: approvals / user input.
|
|
134
|
+
if (msg.id !== undefined && msg.method) {
|
|
135
|
+
const kind = approvalKind(msg.method)
|
|
136
|
+
if (kind) {
|
|
137
|
+
const p = msg.params || {}
|
|
138
|
+
pending.set(String(msg.id), {
|
|
139
|
+
sessionId: 'codex:' + st.threadId,
|
|
140
|
+
nativeId: msg.id,
|
|
141
|
+
kind,
|
|
142
|
+
tool: kind === 'command' ? 'shell' : (kind === 'file' ? 'apply_patch' : 'permissions'),
|
|
143
|
+
arguments: summarizeRequest(kind, p),
|
|
144
|
+
// Verified enum (cankao + 0.171): accept / decline / cancel (+accept_once)
|
|
145
|
+
availableDecisions: Array.isArray(p.availableDecisions) ? p.availableDecisions : null,
|
|
146
|
+
})
|
|
147
|
+
st.pendingCount = countPending('codex:' + st.threadId)
|
|
148
|
+
st.active = true
|
|
149
|
+
notify()
|
|
150
|
+
} else {
|
|
151
|
+
// Unknown server request — decline explicitly so the turn doesn't hang forever
|
|
152
|
+
try { write(st, { id: msg.id, error: { code: -32601, message: 'codepocket: unsupported request' } }) } catch {}
|
|
153
|
+
}
|
|
154
|
+
return
|
|
155
|
+
}
|
|
156
|
+
// Notifications: thread/status/changed is the authoritative activity signal
|
|
157
|
+
// (verified 0.171: params {threadId, status:{type:'active'|'idle'|...}}).
|
|
158
|
+
if (msg.method === 'thread/status/changed') {
|
|
159
|
+
const p = msg.params || {}
|
|
160
|
+
if (p.threadId && p.threadId === st.threadId) {
|
|
161
|
+
st.active = !!(p.status && p.status.type === 'active')
|
|
162
|
+
st.updatedAt = Date.now()
|
|
163
|
+
notify()
|
|
164
|
+
}
|
|
165
|
+
return
|
|
166
|
+
}
|
|
167
|
+
// Other notifications (item updates etc.) — rendering reads rollout files,
|
|
168
|
+
// only refresh activity state occasionally via the poller
|
|
169
|
+
if (msg.method && st.threadId) {
|
|
170
|
+
st.updatedAt = Date.now()
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function approvalKind(method) {
|
|
175
|
+
if (typeof method !== 'string') return null
|
|
176
|
+
if (method.includes('commandExecution') && method.includes('requestApproval')) return 'command'
|
|
177
|
+
if (method.includes('fileChange') && method.includes('requestApproval')) return 'file'
|
|
178
|
+
if (method.includes('permissions') && method.includes('requestApproval')) return 'permission'
|
|
179
|
+
return null
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function summarizeRequest(kind, p) {
|
|
183
|
+
try {
|
|
184
|
+
if (kind === 'command' && typeof (p.command || (p.item && p.item.command)) === 'string') {
|
|
185
|
+
return p.command || p.item.command
|
|
186
|
+
}
|
|
187
|
+
if (kind === 'file' && Array.isArray(p.changes || (p.item && p.item.changes))) {
|
|
188
|
+
const changes = p.changes || p.item.changes
|
|
189
|
+
return changes.map(c => c.path || c.file || '').filter(Boolean).join(', ') || '文件修改'
|
|
190
|
+
}
|
|
191
|
+
return JSON.stringify(p).slice(0, 400)
|
|
192
|
+
} catch { return '' }
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ── Status polling (rendering stays on rollout files) ──
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Verified against codex 0.171: thread/read WITHOUT includeTurns returns
|
|
199
|
+
* thread.status = {type: 'active'|'idle'|'notLoaded'|...}. The includeTurns
|
|
200
|
+
* form is deprecated (deprecationNotice) in favor of thread/turns/list.
|
|
201
|
+
*/
|
|
202
|
+
async function refresh(st) {
|
|
203
|
+
if (!st.proc || !st.threadId) return
|
|
204
|
+
try {
|
|
205
|
+
const result = await rpc(st, 'thread/read', { threadId: st.threadId }, 10000)
|
|
206
|
+
st.updatedAt = Date.now()
|
|
207
|
+
const type = result && result.thread && result.thread.status && result.thread.status.type
|
|
208
|
+
const isActive = type === 'active'
|
|
209
|
+
// Notify ONLY on actual state transitions — the poller runs every 1.5s and
|
|
210
|
+
// unconditional notify() floods the phone with session-updated SSE events
|
|
211
|
+
// (observed: WeChat service-thread timeout under the reload storm).
|
|
212
|
+
if (isActive !== st.active) {
|
|
213
|
+
st.active = isActive
|
|
214
|
+
if (!isActive && st.poller) { clearInterval(st.poller); st.poller = null }
|
|
215
|
+
notify()
|
|
216
|
+
}
|
|
217
|
+
} catch { /* transient read failure — keep last known state */ }
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
function ensurePolling(st) {
|
|
221
|
+
if (st.poller) return
|
|
222
|
+
st.poller = setInterval(() => {
|
|
223
|
+
const s = live.get(st.threadId)
|
|
224
|
+
if (!s || !s.proc) { clearInterval(st.poller); st.poller = null; return }
|
|
225
|
+
refresh(s)
|
|
226
|
+
}, POLL_INTERVAL)
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
// ── Public API (sessionId = 'codex:<threadId>') ──
|
|
230
|
+
|
|
231
|
+
async function spawnSession(dir) {
|
|
232
|
+
// Temp state — keyed in `live` only after thread/start returns the id
|
|
233
|
+
const st = {
|
|
234
|
+
proc: null, nextId: 1, callbacks: new Map(),
|
|
235
|
+
threadId: null, turnId: null, cwd: dir, active: false, updatedAt: Date.now(),
|
|
236
|
+
pendingCount: 0, poller: null,
|
|
237
|
+
}
|
|
238
|
+
await startServer(st)
|
|
239
|
+
const result = await rpc(st, 'thread/start', { cwd: dir })
|
|
240
|
+
// 0.171 shape: { thread: { id, ... }, sessionId, cwd, ... }
|
|
241
|
+
const threadId = result && result.thread && (result.thread.id || result.thread.threadId)
|
|
242
|
+
if (!threadId) throw new Error('Codex thread/start 未返回 threadId')
|
|
243
|
+
st.threadId = threadId
|
|
244
|
+
live.set(threadId, st)
|
|
245
|
+
return 'codex:' + threadId
|
|
246
|
+
}
|
|
247
|
+
|
|
248
|
+
async function ensureLive(sessionId) {
|
|
249
|
+
const threadId = String(sessionId).slice('codex:'.length)
|
|
250
|
+
let st = live.get(threadId)
|
|
251
|
+
if (st && st.proc) return st
|
|
252
|
+
// Cold resume: CLI installed → spawn + thread/resume the same conversation
|
|
253
|
+
st = state(threadId)
|
|
254
|
+
st.threadId = threadId
|
|
255
|
+
await startServer(st)
|
|
256
|
+
await rpc(st, 'thread/resume', { threadId })
|
|
257
|
+
return st
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
async function sendMessage(sessionId, text) {
|
|
261
|
+
const st = await ensureLive(sessionId)
|
|
262
|
+
if (st.active) throw new Error('当前 Codex 任务仍在进行,请先停止或等待完成')
|
|
263
|
+
// Verified 0.171: result = {turn: {id, status: 'inProgress', ...}}
|
|
264
|
+
const result = await rpc(st, 'turn/start', {
|
|
265
|
+
threadId: st.threadId,
|
|
266
|
+
input: [{ type: 'text', text }],
|
|
267
|
+
clientUserMessageId: crypto.randomUUID(),
|
|
268
|
+
})
|
|
269
|
+
st.turnId = (result && result.turn && result.turn.id) || st.turnId || null
|
|
270
|
+
st.active = true
|
|
271
|
+
st.updatedAt = Date.now()
|
|
272
|
+
ensurePolling(st)
|
|
273
|
+
refresh(st)
|
|
274
|
+
return result
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
async function stop(sessionId) {
|
|
278
|
+
const threadId = String(sessionId).slice('codex:'.length)
|
|
279
|
+
const st = live.get(threadId)
|
|
280
|
+
if (!st || !st.proc) throw new Error('该 Codex 会话未在运行')
|
|
281
|
+
let turnId = st.turnId || null
|
|
282
|
+
if (!turnId) {
|
|
283
|
+
// Fallback: newest inProgress turn via the non-deprecated paging call
|
|
284
|
+
try {
|
|
285
|
+
const result = await rpc(st, 'thread/turns/list', { threadId, limit: 20 }, 10000)
|
|
286
|
+
const turns = (result && Array.isArray(result.data)) ? result.data : []
|
|
287
|
+
const activeTurn = turns.find(t => t && t.status === 'inProgress')
|
|
288
|
+
turnId = activeTurn && activeTurn.id
|
|
289
|
+
} catch {}
|
|
290
|
+
}
|
|
291
|
+
if (!turnId) { st.active = false; notify(); return { stopped: false, reason: '没有进行中的任务' } }
|
|
292
|
+
await rpc(st, 'turn/interrupt', { threadId, turnId })
|
|
293
|
+
st.active = false
|
|
294
|
+
refresh(st)
|
|
295
|
+
return { stopped: true }
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
function pendingRequests(sessionId) {
|
|
299
|
+
const out = {}
|
|
300
|
+
for (const [reqId, p] of pending) {
|
|
301
|
+
if (p.sessionId === sessionId) out[reqId] = { tool: p.tool, arguments: p.arguments, kind: p.kind }
|
|
302
|
+
}
|
|
303
|
+
return out
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
function countPending(sessionId) {
|
|
307
|
+
let n = 0
|
|
308
|
+
for (const p of pending.values()) if (p.sessionId === sessionId) n++
|
|
309
|
+
return n
|
|
310
|
+
}
|
|
311
|
+
|
|
312
|
+
async function approve(sessionId, reqId, decision) {
|
|
313
|
+
const p = pending.get(reqId)
|
|
314
|
+
if (!p || p.sessionId !== sessionId) throw new Error('该审批请求已不存在')
|
|
315
|
+
pending.delete(reqId)
|
|
316
|
+
const threadId = String(sessionId).slice('codex:'.length)
|
|
317
|
+
const st = live.get(threadId)
|
|
318
|
+
if (!st || !st.proc) throw new Error('Codex app-server 已断开,无法提交审批')
|
|
319
|
+
// Native enum is accept/decline(/cancel, accept_once). Map the phone's
|
|
320
|
+
// approve/deny onto it, honoring availableDecisions when the server sent it.
|
|
321
|
+
let native
|
|
322
|
+
if (decision === 'denied') native = 'decline'
|
|
323
|
+
else native = 'accept'
|
|
324
|
+
if (p.availableDecisions && p.availableDecisions.length && !p.availableDecisions.includes(native)) {
|
|
325
|
+
const alt = decision === 'denied' ? 'cancel' : 'accept_once'
|
|
326
|
+
if (p.availableDecisions.includes(alt)) native = alt
|
|
327
|
+
}
|
|
328
|
+
respond(st, p.nativeId, { decision: native })
|
|
329
|
+
st.pendingCount = countPending(sessionId)
|
|
330
|
+
notify()
|
|
331
|
+
return { submitted: true, decision: native }
|
|
332
|
+
}
|
|
333
|
+
|
|
334
|
+
/** Live-enrichment for codexRollout.sessionRows/sessionDetail. */
|
|
335
|
+
function liveInfo(rawId) {
|
|
336
|
+
const st = live.get(rawId)
|
|
337
|
+
if (!st) return null
|
|
338
|
+
const sessionId = 'codex:' + rawId
|
|
339
|
+
return { active: st.active, pendingCount: countPending(sessionId), caps: LIVE_CAPS, updatedAt: st.updatedAt }
|
|
340
|
+
}
|
|
341
|
+
|
|
342
|
+
function liveInfoMap() {
|
|
343
|
+
const out = {}
|
|
344
|
+
for (const key of live.keys()) out[key] = liveInfo(key)
|
|
345
|
+
return out
|
|
346
|
+
}
|
|
347
|
+
|
|
348
|
+
function isLiveCapable() { return !!findCodexBin() }
|
|
349
|
+
|
|
350
|
+
/** Caps reported for discovered (non-live) sessions: read-only, or resumable when CLI exists. */
|
|
351
|
+
function discoveredCaps() {
|
|
352
|
+
if (!isLiveCapable()) return null // → codexRollout.READONLY_CAPS
|
|
353
|
+
return { ...LIVE_CAPS, stop: false } // can send/resume/approve, but no stop until a live turn
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
module.exports = {
|
|
357
|
+
LIVE_CAPS,
|
|
358
|
+
onSessionEvent,
|
|
359
|
+
spawnSession,
|
|
360
|
+
sendMessage,
|
|
361
|
+
stop,
|
|
362
|
+
approve,
|
|
363
|
+
pendingRequests,
|
|
364
|
+
liveInfo,
|
|
365
|
+
liveInfoMap,
|
|
366
|
+
discoveredCaps,
|
|
367
|
+
isLiveCapable,
|
|
368
|
+
}
|