chatnus 0.0.0-stage → 1.0.0
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/.env.example +16 -0
- package/README.md +385 -3
- package/dist/agentcfg.js +243 -0
- package/dist/agents.js +159 -0
- package/dist/catalog.js +33 -0
- package/dist/config.js +46 -0
- package/dist/gateway.js +335 -0
- package/dist/hub.js +318 -0
- package/dist/logs.js +69 -0
- package/dist/meter.js +104 -0
- package/dist/platform.js +139 -0
- package/dist/quota.js +82 -0
- package/dist/server.js +505 -0
- package/dist/sidecar.js +76 -0
- package/dist/skills.js +166 -0
- package/dist/store.js +43 -0
- package/dist/terminal.js +289 -0
- package/dist/tokensaver.js +76 -0
- package/dist/util.js +56 -0
- package/package.json +33 -6
- package/public/index.html +1 -0
- package/scripts/build-go.js +24 -0
- package/scripts/dev.js +10 -0
- package/sidecar/go.mod +3 -0
- package/sidecar/main.go +45 -0
- package/sidecar/main_test.go +118 -0
- package/sidecar/meter.go +114 -0
- package/sidecar/relay.go +433 -0
- package/sidecar/tokens.go +42 -0
- package/skills/ringkas-kode/SKILL.md +9 -0
- package/skills/ringkas-kode/run.js +5 -0
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
// Membangun sidecar Go (jalur streaming + penghitung token) -> bin/nusproxy-<os>-<arch>
|
|
2
|
+
// Butuh Go 1.21+ (Termux: pkg install golang). Tanpa Go, ChatNUS tetap jalan lewat jalur Node.
|
|
3
|
+
const { spawnSync } = require('node:child_process');
|
|
4
|
+
const path = require('node:path');
|
|
5
|
+
const fs = require('node:fs');
|
|
6
|
+
const root = path.join(__dirname, '..');
|
|
7
|
+
const v = spawnSync('go', ['version'], { encoding: 'utf8' });
|
|
8
|
+
if (v.error || v.status !== 0) {
|
|
9
|
+
console.error('Go tidak ditemukan. Pasang dari https://go.dev/dl/ (Termux: pkg install golang), lalu ulangi.');
|
|
10
|
+
console.error('Tanpa Go, ChatNUS memakai jalur streaming Node (tidak ada yang rusak).');
|
|
11
|
+
process.exit(1);
|
|
12
|
+
}
|
|
13
|
+
console.log(v.stdout.trim());
|
|
14
|
+
const os = process.platform === 'win32' ? 'windows' : process.platform;
|
|
15
|
+
const arch = process.arch === 'x64' ? 'amd64' : process.arch;
|
|
16
|
+
const out = path.join(root, 'bin', 'nusproxy-' + os + '-' + arch + (process.platform === 'win32' ? '.exe' : ''));
|
|
17
|
+
fs.mkdirSync(path.dirname(out), { recursive: true });
|
|
18
|
+
if (process.argv.includes('--test')) {
|
|
19
|
+
const t = spawnSync('go', ['test', './...'], { cwd: path.join(root, 'sidecar'), stdio: 'inherit' });
|
|
20
|
+
process.exit(t.status === null ? 1 : t.status);
|
|
21
|
+
}
|
|
22
|
+
const b = spawnSync('go', ['build', '-trimpath', '-ldflags', '-s -w', '-o', out, '.'], { cwd: path.join(root, 'sidecar'), stdio: 'inherit' });
|
|
23
|
+
if (b.status !== 0) { console.error('Build Go gagal (lihat pesan di atas). ChatNUS tetap bisa jalan tanpa sidecar.'); process.exit(1); }
|
|
24
|
+
console.log('Selesai: ' + out + '\nJalankan ulang "npm start"; log akan menampilkan "Sidecar streaming Go dijalankan".');
|
package/scripts/dev.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
// Mode pengembangan lintas-platform: kompilasi ulang otomatis + restart server saat file berubah.
|
|
2
|
+
const { spawn } = require('node:child_process');
|
|
3
|
+
const path = require('node:path');
|
|
4
|
+
const tsc = require.resolve('typescript/bin/tsc');
|
|
5
|
+
const run = (cmd, args) => spawn(cmd, args, { stdio: 'inherit', cwd: path.join(__dirname, '..') });
|
|
6
|
+
const first = spawn(process.execPath, [tsc, '-p', 'tsconfig.json'], { stdio: 'inherit', cwd: path.join(__dirname, '..') });
|
|
7
|
+
first.on('close', () => {
|
|
8
|
+
run(process.execPath, [tsc, '-p', 'tsconfig.json', '--watch', '--preserveWatchOutput']);
|
|
9
|
+
run(process.execPath, ['--watch', 'dist/server.js']);
|
|
10
|
+
});
|
package/sidecar/go.mod
ADDED
package/sidecar/main.go
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// nusproxy: jalur panas streaming (SSE) + penghitung token realtime untuk ChatNUS.
|
|
2
|
+
// Hanya pustaka standar Go. Node tetap pusat kontrol (kunci, combo, kuota); program ini
|
|
3
|
+
// hanya memegang koneksi ke provider dan meneruskan potongan teks tanpa buffering.
|
|
4
|
+
package main
|
|
5
|
+
|
|
6
|
+
import (
|
|
7
|
+
"context"
|
|
8
|
+
"log"
|
|
9
|
+
"net/http"
|
|
10
|
+
"os"
|
|
11
|
+
"os/signal"
|
|
12
|
+
"syscall"
|
|
13
|
+
"time"
|
|
14
|
+
)
|
|
15
|
+
|
|
16
|
+
func osGetenv(k string) string { return os.Getenv(k) }
|
|
17
|
+
|
|
18
|
+
func main() {
|
|
19
|
+
listen := getenv("NUS_LISTEN", "127.0.0.1:8788")
|
|
20
|
+
node := getenv("NUS_NODE", "http://127.0.0.1:8787")
|
|
21
|
+
token := getenv("NUS_INTERNAL", "")
|
|
22
|
+
if token == "" {
|
|
23
|
+
log.Fatal("NUS_INTERNAL kosong: jalankan lewat ChatNUS (npm start)")
|
|
24
|
+
}
|
|
25
|
+
s, err := newServer(node, token)
|
|
26
|
+
if err != nil {
|
|
27
|
+
log.Fatal(err)
|
|
28
|
+
}
|
|
29
|
+
stop := make(chan struct{})
|
|
30
|
+
go s.meter.run(stop)
|
|
31
|
+
srv := &http.Server{Addr: listen, Handler: s.handler(), ReadHeaderTimeout: 10 * time.Second}
|
|
32
|
+
go func() {
|
|
33
|
+
sig := make(chan os.Signal, 1)
|
|
34
|
+
signal.Notify(sig, os.Interrupt, syscall.SIGTERM)
|
|
35
|
+
<-sig
|
|
36
|
+
close(stop)
|
|
37
|
+
ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second)
|
|
38
|
+
defer cancel()
|
|
39
|
+
_ = srv.Shutdown(ctx)
|
|
40
|
+
}()
|
|
41
|
+
log.Printf("nusproxy aktif di http://%s (control plane: %s)", listen, node)
|
|
42
|
+
if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
|
|
43
|
+
log.Fatal(err)
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,118 @@
|
|
|
1
|
+
package main
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"encoding/json"
|
|
5
|
+
"fmt"
|
|
6
|
+
"io"
|
|
7
|
+
"net/http"
|
|
8
|
+
"net/http/httptest"
|
|
9
|
+
"strings"
|
|
10
|
+
"sync"
|
|
11
|
+
"testing"
|
|
12
|
+
"time"
|
|
13
|
+
)
|
|
14
|
+
|
|
15
|
+
func TestTokCounterContinuity(t *testing.T) {
|
|
16
|
+
var a, b tokCounter
|
|
17
|
+
a.add("hel")
|
|
18
|
+
a.add("lo wor")
|
|
19
|
+
a.add("ld!")
|
|
20
|
+
b.add("hello world!")
|
|
21
|
+
if a.total() != b.total() {
|
|
22
|
+
t.Fatalf("hitungan terpotong berbeda: %d vs %d", a.total(), b.total())
|
|
23
|
+
}
|
|
24
|
+
var c tokCounter
|
|
25
|
+
c.add("你好")
|
|
26
|
+
if c.total() != 2 {
|
|
27
|
+
t.Fatalf("CJK harus 1 token/karakter, dapat %d", c.total())
|
|
28
|
+
}
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
func TestScanLinesUsageAndPartial(t *testing.T) {
|
|
32
|
+
var tc tokCounter
|
|
33
|
+
pt, ct := 0, 0
|
|
34
|
+
data := []byte("data: {\"choices\":[{\"delta\":{\"content\":\"halo\"}}]}\n\ndata: {\"choices\":[],\"usage\":{\"prompt_tokens\":7,\"completion_tokens\":3}}\n\ndata: {\"cho")
|
|
35
|
+
rest := scanLines(data, &tc, &pt, &ct)
|
|
36
|
+
if pt != 7 || ct != 3 {
|
|
37
|
+
t.Fatalf("usage salah: %d/%d", pt, ct)
|
|
38
|
+
}
|
|
39
|
+
if string(rest) != "data: {\"cho" {
|
|
40
|
+
t.Fatalf("sisa baris salah: %q", rest)
|
|
41
|
+
}
|
|
42
|
+
if tc.total() < 1 {
|
|
43
|
+
t.Fatal("token isi tidak terhitung")
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
func TestRelayStreaming(t *testing.T) {
|
|
48
|
+
// penyedia AI palsu: dua potongan lalu usage
|
|
49
|
+
up := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
50
|
+
if r.Header.Get("Authorization") != "Bearer sk-test" {
|
|
51
|
+
http.Error(w, "no", 401)
|
|
52
|
+
return
|
|
53
|
+
}
|
|
54
|
+
w.Header().Set("Content-Type", "text/event-stream")
|
|
55
|
+
fl := w.(http.Flusher)
|
|
56
|
+
fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"halo \"}}]}\n\n")
|
|
57
|
+
fl.Flush()
|
|
58
|
+
fmt.Fprint(w, "data: {\"choices\":[{\"delta\":{\"content\":\"dunia\"}}]}\n\n")
|
|
59
|
+
fl.Flush()
|
|
60
|
+
fmt.Fprint(w, "data: {\"choices\":[],\"usage\":{\"prompt_tokens\":11,\"completion_tokens\":4}}\n\ndata: [DONE]\n\n")
|
|
61
|
+
fl.Flush()
|
|
62
|
+
}))
|
|
63
|
+
defer up.Close()
|
|
64
|
+
|
|
65
|
+
var mu sync.Mutex
|
|
66
|
+
var got usage
|
|
67
|
+
node := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
68
|
+
if r.Header.Get("X-Nus-Internal") != "rahasia" {
|
|
69
|
+
http.Error(w, "forbidden", 403)
|
|
70
|
+
return
|
|
71
|
+
}
|
|
72
|
+
switch r.URL.Path {
|
|
73
|
+
case "/internal/plan":
|
|
74
|
+
p := plan{Mode: "relay", Stream: true, PT: 5, Body: map[string]json.RawMessage{"messages": json.RawMessage(`[{"role":"user","content":"hai"}]`)},
|
|
75
|
+
Targets: []target{{Provider: "mock", Model: "m1", Base: up.URL, Keys: []keyRef{{Key: "sk-salah", Kid: "k0"}, {Key: "sk-test", Kid: "k1"}}}}}
|
|
76
|
+
_ = json.NewEncoder(w).Encode(p)
|
|
77
|
+
case "/internal/usage":
|
|
78
|
+
var u usage
|
|
79
|
+
_ = json.NewDecoder(r.Body).Decode(&u)
|
|
80
|
+
mu.Lock()
|
|
81
|
+
if u.OK {
|
|
82
|
+
got = u
|
|
83
|
+
}
|
|
84
|
+
mu.Unlock()
|
|
85
|
+
}
|
|
86
|
+
}))
|
|
87
|
+
defer node.Close()
|
|
88
|
+
|
|
89
|
+
s, err := newServer(node.URL, "rahasia")
|
|
90
|
+
if err != nil {
|
|
91
|
+
t.Fatal(err)
|
|
92
|
+
}
|
|
93
|
+
front := httptest.NewServer(s.handler())
|
|
94
|
+
defer front.Close()
|
|
95
|
+
|
|
96
|
+
resp, err := http.Post(front.URL+"/v1/chat/completions", "application/json", strings.NewReader(`{"model":"demo","stream":true}`))
|
|
97
|
+
if err != nil {
|
|
98
|
+
t.Fatal(err)
|
|
99
|
+
}
|
|
100
|
+
b, _ := io.ReadAll(resp.Body)
|
|
101
|
+
resp.Body.Close()
|
|
102
|
+
if resp.StatusCode != 200 || !strings.Contains(string(b), "halo ") || !strings.Contains(string(b), "[DONE]") {
|
|
103
|
+
t.Fatalf("respons stream salah (%d): %s", resp.StatusCode, b)
|
|
104
|
+
}
|
|
105
|
+
deadline := time.Now().Add(2 * time.Second)
|
|
106
|
+
for time.Now().Before(deadline) {
|
|
107
|
+
mu.Lock()
|
|
108
|
+
ok := got.PT == 11 && got.CT == 4 && got.Kid == "k1"
|
|
109
|
+
mu.Unlock()
|
|
110
|
+
if ok {
|
|
111
|
+
return
|
|
112
|
+
}
|
|
113
|
+
time.Sleep(50 * time.Millisecond)
|
|
114
|
+
}
|
|
115
|
+
mu.Lock()
|
|
116
|
+
defer mu.Unlock()
|
|
117
|
+
t.Fatalf("usage tidak sampai/keliru: %+v (key pertama salah harus dilewati, key k1 dipakai)", got)
|
|
118
|
+
}
|
package/sidecar/meter.go
ADDED
|
@@ -0,0 +1,114 @@
|
|
|
1
|
+
package main
|
|
2
|
+
|
|
3
|
+
import (
|
|
4
|
+
"bytes"
|
|
5
|
+
"encoding/json"
|
|
6
|
+
"net/http"
|
|
7
|
+
"sync"
|
|
8
|
+
"time"
|
|
9
|
+
)
|
|
10
|
+
|
|
11
|
+
// live = satu permintaan yang sedang berjalan (dikirim ke Node tiap ~300 ms untuk tampilan realtime).
|
|
12
|
+
type live struct {
|
|
13
|
+
ID string `json:"id"`
|
|
14
|
+
Model string `json:"model"`
|
|
15
|
+
Provider string `json:"provider"`
|
|
16
|
+
State string `json:"state"` // run | done | err
|
|
17
|
+
PT int `json:"pt"`
|
|
18
|
+
CT int `json:"ct"`
|
|
19
|
+
TPS float64 `json:"tps"`
|
|
20
|
+
T0 int64 `json:"t0"`
|
|
21
|
+
Src string `json:"src"`
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
type meter struct {
|
|
25
|
+
mu sync.Mutex
|
|
26
|
+
items map[string]*live
|
|
27
|
+
dirty map[string]bool
|
|
28
|
+
node string
|
|
29
|
+
token string
|
|
30
|
+
client *http.Client
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
func newMeter(node, token string) *meter {
|
|
34
|
+
return &meter{items: map[string]*live{}, dirty: map[string]bool{}, node: node, token: token,
|
|
35
|
+
client: &http.Client{Timeout: 3 * time.Second}}
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
func (m *meter) start(l *live) {
|
|
39
|
+
m.mu.Lock()
|
|
40
|
+
l.Src = "go"
|
|
41
|
+
l.State = "run"
|
|
42
|
+
l.T0 = time.Now().UnixMilli()
|
|
43
|
+
m.items[l.ID] = l
|
|
44
|
+
m.dirty[l.ID] = true
|
|
45
|
+
m.mu.Unlock()
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
func (m *meter) tick(id string, ct int) {
|
|
49
|
+
m.mu.Lock()
|
|
50
|
+
if l, ok := m.items[id]; ok {
|
|
51
|
+
l.CT = ct
|
|
52
|
+
if dt := float64(time.Now().UnixMilli()-l.T0) / 1000; dt > 0 {
|
|
53
|
+
l.TPS = float64(ct) / dt
|
|
54
|
+
}
|
|
55
|
+
m.dirty[id] = true
|
|
56
|
+
}
|
|
57
|
+
m.mu.Unlock()
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
func (m *meter) finish(id string, pt, ct int, state string) {
|
|
61
|
+
m.mu.Lock()
|
|
62
|
+
if l, ok := m.items[id]; ok {
|
|
63
|
+
l.PT, l.CT, l.State = pt, ct, state
|
|
64
|
+
if dt := float64(time.Now().UnixMilli()-l.T0) / 1000; dt > 0 {
|
|
65
|
+
l.TPS = float64(ct) / dt
|
|
66
|
+
}
|
|
67
|
+
m.dirty[id] = true
|
|
68
|
+
}
|
|
69
|
+
m.mu.Unlock()
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// run mengirim perubahan ke Node tiap 300 ms; permintaan selesai dihapus setelah terkirim.
|
|
73
|
+
func (m *meter) run(stop <-chan struct{}) {
|
|
74
|
+
t := time.NewTicker(300 * time.Millisecond)
|
|
75
|
+
defer t.Stop()
|
|
76
|
+
for {
|
|
77
|
+
select {
|
|
78
|
+
case <-stop:
|
|
79
|
+
return
|
|
80
|
+
case <-t.C:
|
|
81
|
+
m.mu.Lock()
|
|
82
|
+
var out []live
|
|
83
|
+
for id := range m.dirty {
|
|
84
|
+
if l, ok := m.items[id]; ok {
|
|
85
|
+
out = append(out, *l)
|
|
86
|
+
if l.State != "run" {
|
|
87
|
+
delete(m.items, id)
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
m.dirty = map[string]bool{}
|
|
92
|
+
m.mu.Unlock()
|
|
93
|
+
if len(out) > 0 {
|
|
94
|
+
m.post(out)
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
func (m *meter) post(ev []live) {
|
|
101
|
+
b, err := json.Marshal(map[string]any{"events": ev})
|
|
102
|
+
if err != nil {
|
|
103
|
+
return
|
|
104
|
+
}
|
|
105
|
+
req, err := http.NewRequest("POST", m.node+"/internal/meter", bytes.NewReader(b))
|
|
106
|
+
if err != nil {
|
|
107
|
+
return
|
|
108
|
+
}
|
|
109
|
+
req.Header.Set("Content-Type", "application/json")
|
|
110
|
+
req.Header.Set("X-Nus-Internal", m.token)
|
|
111
|
+
if resp, err := m.client.Do(req); err == nil {
|
|
112
|
+
resp.Body.Close()
|
|
113
|
+
}
|
|
114
|
+
}
|