@tina_summer/codepocket 2.6.4 → 2.6.8

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
@@ -18,7 +18,6 @@ const crypto = require('crypto')
18
18
  const nacl = require('tweetnacl')
19
19
  const { HttpsProxyAgent } = require('https-proxy-agent')
20
20
  const { startMcpServer, handlePhoneActionResponse: onPhoneActionResponse } = require('../src/mcp-server')
21
- const { runTestCli } = require('../src/mcp-client')
22
21
 
23
22
  // ── Proxy detection ──
24
23
 
@@ -226,12 +225,6 @@ async function isHubRunning(hubUrl) {
226
225
  } catch { return false }
227
226
  }
228
227
 
229
- // 'test' subcommand — standalone
230
- if (args[0] === 'test') {
231
- runTestCli(args.slice(1))
232
- return
233
- }
234
-
235
228
  // ── Background mode helpers ──
236
229
 
237
230
  const PID_FILE = path.join(CONFIG_DIR, 'codepocket.pid')
@@ -336,6 +329,11 @@ if (args[0] === 'status') {
336
329
  const CONNECT_ONLY = ['connect', 'c'].includes(args[0])
337
330
  const filteredArgs = CONNECT_ONLY ? args.slice(1) : args
338
331
 
332
+ if (filteredArgs.includes('--version') || filteredArgs.includes('-v')) {
333
+ console.log(require('../package.json').version)
334
+ process.exit(0)
335
+ }
336
+
339
337
  let hubUrl = process.env.CPKT_HUB_URL || process.env.HAPI_HUB_URL || 'http://127.0.0.1:3006'
340
338
  // Must match miniprogram/utils/config.local.js default — otherwise new users running
341
339
  // `codepocket --key XXX` (no --relay) silently fail to connect.
@@ -400,6 +398,8 @@ if (args[0] === 'start') {
400
398
  let jwt = ''
401
399
  let relayWs = null
402
400
  let relayPingInterval = null
401
+ let relayLastPong = 0
402
+ let _relayOpenedAt = 0
403
403
  let hubBin = findHubBin()
404
404
  let relayConnectFailures = 0
405
405
 
@@ -545,10 +545,16 @@ async function startSSE() {
545
545
  // The relay only forwards e2ePubKey + opaque `enc` envelopes; it cannot decrypt.
546
546
  // Nonces are counter-based with a direction tag to avoid reuse across directions
547
547
  // under the same shared key: connector uses 0xFF prefix, phone uses 0x00.
548
+ //
549
+ // MULTI-CLIENT: several devices (phone 体验版/正式版, DevTools) may pair with the
550
+ // same key. Each client has its own keypair, so we keep ONE shared key PER client
551
+ // pubkey. A single global key would let only the last-paired client decrypt —
552
+ // every other device silently received `data: undefined`.
548
553
 
549
- let e2eKeypair = null // { publicKey, secretKey } Uint8Arrays (X25519)
550
- let e2eSharedKey = null // Uint8Array(32), set when peer pubkey arrives
551
- let e2eNonceCounter = 0
554
+ let e2eKeypair = null // { publicKey, secretKey } Uint8Arrays (X25519)
555
+ const e2eClientKeys = new Map() // clientPubKeyB64 -> Uint8Array(32) shared key
556
+ const e2eNonceCounters = new Map() // clientPubKeyB64 -> counter (connector→phone)
557
+ const e2ePeerByRequest = new Map() // requestId -> clientPubKeyB64 (route responses)
552
558
 
553
559
  function ensureE2EKeypair() {
554
560
  if (e2eKeypair) return e2eKeypair
@@ -566,58 +572,66 @@ function setPeerE2EPubKey(peerPubKeyB64) {
566
572
  try {
567
573
  const peerPub = Buffer.from(peerPubKeyB64, 'base64')
568
574
  if (peerPub.length !== 32) return
569
- e2eSharedKey = nacl.box.before(peerPub, ensureE2EKeypair().secretKey)
570
- e2eNonceCounter = 0
571
- log('[codepocket] ✓ E2E 加密通道已建立')
575
+ e2eClientKeys.set(peerPubKeyB64, nacl.box.before(peerPub, ensureE2EKeypair().secretKey))
576
+ log(`[codepocket] ✓ E2E 加密通道已建立 (client ${peerPubKeyB64.slice(0, 6)}..., 共 ${e2eClientKeys.size} 个客户端)`)
572
577
  } catch (e) {
573
578
  log(`[codepocket] E2E 密钥协商失败: ${e.message}`)
574
579
  }
575
580
  }
576
581
 
577
- function nextNonce() {
578
- e2eNonceCounter++
582
+ function nextNonce(pubKeyB64) {
583
+ const c = (e2eNonceCounters.get(pubKeyB64) || 0) + 1
584
+ e2eNonceCounters.set(pubKeyB64, c)
579
585
  const n = new Uint8Array(24)
580
586
  n[0] = 0xFF // connector→phone direction tag
581
- let c = e2eNonceCounter
582
- for (let i = 6; i >= 1; i--) { n[i] = c & 0xff; c = Math.floor(c / 256) }
587
+ let rest = c
588
+ for (let i = 6; i >= 1; i--) { n[i] = rest & 0xff; rest = Math.floor(rest / 256) }
583
589
  return n
584
590
  }
585
591
 
586
- function e2eEncrypt(obj) {
587
- if (!e2eSharedKey) return undefined
592
+ // Encrypt for ONE specific client. Unknown peer → undefined (caller sends plaintext).
593
+ function e2eEncryptFor(pubKeyB64, obj) {
594
+ const key = e2eClientKeys.get(pubKeyB64)
595
+ if (!key) return undefined
588
596
  try {
589
597
  const msgBytes = Buffer.from(JSON.stringify(obj), 'utf8')
590
- const nonce = nextNonce()
591
- const cipher = nacl.secretbox(msgBytes, nonce, e2eSharedKey)
598
+ const nonce = nextNonce(pubKeyB64)
599
+ const cipher = nacl.secretbox(msgBytes, nonce, key)
592
600
  if (!cipher) return undefined
593
601
  return { n: Buffer.from(nonce).toString('base64'), c: Buffer.from(cipher).toString('base64') }
594
602
  } catch { return undefined }
595
603
  }
596
604
 
605
+ // Inbound may come from ANY connected client — try every known key.
606
+ // Returns { content, from: clientPubKeyB64 } or undefined.
597
607
  function e2eDecrypt(envelope) {
598
608
  if (!envelope || typeof envelope !== 'object') return undefined
599
609
  if (typeof envelope.n !== 'string' || typeof envelope.c !== 'string') return undefined
600
- if (!e2eSharedKey) return undefined
610
+ if (e2eClientKeys.size === 0) return undefined
601
611
  try {
602
612
  const nonce = new Uint8Array(Buffer.from(envelope.n, 'base64'))
603
613
  const cipher = new Uint8Array(Buffer.from(envelope.c, 'base64'))
604
- const plain = nacl.secretbox.open(cipher, nonce, e2eSharedKey)
605
- if (!plain) return undefined
606
- return JSON.parse(Buffer.from(plain).toString('utf8'))
607
- } catch { return undefined }
614
+ for (const [pub, key] of e2eClientKeys) {
615
+ const plain = nacl.secretbox.open(cipher, nonce, key)
616
+ if (plain) return { content: JSON.parse(Buffer.from(plain).toString('utf8')), from: pub }
617
+ }
618
+ } catch {}
619
+ return undefined
608
620
  }
609
621
 
610
622
  // Pack a message for sending: moves sensitive fields into an `enc` envelope.
611
623
  // Routing fields (type, requestId, actionId, success, status, ok) stay plaintext.
612
- function encryptMessage(msg) {
613
- if (!e2eSharedKey) return msg
624
+ // peerPubB64: respond to a specific client. undefined → single-client fallback
625
+ // (broadcast callers use sendToRelay which fans out per client instead).
626
+ function encryptMessage(msg, peerPubB64) {
627
+ if (e2eClientKeys.size === 0) return msg
614
628
  const routing = ['type', 'requestId', 'actionId', 'success', 'status', 'ok', 'reconnected']
615
629
  const content = {}
616
630
  for (const [k, v] of Object.entries(msg)) {
617
- if (!routing.includes(k)) content[k] = v
631
+ if (!routing.includes(k) && k !== '_e2eFrom') content[k] = v
618
632
  }
619
633
  if (Object.keys(content).length === 0) return msg
620
- const enc = e2eEncrypt(content)
634
+ const enc = e2eEncryptFor(peerPubB64, content)
621
635
  if (!enc) return msg
622
636
  const out = { type: msg.type }
623
637
  for (const k of routing) if (k in msg) out[k] = msg[k]
@@ -625,17 +639,30 @@ function encryptMessage(msg) {
625
639
  return out
626
640
  }
627
641
 
628
- // Unpack a received message: merges decrypted content back from `enc`.
642
+ // Unpack a received message: merges decrypted content back from `enc`,
643
+ // remembering which client sent it so the response can be encrypted for them.
629
644
  function decryptMessage(msg) {
630
- if (!msg || !msg.enc || !e2eSharedKey) return msg
631
- const content = e2eDecrypt(msg.enc)
632
- if (content) {
645
+ if (!msg || !msg.enc || e2eClientKeys.size === 0) return msg
646
+ const r = e2eDecrypt(msg.enc)
647
+ if (r) {
633
648
  delete msg.enc
634
- Object.assign(msg, content)
649
+ Object.assign(msg, r.content)
650
+ msg._e2eFrom = r.from
651
+ if (msg.requestId) e2ePeerByRequest.set(msg.requestId, r.from)
652
+ } else {
653
+ log(`[E2E] 解密失败(未知客户端密钥) requestId=${msg.requestId || '?'}`)
635
654
  }
636
655
  return msg
637
656
  }
638
657
 
658
+ // Pop the originating client for a request (one-shot; deleted after read).
659
+ function takePeer(requestId) {
660
+ if (!requestId) return undefined
661
+ const p = e2ePeerByRequest.get(requestId)
662
+ e2ePeerByRequest.delete(requestId)
663
+ return p
664
+ }
665
+
639
666
  // ── Relay ──
640
667
 
641
668
  function connectRelay() {
@@ -660,6 +687,7 @@ function connectRelay() {
660
687
  relayWs = new WebSocket(relayUrl, wsOptions)
661
688
 
662
689
  relayWs.on('open', () => {
690
+ _relayOpenedAt = Date.now()
663
691
  relayConnectFailures = 0
664
692
  relayWs.send(JSON.stringify({
665
693
  type: 'register',
@@ -667,16 +695,30 @@ function connectRelay() {
667
695
  sessionToken: savedSession?.sessionToken || undefined,
668
696
  e2ePubKey: getE2EPubKeyB64(),
669
697
  }))
698
+ // Pong watchdog: relay replies to app-level ping. If it goes silent
699
+ // (zombie TCP after a relay restart / NAT drop), close() alone may never
700
+ // fire — force a reconnect instead of buffering into the void forever.
701
+ relayLastPong = Date.now()
670
702
  relayPingInterval = setInterval(() => {
671
- if (relayWs?.readyState === WebSocket.OPEN) {
672
- relayWs.send(JSON.stringify({ type: 'ping' }))
703
+ if (relayWs?.readyState !== WebSocket.OPEN) return
704
+ if (Date.now() - relayLastPong > 75000) {
705
+ log('[codepocket] ⚠ Relay 75s 无 pong,强制重连')
706
+ try { relayWs.removeAllListeners() } catch {}
707
+ try { relayWs.close() } catch {}
708
+ relayWs = null
709
+ setTimeout(connectRelay, 1000)
710
+ return
673
711
  }
712
+ relayWs.send(JSON.stringify({ type: 'ping' }))
674
713
  }, 25000)
675
714
  })
676
715
 
677
716
  relayWs.on('message', (raw) => {
717
+ // Any traffic proves the relay is alive (pong included)
718
+ relayLastPong = Date.now()
678
719
  let msg
679
720
  try { msg = JSON.parse(raw.toString()) } catch { return }
721
+ if (msg.type === 'pong') return
680
722
  msg = decryptMessage(msg)
681
723
  switch (msg.type) {
682
724
  case 'registered': {
@@ -731,7 +773,8 @@ function connectRelay() {
731
773
  }
732
774
  })
733
775
 
734
- relayWs.on('close', () => {
776
+ relayWs.on('close', (code, reason) => {
777
+ log(`[DEBUG:relay] ws closed: code=${code} reason=${reason ? Buffer.from(reason).toString() : ''} livedSec=${Math.round((Date.now() - _relayOpenedAt) / 1000)}`)
735
778
  if (relayPingInterval) { clearInterval(relayPingInterval); relayPingInterval = null }
736
779
  relayWs = null
737
780
  relayConnectFailures++
@@ -753,22 +796,36 @@ function connectRelay() {
753
796
  relayWs.on('error', () => { relayWs?.close() })
754
797
  }
755
798
 
756
- function sendToRelay(msg) {
757
- if (relayWs?.readyState === WebSocket.OPEN) relayWs.send(JSON.stringify(encryptMessage(msg)))
799
+ function sendToRelay(msg, peerPubB64) {
800
+ if (relayWs?.readyState !== WebSocket.OPEN) return
801
+ if (peerPubB64 !== undefined) {
802
+ // Routed response — encrypt for the requesting client only
803
+ relayWs.send(JSON.stringify(encryptMessage(msg, peerPubB64)))
804
+ } else if (e2eClientKeys.size <= 1) {
805
+ const pub = e2eClientKeys.size ? e2eClientKeys.keys().next().value : undefined
806
+ relayWs.send(JSON.stringify(encryptMessage(msg, pub)))
807
+ } else {
808
+ // Broadcast (sse-event / phone-action): one copy per client key so every
809
+ // paired device can decrypt its own; others ignore the opaque copy.
810
+ for (const pub of e2eClientKeys.keys()) {
811
+ relayWs.send(JSON.stringify(encryptMessage(msg, pub)))
812
+ }
813
+ }
758
814
  }
759
815
 
760
816
  function sendSpawnResult(requestId, sessionId, error) {
817
+ const peer = takePeer(requestId)
761
818
  const msg = error
762
819
  ? { type: 'spawn-session-result', requestId, success: false, error }
763
820
  : { type: 'spawn-session-result', requestId, success: true, sessionId }
764
821
  // Retry sending if relay connection is temporarily down
765
822
  if (relayWs?.readyState === WebSocket.OPEN) {
766
- relayWs.send(JSON.stringify(encryptMessage(msg)))
823
+ relayWs.send(JSON.stringify(encryptMessage(msg, peer)))
767
824
  } else {
768
825
  log(`[codepocket] Relay not open, retrying spawn result in 2s...`)
769
826
  setTimeout(() => {
770
827
  if (relayWs?.readyState === WebSocket.OPEN) {
771
- relayWs.send(JSON.stringify(encryptMessage(msg)))
828
+ relayWs.send(JSON.stringify(encryptMessage(msg, peer)))
772
829
  } else {
773
830
  log(`[codepocket] Failed to send spawn result, relay still down`)
774
831
  }
@@ -786,9 +843,10 @@ async function doForwardToHub(requestId, method, p, body) {
786
843
  }
787
844
 
788
845
  async function forwardToHub(requestId, method, p, body) {
846
+ const peer = takePeer(requestId)
789
847
  // Only allow proxying to /api/ paths
790
848
  if (!p || !p.startsWith('/api/')) {
791
- sendToRelay({ type: 'rest-response', requestId, status: 403, data: { error: 'Forbidden path' } })
849
+ sendToRelay({ type: 'rest-response', requestId, status: 403, data: { error: 'Forbidden path' } }, peer)
792
850
  return
793
851
  }
794
852
  try {
@@ -801,22 +859,23 @@ async function forwardToHub(requestId, method, p, body) {
801
859
  } catch {}
802
860
  }
803
861
  const data = await res.json().catch(() => ({}))
804
- sendToRelay({ type: 'rest-response', requestId, status: res.status, data })
862
+ sendToRelay({ type: 'rest-response', requestId, status: res.status, data }, peer)
805
863
  } catch (err) {
806
- sendToRelay({ type: 'rest-response', requestId, status: 502, data: { error: err.message } })
864
+ sendToRelay({ type: 'rest-response', requestId, status: 502, data: { error: err.message } }, peer)
807
865
  }
808
866
  }
809
867
 
810
868
  async function handleAuthRequest(requestId, accessToken) {
869
+ const peer = takePeer(requestId)
811
870
  try {
812
871
  const res = await fetch(`${hubUrl}/api/auth`, {
813
872
  method: 'POST',
814
873
  headers: { 'Content-Type': 'application/json' },
815
874
  body: JSON.stringify({ accessToken }),
816
875
  })
817
- sendToRelay({ type: 'auth-response', requestId, ok: res.ok, data: await res.json() })
876
+ sendToRelay({ type: 'auth-response', requestId, ok: res.ok, data: await res.json() }, peer)
818
877
  } catch (err) {
819
- sendToRelay({ type: 'auth-response', requestId, ok: false, data: { error: err.message } })
878
+ sendToRelay({ type: 'auth-response', requestId, ok: false, data: { error: err.message } }, peer)
820
879
  }
821
880
  }
822
881
 
@@ -827,12 +886,12 @@ async function handleSpawnSession(requestId, directory) {
827
886
 
828
887
  if (!hubBin) {
829
888
  log(`[DEBUG:spawn] FAIL: hubBin is null`)
830
- sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Hub binary not found' })
889
+ sendSpawnResult(requestId, null, 'Hub binary not found')
831
890
  return
832
891
  }
833
892
  if (!directory || typeof directory !== 'string') {
834
893
  log(`[DEBUG:spawn] FAIL: directory invalid`)
835
- sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Directory is required' })
894
+ sendSpawnResult(requestId, null, 'Directory is required')
836
895
  return
837
896
  }
838
897
 
@@ -844,12 +903,12 @@ async function handleSpawnSession(requestId, directory) {
844
903
  const home = os.homedir()
845
904
  if (!absDir.startsWith(home)) {
846
905
  log(`[DEBUG:spawn] FAIL: directory outside home: ${absDir}`)
847
- sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Access denied: directory outside home' })
906
+ sendSpawnResult(requestId, null, 'Access denied: directory outside home')
848
907
  return
849
908
  }
850
909
  if (!fs.existsSync(absDir) || !fs.statSync(absDir).isDirectory()) {
851
910
  log(`[DEBUG:spawn] FAIL: directory does not exist: ${absDir}`)
852
- sendToRelay({ type: 'spawn-session-result', requestId, success: false, error: 'Directory does not exist' })
911
+ sendSpawnResult(requestId, null, 'Directory does not exist')
853
912
  return
854
913
  }
855
914
 
@@ -956,13 +1015,14 @@ async function handleSpawnSession(requestId, directory) {
956
1015
  async function handleResumeSession(requestId, sessionId) {
957
1016
  log(`[DEBUG:resume] === START resume-session ===`)
958
1017
  log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
1018
+ const peer = takePeer(requestId)
959
1019
 
960
1020
  if (!hubBin) {
961
- sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' })
1021
+ sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Hub binary not found' }, peer)
962
1022
  return
963
1023
  }
964
1024
  if (!sessionId) {
965
- sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' })
1025
+ sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session ID is required' }, peer)
966
1026
  return
967
1027
  }
968
1028
 
@@ -979,14 +1039,14 @@ async function handleResumeSession(requestId, sessionId) {
979
1039
  })
980
1040
  }
981
1041
  if (!res.ok) {
982
- sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` })
1042
+ sendToRelay({ type: 'resume-session-result', requestId, success: false, error: `Session not found (${res.status})` }, peer)
983
1043
  return
984
1044
  }
985
1045
  const data = await res.json()
986
1046
  const session = data.session || data
987
1047
  const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
988
1048
  if (!directory) {
989
- sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' })
1049
+ sendToRelay({ type: 'resume-session-result', requestId, success: false, error: 'Session has no working directory' }, peer)
990
1050
  return
991
1051
  }
992
1052
 
@@ -996,6 +1056,17 @@ async function handleResumeSession(requestId, sessionId) {
996
1056
  claudeSessionId = findClaudeSessionFile(directory)
997
1057
  log(`[DEBUG:resume] claudeSessionId from file scan: ${claudeSessionId || 'NOT FOUND'}`)
998
1058
  }
1059
+ // Stale resume target: the conversation file was deleted (claude retention
1060
+ // cleanup) — launching with --resume crashes claude instantly with
1061
+ // "No conversation found" (exit 1) and the phone spins "thinking" forever.
1062
+ if (claudeSessionId) {
1063
+ const claudeConfigDir = process.env.CLAUDE_CONFIG_DIR || path.join(os.homedir(), '.claude')
1064
+ const convFile = path.join(claudeConfigDir, 'projects', encodeProjectPath(directory), `${claudeSessionId}.jsonl`)
1065
+ if (!fs.existsSync(convFile)) {
1066
+ log(`[DEBUG:resume] conversation file missing (${claudeSessionId}) — starting fresh instead of --resume`)
1067
+ claudeSessionId = null
1068
+ }
1069
+ }
999
1070
  const spawnArgs = ['claude', '--codepocket-starting-mode', 'remote']
1000
1071
  if (claudeSessionId) {
1001
1072
  spawnArgs.push('--resume', claudeSessionId)
@@ -1098,34 +1169,35 @@ async function handleResumeSession(requestId, sessionId) {
1098
1169
  if (newSessionId) {
1099
1170
  // Don't delete old session — mini-program needs it for message history
1100
1171
  log(`[DEBUG:resume] RESULT: new session=${newSessionId}, old session=${sessionId} preserved for history`)
1101
- sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSessionId, oldSessionId: sessionId })
1172
+ sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: newSessionId, oldSessionId: sessionId }, peer)
1102
1173
  } else {
1103
1174
  log(`[DEBUG:resume] RESULT: no new session found after 30 polls`)
1104
- sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' })
1175
+ sendToRelay({ type: 'resume-session-result', requestId, success: true, sessionId: null, warning: 'Session resuming' }, peer)
1105
1176
  }
1106
1177
  } catch (err) {
1107
1178
  log(`[DEBUG:resume] EXCEPTION: ${err.message}`)
1108
- sendToRelay({ type: 'resume-session-result', requestId, success: false, error: err.message })
1179
+ sendToRelay({ type: 'resume-session-result', requestId, success: false, error: err.message }, peer)
1109
1180
  }
1110
1181
  }
1111
1182
 
1112
1183
  function handleListDir(requestId, dirPath) {
1184
+ const peer = takePeer(requestId)
1113
1185
  try {
1114
1186
  const home = os.homedir()
1115
1187
  const resolved = (dirPath || '~').replace(/^~/, home)
1116
1188
  const abs = path.resolve(resolved)
1117
1189
  // Only allow listing under home directory
1118
1190
  if (!abs.startsWith(home)) {
1119
- sendToRelay({ type: 'list-dir-result', requestId, error: 'Access denied: directory outside home' })
1191
+ sendToRelay({ type: 'list-dir-result', requestId, error: 'Access denied: directory outside home' }, peer)
1120
1192
  return
1121
1193
  }
1122
1194
  const entries = fs.readdirSync(abs, { withFileTypes: true })
1123
1195
  .filter(d => d.isDirectory())
1124
1196
  .map(d => ({ name: d.name, path: path.join(abs, d.name) }))
1125
1197
  .sort((a, b) => a.name.localeCompare(b.name))
1126
- sendToRelay({ type: 'list-dir-result', requestId, path: abs, entries })
1198
+ sendToRelay({ type: 'list-dir-result', requestId, path: abs, entries }, peer)
1127
1199
  } catch (err) {
1128
- sendToRelay({ type: 'list-dir-result', requestId, error: err.message })
1200
+ sendToRelay({ type: 'list-dir-result', requestId, error: err.message }, peer)
1129
1201
  }
1130
1202
  }
1131
1203
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tina_summer/codepocket",
3
- "version": "2.6.4",
3
+ "version": "2.6.8",
4
4
  "description": "CodePocket — 基于ClaudeCode的微信小程序工作台",
5
5
  "bin": {
6
6
  "codepocket": "bin/codepocket.js",
@@ -20,10 +20,10 @@
20
20
  "ws": "^8.18.0"
21
21
  },
22
22
  "optionalDependencies": {
23
- "@tina_summer/codepocket-darwin-arm64": "2.6.4",
24
- "@tina_summer/codepocket-darwin-x64": "2.6.4",
25
- "@tina_summer/codepocket-linux-x64": "2.6.4",
26
- "@tina_summer/codepocket-win32-x64": "2.6.4"
23
+ "@tina_summer/codepocket-darwin-arm64": "2.6.8",
24
+ "@tina_summer/codepocket-darwin-x64": "2.6.8",
25
+ "@tina_summer/codepocket-linux-x64": "2.6.8",
26
+ "@tina_summer/codepocket-win32-x64": "2.6.8"
27
27
  },
28
28
  "engines": {
29
29
  "node": ">=18"
package/src/mcp-server.js CHANGED
@@ -62,30 +62,6 @@ const TOOLS = [
62
62
  required: ['todoId'],
63
63
  },
64
64
  },
65
- {
66
- name: 'phone_location_get',
67
- description: 'Get the phone current GPS location. The user will be asked for permission.',
68
- inputSchema: {
69
- type: 'object',
70
- properties: {},
71
- },
72
- },
73
- {
74
- name: 'phone_location_track',
75
- description: 'Start tracking the phone GPS location in the background. Points are collected until phone_location_stop is called. Returns immediately.',
76
- inputSchema: {
77
- type: 'object',
78
- properties: {},
79
- },
80
- },
81
- {
82
- name: 'phone_location_stop',
83
- description: 'Stop GPS location tracking and return all collected coordinate points since tracking started.',
84
- inputSchema: {
85
- type: 'object',
86
- properties: {},
87
- },
88
- },
89
65
  {
90
66
  name: 'phone_notification_send',
91
67
  description: 'Send a notification to the phone. The user will confirm on their phone.',
@@ -110,53 +86,6 @@ const TOOLS = [
110
86
  required: ['text'],
111
87
  },
112
88
  },
113
- {
114
- name: 'phone_map_show',
115
- description: 'Show a map with markers and/or polyline on the phone screen. The user will see the map and confirm when done.',
116
- inputSchema: {
117
- type: 'object',
118
- properties: {
119
- markers: {
120
- type: 'array',
121
- description: 'Marker points to display on the map',
122
- items: {
123
- type: 'object',
124
- properties: {
125
- latitude: { type: 'number', description: 'Marker latitude' },
126
- longitude: { type: 'number', description: 'Marker longitude' },
127
- title: { type: 'string', description: 'Marker label text' },
128
- },
129
- required: ['latitude', 'longitude'],
130
- },
131
- },
132
- polyline: {
133
- type: 'array',
134
- description: 'Polylines to draw on the map',
135
- items: {
136
- type: 'object',
137
- properties: {
138
- points: {
139
- type: 'array',
140
- items: {
141
- type: 'object',
142
- properties: {
143
- latitude: { type: 'number' },
144
- longitude: { type: 'number' },
145
- timestamp: { type: 'number', description: 'Unix timestamp ms (optional, for speed calc)' },
146
- },
147
- required: ['latitude', 'longitude'],
148
- },
149
- },
150
- color: { type: 'string', description: 'Line color, e.g. #FF0000', default: '#1677FF' },
151
- width: { type: 'number', description: 'Line width in pixels', default: 4 },
152
- },
153
- required: ['points'],
154
- },
155
- },
156
- title: { type: 'string', description: 'Map page title', default: '地图' },
157
- },
158
- },
159
- },
160
89
  ]
161
90
 
162
91
  // phone_calendar_query and phone_todo_list are also sent to the mini-program,
package/src/mcp-client.js DELETED
@@ -1,348 +0,0 @@
1
- /**
2
- * Simple MCP client — connects to the running codepocket MCP server via SSE,
3
- * sends tool calls, and returns results.
4
- */
5
-
6
- const http = require('http')
7
- const fs = require('fs')
8
- const path = require('path')
9
- const readline = require('readline')
10
- const os = require('os')
11
-
12
- const MCP_PORTS = Array.from({ length: 10 }, (_, i) => 3007 + i)
13
- const TRACK_FILE = path.join(os.tmpdir(), 'codepocket-last-track.json')
14
-
15
- // ── MCP Client ──
16
-
17
- class McpClient {
18
- constructor(port) {
19
- this.port = port
20
- this.baseUrl = `http://127.0.0.1:${port}`
21
- this.sseBuffer = ''
22
- this.pending = new Map() // id -> { resolve, reject }
23
- this.nextId = 1
24
- this.connected = false
25
- }
26
-
27
- /** Discover and connect to a running MCP server */
28
- static async connect() {
29
- for (const port of MCP_PORTS) {
30
- try {
31
- const res = await new Promise((resolve, reject) => {
32
- const req = http.get(`http://127.0.0.1:${port}/sse`, (res) => {
33
- resolve(res)
34
- })
35
- req.on('error', reject)
36
- req.setTimeout(2000, () => { req.destroy(); reject(new Error('timeout')) })
37
- })
38
-
39
- if (res.statusCode === 200) {
40
- const client = new McpClient(port)
41
- await client._startSSE(res)
42
- return client
43
- }
44
- res.resume()
45
- } catch {}
46
- }
47
- throw new Error('未找到运行中的 MCP server (tried ports 3007-3016)')
48
- }
49
-
50
- _startSSE(res) {
51
- return new Promise((resolve, reject) => {
52
- let buffer = ''
53
- res.setEncoding('utf-8')
54
- res.on('data', (chunk) => {
55
- buffer += chunk
56
- const lines = buffer.split('\n')
57
- buffer = lines.pop() || ''
58
-
59
- for (const line of lines) {
60
- if (line.startsWith('data: ')) {
61
- const data = line.slice(6).trim()
62
- if (data.startsWith('http')) {
63
- // endpoint event — connected
64
- this.connected = true
65
- resolve()
66
- continue
67
- }
68
- try {
69
- const msg = JSON.parse(data)
70
- if (msg.id && this.pending.has(msg.id)) {
71
- const { resolve: done } = this.pending.get(msg.id)
72
- this.pending.delete(msg.id)
73
- done(msg)
74
- }
75
- } catch {}
76
- }
77
- }
78
- })
79
- res.on('error', reject)
80
- res.on('end', () => {
81
- this.connected = false
82
- // Reject all pending
83
- for (const [id, { reject }] of this.pending) {
84
- this.pending.delete(id)
85
- reject(new Error('SSE connection closed'))
86
- }
87
- })
88
- // Timeout for initial connection
89
- setTimeout(() => {
90
- if (!this.connected) reject(new Error('SSE connection timeout'))
91
- }, 3000)
92
- })
93
- }
94
-
95
- /** Call an MCP tool and return the parsed result */
96
- async call(toolName, args = {}) {
97
- const id = this.nextId++
98
- const msg = {
99
- jsonrpc: '2.0',
100
- id,
101
- method: 'tools/call',
102
- params: { name: toolName, arguments: args },
103
- }
104
-
105
- return new Promise((resolve, reject) => {
106
- const timer = setTimeout(() => {
107
- this.pending.delete(id)
108
- reject(new Error(`Tool call "${toolName}" timed out (60s)`))
109
- }, 60000)
110
-
111
- this.pending.set(id, {
112
- resolve: (msg) => {
113
- clearTimeout(timer)
114
- resolve(msg)
115
- },
116
- reject: (err) => {
117
- clearTimeout(timer)
118
- reject(err)
119
- },
120
- })
121
-
122
- const body = JSON.stringify(msg)
123
- const req = http.request(`${this.baseUrl}/message`, {
124
- method: 'POST',
125
- headers: { 'Content-Type': 'application/json', 'Content-Length': Buffer.byteLength(body) },
126
- }, (res) => {
127
- res.resume()
128
- if (res.statusCode !== 202) {
129
- this.pending.delete(id)
130
- clearTimeout(timer)
131
- reject(new Error(`Unexpected status: ${res.statusCode}`))
132
- }
133
- })
134
- req.on('error', (err) => {
135
- this.pending.delete(id)
136
- clearTimeout(timer)
137
- reject(err)
138
- })
139
- req.write(body)
140
- req.end()
141
- })
142
- }
143
-
144
- /** Extract tool result from MCP response */
145
- static extractResult(mcpMsg) {
146
- try {
147
- const text = mcpMsg.result?.content?.[0]?.text
148
- if (text) return JSON.parse(text)
149
- } catch {}
150
- return null
151
- }
152
- }
153
-
154
- // ── Test Commands ──
155
-
156
- async function cmdLocation() {
157
- const client = await McpClient.connect()
158
- console.log('获取位置中...')
159
- const resp = await client.call('phone_location_get')
160
- const result = McpClient.extractResult(resp)
161
- if (result?.accepted && result.result) {
162
- const loc = result.result
163
- console.log(` 纬度: ${loc.latitude}`)
164
- console.log(` 经度: ${loc.longitude}`)
165
- console.log(` 精度: ${loc.accuracy}m`)
166
- } else {
167
- console.error(' 获取失败:', result?.error || '未知错误')
168
- }
169
- }
170
-
171
- async function cmdTrack() {
172
- const client = await McpClient.connect()
173
- console.log('开始追踪,手机上确认...')
174
- const resp = await client.call('phone_location_track')
175
- const result = McpClient.extractResult(resp)
176
- if (result?.accepted && result.result?.success) {
177
- console.log(' 追踪已开始,走动一会儿后运行:')
178
- console.log(' codepocket test stop')
179
- } else {
180
- console.error(' 启动失败:', result?.error || '未知错误')
181
- }
182
- }
183
-
184
- async function cmdStop() {
185
- const client = await McpClient.connect()
186
- console.log('停止追踪...')
187
- const resp = await client.call('phone_location_stop')
188
- const result = McpClient.extractResult(resp)
189
- if (result?.accepted && result.result?.success) {
190
- const { points, count, debug } = result.result
191
- const duration = count >= 2
192
- ? ((points[points.length - 1].timestamp - points[0].timestamp) / 1000).toFixed(1) + 's'
193
- : 'N/A'
194
-
195
- console.log(` 采集点数: ${count}`)
196
- console.log(` 时长: ${duration}`)
197
-
198
- if (debug?.length) {
199
- console.log(' 调试日志:')
200
- debug.forEach((d) => console.log(` ${d}`))
201
- }
202
-
203
- // Save track data for map command
204
- if (count >= 2) {
205
- fs.writeFileSync(TRACK_FILE, JSON.stringify({ points, count, savedAt: Date.now() }))
206
- console.log(`\n 轨迹已保存,运行下面命令查看地图:`)
207
- console.log(' codepocket test map')
208
- }
209
- } else {
210
- console.error(' 停止失败:', result?.error || '未知错误')
211
- }
212
- }
213
-
214
- async function cmdMap() {
215
- // Load saved track data
216
- if (!fs.existsSync(TRACK_FILE)) {
217
- console.error(' 未找到轨迹数据,请先运行 codepocket test track → stop')
218
- process.exit(1)
219
- }
220
-
221
- const track = JSON.parse(fs.readFileSync(TRACK_FILE, 'utf-8'))
222
- const { points } = track
223
-
224
- console.log(` 加载 ${points.length} 个轨迹点...`)
225
-
226
- const polylinePoints = points.map((p) => ({
227
- latitude: p.latitude,
228
- longitude: p.longitude,
229
- timestamp: p.timestamp,
230
- }))
231
-
232
- const markers = [
233
- { latitude: points[0].latitude, longitude: points[0].longitude, title: '起点' },
234
- { latitude: points[points.length - 1].latitude, longitude: points[points.length - 1].longitude, title: '终点' },
235
- ]
236
-
237
- const client = await McpClient.connect()
238
- console.log(' 发送地图到手机...')
239
- const resp = await client.call('phone_map_show', {
240
- polyline: [{ points: polylinePoints, color: '#00C853', width: 4 }],
241
- markers,
242
- title: '轨迹地图',
243
- })
244
-
245
- const result = McpClient.extractResult(resp)
246
- if (result?.accepted) {
247
- console.log(' 地图已显示到手机!')
248
- } else {
249
- console.error(' 显示失败:', result?.error || '未知错误')
250
- }
251
- }
252
-
253
- async function cmdFlow() {
254
- const client = await McpClient.connect()
255
-
256
- // Step 1: Track
257
- console.log('\n[1/3] 开始追踪,手机上确认...')
258
- const trackResp = await client.call('phone_location_track')
259
- const trackResult = McpClient.extractResult(trackResp)
260
- if (!trackResult?.accepted || !trackResult.result?.success) {
261
- console.error(' 追踪启动失败:', trackResult?.error || '未知错误')
262
- process.exit(1)
263
- }
264
- console.log(' 追踪中...')
265
-
266
- // Step 2: Wait for user
267
- console.log('\n 走动一会儿,按回车停止追踪...')
268
- await new Promise((resolve) => {
269
- const rl = readline.createInterface({ input: process.stdin, output: process.stdout })
270
- rl.on('line', () => { rl.close(); resolve() })
271
- })
272
-
273
- // Step 3: Stop
274
- console.log('\n[2/3] 停止追踪...')
275
- const stopResp = await client.call('phone_location_stop')
276
- const stopResult = McpClient.extractResult(stopResp)
277
- if (!stopResult?.accepted || !stopResult.result?.success) {
278
- console.error(' 停止失败:', stopResult?.error || '未知错误')
279
- process.exit(1)
280
- }
281
-
282
- const { points, count } = stopResult.result
283
- const duration = count >= 2
284
- ? ((points[points.length - 1].timestamp - points[0].timestamp) / 1000).toFixed(1) + 's'
285
- : 'N/A'
286
- console.log(` ${count} 个点, ${duration}`)
287
-
288
- if (count < 2) {
289
- console.error(' 点数不足,无法画地图')
290
- process.exit(1)
291
- }
292
-
293
- // Save track
294
- fs.writeFileSync(TRACK_FILE, JSON.stringify({ points, count, savedAt: Date.now() }))
295
-
296
- // Step 4: Map
297
- console.log('\n[3/3] 画地图...')
298
- const polylinePoints = points.map((p) => ({
299
- latitude: p.latitude,
300
- longitude: p.longitude,
301
- timestamp: p.timestamp,
302
- }))
303
- const markers = [
304
- { latitude: points[0].latitude, longitude: points[0].longitude, title: '起点' },
305
- { latitude: points[points.length - 1].latitude, longitude: points[points.length - 1].longitude, title: '终点' },
306
- ]
307
-
308
- const mapResp = await client.call('phone_map_show', {
309
- polyline: [{ points: polylinePoints, color: '#00C853', width: 4 }],
310
- markers,
311
- title: '轨迹地图',
312
- })
313
-
314
- const mapResult = McpClient.extractResult(mapResp)
315
- if (mapResult?.accepted) {
316
- console.log(' 地图已显示到手机!')
317
- } else {
318
- console.error(' 显示失败:', mapResult?.error || '未知错误')
319
- }
320
- }
321
-
322
- // ── CLI Entry ──
323
-
324
- const COMMANDS = { location: cmdLocation, track: cmdTrack, stop: cmdStop, map: cmdMap, flow: cmdFlow }
325
-
326
- async function runTestCli(args) {
327
- const cmd = args[0]
328
- if (!cmd || !COMMANDS[cmd]) {
329
- console.log('用法: codepocket test <command>')
330
- console.log('')
331
- console.log('命令:')
332
- console.log(' location 获取当前位置')
333
- console.log(' track 开始位置追踪')
334
- console.log(' stop 停止追踪并保存轨迹')
335
- console.log(' map 用最近轨迹画地图')
336
- console.log(' flow 全流程: 追踪 → 停止 → 画地图')
337
- process.exit(cmd ? 1 : 0)
338
- }
339
-
340
- try {
341
- await COMMANDS[cmd]()
342
- } catch (err) {
343
- console.error(`\n [!] ${err.message}`)
344
- process.exit(1)
345
- }
346
- }
347
-
348
- module.exports = { runTestCli }