@tina_summer/codepocket 2.2.2 → 2.2.3

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
@@ -49,6 +49,48 @@ function injectMcpConfig(port) {
49
49
 
50
50
  // ── Helpers ──
51
51
 
52
+ /**
53
+ * Encode a directory path the same way Claude Code does:
54
+ * resolve() then replace non-alphanumeric with '-'
55
+ */
56
+ function encodeProjectPath(dir) {
57
+ return path.resolve(dir).replace(/[^a-zA-Z0-9]/g, '-')
58
+ }
59
+
60
+ /**
61
+ * Find the Claude Code session ID (.jsonl file) for a given working directory.
62
+ * Tries to match by directory encoding; falls back to most recent valid file.
63
+ */
64
+ function findClaudeSessionFile(directory) {
65
+ const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude')
66
+ const projectId = encodeProjectPath(directory)
67
+ const projectDir = path.join(claudeConfigDir, 'projects', projectId)
68
+
69
+ if (!fs.existsSync(projectDir)) return null
70
+
71
+ try {
72
+ const files = fs.readdirSync(projectDir)
73
+ .filter(f => f.endsWith('.jsonl'))
74
+ .map(f => {
75
+ const filePath = path.join(projectDir, f)
76
+ try {
77
+ const stat = fs.statSync(filePath)
78
+ // Check file has real content (at least one line with uuid)
79
+ const data = fs.readFileSync(filePath, 'utf-8').split('\n')
80
+ const hasContent = data.some(line => {
81
+ try { return typeof JSON.parse(line).uuid === 'string' }
82
+ catch { return false }
83
+ })
84
+ return { name: f.replace('.jsonl', ''), mtime: stat.mtime.getTime(), hasContent }
85
+ } catch { return null }
86
+ })
87
+ .filter(f => f && f.hasContent)
88
+ .sort((a, b) => b.mtime - a.mtime)
89
+
90
+ return files.length > 0 ? files[0].name : null
91
+ } catch { return null }
92
+ }
93
+
52
94
  function findHubBin() {
53
95
  const bundledBin = path.join(__dirname, '..', 'vendor', process.platform === 'win32' ? 'cpkt-hub.exe' : 'cpkt-hub')
54
96
  if (fs.existsSync(bundledBin)) return bundledBin
@@ -136,7 +178,7 @@ const CONNECT_ONLY = ['connect', 'c'].includes(args[0])
136
178
  const filteredArgs = CONNECT_ONLY ? args.slice(1) : args
137
179
 
138
180
  let hubUrl = process.env.CPKT_HUB_URL || process.env.HAPI_HUB_URL || 'http://127.0.0.1:3006'
139
- const DEFAULT_RELAY_URL = 'wss://bkstory.cn/ws'
181
+ const DEFAULT_RELAY_URL = ''
140
182
  let relayUrl = process.env.RELAY_WS_URL || process.env.RELAY_URL || DEFAULT_RELAY_URL
141
183
  let relayKey = process.env.RELAY_KEY || ''
142
184
  let noHub = false
@@ -388,6 +430,25 @@ function sendToRelay(msg) {
388
430
  if (relayWs?.readyState === WebSocket.OPEN) relayWs.send(JSON.stringify(msg))
389
431
  }
390
432
 
433
+ function sendSpawnResult(requestId, sessionId, error) {
434
+ const msg = error
435
+ ? { type: 'spawn-session-result', requestId, success: false, error }
436
+ : { type: 'spawn-session-result', requestId, success: true, sessionId }
437
+ // Retry sending if relay connection is temporarily down
438
+ if (relayWs?.readyState === WebSocket.OPEN) {
439
+ relayWs.send(JSON.stringify(msg))
440
+ } else {
441
+ log(`[codepocket] Relay not open, retrying spawn result in 2s...`)
442
+ setTimeout(() => {
443
+ if (relayWs?.readyState === WebSocket.OPEN) {
444
+ relayWs.send(JSON.stringify(msg))
445
+ } else {
446
+ log(`[codepocket] Failed to send spawn result, relay still down`)
447
+ }
448
+ }, 2000)
449
+ }
450
+ }
451
+
391
452
  async function doForwardToHub(requestId, method, p, body) {
392
453
  const init = {
393
454
  method,
@@ -444,23 +505,26 @@ async function handleSpawnSession(requestId, directory) {
444
505
 
445
506
  try {
446
507
  const child = spawn(hubBin, ['--path', directory], {
447
- stdio: ['ignore', 'pipe', 'pipe'],
508
+ stdio: 'ignore',
448
509
  detached: true,
449
510
  env: { ...process.env, ...HOME_ENV },
450
511
  })
451
512
  child.unref()
513
+ child.on('error', (err) => {
514
+ log(`[codepocket] Spawn process error: ${err.message}`)
515
+ })
452
516
 
453
517
  // Wait for session to be created by polling /sessions
454
518
  let sessionId = null
455
519
  for (let i = 0; i < 30; i++) {
456
520
  await new Promise(r => setTimeout(r, 1000))
457
521
  try {
458
- const res = await fetch(`${hubUrl}/sessions`, {
522
+ const res = await fetch(`${hubUrl}/api/sessions`, {
459
523
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
460
524
  })
461
- const sessions = await res.json()
462
- // Find the newest session with matching path
463
- const match = (Array.isArray(sessions) ? sessions : []).find(s =>
525
+ const data = await res.json()
526
+ const sessions = data.sessions || (Array.isArray(data) ? data : [])
527
+ const match = sessions.find(s =>
464
528
  s.metadata?.path === directory && s.id
465
529
  )
466
530
  if (match) {
@@ -472,14 +536,13 @@ async function handleSpawnSession(requestId, directory) {
472
536
 
473
537
  if (sessionId) {
474
538
  log(`[codepocket] Session created: ${sessionId}`)
475
- sendToRelay({ type: 'spawn-session-result', requestId, success: true, sessionId })
476
539
  } else {
477
- // Timeout but process started — might still be initializing
478
- sendToRelay({ type: 'spawn-session-result', requestId, success: true, sessionId: null, warning: 'Session initializing' })
540
+ log(`[codepocket] Session not found after polling, directory=${directory}`)
479
541
  }
542
+ sendSpawnResult(requestId, sessionId)
480
543
  } catch (err) {
481
544
  console.error(`[codepocket] Spawn failed: ${err.message}`)
482
- sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: err.message })
545
+ sendSpawnResult(requestId, null, err.message)
483
546
  }
484
547
  }
485
548
 
@@ -514,32 +577,47 @@ async function handleResumeSession(requestId, sessionId) {
514
577
  const data = await res.json()
515
578
  const session = data.session || data
516
579
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
517
- const claudeSessionId = session.metadata?.claudeSessionId || session.id
580
+ let claudeSessionId = session.metadata?.claudeSessionId
518
581
 
519
582
  if (!directory) {
520
583
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
521
584
  return
522
585
  }
523
586
 
587
+ // Fallback: if claudeSessionId not in metadata, scan for the session file directly
588
+ if (!claudeSessionId) {
589
+ claudeSessionId = findClaudeSessionFile(directory)
590
+ if (claudeSessionId) {
591
+ log(`[codepocket] claudeSessionId not in metadata, found session file: ${claudeSessionId}`)
592
+ } else {
593
+ log(`[codepocket] claudeSessionId not in metadata and no session file found, using Hub session ID as fallback`)
594
+ claudeSessionId = sessionId
595
+ }
596
+ }
597
+
524
598
  // 2. Spawn with --resume
525
599
  log(`[codepocket] Spawning resume: --path ${directory} --resume ${claudeSessionId}`)
526
600
  const child = spawn(hubBin, ['--path', directory, '--resume', claudeSessionId], {
527
- stdio: ['ignore', 'pipe', 'pipe'],
601
+ stdio: 'ignore',
528
602
  detached: true,
529
603
  env: { ...process.env, ...HOME_ENV },
530
604
  })
531
605
  child.unref()
606
+ child.on('error', (err) => {
607
+ log(`[codepocket] Resume spawn process error: ${err.message}`)
608
+ })
532
609
 
533
610
  // 3. Poll for session to become active
534
611
  let resumed = false
535
612
  for (let i = 0; i < 30; i++) {
536
613
  await new Promise(r => setTimeout(r, 1000))
537
614
  try {
538
- const pollRes = await fetch(`${hubUrl}/sessions`, {
615
+ const pollRes = await fetch(`${hubUrl}/api/sessions`, {
539
616
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
540
617
  })
541
- const sessions = await pollRes.json()
542
- const match = (Array.isArray(sessions) ? sessions : []).find(s =>
618
+ const pollData = await pollRes.json()
619
+ const sessions = pollData.sessions || (Array.isArray(pollData) ? pollData : [])
620
+ const match = sessions.find(s =>
543
621
  s.metadata?.path === directory && s.active
544
622
  )
545
623
  if (match) {
@@ -617,7 +695,7 @@ async function run() {
617
695
  }
618
696
  }
619
697
 
620
- // 1.5 Relay URL (default: wss://bkstory.cn/ws)
698
+ // 1.5 Relay URL (set RELAY_WS_URL env or --relay flag)
621
699
  if (!relayUrl) {
622
700
  relayUrl = DEFAULT_RELAY_URL
623
701
  }
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.2.2",
4
- "description": "CodePocket — 你的全能 AI 随身控制台",
3
+ "version": "2.2.3",
4
+ "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",
7
7
  "cpkt": "bin/codepocket.js"
package/vendor/cpkt-hub CHANGED
Binary file