@tina_summer/codepocket 2.2.4 → 2.2.7

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 +155 -42
  2. package/package.json +1 -1
package/bin/codepocket.js CHANGED
@@ -98,9 +98,13 @@ function findHubBin() {
98
98
  return null
99
99
  }
100
100
 
101
- function isHubRunning(hubUrl) {
101
+ async 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 controller = new AbortController()
104
+ const timer = setTimeout(() => controller.abort(), 2000)
105
+ const res = await fetch(`${hubUrl}/api/sessions`, { signal: controller.signal })
106
+ clearTimeout(timer)
107
+ return res.status > 0 // Any HTTP response means hub is up
104
108
  } catch { return false }
105
109
  }
106
110
 
@@ -264,27 +268,25 @@ function log(msg) {
264
268
 
265
269
  function waitForHub() {
266
270
  return new Promise((resolve) => {
267
- if (noHub || isHubRunning(hubUrl)) { resolve(); return }
271
+ if (noHub) { resolve(); return }
272
+ isHubRunning(hubUrl).then(up => { if (up) { resolve(); return } })
268
273
  let attempts = 0
269
274
  const check = setInterval(() => {
270
275
  attempts++
271
- if (isHubRunning(hubUrl)) {
272
- clearInterval(check)
273
- resolve()
274
- } else if (attempts > 30) {
275
- clearInterval(check)
276
- resolve()
277
- }
276
+ isHubRunning(hubUrl).then(up => {
277
+ if (up) { clearInterval(check); resolve() }
278
+ else if (attempts > 30) { clearInterval(check); resolve() }
279
+ })
278
280
  }, 1000)
279
281
  })
280
282
  }
281
283
 
282
- function startHub(hubBin) {
283
- return new Promise((resolve) => {
284
- if (noHub) { resolve(); return }
285
- if (isHubRunning(hubUrl)) { resolve(); return }
286
- if (!hubBin) { resolve(); return }
284
+ async function startHub(hubBin) {
285
+ if (noHub) return
286
+ if (await isHubRunning(hubUrl)) return
287
+ if (!hubBin) return
287
288
 
289
+ return new Promise((resolve) => {
288
290
  const hub = spawn(hubBin, ['hub', 'start'], {
289
291
  stdio: ['ignore', 'pipe', 'pipe'],
290
292
  detached: false,
@@ -301,8 +303,8 @@ function startHub(hubBin) {
301
303
  }
302
304
  })
303
305
 
304
- setTimeout(() => {
305
- if (!started && isHubRunning(hubUrl)) { started = true }
306
+ setTimeout(async () => {
307
+ if (!started && await isHubRunning(hubUrl)) { started = true }
306
308
  resolve()
307
309
  }, 8000)
308
310
 
@@ -405,10 +407,12 @@ function connectRelay() {
405
407
  break
406
408
  }
407
409
  case 'rest-request': {
410
+ log(`[DEBUG:relay] rest-request: ${msg.method} ${msg.path}`)
408
411
  forwardToHub(msg.requestId, msg.method, msg.path, msg.body)
409
412
  break
410
413
  }
411
414
  case 'auth-request': {
415
+ log(`[DEBUG:relay] auth-request`)
412
416
  handleAuthRequest(msg.requestId, msg.accessToken)
413
417
  break
414
418
  }
@@ -421,10 +425,12 @@ function connectRelay() {
421
425
  break
422
426
  }
423
427
  case 'spawn-session': {
428
+ log(`[DEBUG:relay] >>> spawn-session received, directory=${msg.directory}`)
424
429
  handleSpawnSession(msg.requestId, msg.directory)
425
430
  break
426
431
  }
427
432
  case 'resume-session': {
433
+ log(`[DEBUG:relay] >>> resume-session received, sessionId=${msg.sessionId}`)
428
434
  handleResumeSession(msg.requestId, msg.sessionId)
429
435
  break
430
436
  }
@@ -506,11 +512,17 @@ async function handleAuthRequest(requestId, accessToken) {
506
512
  }
507
513
 
508
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
+
509
519
  if (!hubBin) {
520
+ log(`[DEBUG:spawn] FAIL: hubBin is null`)
510
521
  sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Hub binary not found' })
511
522
  return
512
523
  }
513
524
  if (!directory || typeof directory !== 'string') {
525
+ log(`[DEBUG:spawn] FAIL: directory invalid`)
514
526
  sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Directory is required' })
515
527
  return
516
528
  }
@@ -518,76 +530,139 @@ async function handleSpawnSession(requestId, directory) {
518
530
  // Expand ~ to home directory
519
531
  directory = directory.replace(/^~/, os.homedir())
520
532
 
521
- log(`[codepocket] Spawning session in: ${directory}`)
533
+ log(`[DEBUG:spawn] Expanded directory: ${directory}`)
522
534
 
523
535
  try {
524
- const child = spawn(hubBin, ['--path', directory], {
525
- stdio: 'ignore',
536
+ const spawnArgs = ['--path', directory]
537
+ log(`[DEBUG:spawn] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
538
+
539
+ const child = spawn(hubBin, spawnArgs, {
540
+ stdio: ['ignore', 'pipe', 'pipe'],
526
541
  detached: true,
527
542
  env: { ...process.env, ...HOME_ENV },
528
543
  })
544
+ log(`[DEBUG:spawn] Process spawned, PID=${child.pid}`)
545
+ let spawnStderr = ''
546
+ child.stderr.on('data', (d) => {
547
+ const text = d.toString().trim()
548
+ if (text) {
549
+ spawnStderr += text + '\n'
550
+ log(`[DEBUG:spawn] stderr: ${text.slice(0, 500)}`)
551
+ }
552
+ })
553
+ child.stdout.on('data', (d) => {
554
+ const text = d.toString().trim()
555
+ if (text) log(`[DEBUG:spawn] stdout: ${text.slice(0, 500)}`)
556
+ })
529
557
  child.unref()
530
558
  child.on('error', (err) => {
531
- log(`[codepocket] Spawn process error: ${err.message}`)
559
+ log(`[DEBUG:spawn] Process error: ${err.message}`)
560
+ })
561
+ child.on('exit', (code, signal) => {
562
+ log(`[DEBUG:spawn] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
563
+ if (spawnStderr) log(`[DEBUG:spawn] Full stderr:\n${spawnStderr.slice(0, 2000)}`)
532
564
  })
533
565
 
566
+ // Refresh JWT before polling
567
+ log(`[DEBUG:spawn] Refreshing JWT...`)
568
+ try {
569
+ const token = await findHubToken()
570
+ jwt = await authenticateHub(token)
571
+ log(`[DEBUG:spawn] JWT refreshed OK`)
572
+ } catch (err) {
573
+ log(`[DEBUG:spawn] JWT refresh failed: ${err.message}`)
574
+ }
575
+
534
576
  // Wait for session to be created by polling /sessions
577
+ const spawnTime = Date.now()
535
578
  let sessionId = null
579
+ let sessionActive = false
536
580
  for (let i = 0; i < 30; i++) {
537
581
  await new Promise(r => setTimeout(r, 1000))
538
582
  try {
539
- const res = await fetch(`${hubUrl}/api/sessions`, {
583
+ let res = await fetch(`${hubUrl}/api/sessions`, {
540
584
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
541
585
  })
586
+ // Refresh JWT on 401
587
+ if (res.status === 401) {
588
+ log(`[DEBUG:spawn] Poll #${i + 1}: got 401, refreshing JWT...`)
589
+ try {
590
+ const token = await findHubToken()
591
+ jwt = await authenticateHub(token)
592
+ res = await fetch(`${hubUrl}/api/sessions`, {
593
+ headers: { Authorization: `Bearer ${jwt}` },
594
+ })
595
+ } catch (err) {
596
+ log(`[DEBUG:spawn] JWT refresh on 401 failed: ${err.message}`)
597
+ }
598
+ }
542
599
  const data = await res.json()
543
600
  const sessions = data.sessions || (Array.isArray(data) ? data : [])
601
+ log(`[DEBUG:spawn] Poll #${i + 1}: ${sessions.length} sessions, status=${res.status}`)
602
+
603
+ // Match by path AND updated after spawn (avoid stale sessions)
544
604
  const match = sessions.find(s =>
545
605
  s.metadata?.path === directory && s.id
606
+ && (!s.updatedAt || s.updatedAt * 1000 >= spawnTime - 5000)
546
607
  )
547
608
  if (match) {
548
609
  sessionId = match.id
549
- break
610
+ sessionActive = !!match.active
611
+ log(`[DEBUG:spawn] Poll #${i + 1}: FOUND session=${sessionId}, active=${sessionActive}`)
612
+ if (sessionActive) break // found and active, done
613
+ // Session exists but not yet active — keep polling
550
614
  }
551
- } catch {}
615
+ } catch (err) {
616
+ log(`[DEBUG:spawn] Poll #${i + 1}: fetch error: ${err.message}`)
617
+ }
552
618
  }
553
619
 
554
620
  if (sessionId) {
555
- log(`[codepocket] Session created: ${sessionId}`)
621
+ log(`[DEBUG:spawn] RESULT: sessionId=${sessionId}, active=${sessionActive}`)
556
622
  } else {
557
- log(`[codepocket] Session not found after polling, directory=${directory}`)
623
+ log(`[DEBUG:spawn] RESULT: session NOT FOUND after 30 polls, directory=${directory}`)
558
624
  }
559
625
  sendSpawnResult(requestId, sessionId)
560
626
  } catch (err) {
561
- console.error(`[codepocket] Spawn failed: ${err.message}`)
627
+ log(`[DEBUG:spawn] EXCEPTION: ${err.message}`)
562
628
  sendSpawnResult(requestId, null, err.message)
563
629
  }
564
630
  }
565
631
 
566
632
  async function handleResumeSession(requestId, sessionId) {
633
+ log(`[DEBUG:resume] === START resume-session ===`)
634
+ log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
635
+ log(`[DEBUG:resume] hubBin=${hubBin}, hubUrl=${hubUrl}, jwt=${jwt ? 'set' : 'EMPTY'}`)
636
+
567
637
  if (!hubBin) {
638
+ log(`[DEBUG:resume] FAIL: hubBin is null`)
568
639
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' })
569
640
  return
570
641
  }
571
642
  if (!sessionId) {
643
+ log(`[DEBUG:resume] FAIL: sessionId is empty`)
572
644
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' })
573
645
  return
574
646
  }
575
647
 
576
- log(`[codepocket] Resuming session: ${sessionId}`)
577
-
578
648
  try {
579
649
  // 1. Fetch session metadata from Hub
650
+ log(`[DEBUG:resume] Fetching session metadata...`)
580
651
  let res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
581
652
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
582
653
  })
654
+ log(`[DEBUG:resume] Metadata fetch status=${res.status}`)
583
655
  if (res.status === 401) {
656
+ log(`[DEBUG:resume] Got 401, refreshing JWT...`)
584
657
  const token = await findHubToken()
585
658
  jwt = await authenticateHub(token)
586
659
  res = await fetch(`${hubUrl}/api/sessions/${sessionId}`, {
587
660
  headers: { Authorization: `Bearer ${jwt}` },
588
661
  })
662
+ log(`[DEBUG:resume] Retry status=${res.status}`)
589
663
  }
590
664
  if (!res.ok) {
665
+ log(`[DEBUG:resume] FAIL: metadata fetch returned ${res.status}`)
591
666
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` })
592
667
  return
593
668
  }
@@ -596,7 +671,11 @@ async function handleResumeSession(requestId, sessionId) {
596
671
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
597
672
  let claudeSessionId = session.metadata?.agentSessionId || session.metadata?.claudeSessionId
598
673
 
674
+ log(`[DEBUG:resume] Session metadata: directory=${directory}, claudeSessionId=${claudeSessionId || 'NOT SET'}`)
675
+ log(`[DEBUG:resume] Full metadata: ${JSON.stringify(session.metadata || {})}`)
676
+
599
677
  if (!directory) {
678
+ log(`[DEBUG:resume] FAIL: no directory in metadata`)
600
679
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
601
680
  return
602
681
  }
@@ -605,23 +684,41 @@ async function handleResumeSession(requestId, sessionId) {
605
684
  if (!claudeSessionId) {
606
685
  claudeSessionId = findClaudeSessionFile(directory)
607
686
  if (claudeSessionId) {
608
- log(`[codepocket] claudeSessionId not in metadata, found session file: ${claudeSessionId}`)
687
+ log(`[DEBUG:resume] claudeSessionId resolved from file scan: ${claudeSessionId}`)
609
688
  } else {
610
- log(`[codepocket] claudeSessionId not in metadata and no session file found, using Hub session ID as fallback`)
689
+ log(`[DEBUG:resume] No session file found, using Hub session ID as fallback`)
611
690
  claudeSessionId = sessionId
612
691
  }
613
692
  }
614
693
 
615
694
  // 2. Spawn with --resume
616
- log(`[codepocket] Spawning resume: --path ${directory} --resume ${claudeSessionId}`)
617
- const child = spawn(hubBin, ['--path', directory, '--resume', claudeSessionId], {
618
- stdio: 'ignore',
695
+ const spawnArgs = ['--path', directory, '--resume', claudeSessionId]
696
+ log(`[DEBUG:resume] Spawning: ${hubBin} ${spawnArgs.join(' ')}`)
697
+ const child = spawn(hubBin, spawnArgs, {
698
+ stdio: ['ignore', 'pipe', 'pipe'],
619
699
  detached: true,
620
700
  env: { ...process.env, ...HOME_ENV },
621
701
  })
702
+ log(`[DEBUG:resume] Process spawned, PID=${child.pid}`)
703
+ let resumeStderr = ''
704
+ child.stderr.on('data', (d) => {
705
+ const text = d.toString().trim()
706
+ if (text) {
707
+ resumeStderr += text + '\n'
708
+ log(`[DEBUG:resume] stderr: ${text.slice(0, 500)}`)
709
+ }
710
+ })
711
+ child.stdout.on('data', (d) => {
712
+ const text = d.toString().trim()
713
+ if (text) log(`[DEBUG:resume] stdout: ${text.slice(0, 500)}`)
714
+ })
622
715
  child.unref()
623
716
  child.on('error', (err) => {
624
- log(`[codepocket] Resume spawn process error: ${err.message}`)
717
+ log(`[DEBUG:resume] Process error: ${err.message}`)
718
+ })
719
+ child.on('exit', (code, signal) => {
720
+ log(`[DEBUG:resume] Process exited: code=${code}, signal=${signal}, PID=${child.pid}`)
721
+ if (resumeStderr) log(`[DEBUG:resume] Full stderr:\n${resumeStderr.slice(0, 2000)}`)
625
722
  })
626
723
 
627
724
  // 3. Poll for session to become active
@@ -635,15 +732,21 @@ async function handleResumeSession(requestId, sessionId) {
635
732
  })
636
733
  const pollData = await pollRes.json()
637
734
  const sessions = pollData.sessions || (Array.isArray(pollData) ? pollData : [])
735
+ if (i === 0 || sessions.find(s => s.metadata?.path === directory)) {
736
+ 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(', ')}`)
737
+ }
638
738
  const match = sessions.find(s =>
639
739
  s.metadata?.path === directory && s.active && s.id !== sessionId
640
740
  )
641
741
  if (match) {
642
742
  newSession = match
643
743
  resumed = true
744
+ log(`[DEBUG:resume] Poll #${i + 1}: FOUND active session=${match.id}`)
644
745
  break
645
746
  }
646
- } catch {}
747
+ } catch (err) {
748
+ log(`[DEBUG:resume] Poll #${i + 1}: fetch error: ${err.message}`)
749
+ }
647
750
  }
648
751
 
649
752
  if (resumed) {
@@ -653,17 +756,18 @@ async function handleResumeSession(requestId, sessionId) {
653
756
  method: 'DELETE',
654
757
  headers: jwt ? { Authorization: `Bearer ${jwt}` } : {},
655
758
  })
656
- log(`[codepocket] Deleted old session: ${sessionId}`)
759
+ log(`[DEBUG:resume] Deleted old session: ${sessionId}`)
657
760
  } catch (e) {
658
- log(`[codepocket] Failed to delete old session: ${e.message}`)
761
+ log(`[DEBUG:resume] Failed to delete old session: ${e.message}`)
659
762
  }
660
- log(`[codepocket] Session resumed: ${newSession.id} (replaced ${sessionId})`)
763
+ log(`[DEBUG:resume] RESULT: resumed=${newSession.id} (replaced ${sessionId})`)
661
764
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSession.id })
662
765
  } else {
766
+ log(`[DEBUG:resume] RESULT: no active session found after 30 polls`)
663
767
  sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
664
768
  }
665
769
  } catch (err) {
666
- console.error(`[codepocket] Resume failed: ${err.message}`)
770
+ log(`[DEBUG:resume] EXCEPTION: ${err.message}`)
667
771
  sendToRelay({ type: 'resume-session-result', requestId, success: false, error: err.message })
668
772
  }
669
773
  }
@@ -685,22 +789,31 @@ function handleListDir(requestId, dirPath) {
685
789
  // ── Background connect: auth + MCP + SSE + relay ──
686
790
 
687
791
  async function connectInBackground() {
792
+ log(`[DEBUG:bg] connectInBackground called, relayUrl=${relayUrl || 'EMPTY'}`)
688
793
  if (!relayUrl) {
794
+ log(`[DEBUG:bg] No relay URL configured, skipping background connect`)
689
795
  console.log('[codepocket] 未配置 Relay 地址,手机连接功能不可用')
690
796
  return
691
797
  }
692
798
  try {
693
799
  const token = await findHubToken()
694
800
  jwt = await authenticateHub(token)
695
- } catch {}
801
+ log(`[DEBUG:bg] JWT acquired OK`)
802
+ } catch (err) {
803
+ log(`[DEBUG:bg] JWT acquire failed: ${err.message}`)
804
+ }
696
805
 
697
806
  try {
698
807
  const mcpPort = await startMcpServer(sendToRelay)
699
808
  injectMcpConfig(mcpPort)
700
- } catch {}
809
+ log(`[DEBUG:bg] MCP server started on port ${mcpPort}`)
810
+ } catch (err) {
811
+ log(`[DEBUG:bg] MCP server failed: ${err.message}`)
812
+ }
701
813
 
702
814
  startSSE()
703
815
  connectRelay()
816
+ log(`[DEBUG:bg] Background connect complete`)
704
817
  }
705
818
 
706
819
  // ── Main ──
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.2.4",
3
+ "version": "2.2.7",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",