@tina_summer/codepocket 2.2.2 → 2.2.4

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
@@ -220,6 +262,23 @@ function log(msg) {
220
262
 
221
263
  // ── Hub ──
222
264
 
265
+ function waitForHub() {
266
+ return new Promise((resolve) => {
267
+ if (noHub || isHubRunning(hubUrl)) { resolve(); return }
268
+ let attempts = 0
269
+ const check = setInterval(() => {
270
+ attempts++
271
+ if (isHubRunning(hubUrl)) {
272
+ clearInterval(check)
273
+ resolve()
274
+ } else if (attempts > 30) {
275
+ clearInterval(check)
276
+ resolve()
277
+ }
278
+ }, 1000)
279
+ })
280
+ }
281
+
223
282
  function startHub(hubBin) {
224
283
  return new Promise((resolve) => {
225
284
  if (noHub) { resolve(); return }
@@ -388,6 +447,25 @@ function sendToRelay(msg) {
388
447
  if (relayWs?.readyState === WebSocket.OPEN) relayWs.send(JSON.stringify(msg))
389
448
  }
390
449
 
450
+ function sendSpawnResult(requestId, sessionId, error) {
451
+ const msg = error
452
+ ? { type: 'spawn-session-result', requestId, success: false, error }
453
+ : { type: 'spawn-session-result', requestId, success: true, sessionId }
454
+ // Retry sending if relay connection is temporarily down
455
+ if (relayWs?.readyState === WebSocket.OPEN) {
456
+ relayWs.send(JSON.stringify(msg))
457
+ } else {
458
+ log(`[codepocket] Relay not open, retrying spawn result in 2s...`)
459
+ setTimeout(() => {
460
+ if (relayWs?.readyState === WebSocket.OPEN) {
461
+ relayWs.send(JSON.stringify(msg))
462
+ } else {
463
+ log(`[codepocket] Failed to send spawn result, relay still down`)
464
+ }
465
+ }, 2000)
466
+ }
467
+ }
468
+
391
469
  async function doForwardToHub(requestId, method, p, body) {
392
470
  const init = {
393
471
  method,
@@ -444,23 +522,26 @@ async function handleSpawnSession(requestId, directory) {
444
522
 
445
523
  try {
446
524
  const child = spawn(hubBin, ['--path', directory], {
447
- stdio: ['ignore', 'pipe', 'pipe'],
525
+ stdio: 'ignore',
448
526
  detached: true,
449
527
  env: { ...process.env, ...HOME_ENV },
450
528
  })
451
529
  child.unref()
530
+ child.on('error', (err) => {
531
+ log(`[codepocket] Spawn process error: ${err.message}`)
532
+ })
452
533
 
453
534
  // Wait for session to be created by polling /sessions
454
535
  let sessionId = null
455
536
  for (let i = 0; i < 30; i++) {
456
537
  await new Promise(r => setTimeout(r, 1000))
457
538
  try {
458
- const res = await fetch(`${hubUrl}/sessions`, {
539
+ const res = await fetch(`${hubUrl}/api/sessions`, {
459
540
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
460
541
  })
461
- const sessions = await res.json()
462
- // Find the newest session with matching path
463
- const match = (Array.isArray(sessions) ? sessions : []).find(s =>
542
+ const data = await res.json()
543
+ const sessions = data.sessions || (Array.isArray(data) ? data : [])
544
+ const match = sessions.find(s =>
464
545
  s.metadata?.path === directory && s.id
465
546
  )
466
547
  if (match) {
@@ -472,14 +553,13 @@ async function handleSpawnSession(requestId, directory) {
472
553
 
473
554
  if (sessionId) {
474
555
  log(`[codepocket] Session created: ${sessionId}`)
475
- sendToRelay({ type: 'spawn-session-result', requestId, success: true, sessionId })
476
556
  } else {
477
- // Timeout but process started — might still be initializing
478
- sendToRelay({ type: 'spawn-session-result', requestId, success: true, sessionId: null, warning: 'Session initializing' })
557
+ log(`[codepocket] Session not found after polling, directory=${directory}`)
479
558
  }
559
+ sendSpawnResult(requestId, sessionId)
480
560
  } catch (err) {
481
561
  console.error(`[codepocket] Spawn failed: ${err.message}`)
482
- sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: err.message })
562
+ sendSpawnResult(requestId, null, err.message)
483
563
  }
484
564
  }
485
565
 
@@ -514,35 +594,52 @@ async function handleResumeSession(requestId, sessionId) {
514
594
  const data = await res.json()
515
595
  const session = data.session || data
516
596
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
517
- const claudeSessionId = session.metadata?.claudeSessionId || session.id
597
+ let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
518
598
 
519
599
  if (!directory) {
520
600
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
521
601
  return
522
602
  }
523
603
 
604
+ // Fallback: if claudeSessionId not in metadata, scan for the session file directly
605
+ if (!claudeSessionId) {
606
+ claudeSessionId = findClaudeSessionFile(directory)
607
+ if (claudeSessionId) {
608
+ log(`[codepocket] claudeSessionId not in metadata, found session file: ${claudeSessionId}`)
609
+ } else {
610
+ log(`[codepocket] claudeSessionId not in metadata and no session file found, using Hub session ID as fallback`)
611
+ claudeSessionId = sessionId
612
+ }
613
+ }
614
+
524
615
  // 2. Spawn with --resume
525
616
  log(`[codepocket] Spawning resume: --path ${directory} --resume ${claudeSessionId}`)
526
617
  const child = spawn(hubBin, ['--path', directory, '--resume', claudeSessionId], {
527
- stdio: ['ignore', 'pipe', 'pipe'],
618
+ stdio: 'ignore',
528
619
  detached: true,
529
620
  env: { ...process.env, ...HOME_ENV },
530
621
  })
531
622
  child.unref()
623
+ child.on('error', (err) => {
624
+ log(`[codepocket] Resume spawn process error: ${err.message}`)
625
+ })
532
626
 
533
627
  // 3. Poll for session to become active
534
628
  let resumed = false
629
+ let newSession = null
535
630
  for (let i = 0; i < 30; i++) {
536
631
  await new Promise(r => setTimeout(r, 1000))
537
632
  try {
538
- const pollRes = await fetch(`${hubUrl}/sessions`, {
633
+ const pollRes = await fetch(`${hubUrl}/api/sessions`, {
539
634
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
540
635
  })
541
- const sessions = await pollRes.json()
542
- const match = (Array.isArray(sessions) ? sessions : []).find(s =>
543
- s.metadata?.path === directory && s.active
636
+ const pollData = await pollRes.json()
637
+ const sessions = pollData.sessions || (Array.isArray(pollData) ? pollData : [])
638
+ const match = sessions.find(s =>
639
+ s.metadata?.path === directory && s.active && s.id !== sessionId
544
640
  )
545
641
  if (match) {
642
+ newSession = match
546
643
  resumed = true
547
644
  break
548
645
  }
@@ -550,8 +647,18 @@ async function handleResumeSession(requestId, sessionId) {
550
647
  }
551
648
 
552
649
  if (resumed) {
553
- log(`[codepocket] Session resumed: ${sessionId}`)
554
- sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId })
650
+ // Delete the old inactive session to avoid duplicates
651
+ try {
652
+ await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
653
+ method: 'DELETE',
654
+ headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
655
+ })
656
+ log(`[codepocket] Deleted old session: ${sessionId}`)
657
+ } catch (e) {
658
+ log(`[codepocket] Failed to delete old session: ${e.message}`)
659
+ }
660
+ log(`[codepocket] Session resumed: ${newSession.id} (replaced ${sessionId})`)
661
+ sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSession.id })
555
662
  } else {
556
663
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
557
664
  }
@@ -602,6 +709,10 @@ async function run() {
602
709
 
603
710
  // 1. Key setup (interactive if first time)
604
711
  if (!relayKey) {
712
+ if (process.env.CODEPOCKET_DAEMON) {
713
+ console.error('[codepocket] ✗ 无 Key,请在前台运行 codepocket 配置')
714
+ process.exit(1)
715
+ }
605
716
  console.log('[codepocket] 首次使用,请输入 Key')
606
717
  console.log(' 在 CodePocket 小程序中获取 Key →')
607
718
  relayKey = await new Promise((resolve) => {
@@ -617,7 +728,7 @@ async function run() {
617
728
  }
618
729
  }
619
730
 
620
- // 1.5 Relay URL (default: wss://bkstory.cn/ws)
731
+ // 1.5 Relay URL (set RELAY_WS_URL env or --relay flag)
621
732
  if (!relayUrl) {
622
733
  relayUrl = DEFAULT_RELAY_URL
623
734
  }
@@ -627,20 +738,45 @@ async function run() {
627
738
  console.log('[codepocket] ✓ 配置已保存')
628
739
  }
629
740
 
630
- // 2. Start hub (quiet, wait for ready)
631
- if (!noHub) {
632
- await startHub(hubBin)
741
+ // 2. Daemon mode: full hub + relay setup
742
+ if (process.env.CODEPOCKET_DAEMON) {
743
+ if (!noHub) await startHub(hubBin)
744
+ connectInBackground()
745
+ console.log('[codepocket] ✓ 后台服务已就绪,等待小程序...')
746
+ return
633
747
  }
634
748
 
635
- // 3. Connect relay (auth + MCP + SSE + relay)
636
- connectInBackground()
637
-
638
- // 4. Daemon mode — just wait
639
- if (process.env.CODEPOCKET_DAEMON || CONNECT_ONLY) {
749
+ // 3. Connect-only mode (same as old daemon for manual use)
750
+ if (CONNECT_ONLY) {
751
+ if (!noHub) await startHub(hubBin)
752
+ connectInBackground()
640
753
  console.log('[codepocket] ✓ 已连接,等待小程序...')
641
754
  return
642
755
  }
643
756
 
757
+ // 4. Foreground: ensure daemon running, then just spawn Claude
758
+ if (!noHub) {
759
+ const daemonPid = checkRunning()
760
+ if (!daemonPid) {
761
+ // Auto-start daemon
762
+ fs.mkdirSync(LOG_DIR, { recursive: true })
763
+ const logFile = getLogFile()
764
+ const out = fs.openSync(logFile, 'a')
765
+ const daemonChild = spawn(process.argv[0], [process.argv[1], 'start'], {
766
+ stdio: ['ignore', out, out],
767
+ detached: true,
768
+ env: { ...process.env, CODEPOCKET_DAEMON: '1' },
769
+ })
770
+ daemonChild.unref()
771
+ fs.writeFileSync(PID_FILE, String(daemonChild.pid))
772
+ console.log(`[codepocket] ✓ 后台服务已启动 (PID ${daemonChild.pid})`)
773
+ } else {
774
+ console.log(`[codepocket] ✓ 后台服务运行中 (PID ${daemonPid})`)
775
+ }
776
+ // Wait for hub to be ready (started by daemon)
777
+ await waitForHub()
778
+ }
779
+
644
780
  // 5. Launch Claude Code (foreground)
645
781
  if (!hubBin) {
646
782
  console.error('[codepocket] ✗ 找不到 Hub 二进制')
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.4",
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