@tina_summer/codepocket 2.1.0 → 2.1.2
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 +203 -202
- package/bin/run.js +4 -4
- package/package.json +1 -1
package/bin/codepocket.js
CHANGED
|
@@ -3,9 +3,9 @@
|
|
|
3
3
|
/**
|
|
4
4
|
* CodePocket — 你的全能 AI 随身控制台
|
|
5
5
|
*
|
|
6
|
-
* npx codepocket
|
|
7
|
-
*
|
|
8
|
-
*
|
|
6
|
+
* npx codepocket 启动 Claude Code + 自动连接手机
|
|
7
|
+
* npx codepocket --key X 首次配对(保存 Key)
|
|
8
|
+
* npx cpkt 短命令
|
|
9
9
|
*/
|
|
10
10
|
|
|
11
11
|
const { WebSocket } = require('ws')
|
|
@@ -22,6 +22,7 @@ const { runTestCli } = require('../src/mcp-client')
|
|
|
22
22
|
const CONFIG_DIR = path.join(os.homedir(), '.codepocket')
|
|
23
23
|
const CONFIG_FILE = path.join(CONFIG_DIR, 'config.json')
|
|
24
24
|
const SESSION_FILE = path.join(CONFIG_DIR, 'session.json')
|
|
25
|
+
const HOME_ENV = { CODEPOCKET_HOME: path.join(os.homedir(), '.codepocket') }
|
|
25
26
|
|
|
26
27
|
function loadConfig() {
|
|
27
28
|
try { return JSON.parse(fs.readFileSync(CONFIG_FILE, 'utf-8')) } catch { return {} }
|
|
@@ -37,148 +38,114 @@ function injectMcpConfig(port) {
|
|
|
37
38
|
let settings = {}
|
|
38
39
|
try { settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8')) } catch {}
|
|
39
40
|
if (!settings.mcpServers) settings.mcpServers = {}
|
|
40
|
-
if (settings.mcpServers['codepocket-phone']) return
|
|
41
|
+
if (settings.mcpServers['codepocket-phone']) return
|
|
41
42
|
settings.mcpServers['codepocket-phone'] = {
|
|
42
43
|
type: 'sse',
|
|
43
44
|
url: `http://127.0.0.1:${port}/sse`,
|
|
44
45
|
}
|
|
45
46
|
fs.mkdirSync(path.dirname(settingsPath), { recursive: true })
|
|
46
47
|
fs.writeFileSync(settingsPath, JSON.stringify(settings, null, 2))
|
|
47
|
-
console.log(` [✓] MCP 配置已写入 ${settingsPath}`)
|
|
48
48
|
}
|
|
49
49
|
|
|
50
|
-
// ──
|
|
50
|
+
// ── Helpers ──
|
|
51
51
|
|
|
52
|
-
|
|
52
|
+
function findHubBin() {
|
|
53
|
+
const bundledBin = path.join(__dirname, '..', 'vendor', process.platform === 'win32' ? 'cpkt-hub.exe' : 'cpkt-hub')
|
|
54
|
+
if (fs.existsSync(bundledBin)) return bundledBin
|
|
55
|
+
try { const r = execSync('which cpkt-hub 2>/dev/null').toString().trim(); if (r) return r } catch {}
|
|
56
|
+
return null
|
|
57
|
+
}
|
|
53
58
|
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
59
|
+
function isHubRunning(hubUrl) {
|
|
60
|
+
try {
|
|
61
|
+
return execSync(`curl -s -o /dev/null -w "%{http_code}" ${hubUrl}/ 2>/dev/null`).toString().trim() === '200'
|
|
62
|
+
} catch { return false }
|
|
63
|
+
}
|
|
58
64
|
|
|
59
|
-
//
|
|
60
|
-
const CONNECT_ARGS = ['connect', 'c']
|
|
65
|
+
// ── Parse args ──
|
|
61
66
|
|
|
62
|
-
|
|
67
|
+
const args = process.argv.slice(2)
|
|
68
|
+
|
|
69
|
+
// 'test' subcommand — standalone
|
|
63
70
|
if (args[0] === 'test') {
|
|
64
71
|
runTestCli(args.slice(1))
|
|
65
72
|
return
|
|
66
73
|
}
|
|
67
74
|
|
|
68
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
return
|
|
72
|
-
}
|
|
75
|
+
// Determine mode
|
|
76
|
+
const CONNECT_ONLY = ['connect', 'c'].includes(args[0])
|
|
77
|
+
const filteredArgs = CONNECT_ONLY ? args.slice(1) : args
|
|
73
78
|
|
|
74
|
-
|
|
79
|
+
let hubUrl = process.env.CPKT_HUB_URL || process.env.HAPI_HUB_URL || 'http://127.0.0.1:3006'
|
|
80
|
+
let relayUrl = process.env.RELAY_WS_URL || process.env.RELAY_URL || ''
|
|
81
|
+
let relayKey = process.env.RELAY_KEY || ''
|
|
82
|
+
let noHub = false
|
|
75
83
|
|
|
76
|
-
|
|
77
|
-
|
|
84
|
+
const passThroughArgs = []
|
|
85
|
+
for (let i = 0; i < filteredArgs.length; i++) {
|
|
86
|
+
const arg = filteredArgs[i]
|
|
78
87
|
if (arg.startsWith('--hub=')) hubUrl = arg.slice(6).replace(/\/+$/, '')
|
|
79
|
-
if (arg === '--hub' &&
|
|
80
|
-
if (arg.startsWith('--relay=')) relayUrl = arg.slice(8)
|
|
81
|
-
if (arg === '--relay' &&
|
|
82
|
-
if (arg.startsWith('--key=')) relayKey = arg.slice(6)
|
|
83
|
-
if (arg === '--key' &&
|
|
84
|
-
if (arg === '--no-hub') noHub = true
|
|
88
|
+
else if (arg === '--hub' && filteredArgs[i + 1]) { hubUrl = filteredArgs[++i].replace(/\/+$/, '') }
|
|
89
|
+
else if (arg.startsWith('--relay=')) relayUrl = arg.slice(8)
|
|
90
|
+
else if (arg === '--relay' && filteredArgs[i + 1]) { relayUrl = filteredArgs[++i] }
|
|
91
|
+
else if (arg.startsWith('--key=')) relayKey = arg.slice(6)
|
|
92
|
+
else if (arg === '--key' && filteredArgs[i + 1]) { relayKey = filteredArgs[++i] }
|
|
93
|
+
else if (arg === '--no-hub') noHub = true
|
|
94
|
+
else passThroughArgs.push(arg)
|
|
85
95
|
}
|
|
86
96
|
|
|
97
|
+
// Load/merge config
|
|
87
98
|
const saved = loadConfig()
|
|
88
99
|
if (relayKey) {
|
|
89
|
-
saveConfig({ ...saved, relayKey, relayUrl: relayUrl || saved.relayUrl || '
|
|
100
|
+
saveConfig({ ...saved, relayKey, relayUrl: relayUrl || saved.relayUrl || '' })
|
|
90
101
|
} else {
|
|
91
102
|
relayKey = saved.relayKey || ''
|
|
92
103
|
}
|
|
93
|
-
if (!relayUrl) relayUrl = saved.relayUrl || '
|
|
104
|
+
if (!relayUrl) relayUrl = saved.relayUrl || ''
|
|
105
|
+
|
|
106
|
+
// ── State ──
|
|
94
107
|
|
|
95
108
|
let jwt = ''
|
|
96
109
|
let relayWs = null
|
|
110
|
+
let relayPingInterval = null
|
|
97
111
|
|
|
98
|
-
// ──
|
|
112
|
+
// ── Hub ──
|
|
99
113
|
|
|
100
|
-
function startHub() {
|
|
101
|
-
return new Promise((resolve
|
|
114
|
+
function startHub(hubBin) {
|
|
115
|
+
return new Promise((resolve) => {
|
|
102
116
|
if (noHub) { resolve(); return }
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
try {
|
|
106
|
-
const result = execSync(`curl -s -o /dev/null -w "%{http_code}" ${hubUrl}/ 2>/dev/null`).toString().trim()
|
|
107
|
-
if (result === '200') {
|
|
108
|
-
console.log(' [✓] Hub 已在运行')
|
|
109
|
-
resolve()
|
|
110
|
-
return
|
|
111
|
-
}
|
|
112
|
-
} catch {}
|
|
113
|
-
|
|
114
|
-
console.log(' 启动 Hub...')
|
|
115
|
-
const hubBin = findHubBin()
|
|
116
|
-
if (!hubBin) {
|
|
117
|
-
console.error(' [!] 找不到 Hub 二进制')
|
|
118
|
-
reject(new Error('Hub binary not found'))
|
|
119
|
-
return
|
|
120
|
-
}
|
|
117
|
+
if (isHubRunning(hubUrl)) { resolve(); return }
|
|
118
|
+
if (!hubBin) { resolve(); return }
|
|
121
119
|
|
|
122
120
|
const hub = spawn(hubBin, ['hub', 'start'], {
|
|
123
121
|
stdio: ['ignore', 'pipe', 'pipe'],
|
|
124
122
|
detached: false,
|
|
125
|
-
env: {
|
|
126
|
-
...process.env,
|
|
127
|
-
CODEPOCKET_HOME: path.join(os.homedir(), '.codepocket'),
|
|
128
|
-
},
|
|
123
|
+
env: { ...process.env, ...HOME_ENV },
|
|
129
124
|
})
|
|
130
125
|
|
|
131
126
|
let started = false
|
|
132
|
-
hub.stdout.on('data', (
|
|
133
|
-
const text = data.toString()
|
|
134
|
-
if (!started) process.stdout.write(' ')
|
|
135
|
-
process.stdout.write(text)
|
|
136
|
-
})
|
|
127
|
+
hub.stdout.on('data', () => {}) // swallow
|
|
137
128
|
hub.stderr.on('data', (data) => {
|
|
138
129
|
const text = data.toString()
|
|
139
|
-
if (text.includes('listening') || text.includes('ready') || text.includes('started')) {
|
|
140
|
-
|
|
130
|
+
if (!started && (text.includes('listening') || text.includes('ready') || text.includes('started'))) {
|
|
131
|
+
started = true
|
|
132
|
+
resolve()
|
|
141
133
|
}
|
|
142
134
|
})
|
|
143
135
|
|
|
144
|
-
// Wait up to 10s for hub
|
|
145
136
|
setTimeout(() => {
|
|
146
|
-
if (!started) {
|
|
147
|
-
|
|
148
|
-
try {
|
|
149
|
-
execSync(`curl -s -o /dev/null -w "%{http_code}" ${hubUrl}/ 2>/dev/null`)
|
|
150
|
-
started = true
|
|
151
|
-
resolve()
|
|
152
|
-
} catch {
|
|
153
|
-
console.log(' [i] Hub 启动中,继续连接...')
|
|
154
|
-
resolve()
|
|
155
|
-
}
|
|
156
|
-
}
|
|
137
|
+
if (!started && isHubRunning(hubUrl)) { started = true }
|
|
138
|
+
resolve()
|
|
157
139
|
}, 8000)
|
|
158
140
|
|
|
159
|
-
hub.on('exit', (
|
|
160
|
-
if (!started && code !== 0) {
|
|
161
|
-
reject(new Error(`Hub exited with code ${code}`))
|
|
162
|
-
}
|
|
163
|
-
})
|
|
141
|
+
hub.on('exit', () => resolve())
|
|
164
142
|
})
|
|
165
143
|
}
|
|
166
144
|
|
|
167
|
-
|
|
168
|
-
// 1. Bundled binary in vendor/
|
|
169
|
-
const bundledBin = path.join(__dirname, '..', 'vendor', process.platform === 'win32' ? 'cpkt-hub.exe' : 'cpkt-hub')
|
|
170
|
-
if (fs.existsSync(bundledBin)) return bundledBin
|
|
171
|
-
|
|
172
|
-
// 2. Global install
|
|
173
|
-
try { const r = execSync('which cpkt-hub 2>/dev/null').toString().trim(); if (r) return r } catch {}
|
|
174
|
-
|
|
175
|
-
return null
|
|
176
|
-
}
|
|
177
|
-
|
|
178
|
-
// ── Step 2: Authenticate ──
|
|
145
|
+
// ── Auth ──
|
|
179
146
|
|
|
180
147
|
async function findHubToken() {
|
|
181
|
-
const hubHome = process.env.CODEPOCKET_HOME ||
|
|
148
|
+
const hubHome = process.env.CODEPOCKET_HOME || HOME_ENV.CODEPOCKET_HOME
|
|
182
149
|
const settingsPath = path.join(hubHome, 'settings.json')
|
|
183
150
|
try {
|
|
184
151
|
const settings = JSON.parse(fs.readFileSync(settingsPath, 'utf-8'))
|
|
@@ -198,14 +165,13 @@ async function authenticateHub(token) {
|
|
|
198
165
|
return (await res.json()).token
|
|
199
166
|
}
|
|
200
167
|
|
|
201
|
-
// ──
|
|
168
|
+
// ── SSE ──
|
|
202
169
|
|
|
203
170
|
async function startSSE() {
|
|
204
171
|
const url = `${hubUrl}/api/events?token=${encodeURIComponent(jwt)}&all=true`
|
|
205
172
|
try {
|
|
206
173
|
const res = await fetch(url, { headers: { Accept: 'text/event-stream' } })
|
|
207
174
|
if (!res.ok || !res.body) { setTimeout(startSSE, 5000); return }
|
|
208
|
-
console.log(' [✓] SSE 已连接,监听事件...')
|
|
209
175
|
const reader = res.body.getReader()
|
|
210
176
|
const decoder = new TextDecoder()
|
|
211
177
|
let buffer = ''
|
|
@@ -218,11 +184,7 @@ async function startSSE() {
|
|
|
218
184
|
buffer = lines.pop() || ''
|
|
219
185
|
for (const line of lines) {
|
|
220
186
|
if (line.startsWith('data:')) {
|
|
221
|
-
try {
|
|
222
|
-
const event = JSON.parse(line.slice(5).trim())
|
|
223
|
-
console.log(`[SSE] ${event.type || 'unknown'}`)
|
|
224
|
-
sendToRelay({ type: 'sse-event', event })
|
|
225
|
-
} catch {}
|
|
187
|
+
try { sendToRelay({ type: 'sse-event', event: JSON.parse(line.slice(5).trim()) }) } catch {}
|
|
226
188
|
}
|
|
227
189
|
}
|
|
228
190
|
}
|
|
@@ -232,21 +194,14 @@ async function startSSE() {
|
|
|
232
194
|
} catch { setTimeout(startSSE, 5000) }
|
|
233
195
|
}
|
|
234
196
|
|
|
235
|
-
// ──
|
|
236
|
-
|
|
237
|
-
let relayPingInterval = null
|
|
197
|
+
// ── Relay ──
|
|
238
198
|
|
|
239
199
|
function connectRelay() {
|
|
240
200
|
let savedSession = null
|
|
241
201
|
try { savedSession = JSON.parse(fs.readFileSync(SESSION_FILE, 'utf-8')) } catch {}
|
|
242
202
|
|
|
243
|
-
// Clean up old connection
|
|
244
203
|
if (relayPingInterval) { clearInterval(relayPingInterval); relayPingInterval = null }
|
|
245
|
-
if (relayWs) {
|
|
246
|
-
try { relayWs.removeAllListeners() } catch {}
|
|
247
|
-
try { relayWs.close() } catch {}
|
|
248
|
-
relayWs = null
|
|
249
|
-
}
|
|
204
|
+
if (relayWs) { try { relayWs.removeAllListeners() } catch {} try { relayWs.close() } catch {} relayWs = null }
|
|
250
205
|
|
|
251
206
|
relayWs = new WebSocket(relayUrl)
|
|
252
207
|
|
|
@@ -256,11 +211,8 @@ function connectRelay() {
|
|
|
256
211
|
key: relayKey,
|
|
257
212
|
sessionToken: savedSession?.sessionToken || undefined,
|
|
258
213
|
}))
|
|
259
|
-
// Heartbeat every 30s to detect stale connections
|
|
260
214
|
relayPingInterval = setInterval(() => {
|
|
261
|
-
if (relayWs?.readyState === WebSocket.OPEN)
|
|
262
|
-
relayWs.ping()
|
|
263
|
-
}
|
|
215
|
+
if (relayWs?.readyState === WebSocket.OPEN) relayWs.ping()
|
|
264
216
|
}, 30000)
|
|
265
217
|
})
|
|
266
218
|
|
|
@@ -274,14 +226,14 @@ function connectRelay() {
|
|
|
274
226
|
fs.writeFileSync(SESSION_FILE, JSON.stringify({ sessionToken: msg.sessionToken, hubUrl, relayUrl }))
|
|
275
227
|
} catch {}
|
|
276
228
|
if (msg.reconnected) {
|
|
277
|
-
console.log('
|
|
229
|
+
console.log('[codepocket] ✓ 已重新连接')
|
|
278
230
|
} else {
|
|
279
|
-
console.log('
|
|
231
|
+
console.log('[codepocket] ✓ 已连接中继')
|
|
280
232
|
}
|
|
281
233
|
break
|
|
282
234
|
}
|
|
283
235
|
case 'client-connected': {
|
|
284
|
-
console.log('
|
|
236
|
+
console.log('[codepocket] ✓ 小程序已连接')
|
|
285
237
|
break
|
|
286
238
|
}
|
|
287
239
|
case 'rest-request': {
|
|
@@ -293,26 +245,34 @@ function connectRelay() {
|
|
|
293
245
|
break
|
|
294
246
|
}
|
|
295
247
|
case 'register-error': {
|
|
296
|
-
console.error(`
|
|
248
|
+
console.error(`[codepocket] ✗ ${msg.error}`)
|
|
297
249
|
break
|
|
298
250
|
}
|
|
299
251
|
case 'phone-action-response': {
|
|
300
252
|
onPhoneActionResponse(msg)
|
|
301
253
|
break
|
|
302
254
|
}
|
|
255
|
+
case 'spawn-session': {
|
|
256
|
+
handleSpawnSession(msg.requestId, msg.directory)
|
|
257
|
+
break
|
|
258
|
+
}
|
|
259
|
+
case 'list-dir': {
|
|
260
|
+
handleListDir(msg.requestId, msg.path)
|
|
261
|
+
break
|
|
262
|
+
}
|
|
263
|
+
case 'list-dir': {
|
|
264
|
+
handleListDir(msg.requestId, msg.path)
|
|
265
|
+
break
|
|
266
|
+
}
|
|
303
267
|
}
|
|
304
268
|
})
|
|
305
269
|
|
|
306
270
|
relayWs.on('close', () => {
|
|
307
271
|
if (relayPingInterval) { clearInterval(relayPingInterval); relayPingInterval = null }
|
|
308
272
|
relayWs = null
|
|
309
|
-
console.log('[relay] 连接断开,3秒后重连...')
|
|
310
273
|
setTimeout(connectRelay, 3000)
|
|
311
274
|
})
|
|
312
|
-
relayWs.on('error', (
|
|
313
|
-
console.error('[relay] 连接错误:', err.message)
|
|
314
|
-
relayWs?.close()
|
|
315
|
-
})
|
|
275
|
+
relayWs.on('error', () => { relayWs?.close() })
|
|
316
276
|
}
|
|
317
277
|
|
|
318
278
|
function sendToRelay(msg) {
|
|
@@ -331,21 +291,16 @@ async function doForwardToHub(requestId, method, p, body) {
|
|
|
331
291
|
async function forwardToHub(requestId, method, p, body) {
|
|
332
292
|
try {
|
|
333
293
|
let res = await doForwardToHub(requestId, method, p, body)
|
|
334
|
-
// JWT expired — re-authenticate and retry
|
|
335
294
|
if (res.status === 401) {
|
|
336
|
-
console.log('[REST] JWT expired, re-authenticating...')
|
|
337
295
|
try {
|
|
338
296
|
const token = await findHubToken()
|
|
339
297
|
jwt = await authenticateHub(token)
|
|
340
298
|
res = await doForwardToHub(requestId, method, p, body)
|
|
341
|
-
} catch
|
|
342
|
-
console.error('[REST] Re-auth failed:', authErr.message)
|
|
343
|
-
}
|
|
299
|
+
} catch {}
|
|
344
300
|
}
|
|
345
301
|
const data = await res.json().catch(() => ({}))
|
|
346
302
|
sendToRelay({ type: 'rest-response', requestId, status: res.status, data })
|
|
347
303
|
} catch (err) {
|
|
348
|
-
console.error(`[REST] ${method} ${p} failed:`, err.message, err.cause?.message || '')
|
|
349
304
|
sendToRelay({ type: 'rest-response', requestId, status: 502, data: { error: err.message } })
|
|
350
305
|
}
|
|
351
306
|
}
|
|
@@ -363,55 +318,105 @@ async function handleAuthRequest(requestId, accessToken) {
|
|
|
363
318
|
}
|
|
364
319
|
}
|
|
365
320
|
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
async function runDefault(passThroughArgs) {
|
|
369
|
-
const hubBin = findHubBin()
|
|
321
|
+
async function handleSpawnSession(requestId, directory) {
|
|
370
322
|
if (!hubBin) {
|
|
371
|
-
|
|
372
|
-
|
|
323
|
+
sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Hub binary not found' })
|
|
324
|
+
return
|
|
325
|
+
}
|
|
326
|
+
if (!directory || typeof directory !== 'string') {
|
|
327
|
+
sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Directory is required' })
|
|
328
|
+
return
|
|
373
329
|
}
|
|
374
330
|
|
|
375
|
-
//
|
|
376
|
-
|
|
331
|
+
// Expand ~ to home directory
|
|
332
|
+
directory = directory.replace(/^~/, os.homedir())
|
|
333
|
+
|
|
334
|
+
console.log(`[codepocket] Spawning session in: ${directory}`)
|
|
335
|
+
|
|
377
336
|
try {
|
|
378
|
-
const
|
|
379
|
-
|
|
380
|
-
|
|
337
|
+
const child = spawn(hubBin, ['--path', directory], {
|
|
338
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
339
|
+
detached: true,
|
|
340
|
+
env: { ...process.env, ...HOME_ENV },
|
|
341
|
+
})
|
|
342
|
+
child.unref()
|
|
381
343
|
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
344
|
+
// Wait for session to be created by polling /sessions
|
|
345
|
+
let sessionId = null
|
|
346
|
+
for (let i = 0; i < 30; i++) {
|
|
347
|
+
await new Promise(r => setTimeout(r, 1000))
|
|
348
|
+
try {
|
|
349
|
+
const res = await fetch(`${hubUrl}/sessions`, {
|
|
350
|
+
headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
|
|
351
|
+
})
|
|
352
|
+
const sessions = await res.json()
|
|
353
|
+
// Find the newest session with matching path
|
|
354
|
+
const match = (Array.isArray(sessions) ? sessions : []).find(s =>
|
|
355
|
+
s.metadata?.path === directory && s.id
|
|
356
|
+
)
|
|
357
|
+
if (match) {
|
|
358
|
+
sessionId = match.id
|
|
359
|
+
break
|
|
360
|
+
}
|
|
361
|
+
} catch {}
|
|
393
362
|
}
|
|
363
|
+
|
|
364
|
+
if (sessionId) {
|
|
365
|
+
console.log(`[codepocket] Session created: ${sessionId}`)
|
|
366
|
+
sendToRelay({ type: 'spawn-session-result', requestId, success: true, sessionId })
|
|
367
|
+
} else {
|
|
368
|
+
// Timeout but process started — might still be initializing
|
|
369
|
+
sendToRelay({ type: 'spawn-session-result', requestId, success: true, sessionId: null, warning: 'Session initializing' })
|
|
370
|
+
}
|
|
371
|
+
} catch (err) {
|
|
372
|
+
console.error(`[codepocket] Spawn failed: ${err.message}`)
|
|
373
|
+
sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: err.message })
|
|
394
374
|
}
|
|
375
|
+
}
|
|
395
376
|
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
401
|
-
|
|
377
|
+
function handleListDir(requestId, dirPath) {
|
|
378
|
+
try {
|
|
379
|
+
const resolved = (dirPath || '~').replace(/^~/, os.homedir())
|
|
380
|
+
const abs = path.resolve(resolved)
|
|
381
|
+
const entries = fs.readdirSync(abs, { withFileTypes: true })
|
|
382
|
+
.filter(d => d.isDirectory())
|
|
383
|
+
.map(d => ({ name: d.name, path: path.join(abs, d.name) }))
|
|
384
|
+
.sort((a, b) => a.name.localeCompare(b.name))
|
|
385
|
+
sendToRelay({ type: 'list-dir-result', requestId, path: abs, entries })
|
|
386
|
+
} catch (err) {
|
|
387
|
+
sendToRelay({ type: 'list-dir-result', requestId, error: err.message })
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
|
|
391
|
+
// ── Background connect: auth + MCP + SSE + relay ──
|
|
392
|
+
|
|
393
|
+
async function connectInBackground() {
|
|
394
|
+
if (!relayUrl) {
|
|
395
|
+
console.log('[codepocket] 未配置 Relay 地址,手机连接功能不可用')
|
|
396
|
+
return
|
|
397
|
+
}
|
|
398
|
+
try {
|
|
399
|
+
const token = await findHubToken()
|
|
400
|
+
jwt = await authenticateHub(token)
|
|
401
|
+
} catch {}
|
|
402
|
+
|
|
403
|
+
try {
|
|
404
|
+
const mcpPort = await startMcpServer(sendToRelay)
|
|
405
|
+
injectMcpConfig(mcpPort)
|
|
406
|
+
} catch {}
|
|
407
|
+
|
|
408
|
+
startSSE()
|
|
409
|
+
connectRelay()
|
|
402
410
|
}
|
|
403
411
|
|
|
404
|
-
// ── Main
|
|
412
|
+
// ── Main ──
|
|
405
413
|
|
|
406
|
-
async function
|
|
407
|
-
|
|
408
|
-
console.log(' ╔══════════════════════════════════════╗')
|
|
409
|
-
console.log(' ║ CodePocket ║')
|
|
410
|
-
console.log(' ╚══════════════════════════════════════╝')
|
|
411
|
-
console.log()
|
|
414
|
+
async function run() {
|
|
415
|
+
const hubBin = findHubBin()
|
|
412
416
|
|
|
417
|
+
// 1. Key setup (interactive if first time)
|
|
413
418
|
if (!relayKey) {
|
|
414
|
-
console.log('
|
|
419
|
+
console.log('[codepocket] 首次使用,请输入 Key')
|
|
415
420
|
console.log(' 在 CodePocket 小程序中获取 Key →')
|
|
416
421
|
relayKey = await new Promise((resolve) => {
|
|
417
422
|
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
@@ -421,58 +426,54 @@ async function main() {
|
|
|
421
426
|
})
|
|
422
427
|
})
|
|
423
428
|
if (!relayKey) {
|
|
424
|
-
console.error('')
|
|
425
|
-
console.error(' [!] Key 不能为空')
|
|
429
|
+
console.error('[codepocket] ✗ Key 不能为空')
|
|
426
430
|
process.exit(1)
|
|
427
431
|
}
|
|
428
|
-
saveConfig({ ...loadConfig(), relayKey, relayUrl })
|
|
429
|
-
console.log('')
|
|
430
|
-
console.log(' [✓] 配置已保存')
|
|
431
|
-
console.log('')
|
|
432
432
|
}
|
|
433
433
|
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
434
|
+
// 1.5 Relay URL (prompt if missing)
|
|
435
|
+
if (!relayUrl) {
|
|
436
|
+
relayUrl = await new Promise((resolve) => {
|
|
437
|
+
const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
|
|
438
|
+
rl.question(' Relay URL (如 wss://example.com/ws): ', (answer) => {
|
|
439
|
+
rl.close()
|
|
440
|
+
resolve(answer.trim())
|
|
441
|
+
})
|
|
442
|
+
})
|
|
443
|
+
}
|
|
437
444
|
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
await startHub()
|
|
442
|
-
} catch (e) {
|
|
443
|
-
console.error(` [!] ${e.message}`)
|
|
444
|
-
console.error(' 你可以用 --no-hub 跳过自动启动')
|
|
445
|
-
process.exit(1)
|
|
445
|
+
if (relayKey) {
|
|
446
|
+
saveConfig({ ...loadConfig(), relayKey, relayUrl })
|
|
447
|
+
console.log('[codepocket] ✓ 配置已保存')
|
|
446
448
|
}
|
|
447
449
|
|
|
448
|
-
//
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
const mcpPort = await startMcpServer(sendToRelay)
|
|
452
|
-
injectMcpConfig(mcpPort)
|
|
453
|
-
} catch (e) {
|
|
454
|
-
console.error(` [!] MCP server 启动失败: ${e.message}`)
|
|
455
|
-
console.error(' 手机工具功能将不可用')
|
|
450
|
+
// 2. Start hub (quiet, wait for ready)
|
|
451
|
+
if (!noHub) {
|
|
452
|
+
await startHub(hubBin)
|
|
456
453
|
}
|
|
457
454
|
|
|
458
|
-
//
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
console.log('
|
|
464
|
-
|
|
465
|
-
|
|
455
|
+
// 3. Connect relay in background (auth + MCP + SSE + relay)
|
|
456
|
+
connectInBackground()
|
|
457
|
+
|
|
458
|
+
// 4. Launch Claude Code (foreground) — unless connect-only mode
|
|
459
|
+
if (CONNECT_ONLY) {
|
|
460
|
+
console.log('[codepocket] 已连接,等待小程序...')
|
|
461
|
+
return
|
|
462
|
+
}
|
|
463
|
+
|
|
464
|
+
if (!hubBin) {
|
|
465
|
+
console.error('[codepocket] ✗ 找不到 Hub 二进制')
|
|
466
466
|
process.exit(1)
|
|
467
467
|
}
|
|
468
468
|
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
469
|
+
const child = spawn(hubBin, passThroughArgs, {
|
|
470
|
+
stdio: 'inherit',
|
|
471
|
+
env: { ...process.env, ...HOME_ENV },
|
|
472
|
+
})
|
|
473
|
+
child.on('exit', (code) => process.exit(code || 0))
|
|
473
474
|
}
|
|
474
475
|
|
|
475
|
-
|
|
476
|
-
console.error('[
|
|
476
|
+
run().catch((err) => {
|
|
477
|
+
console.error('[codepocket] ✗ 启动失败:', err.message)
|
|
477
478
|
process.exit(1)
|
|
478
479
|
})
|
package/bin/run.js
CHANGED
|
@@ -52,11 +52,11 @@ for (let i = 0; i < args.length; i++) {
|
|
|
52
52
|
const saved = loadConfig()
|
|
53
53
|
if (relayKey) {
|
|
54
54
|
// New key provided — save it
|
|
55
|
-
saveConfig({ ...saved, relayKey, relayUrl: relayUrl || saved.relayUrl || '
|
|
55
|
+
saveConfig({ ...saved, relayKey, relayUrl: relayUrl || saved.relayUrl || '' })
|
|
56
56
|
} else {
|
|
57
57
|
relayKey = saved.relayKey || ''
|
|
58
58
|
}
|
|
59
|
-
if (!relayUrl) relayUrl = saved.relayUrl || '
|
|
59
|
+
if (!relayUrl) relayUrl = saved.relayUrl || ''
|
|
60
60
|
|
|
61
61
|
let jwt = ''
|
|
62
62
|
let relayWs = null
|
|
@@ -199,7 +199,7 @@ function handleRelayMessage(msg) {
|
|
|
199
199
|
case 'register-error': {
|
|
200
200
|
console.error(` [!] ${msg.error}`)
|
|
201
201
|
console.error(' 请检查 key 是否正确')
|
|
202
|
-
console.error('
|
|
202
|
+
console.error(' 请在小程序中查看 Key')
|
|
203
203
|
break
|
|
204
204
|
}
|
|
205
205
|
}
|
|
@@ -258,7 +258,7 @@ async function main() {
|
|
|
258
258
|
console.error(' codepocket --key YOUR_KEY')
|
|
259
259
|
console.error()
|
|
260
260
|
console.error(' 获取 key:')
|
|
261
|
-
console.error('
|
|
261
|
+
console.error(' 在 CodePocket 小程序中获取 Key')
|
|
262
262
|
console.error()
|
|
263
263
|
console.error(' 或设置环境变量:')
|
|
264
264
|
console.error(' export RELAY_KEY=xxx')
|