@tina_summer/codepocket 2.2.3 → 2.2.6

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.
Files changed (2) hide show
  1. package/bin/codepocket.js +178 -33
  2. package/package.json +1 -1
package/bin/codepocket.js CHANGED
@@ -100,7 +100,9 @@ function findHubBin() {
100
100
 
101
101
  function isHubRunning(hubUrl) {
102
102
  try {
103
- return execSync(`curl -s -o /dev/null -w "%{http_code}" ${hubUrl}/ 2>/dev/null`).toString().trim() === '200'
103
+ const code = execSync(`curl -s -o /dev/null -w "%{http_code}" --max-time 2 ${hubUrl}/api/sessions 2>/dev/null`).toString().trim()
104
+ // Any HTTP response (including 401) means the hub server is up
105
+ return /^\d{3}$/.test(code) && code !== '000'
104
106
  } catch { return false }
105
107
  }
106
108
 
@@ -262,6 +264,23 @@ function log(msg) {
262
264
 
263
265
  // ── Hub ──
264
266
 
267
+ function waitForHub() {
268
+ return new Promise((resolve) => {
269
+ if (noHub || isHubRunning(hubUrl)) { resolve(); return }
270
+ let attempts = 0
271
+ const check = setInterval(() => {
272
+ attempts++
273
+ if (isHubRunning(hubUrl)) {
274
+ clearInterval(check)
275
+ resolve()
276
+ } else if (attempts > 30) {
277
+ clearInterval(check)
278
+ resolve()
279
+ }
280
+ }, 1000)
281
+ })
282
+ }
283
+
265
284
  function startHub(hubBin) {
266
285
  return new Promise((resolve) => {
267
286
  if (noHub) { resolve(); return }
@@ -388,10 +407,12 @@ function connectRelay() {
388
407
  break
389
408
  }
390
409
  case 'rest-request': {
410
+ log(`[DEBUG:relay] rest-request: ${msg.method} ${msg.path}`)
391
411
  forwardToHub(msg.requestId, msg.method, msg.path, msg.body)
392
412
  break
393
413
  }
394
414
  case 'auth-request': {
415
+ log(`[DEBUG:relay] auth-request`)
395
416
  handleAuthRequest(msg.requestId, msg.accessToken)
396
417
  break
397
418
  }
@@ -404,10 +425,12 @@ function connectRelay() {
404
425
  break
405
426
  }
406
427
  case 'spawn-session': {
428
+ log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}`)
407
429
  handleSpawnSession(msg.requestId, msg.directory)
408
430
  break
409
431
  }
410
432
  case 'resume-session': {
433
+ log(`[DEBUG:relay] >>> resume-session received, sessionId=${msg.sessionId}`)
411
434
  handleResumeSession(msg.requestId, msg.sessionId)
412
435
  break
413
436
  }
@@ -489,11 +512,17 @@ async function handleAuthRequest(requestId, accessToken) {
489
512
  }
490
513
 
491
514
  async function handleSpawnSession(requestId, directory) {
515
+ log(`[DEBUG:spawn] === START spawn-session ===`)
516
+ log(`[DEBUG:spawn] requestId=${requestId}, raw directory=${directory}`)
517
+ log(`[DEBUG:spawn] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
518
+
492
519
  if (!hubBin) {
520
+ log(`[DEBUG:spawn] FAIL: hubBin is null`)
493
521
  sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Hub binary not found' })
494
522
  return
495
523
  }
496
524
  if (!directory || typeof directory !== 'string') {
525
+ log(`[DEBUG:spawn] FAIL: directory invalid`)
497
526
  sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Directory is required' })
498
527
  return
499
528
  }
@@ -501,85 +530,139 @@ async function handleSpawnSession(requestId, directory) {
501
530
  // Expand ~ to home directory
502
531
  directory = directory.replace(/^~/, os.homedir())
503
532
 
504
- log(`[codepocket] Spawning session in: ${directory}`)
533
+ log(`[DEBUG:spawn] Expanded directory: ${directory}`)
505
534
 
506
535
  try {
507
- const child = spawn(hubBin, ['--path', directory], {
536
+ const spawnArgs = ['--path', directory]
537
+ log(`[DEBUG:spawn] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
538
+
539
+ const child = spawn(hubBin, spawnArgs, {
508
540
  stdio: 'ignore',
509
541
  detached: true,
510
542
  env: { ...process.env, ...HOME_ENV },
511
543
  })
544
+ log(`[DEBUG:spawn] Process spawned, PID=${child.pid}`)
512
545
  child.unref()
513
546
  child.on('error', (err) => {
514
- log(`[codepocket] Spawn process error: ${err.message}`)
547
+ log(`[DEBUG:spawn] Process error: ${err.message}`)
548
+ })
549
+ child.on('exit', (code, signal) => {
550
+ log(`[DEBUG:spawn] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
515
551
  })
516
552
 
553
+ // Refresh JWT before polling
554
+ log(`[DEBUG:spawn] Refreshing JWT...`)
555
+ try {
556
+ const token = await findHubToken()
557
+ jwt = await authenticateHub(token)
558
+ log(`[DEBUG:spawn] JWT refreshed OK`)
559
+ } catch (err) {
560
+ log(`[DEBUG:spawn] JWT refresh failed: ${err.message}`)
561
+ }
562
+
517
563
  // Wait for session to be created by polling /sessions
564
+ const spawnTime = Date.now()
518
565
  let sessionId = null
566
+ let sessionActive = false
519
567
  for (let i = 0; i < 30; i++) {
520
568
  await new Promise(r => setTimeout(r, 1000))
521
569
  try {
522
- const res = await fetch(`${hubUrl}/api/sessions`, {
570
+ let res = await fetch(`${hubUrl}/api/sessions`, {
523
571
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
524
572
  })
573
+ // Refresh JWT on 401
574
+ if (res.status === 401) {
575
+ log(`[DEBUG:spawn] Poll #${i + 1}: got 401, refreshing JWT...`)
576
+ try {
577
+ const token = await findHubToken()
578
+ jwt = await authenticateHub(token)
579
+ res = await fetch(`${hubUrl}/api/sessions`, {
580
+ headers: { Authorization: `Bearer ${jwt}` },
581
+ })
582
+ } catch (err) {
583
+ log(`[DEBUG:spawn] JWT refresh on 401 failed: ${err.message}`)
584
+ }
585
+ }
525
586
  const data = await res.json()
526
587
  const sessions = data.sessions || (Array.isArray(data) ? data : [])
588
+ log(`[DEBUG:spawn] Poll #${i + 1}: ${sessions.length} sessions, status=${res.status}`)
589
+
590
+ // Match by path AND updated after spawn (avoid stale sessions)
527
591
  const match = sessions.find(s =>
528
592
  s.metadata?.path === directory && s.id
593
+ && (!s.updatedAt || s.updatedAt * 1000 >= spawnTime - 5000)
529
594
  )
530
595
  if (match) {
531
596
  sessionId = match.id
532
- break
597
+ sessionActive = !!match.active
598
+ log(`[DEBUG:spawn] Poll #${i + 1}: FOUND session=${sessionId}, active=${sessionActive}`)
599
+ if (sessionActive) break // found and active, done
600
+ // Session exists but not yet active — keep polling
533
601
  }
534
- } catch {}
602
+ } catch (err) {
603
+ log(`[DEBUG:spawn] Poll #${i + 1}: fetch error: ${err.message}`)
604
+ }
535
605
  }
536
606
 
537
607
  if (sessionId) {
538
- log(`[codepocket] Session created: ${sessionId}`)
608
+ log(`[DEBUG:spawn] RESULT: sessionId=${sessionId}, active=${sessionActive}`)
539
609
  } else {
540
- log(`[codepocket] Session not found after polling, directory=${directory}`)
610
+ log(`[DEBUG:spawn] RESULT: session NOT FOUND after 30 polls, directory=${directory}`)
541
611
  }
542
612
  sendSpawnResult(requestId, sessionId)
543
613
  } catch (err) {
544
- console.error(`[codepocket] Spawn failed: ${err.message}`)
614
+ log(`[DEBUG:spawn] EXCEPTION: ${err.message}`)
545
615
  sendSpawnResult(requestId, null, err.message)
546
616
  }
547
617
  }
548
618
 
549
619
  async function handleResumeSession(requestId, sessionId) {
620
+ log(`[DEBUG:resume] === START resume-session ===`)
621
+ log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
622
+ log(`[DEBUG:resume] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
623
+
550
624
  if (!hubBin) {
625
+ log(`[DEBUG:resume] FAIL: hubBin is null`)
551
626
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' })
552
627
  return
553
628
  }
554
629
  if (!sessionId) {
630
+ log(`[DEBUG:resume] FAIL: sessionId is empty`)
555
631
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' })
556
632
  return
557
633
  }
558
634
 
559
- log(`[codepocket] Resuming session: ${sessionId}`)
560
-
561
635
  try {
562
636
  // 1. Fetch session metadata from Hub
637
+ log(`[DEBUG:resume] Fetching session metadata...`)
563
638
  let res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
564
639
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
565
640
  })
641
+ log(`[DEBUG:resume] Metadata fetch status=${res.status}`)
566
642
  if (res.status === 401) {
643
+ log(`[DEBUG:resume] Got 401, refreshing JWT...`)
567
644
  const token = await findHubToken()
568
645
  jwt = await authenticateHub(token)
569
646
  res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
570
647
  headers: { Authorization: `Bearer ${jwt}` },
571
648
  })
649
+ log(`[DEBUG:resume] Retry status=${res.status}`)
572
650
  }
573
651
  if (!res.ok) {
652
+ log(`[DEBUG:resume] FAIL: metadata fetch returned ${res.status}`)
574
653
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` })
575
654
  return
576
655
  }
577
656
  const data = await res.json()
578
657
  const session = data.session || data
579
658
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
580
- let claudeSessionId = session.metadata?.claudeSessionId
659
+ let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
660
+
661
+ log(`[DEBUG:resume] Session metadata: directory=${directory}, claudeSessionId=${claudeSessionId || 'NOT SET'}`)
662
+ log(`[DEBUG:resume] Full metadata: ${JSON.stringify(session.metadata || {})}`)
581
663
 
582
664
  if (!directory) {
665
+ log(`[DEBUG:resume] FAIL: no directory in metadata`)
583
666
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
584
667
  return
585
668
  }
@@ -588,27 +671,33 @@ async function handleResumeSession(requestId, sessionId) {
588
671
  if (!claudeSessionId) {
589
672
  claudeSessionId = findClaudeSessionFile(directory)
590
673
  if (claudeSessionId) {
591
- log(`[codepocket] claudeSessionId not in metadata, found session file: ${claudeSessionId}`)
674
+ log(`[DEBUG:resume] claudeSessionId resolved from file scan: ${claudeSessionId}`)
592
675
  } else {
593
- log(`[codepocket] claudeSessionId not in metadata and no session file found, using Hub session ID as fallback`)
676
+ log(`[DEBUG:resume] No session file found, using Hub session ID as fallback`)
594
677
  claudeSessionId = sessionId
595
678
  }
596
679
  }
597
680
 
598
681
  // 2. Spawn with --resume
599
- log(`[codepocket] Spawning resume: --path ${directory} --resume ${claudeSessionId}`)
600
- const child = spawn(hubBin, ['--path', directory, '--resume', claudeSessionId], {
682
+ const spawnArgs = ['--path', directory, '--resume', claudeSessionId]
683
+ log(`[DEBUG:resume] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
684
+ const child = spawn(hubBin, spawnArgs, {
601
685
  stdio: 'ignore',
602
686
  detached: true,
603
687
  env: { ...process.env, ...HOME_ENV },
604
688
  })
689
+ log(`[DEBUG:resume] Process spawned, PID=${child.pid}`)
605
690
  child.unref()
606
691
  child.on('error', (err) => {
607
- log(`[codepocket] Resume spawn process error: ${err.message}`)
692
+ log(`[DEBUG:resume] Process error: ${err.message}`)
693
+ })
694
+ child.on('exit', (code, signal) => {
695
+ log(`[DEBUG:resume] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
608
696
  })
609
697
 
610
698
  // 3. Poll for session to become active
611
699
  let resumed = false
700
+ let newSession = null
612
701
  for (let i = 0; i < 30; i++) {
613
702
  await new Promise(r => setTimeout(r, 1000))
614
703
  try {
@@ -617,24 +706,42 @@ async function handleResumeSession(requestId, sessionId) {
617
706
  })
618
707
  const pollData = await pollRes.json()
619
708
  const sessions = pollData.sessions || (Array.isArray(pollData) ? pollData : [])
709
+ if (i === 0 || sessions.find(s => s.metadata?.path === directory)) {
710
+ log(`[DEBUG:resume] Poll #${i + 1}: ${sessions.length} sessions, matching path sessions: ${sessions.filter(s => s.metadata?.path === directory).map(s => `${s.id}(active=${s.active})`).join(', ')}`)
711
+ }
620
712
  const match = sessions.find(s =>
621
- s.metadata?.path === directory && s.active
713
+ s.metadata?.path === directory && s.active && s.id !== sessionId
622
714
  )
623
715
  if (match) {
716
+ newSession = match
624
717
  resumed = true
718
+ log(`[DEBUG:resume] Poll #${i + 1}: FOUND active session=${match.id}`)
625
719
  break
626
720
  }
627
- } catch {}
721
+ } catch (err) {
722
+ log(`[DEBUG:resume] Poll #${i + 1}: fetch error: ${err.message}`)
723
+ }
628
724
  }
629
725
 
630
726
  if (resumed) {
631
- log(`[codepocket] Session resumed: ${sessionId}`)
632
- sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId })
727
+ // Delete the old inactive session to avoid duplicates
728
+ try {
729
+ await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
730
+ method: 'DELETE',
731
+ headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
732
+ })
733
+ log(`[DEBUG:resume] Deleted old session: ${sessionId}`)
734
+ } catch (e) {
735
+ log(`[DEBUG:resume] Failed to delete old session: ${e.message}`)
736
+ }
737
+ log(`[DEBUG:resume] RESULT: resumed=${newSession.id} (replaced ${sessionId})`)
738
+ sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSession.id })
633
739
  } else {
740
+ log(`[DEBUG:resume] RESULT: no active session found after 30 polls`)
634
741
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
635
742
  }
636
743
  } catch (err) {
637
- console.error(`[codepocket] Resume failed: ${err.message}`)
744
+ log(`[DEBUG:resume] EXCEPTION: ${err.message}`)
638
745
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: err.message })
639
746
  }
640
747
  }
@@ -656,22 +763,31 @@ function handleListDir(requestId, dirPath) {
656
763
  // ── Background connect: auth + MCP + SSE + relay ──
657
764
 
658
765
  async function connectInBackground() {
766
+ log(`[DEBUG:bg] connectInBackground called, relayUrl=${relayUrl || 'EMPTY'}`)
659
767
  if (!relayUrl) {
768
+ log(`[DEBUG:bg] No relay URL configured, skipping background connect`)
660
769
  console.log('[codepocket] 未配置 Relay 地址,手机连接功能不可用')
661
770
  return
662
771
  }
663
772
  try {
664
773
  const token = await findHubToken()
665
774
  jwt = await authenticateHub(token)
666
- } catch {}
775
+ log(`[DEBUG:bg] JWT acquired OK`)
776
+ } catch (err) {
777
+ log(`[DEBUG:bg] JWT acquire failed: ${err.message}`)
778
+ }
667
779
 
668
780
  try {
669
781
  const mcpPort = await startMcpServer(sendToRelay)
670
782
  injectMcpConfig(mcpPort)
671
- } catch {}
783
+ log(`[DEBUG:bg] MCP server started on port ${mcpPort}`)
784
+ } catch (err) {
785
+ log(`[DEBUG:bg] MCP server failed: ${err.message}`)
786
+ }
672
787
 
673
788
  startSSE()
674
789
  connectRelay()
790
+ log(`[DEBUG:bg] Background connect complete`)
675
791
  }
676
792
 
677
793
  // ── Main ──
@@ -680,6 +796,10 @@ async function run() {
680
796
 
681
797
  // 1. Key setup (interactive if first time)
682
798
  if (!relayKey) {
799
+ if (process.env.CODEPOCKET_DAEMON) {
800
+ console.error('[codepocket] ✗ 无 Key,请在前台运行 codepocket 配置')
801
+ process.exit(1)
802
+ }
683
803
  console.log('[codepocket] 首次使用,请输入 Key')
684
804
  console.log(' 在 CodePocket 小程序中获取 Key →')
685
805
  relayKey = await new Promise((resolve) => {
@@ -705,20 +825,45 @@ async function run() {
705
825
  console.log('[codepocket] ✓ 配置已保存')
706
826
  }
707
827
 
708
- // 2. Start hub (quiet, wait for ready)
709
- if (!noHub) {
710
- await startHub(hubBin)
828
+ // 2. Daemon mode: full hub + relay setup
829
+ if (process.env.CODEPOCKET_DAEMON) {
830
+ if (!noHub) await startHub(hubBin)
831
+ connectInBackground()
832
+ console.log('[codepocket] ✓ 后台服务已就绪,等待小程序...')
833
+ return
711
834
  }
712
835
 
713
- // 3. Connect relay (auth + MCP + SSE + relay)
714
- connectInBackground()
715
-
716
- // 4. Daemon mode — just wait
717
- if (process.env.CODEPOCKET_DAEMON || CONNECT_ONLY) {
836
+ // 3. Connect-only mode (same as old daemon for manual use)
837
+ if (CONNECT_ONLY) {
838
+ if (!noHub) await startHub(hubBin)
839
+ connectInBackground()
718
840
  console.log('[codepocket] ✓ 已连接,等待小程序...')
719
841
  return
720
842
  }
721
843
 
844
+ // 4. Foreground: ensure daemon running, then just spawn Claude
845
+ if (!noHub) {
846
+ const daemonPid = checkRunning()
847
+ if (!daemonPid) {
848
+ // Auto-start daemon
849
+ fs.mkdirSync(LOG_DIR, { recursive: true })
850
+ const logFile = getLogFile()
851
+ const out = fs.openSync(logFile, 'a')
852
+ const daemonChild = spawn(process.argv[0], [process.argv[1], 'start'], {
853
+ stdio: ['ignore', out, out],
854
+ detached: true,
855
+ env: { ...process.env, CODEPOCKET_DAEMON: '1' },
856
+ })
857
+ daemonChild.unref()
858
+ fs.writeFileSync(PID_FILE, String(daemonChild.pid))
859
+ console.log(`[codepocket] ✓ 后台服务已启动 (PID ${daemonChild.pid})`)
860
+ } else {
861
+ console.log(`[codepocket] ✓ 后台服务运行中 (PID ${daemonPid})`)
862
+ }
863
+ // Wait for hub to be ready (started by daemon)
864
+ await waitForHub()
865
+ }
866
+
722
867
  // 5. Launch Claude Code (foreground)
723
868
  if (!hubBin) {
724
869
  console.error('[codepocket] ✗ 找不到 Hub 二进制')
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.2.3",
3
+ "version": "2.2.6",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",