@tina_summer/codepocket 2.6.5 → 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 +128 -61
- package/package.json +5 -5
- package/src/mcp-server.js +0 -71
- package/src/mcp-client.js +0 -348
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')
|
|
@@ -405,6 +398,8 @@ if (args[0] === 'start') {
|
|
|
405
398
|
let jwt = ''
|
|
406
399
|
let relayWs = null
|
|
407
400
|
let relayPingInterval = null
|
|
401
|
+
let relayLastPong = 0
|
|
402
|
+
let _relayOpenedAt = 0
|
|
408
403
|
let hubBin = findHubBin()
|
|
409
404
|
let relayConnectFailures = 0
|
|
410
405
|
|
|
@@ -550,10 +545,16 @@ async function startSSE() {
|
|
|
550
545
|
// The relay only forwards e2ePubKey + opaque `enc` envelopes; it cannot decrypt.
|
|
551
546
|
// Nonces are counter-based with a direction tag to avoid reuse across directions
|
|
552
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`.
|
|
553
553
|
|
|
554
|
-
let e2eKeypair = null
|
|
555
|
-
|
|
556
|
-
|
|
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)
|
|
557
558
|
|
|
558
559
|
function ensureE2EKeypair() {
|
|
559
560
|
if (e2eKeypair) return e2eKeypair
|
|
@@ -571,58 +572,66 @@ function setPeerE2EPubKey(peerPubKeyB64) {
|
|
|
571
572
|
try {
|
|
572
573
|
const peerPub = Buffer.from(peerPubKeyB64, 'base64')
|
|
573
574
|
if (peerPub.length !== 32) return
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
log('[codepocket] ✓ E2E 加密通道已建立')
|
|
575
|
+
e2eClientKeys.set(peerPubKeyB64, nacl.box.before(peerPub, ensureE2EKeypair().secretKey))
|
|
576
|
+
log(`[codepocket] ✓ E2E 加密通道已建立 (client ${peerPubKeyB64.slice(0, 6)}..., 共 ${e2eClientKeys.size} 个客户端)`)
|
|
577
577
|
} catch (e) {
|
|
578
578
|
log(`[codepocket] E2E 密钥协商失败: ${e.message}`)
|
|
579
579
|
}
|
|
580
580
|
}
|
|
581
581
|
|
|
582
|
-
function nextNonce() {
|
|
583
|
-
|
|
582
|
+
function nextNonce(pubKeyB64) {
|
|
583
|
+
const c = (e2eNonceCounters.get(pubKeyB64) || 0) + 1
|
|
584
|
+
e2eNonceCounters.set(pubKeyB64, c)
|
|
584
585
|
const n = new Uint8Array(24)
|
|
585
586
|
n[0] = 0xFF // connector→phone direction tag
|
|
586
|
-
let
|
|
587
|
-
for (let i = 6; i >= 1; i--) { n[i] =
|
|
587
|
+
let rest = c
|
|
588
|
+
for (let i = 6; i >= 1; i--) { n[i] = rest & 0xff; rest = Math.floor(rest / 256) }
|
|
588
589
|
return n
|
|
589
590
|
}
|
|
590
591
|
|
|
591
|
-
|
|
592
|
-
|
|
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
|
|
593
596
|
try {
|
|
594
597
|
const msgBytes = Buffer.from(JSON.stringify(obj), 'utf8')
|
|
595
|
-
const nonce = nextNonce()
|
|
596
|
-
const cipher = nacl.secretbox(msgBytes, nonce,
|
|
598
|
+
const nonce = nextNonce(pubKeyB64)
|
|
599
|
+
const cipher = nacl.secretbox(msgBytes, nonce, key)
|
|
597
600
|
if (!cipher) return undefined
|
|
598
601
|
return { n: Buffer.from(nonce).toString('base64'), c: Buffer.from(cipher).toString('base64') }
|
|
599
602
|
} catch { return undefined }
|
|
600
603
|
}
|
|
601
604
|
|
|
605
|
+
// Inbound may come from ANY connected client — try every known key.
|
|
606
|
+
// Returns { content, from: clientPubKeyB64 } or undefined.
|
|
602
607
|
function e2eDecrypt(envelope) {
|
|
603
608
|
if (!envelope || typeof envelope !== 'object') return undefined
|
|
604
609
|
if (typeof envelope.n !== 'string' || typeof envelope.c !== 'string') return undefined
|
|
605
|
-
if (
|
|
610
|
+
if (e2eClientKeys.size === 0) return undefined
|
|
606
611
|
try {
|
|
607
612
|
const nonce = new Uint8Array(Buffer.from(envelope.n, 'base64'))
|
|
608
613
|
const cipher = new Uint8Array(Buffer.from(envelope.c, 'base64'))
|
|
609
|
-
const
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
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
|
|
613
620
|
}
|
|
614
621
|
|
|
615
622
|
// Pack a message for sending: moves sensitive fields into an `enc` envelope.
|
|
616
623
|
// Routing fields (type, requestId, actionId, success, status, ok) stay plaintext.
|
|
617
|
-
|
|
618
|
-
|
|
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
|
|
619
628
|
const routing = ['type', 'requestId', 'actionId', 'success', 'status', 'ok', 'reconnected']
|
|
620
629
|
const content = {}
|
|
621
630
|
for (const [k, v] of Object.entries(msg)) {
|
|
622
|
-
if (!routing.includes(k)) content[k] = v
|
|
631
|
+
if (!routing.includes(k) && k !== '_e2eFrom') content[k] = v
|
|
623
632
|
}
|
|
624
633
|
if (Object.keys(content).length === 0) return msg
|
|
625
|
-
const enc =
|
|
634
|
+
const enc = e2eEncryptFor(peerPubB64, content)
|
|
626
635
|
if (!enc) return msg
|
|
627
636
|
const out = { type: msg.type }
|
|
628
637
|
for (const k of routing) if (k in msg) out[k] = msg[k]
|
|
@@ -630,17 +639,30 @@ function encryptMessage(msg) {
|
|
|
630
639
|
return out
|
|
631
640
|
}
|
|
632
641
|
|
|
633
|
-
// 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.
|
|
634
644
|
function decryptMessage(msg) {
|
|
635
|
-
if (!msg || !msg.enc ||
|
|
636
|
-
const
|
|
637
|
-
if (
|
|
645
|
+
if (!msg || !msg.enc || e2eClientKeys.size === 0) return msg
|
|
646
|
+
const r = e2eDecrypt(msg.enc)
|
|
647
|
+
if (r) {
|
|
638
648
|
delete msg.enc
|
|
639
|
-
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 || '?'}`)
|
|
640
654
|
}
|
|
641
655
|
return msg
|
|
642
656
|
}
|
|
643
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
|
+
|
|
644
666
|
// ── Relay ──
|
|
645
667
|
|
|
646
668
|
function connectRelay() {
|
|
@@ -665,6 +687,7 @@ function connectRelay() {
|
|
|
665
687
|
relayWs = new WebSocket(relayUrl, wsOptions)
|
|
666
688
|
|
|
667
689
|
relayWs.on('open', () => {
|
|
690
|
+
_relayOpenedAt = Date.now()
|
|
668
691
|
relayConnectFailures = 0
|
|
669
692
|
relayWs.send(JSON.stringify({
|
|
670
693
|
type: 'register',
|
|
@@ -672,16 +695,30 @@ function connectRelay() {
|
|
|
672
695
|
sessionToken: savedSession?.sessionToken || undefined,
|
|
673
696
|
e2ePubKey: getE2EPubKeyB64(),
|
|
674
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()
|
|
675
702
|
relayPingInterval = setInterval(() => {
|
|
676
|
-
if (relayWs?.readyState
|
|
677
|
-
|
|
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
|
|
678
711
|
}
|
|
712
|
+
relayWs.send(JSON.stringify({ type: 'ping' }))
|
|
679
713
|
}, 25000)
|
|
680
714
|
})
|
|
681
715
|
|
|
682
716
|
relayWs.on('message', (raw) => {
|
|
717
|
+
// Any traffic proves the relay is alive (pong included)
|
|
718
|
+
relayLastPong = Date.now()
|
|
683
719
|
let msg
|
|
684
720
|
try { msg = JSON.parse(raw.toString()) } catch { return }
|
|
721
|
+
if (msg.type === 'pong') return
|
|
685
722
|
msg = decryptMessage(msg)
|
|
686
723
|
switch (msg.type) {
|
|
687
724
|
case 'registered': {
|
|
@@ -736,7 +773,8 @@ function connectRelay() {
|
|
|
736
773
|
}
|
|
737
774
|
})
|
|
738
775
|
|
|
739
|
-
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)}`)
|
|
740
778
|
if (relayPingInterval) { clearInterval(relayPingInterval); relayPingInterval = null }
|
|
741
779
|
relayWs = null
|
|
742
780
|
relayConnectFailures++
|
|
@@ -758,22 +796,36 @@ function connectRelay() {
|
|
|
758
796
|
relayWs.on('error', () => { relayWs?.close() })
|
|
759
797
|
}
|
|
760
798
|
|
|
761
|
-
function sendToRelay(msg) {
|
|
762
|
-
if (relayWs?.readyState
|
|
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
|
+
}
|
|
763
814
|
}
|
|
764
815
|
|
|
765
816
|
function sendSpawnResult(requestId, sessionId, error) {
|
|
817
|
+
const peer = takePeer(requestId)
|
|
766
818
|
const msg = error
|
|
767
819
|
? { type: 'spawn-session-result', requestId, success: false, error }
|
|
768
820
|
: { type: 'spawn-session-result', requestId, success: true, sessionId }
|
|
769
821
|
// Retry sending if relay connection is temporarily down
|
|
770
822
|
if (relayWs?.readyState === WebSocket.OPEN) {
|
|
771
|
-
relayWs.send(JSON.stringify(encryptMessage(msg)))
|
|
823
|
+
relayWs.send(JSON.stringify(encryptMessage(msg, peer)))
|
|
772
824
|
} else {
|
|
773
825
|
log(`[codepocket] Relay not open, retrying spawn result in 2s...`)
|
|
774
826
|
setTimeout(() => {
|
|
775
827
|
if (relayWs?.readyState === WebSocket.OPEN) {
|
|
776
|
-
relayWs.send(JSON.stringify(encryptMessage(msg)))
|
|
828
|
+
relayWs.send(JSON.stringify(encryptMessage(msg, peer)))
|
|
777
829
|
} else {
|
|
778
830
|
log(`[codepocket] Failed to send spawn result, relay still down`)
|
|
779
831
|
}
|
|
@@ -791,9 +843,10 @@ async function doForwardToHub(requestId, method, p, body) {
|
|
|
791
843
|
}
|
|
792
844
|
|
|
793
845
|
async function forwardToHub(requestId, method, p, body) {
|
|
846
|
+
const peer = takePeer(requestId)
|
|
794
847
|
// Only allow proxying to /api/ paths
|
|
795
848
|
if (!p || !p.startsWith('/api/')) {
|
|
796
|
-
sendToRelay({ type: 'rest-response', requestId, status: 403, data: { error: 'Forbidden path' } })
|
|
849
|
+
sendToRelay({ type: 'rest-response', requestId, status: 403, data: { error: 'Forbidden path' } }, peer)
|
|
797
850
|
return
|
|
798
851
|
}
|
|
799
852
|
try {
|
|
@@ -806,22 +859,23 @@ async function forwardToHub(requestId, method, p, body) {
|
|
|
806
859
|
} catch {}
|
|
807
860
|
}
|
|
808
861
|
const data = await res.json().catch(() => ({}))
|
|
809
|
-
sendToRelay({ type: 'rest-response', requestId, status: res.status, data })
|
|
862
|
+
sendToRelay({ type: 'rest-response', requestId, status: res.status, data }, peer)
|
|
810
863
|
} catch (err) {
|
|
811
|
-
sendToRelay({ type: 'rest-response', requestId, status: 502, data: { error: err.message } })
|
|
864
|
+
sendToRelay({ type: 'rest-response', requestId, status: 502, data: { error: err.message } }, peer)
|
|
812
865
|
}
|
|
813
866
|
}
|
|
814
867
|
|
|
815
868
|
async function handleAuthRequest(requestId, accessToken) {
|
|
869
|
+
const peer = takePeer(requestId)
|
|
816
870
|
try {
|
|
817
871
|
const res = await fetch(`${hubUrl}/api/auth`, {
|
|
818
872
|
method: 'POST',
|
|
819
873
|
headers: { 'Content-Type': 'application/json' },
|
|
820
874
|
body: JSON.stringify({ accessToken }),
|
|
821
875
|
})
|
|
822
|
-
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)
|
|
823
877
|
} catch (err) {
|
|
824
|
-
sendToRelay({ type: 'auth-response', requestId, ok: false, data: { error: err.message } })
|
|
878
|
+
sendToRelay({ type: 'auth-response', requestId, ok: false, data: { error: err.message } }, peer)
|
|
825
879
|
}
|
|
826
880
|
}
|
|
827
881
|
|
|
@@ -832,12 +886,12 @@ async function handleSpawnSession(requestId, directory) {
|
|
|
832
886
|
|
|
833
887
|
if (!hubBin) {
|
|
834
888
|
log(`[DEBUG:spawn] FAIL: hubBin is null`)
|
|
835
|
-
|
|
889
|
+
sendSpawnResult(requestId, null, 'Hub binary not found')
|
|
836
890
|
return
|
|
837
891
|
}
|
|
838
892
|
if (!directory || typeof directory !== 'string') {
|
|
839
893
|
log(`[DEBUG:spawn] FAIL: directory invalid`)
|
|
840
|
-
|
|
894
|
+
sendSpawnResult(requestId, null, 'Directory is required')
|
|
841
895
|
return
|
|
842
896
|
}
|
|
843
897
|
|
|
@@ -849,12 +903,12 @@ async function handleSpawnSession(requestId, directory) {
|
|
|
849
903
|
const home = os.homedir()
|
|
850
904
|
if (!absDir.startsWith(home)) {
|
|
851
905
|
log(`[DEBUG:spawn] FAIL: directory outside home: ${absDir}`)
|
|
852
|
-
|
|
906
|
+
sendSpawnResult(requestId, null, 'Access denied: directory outside home')
|
|
853
907
|
return
|
|
854
908
|
}
|
|
855
909
|
if (!fs.existsSync(absDir) || !fs.statSync(absDir).isDirectory()) {
|
|
856
910
|
log(`[DEBUG:spawn] FAIL: directory does not exist: ${absDir}`)
|
|
857
|
-
|
|
911
|
+
sendSpawnResult(requestId, null, 'Directory does not exist')
|
|
858
912
|
return
|
|
859
913
|
}
|
|
860
914
|
|
|
@@ -961,13 +1015,14 @@ async function handleSpawnSession(requestId, directory) {
|
|
|
961
1015
|
async function handleResumeSession(requestId, sessionId) {
|
|
962
1016
|
log(`[DEBUG:resume] === START resume-session ===`)
|
|
963
1017
|
log(`[DEBUG:resume] requestId=${requestId}, sessionId=${sessionId}`)
|
|
1018
|
+
const peer = takePeer(requestId)
|
|
964
1019
|
|
|
965
1020
|
if (!hubBin) {
|
|
966
|
-
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)
|
|
967
1022
|
return
|
|
968
1023
|
}
|
|
969
1024
|
if (!sessionId) {
|
|
970
|
-
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)
|
|
971
1026
|
return
|
|
972
1027
|
}
|
|
973
1028
|
|
|
@@ -984,14 +1039,14 @@ async function handleResumeSession(requestId, sessionId) {
|
|
|
984
1039
|
})
|
|
985
1040
|
}
|
|
986
1041
|
if (!res.ok) {
|
|
987
|
-
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)
|
|
988
1043
|
return
|
|
989
1044
|
}
|
|
990
1045
|
const data = await res.json()
|
|
991
1046
|
const session = data.session || data
|
|
992
1047
|
const directory = (session.metadata?.path || '').replace(/^~/, os.homedir())
|
|
993
1048
|
if (!directory) {
|
|
994
|
-
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)
|
|
995
1050
|
return
|
|
996
1051
|
}
|
|
997
1052
|
|
|
@@ -1001,6 +1056,17 @@ async function handleResumeSession(requestId, sessionId) {
|
|
|
1001
1056
|
claudeSessionId = findClaudeSessionFile(directory)
|
|
1002
1057
|
log(`[DEBUG:resume] claudeSessionId from file scan: ${claudeSessionId || 'NOT FOUND'}`)
|
|
1003
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
|
+
}
|
|
1004
1070
|
const spawnArgs = ['claude', '--codepocket-starting-mode', 'remote']
|
|
1005
1071
|
if (claudeSessionId) {
|
|
1006
1072
|
spawnArgs.push('--resume', claudeSessionId)
|
|
@@ -1103,34 +1169,35 @@ async function handleResumeSession(requestId, sessionId) {
|
|
|
1103
1169
|
if (newSessionId) {
|
|
1104
1170
|
// Don't delete old session — mini-program needs it for message history
|
|
1105
1171
|
log(`[DEBUG:resume] RESULT: new session=${newSessionId}, old session=${sessionId} preserved for history`)
|
|
1106
|
-
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)
|
|
1107
1173
|
} else {
|
|
1108
1174
|
log(`[DEBUG:resume] RESULT: no new session found after 30 polls`)
|
|
1109
|
-
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)
|
|
1110
1176
|
}
|
|
1111
1177
|
} catch (err) {
|
|
1112
1178
|
log(`[DEBUG:resume] EXCEPTION: ${err.message}`)
|
|
1113
|
-
sendToRelay({ type: 'resume-session-result', requestId, success: false, error: err.message })
|
|
1179
|
+
sendToRelay({ type: 'resume-session-result', requestId, success: false, error: err.message }, peer)
|
|
1114
1180
|
}
|
|
1115
1181
|
}
|
|
1116
1182
|
|
|
1117
1183
|
function handleListDir(requestId, dirPath) {
|
|
1184
|
+
const peer = takePeer(requestId)
|
|
1118
1185
|
try {
|
|
1119
1186
|
const home = os.homedir()
|
|
1120
1187
|
const resolved = (dirPath || '~').replace(/^~/, home)
|
|
1121
1188
|
const abs = path.resolve(resolved)
|
|
1122
1189
|
// Only allow listing under home directory
|
|
1123
1190
|
if (!abs.startsWith(home)) {
|
|
1124
|
-
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)
|
|
1125
1192
|
return
|
|
1126
1193
|
}
|
|
1127
1194
|
const entries = fs.readdirSync(abs, { withFileTypes: true })
|
|
1128
1195
|
.filter(d => d.isDirectory())
|
|
1129
1196
|
.map(d => ({ name: d.name, path: path.join(abs, d.name) }))
|
|
1130
1197
|
.sort((a, b) => a.name.localeCompare(b.name))
|
|
1131
|
-
sendToRelay({ type: 'list-dir-result', requestId, path: abs, entries })
|
|
1198
|
+
sendToRelay({ type: 'list-dir-result', requestId, path: abs, entries }, peer)
|
|
1132
1199
|
} catch (err) {
|
|
1133
|
-
sendToRelay({ type: 'list-dir-result', requestId, error: err.message })
|
|
1200
|
+
sendToRelay({ type: 'list-dir-result', requestId, error: err.message }, peer)
|
|
1134
1201
|
}
|
|
1135
1202
|
}
|
|
1136
1203
|
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@tina_summer/codepocket",
|
|
3
|
-
"version": "2.6.
|
|
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.
|
|
24
|
-
"@tina_summer/codepocket-darwin-x64": "2.6.
|
|
25
|
-
"@tina_summer/codepocket-linux-x64": "2.6.
|
|
26
|
-
"@tina_summer/codepocket-win32-x64": "2.6.
|
|
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 }
|