@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.
- package/bin/codepocket.js +88 -22
- 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
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
|
|
|
@@ -270,21 +277,28 @@ if (args[0] === 'stop') {
|
|
|
270
277
|
console.log(`[codepocket] Stopped (PID ${pid})${extra}`)
|
|
271
278
|
process.exit(0)
|
|
272
279
|
}, 300)
|
|
280
|
+
// CRITICAL: do not fall through. The exit is scheduled 300ms out; without
|
|
281
|
+
// this return, execution continues to run(), whose foreground path sees
|
|
282
|
+
// "no daemon running", auto-starts a NEW daemon (stop never sticks), and
|
|
283
|
+
// spawns a claude session with the CLI args as prompt (trust banner +
|
|
284
|
+
// "--print needs input" error noise).
|
|
285
|
+
return
|
|
273
286
|
}
|
|
274
287
|
|
|
275
|
-
// Kill orphaned hub
|
|
276
|
-
//
|
|
277
|
-
//
|
|
288
|
+
// Kill orphaned hub processes (cross-platform). Only `hub start` mode is
|
|
289
|
+
// targeted — the same binary also runs claude session wrappers and the
|
|
290
|
+
// runner, so never match the bare binary name. Covers the shipped path
|
|
291
|
+
// (`.../bin/codepocket hub start`) and dev/legacy `cpkt-hub` builds.
|
|
278
292
|
function killOrphans() {
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
}
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
}
|
|
287
|
-
return ''
|
|
293
|
+
const killed = []
|
|
294
|
+
const run = (cmd) => { try { execSync(cmd, { stdio: 'ignore' }); return true } catch { return false } }
|
|
295
|
+
if (process.platform === 'win32') {
|
|
296
|
+
if (run('powershell -NoProfile -Command "Get-CimInstance Win32_Process -Filter \\"Name=\'codepocket.exe\' or Name=\'cpkt-hub.exe\'\\" | Where-Object { $_.CommandLine -match \'hub start\' } | ForEach-Object { Stop-Process -Id $_.ProcessId -Force }"')) killed.push('hub')
|
|
297
|
+
} else {
|
|
298
|
+
if (run('pkill -f "bin/codepocket hub start"')) killed.push('hub')
|
|
299
|
+
if (run('pkill -f "cpkt-hub hub start"')) killed.push('hub')
|
|
300
|
+
}
|
|
301
|
+
return [...new Set(killed)].join('+')
|
|
288
302
|
}
|
|
289
303
|
|
|
290
304
|
// 'logs' subcommand
|
|
@@ -761,8 +775,8 @@ function connectRelay() {
|
|
|
761
775
|
break
|
|
762
776
|
}
|
|
763
777
|
case 'spawn-session': {
|
|
764
|
-
log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}`)
|
|
765
|
-
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)
|
|
766
780
|
break
|
|
767
781
|
}
|
|
768
782
|
case 'resume-session': {
|
|
@@ -853,6 +867,40 @@ async function forwardToHub(requestId, method, p, body) {
|
|
|
853
867
|
sendToRelay({ type: 'rest-response', requestId, status: 403, data: { error: 'Forbidden path' } }, peer)
|
|
854
868
|
return
|
|
855
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
|
+
|
|
856
904
|
try {
|
|
857
905
|
let res = await doForwardToHub(requestId, method, p, body)
|
|
858
906
|
if (res.status === 401) {
|
|
@@ -883,27 +931,28 @@ async function handleAuthRequest(requestId, accessToken) {
|
|
|
883
931
|
}
|
|
884
932
|
}
|
|
885
933
|
|
|
886
|
-
async function handleSpawnSession(requestId, directory) {
|
|
934
|
+
async function handleSpawnSession(requestId, directory, provider) {
|
|
887
935
|
log(`[DEBUG:spawn] === START spawn-session ===`)
|
|
888
|
-
log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}`)
|
|
936
|
+
log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}, provider=${provider || 'claude'}`)
|
|
889
937
|
log(`[DEBUG:spawn] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
|
|
890
938
|
|
|
891
|
-
|
|
892
|
-
|
|
893
|
-
|
|
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} 会话不能从手机创建(在对应客户端内新建)`)
|
|
894
944
|
return
|
|
895
945
|
}
|
|
946
|
+
|
|
896
947
|
if (!directory || typeof directory !== 'string') {
|
|
897
948
|
log(`[DEBUG:spawn] FAIL: directory invalid`)
|
|
898
949
|
sendSpawnResult(requestId, null, 'Directory is required')
|
|
899
950
|
return
|
|
900
951
|
}
|
|
901
952
|
|
|
902
|
-
// Expand ~
|
|
953
|
+
// Expand ~ and enforce the same home-only boundary for every agent
|
|
903
954
|
directory = directory.replace(/^~/, os.homedir())
|
|
904
955
|
const absDir = path.resolve(directory)
|
|
905
|
-
|
|
906
|
-
// Only allow spawning in home directory
|
|
907
956
|
const home = os.homedir()
|
|
908
957
|
if (!absDir.startsWith(home)) {
|
|
909
958
|
log(`[DEBUG:spawn] FAIL: directory outside home: ${absDir}`)
|
|
@@ -916,6 +965,23 @@ async function handleSpawnSession(requestId, directory) {
|
|
|
916
965
|
return
|
|
917
966
|
}
|
|
918
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
|
+
|
|
919
985
|
log(`[DEBUG:spawn] Expanded directory: ${absDir}`)
|
|
920
986
|
|
|
921
987
|
try {
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tina_summer/codepocket",
|
|
3
|
-
"version": "2.
|
|
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.
|
|
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.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
|
+
}
|