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.
@@ -0,0 +1,433 @@
1
+ package main
2
+
3
+ import (
4
+ "bytes"
5
+ "context"
6
+ "crypto/rand"
7
+ "encoding/hex"
8
+ "encoding/json"
9
+ "fmt"
10
+ "io"
11
+ "net"
12
+ "net/http"
13
+ "net/http/httputil"
14
+ "net/url"
15
+ "strconv"
16
+ "strings"
17
+ "time"
18
+ )
19
+
20
+ // ---- Bentuk rencana dari Node (control plane) ----
21
+ type keyRef struct {
22
+ Key string `json:"key"`
23
+ Kid string `json:"kid"`
24
+ }
25
+ type target struct {
26
+ Provider string `json:"provider"`
27
+ Model string `json:"model"`
28
+ Base string `json:"base"`
29
+ Keys []keyRef `json:"keys"`
30
+ }
31
+ type plan struct {
32
+ Status int `json:"status"`
33
+ Error json.RawMessage `json:"error"`
34
+ Mode string `json:"mode"` // relay | node
35
+ Stream bool `json:"stream"`
36
+ PT int `json:"pt"`
37
+ Body map[string]json.RawMessage `json:"body"`
38
+ Targets []target `json:"targets"`
39
+ }
40
+ type usage struct {
41
+ Provider string `json:"provider"`
42
+ Model string `json:"model"`
43
+ Kid string `json:"kid"`
44
+ PT int `json:"pt"`
45
+ CT int `json:"ct"`
46
+ OK bool `json:"ok"`
47
+ Status int `json:"status"`
48
+ MS int64 `json:"ms"`
49
+ TTFB int64 `json:"ttfb"`
50
+ CooldownSec int `json:"cooldownSec"`
51
+ }
52
+
53
+ type chunk struct {
54
+ Choices []struct {
55
+ Delta struct {
56
+ Content string `json:"content"`
57
+ ReasoningContent string `json:"reasoning_content"`
58
+ } `json:"delta"`
59
+ } `json:"choices"`
60
+ Usage *struct {
61
+ PromptTokens int `json:"prompt_tokens"`
62
+ CompletionTokens int `json:"completion_tokens"`
63
+ } `json:"usage"`
64
+ }
65
+
66
+ type server struct {
67
+ node *url.URL
68
+ token string
69
+ client *http.Client // ke provider AI
70
+ ctl *http.Client // ke Node (control plane)
71
+ meter *meter
72
+ proxy *httputil.ReverseProxy
73
+ }
74
+
75
+ func newServer(nodeURL, token string) (*server, error) {
76
+ u, err := url.Parse(nodeURL)
77
+ if err != nil {
78
+ return nil, err
79
+ }
80
+ hdr := 300 * time.Second
81
+ if v, err := strconv.Atoi(getenv("NUS_HEADER_TIMEOUT_SEC", "300")); err == nil && v > 0 {
82
+ hdr = time.Duration(v) * time.Second
83
+ }
84
+ tr := &http.Transport{
85
+ Proxy: http.ProxyFromEnvironment,
86
+ ForceAttemptHTTP2: true,
87
+ MaxIdleConns: 256,
88
+ MaxIdleConnsPerHost: 64,
89
+ IdleConnTimeout: 90 * time.Second,
90
+ TLSHandshakeTimeout: 10 * time.Second,
91
+ ResponseHeaderTimeout: hdr,
92
+ DisableCompression: true, // jangan buffer gzip: potongan SSE harus langsung lewat
93
+ DialContext: (&net.Dialer{Timeout: 10 * time.Second, KeepAlive: 30 * time.Second}).DialContext,
94
+ }
95
+ rp := httputil.NewSingleHostReverseProxy(u)
96
+ rp.FlushInterval = -1 // teruskan segera
97
+ orig := rp.Director
98
+ rp.Director = func(r *http.Request) { orig(r); r.Host = u.Host }
99
+ return &server{node: u, token: token, client: &http.Client{Transport: tr},
100
+ ctl: &http.Client{Timeout: 10 * time.Second}, meter: newMeter(strings.TrimRight(nodeURL, "/"), token), proxy: rp}, nil
101
+ }
102
+
103
+ func getenv(k, d string) string {
104
+ if v := strings.TrimSpace(osGetenv(k)); v != "" {
105
+ return v
106
+ }
107
+ return d
108
+ }
109
+
110
+ func newID() string {
111
+ b := make([]byte, 6)
112
+ _, _ = rand.Read(b)
113
+ return hex.EncodeToString(b)
114
+ }
115
+
116
+ func writeErr(w http.ResponseWriter, code int, msg string) {
117
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
118
+ w.WriteHeader(code)
119
+ _ = json.NewEncoder(w).Encode(map[string]any{"error": map[string]string{"message": msg}})
120
+ }
121
+
122
+ func cors(w http.ResponseWriter) {
123
+ h := w.Header()
124
+ h.Set("Access-Control-Allow-Origin", "*")
125
+ h.Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
126
+ h.Set("Access-Control-Allow-Methods", "GET, POST, OPTIONS")
127
+ h.Set("Access-Control-Expose-Headers", "X-Nus-Model")
128
+ }
129
+
130
+ func (s *server) handler() http.Handler {
131
+ mux := http.NewServeMux()
132
+ mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
133
+ w.Header().Set("Content-Type", "application/json")
134
+ _, _ = w.Write([]byte(`{"ok":true,"name":"nusproxy","version":"1.0.0"}`))
135
+ })
136
+ mux.HandleFunc("/v1/chat/completions", s.chat)
137
+ mux.Handle("/", s.proxy) // selain jalur panas: teruskan ke Node apa adanya
138
+ return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
139
+ if r.Method == http.MethodOptions && strings.HasPrefix(r.URL.Path, "/v1/") {
140
+ cors(w)
141
+ w.WriteHeader(http.StatusNoContent)
142
+ return
143
+ }
144
+ mux.ServeHTTP(w, r)
145
+ })
146
+ }
147
+
148
+ func (s *server) getPlan(ctx context.Context, auth string, body []byte) (*plan, error) {
149
+ b, err := json.Marshal(struct {
150
+ Auth string `json:"auth"`
151
+ Body json.RawMessage `json:"body"`
152
+ }{auth, json.RawMessage(body)})
153
+ if err != nil {
154
+ return nil, err
155
+ }
156
+ req, err := http.NewRequestWithContext(ctx, "POST", s.node.String()+"/internal/plan", bytes.NewReader(b))
157
+ if err != nil {
158
+ return nil, err
159
+ }
160
+ req.Header.Set("Content-Type", "application/json")
161
+ req.Header.Set("X-Nus-Internal", s.token)
162
+ resp, err := s.ctl.Do(req)
163
+ if err != nil {
164
+ return nil, err
165
+ }
166
+ defer resp.Body.Close()
167
+ var p plan
168
+ if err := json.NewDecoder(io.LimitReader(resp.Body, 64<<20)).Decode(&p); err != nil {
169
+ return nil, err
170
+ }
171
+ return &p, nil
172
+ }
173
+
174
+ func (s *server) chat(w http.ResponseWriter, r *http.Request) {
175
+ cors(w)
176
+ if r.Method != http.MethodPost {
177
+ writeErr(w, 404, "Endpoint tidak ada")
178
+ return
179
+ }
180
+ body, err := io.ReadAll(io.LimitReader(r.Body, 32<<20))
181
+ if err != nil {
182
+ writeErr(w, 400, "Body tidak terbaca")
183
+ return
184
+ }
185
+ p, err := s.getPlan(r.Context(), r.Header.Get("Authorization"), body)
186
+ if err != nil {
187
+ writeErr(w, 502, "Node tidak menjawab: "+err.Error())
188
+ return
189
+ }
190
+ if p.Status != 0 && p.Status != 200 {
191
+ w.Header().Set("Content-Type", "application/json; charset=utf-8")
192
+ w.WriteHeader(p.Status)
193
+ _, _ = w.Write(p.Error)
194
+ return
195
+ }
196
+ if p.Mode == "node" { // fusion / agent CLI: logikanya ada di Node
197
+ r.Body = io.NopCloser(bytes.NewReader(body))
198
+ r.ContentLength = int64(len(body))
199
+ s.proxy.ServeHTTP(w, r)
200
+ return
201
+ }
202
+ s.relay(w, r, p)
203
+ }
204
+
205
+ type outcome int
206
+
207
+ const (
208
+ delivered outcome = iota
209
+ tryNextKey
210
+ tryNextTarget
211
+ )
212
+
213
+ func (s *server) relay(w http.ResponseWriter, r *http.Request, p *plan) {
214
+ id := newID()
215
+ last := "tidak ada target"
216
+ for _, t := range p.Targets {
217
+ for _, k := range t.Keys {
218
+ oc, msg := s.attempt(r.Context(), w, p, t, k, id)
219
+ if oc == delivered {
220
+ return
221
+ }
222
+ last = t.Provider + "/" + t.Model + " → " + msg
223
+ if oc == tryNextTarget {
224
+ break
225
+ }
226
+ }
227
+ }
228
+ writeErr(w, 502, "Semua target gagal: "+last)
229
+ }
230
+
231
+ func rawString(s string) json.RawMessage { b, _ := json.Marshal(s); return b }
232
+
233
+ func (s *server) post(path string, v any) {
234
+ b, err := json.Marshal(v)
235
+ if err != nil {
236
+ return
237
+ }
238
+ req, err := http.NewRequest("POST", s.node.String()+path, bytes.NewReader(b))
239
+ if err != nil {
240
+ return
241
+ }
242
+ req.Header.Set("Content-Type", "application/json")
243
+ req.Header.Set("X-Nus-Internal", s.token)
244
+ if resp, err := s.ctl.Do(req); err == nil {
245
+ resp.Body.Close()
246
+ }
247
+ }
248
+
249
+ func (s *server) attempt(ctx context.Context, w http.ResponseWriter, p *plan, t target, k keyRef, id string) (outcome, string) {
250
+ payload := make(map[string]json.RawMessage, len(p.Body)+2)
251
+ for kk, vv := range p.Body {
252
+ payload[kk] = vv
253
+ }
254
+ payload["model"] = rawString(t.Model)
255
+ if p.Stream {
256
+ payload["stream"] = json.RawMessage("true")
257
+ if _, has := payload["stream_options"]; !has {
258
+ payload["stream_options"] = json.RawMessage(`{"include_usage":true}`)
259
+ }
260
+ } else {
261
+ payload["stream"] = json.RawMessage("false")
262
+ }
263
+ for pass := 0; pass < 2; pass++ {
264
+ b, err := json.Marshal(payload)
265
+ if err != nil {
266
+ return tryNextTarget, err.Error()
267
+ }
268
+ req, err := http.NewRequestWithContext(ctx, "POST", strings.TrimRight(t.Base, "/")+"/chat/completions", bytes.NewReader(b))
269
+ if err != nil {
270
+ return tryNextTarget, err.Error()
271
+ }
272
+ req.Header.Set("Content-Type", "application/json")
273
+ if k.Key != "" {
274
+ req.Header.Set("Authorization", "Bearer "+k.Key)
275
+ }
276
+ if p.Stream {
277
+ req.Header.Set("Accept", "text/event-stream")
278
+ }
279
+ t0 := time.Now()
280
+ resp, err := s.client.Do(req)
281
+ if err != nil {
282
+ go s.post("/internal/usage", usage{Provider: t.Provider, Model: t.Model, Kid: k.Kid, OK: false, MS: time.Since(t0).Milliseconds()})
283
+ return tryNextTarget, err.Error()
284
+ }
285
+ if resp.StatusCode >= 400 {
286
+ eb, _ := io.ReadAll(io.LimitReader(resp.Body, 2048))
287
+ resp.Body.Close()
288
+ msg := fmt.Sprintf("%d %s", resp.StatusCode, strings.TrimSpace(string(eb)))
289
+ // sebagian provider menolak stream_options: ulangi tanpa itu
290
+ if pass == 0 && p.Stream && (resp.StatusCode == 400 || resp.StatusCode == 422) && strings.Contains(string(eb), "stream_options") {
291
+ delete(payload, "stream_options")
292
+ continue
293
+ }
294
+ cd := 0
295
+ switch resp.StatusCode {
296
+ case 401, 402, 403:
297
+ cd = 600
298
+ case 429:
299
+ cd = 60
300
+ if ra, err := strconv.Atoi(resp.Header.Get("Retry-After")); err == nil && ra > 0 {
301
+ cd = ra
302
+ }
303
+ }
304
+ go s.post("/internal/usage", usage{Provider: t.Provider, Model: t.Model, Kid: k.Kid, OK: false, Status: resp.StatusCode, MS: time.Since(t0).Milliseconds(), CooldownSec: cd})
305
+ if cd > 0 {
306
+ return tryNextKey, msg
307
+ }
308
+ return tryNextTarget, msg
309
+ }
310
+ s.deliver(w, resp, p, t, k, id, t0)
311
+ return delivered, ""
312
+ }
313
+ return tryNextTarget, "stream_options ditolak"
314
+ }
315
+
316
+ // scanLines membaca baris SSE lengkap dari data, menghitung token isi, dan mengembalikan sisa tanpa newline.
317
+ func scanLines(data []byte, tc *tokCounter, upt, uct *int) []byte {
318
+ for {
319
+ i := bytes.IndexByte(data, '\n')
320
+ if i < 0 {
321
+ break
322
+ }
323
+ line := bytes.TrimSpace(data[:i])
324
+ data = data[i+1:]
325
+ if !bytes.HasPrefix(line, []byte("data:")) {
326
+ continue
327
+ }
328
+ js := bytes.TrimSpace(line[5:])
329
+ if len(js) == 0 || string(js) == "[DONE]" {
330
+ continue
331
+ }
332
+ var ch chunk
333
+ if json.Unmarshal(js, &ch) != nil {
334
+ continue
335
+ }
336
+ for _, c := range ch.Choices {
337
+ tc.add(c.Delta.Content)
338
+ tc.add(c.Delta.ReasoningContent)
339
+ }
340
+ if ch.Usage != nil {
341
+ *upt, *uct = ch.Usage.PromptTokens, ch.Usage.CompletionTokens
342
+ }
343
+ }
344
+ return data
345
+ }
346
+
347
+ func (s *server) deliver(w http.ResponseWriter, resp *http.Response, p *plan, t target, k keyRef, id string, t0 time.Time) {
348
+ defer resp.Body.Close()
349
+ s.meter.start(&live{ID: id, Model: t.Model, Provider: t.Provider, PT: p.PT})
350
+ h := w.Header()
351
+ h.Set("X-Nus-Model", t.Provider+"/"+t.Model)
352
+ if !p.Stream {
353
+ b, _ := io.ReadAll(io.LimitReader(resp.Body, 64<<20))
354
+ var j struct {
355
+ Usage struct {
356
+ PromptTokens int `json:"prompt_tokens"`
357
+ CompletionTokens int `json:"completion_tokens"`
358
+ } `json:"usage"`
359
+ }
360
+ _ = json.Unmarshal(b, &j)
361
+ pt, ct := j.Usage.PromptTokens, j.Usage.CompletionTokens
362
+ if pt == 0 {
363
+ pt = p.PT
364
+ }
365
+ if ct == 0 {
366
+ var tc tokCounter
367
+ tc.add(string(b))
368
+ ct = tc.total()
369
+ }
370
+ ctype := resp.Header.Get("Content-Type")
371
+ if ctype == "" {
372
+ ctype = "application/json"
373
+ }
374
+ h.Set("Content-Type", ctype)
375
+ w.WriteHeader(http.StatusOK)
376
+ _, _ = w.Write(b)
377
+ s.meter.finish(id, pt, ct, "done")
378
+ go s.post("/internal/usage", usage{Provider: t.Provider, Model: t.Model, Kid: k.Kid, PT: pt, CT: ct, OK: true, Status: 200, MS: time.Since(t0).Milliseconds()})
379
+ return
380
+ }
381
+ h.Set("Content-Type", "text/event-stream")
382
+ h.Set("Cache-Control", "no-cache")
383
+ h.Set("X-Accel-Buffering", "no")
384
+ w.WriteHeader(http.StatusOK)
385
+ fl, _ := w.(http.Flusher)
386
+ if fl != nil {
387
+ fl.Flush()
388
+ }
389
+ buf := make([]byte, 16<<10)
390
+ var carry []byte
391
+ tc := &tokCounter{}
392
+ upt, uct := 0, 0
393
+ var ttfb time.Duration
394
+ first, aborted := true, false
395
+ for {
396
+ n, err := resp.Body.Read(buf)
397
+ if n > 0 {
398
+ if first {
399
+ ttfb = time.Since(t0)
400
+ first = false
401
+ }
402
+ if _, werr := w.Write(buf[:n]); werr != nil { // klien putus: hentikan, bebaskan koneksi
403
+ aborted = true
404
+ break
405
+ }
406
+ if fl != nil {
407
+ fl.Flush()
408
+ }
409
+ carry = append(carry, buf[:n]...)
410
+ carry = scanLines(carry, tc, &upt, &uct)
411
+ if len(carry) > 1<<20 {
412
+ carry = nil
413
+ }
414
+ s.meter.tick(id, tc.total())
415
+ }
416
+ if err != nil {
417
+ break
418
+ }
419
+ }
420
+ pt, ct := upt, uct
421
+ if pt == 0 {
422
+ pt = p.PT
423
+ }
424
+ if ct == 0 {
425
+ ct = tc.total()
426
+ }
427
+ state := "done"
428
+ if aborted {
429
+ state = "err"
430
+ }
431
+ s.meter.finish(id, pt, ct, state)
432
+ go s.post("/internal/usage", usage{Provider: t.Provider, Model: t.Model, Kid: k.Kid, PT: pt, CT: ct, OK: !aborted, Status: 200, MS: time.Since(t0).Milliseconds(), TTFB: ttfb.Milliseconds()})
433
+ }
@@ -0,0 +1,42 @@
1
+ package main
2
+
3
+ import "unicode"
4
+
5
+ // tokCounter memperkirakan jumlah token secara bertahap (streaming) tanpa tokenizer penuh:
6
+ // kata/angka ≈ 1 token per 4 karakter, tanda baca dan aksara CJK ≈ 1 token per karakter.
7
+ // Hasilnya estimasi; jika provider mengirim angka `usage`, angka itu yang dipakai.
8
+ type tokCounter struct {
9
+ n int // token yang sudah pasti
10
+ run int // panjang kata yang sedang berjalan (bisa terpotong antar potongan stream)
11
+ }
12
+
13
+ func isCJK(r rune) bool {
14
+ return unicode.Is(unicode.Han, r) || unicode.Is(unicode.Hiragana, r) ||
15
+ unicode.Is(unicode.Katakana, r) || unicode.Is(unicode.Hangul, r)
16
+ }
17
+
18
+ func (t *tokCounter) flush() {
19
+ if t.run > 0 {
20
+ t.n += (t.run + 3) / 4
21
+ t.run = 0
22
+ }
23
+ }
24
+
25
+ func (t *tokCounter) add(s string) {
26
+ for _, r := range s {
27
+ switch {
28
+ case isCJK(r):
29
+ t.flush()
30
+ t.n++
31
+ case unicode.IsLetter(r) || unicode.IsDigit(r):
32
+ t.run++
33
+ case unicode.IsSpace(r):
34
+ t.flush()
35
+ default:
36
+ t.flush()
37
+ t.n++
38
+ }
39
+ }
40
+ }
41
+
42
+ func (t *tokCounter) total() int { return t.n + (t.run+3)/4 }
@@ -0,0 +1,9 @@
1
+ ---
2
+ name: ringkas-kode
3
+ description: Ringkas file kode atau teks menjadi poin singkat (contoh skill dengan skrip run.js)
4
+ ---
5
+ Saat pengguna meminta ringkasan kode, jawab dengan:
6
+ 1. Tujuan file dalam satu kalimat.
7
+ 2. Daftar fungsi/kelas utama (maks 7 poin).
8
+ 3. Risiko atau bug yang terlihat.
9
+ Pertahankan nama fungsi persis seperti di kode.
@@ -0,0 +1,5 @@
1
+ // Contoh eksekusi skill: hitung baris/kata dari SKILL_INPUT (atau argumen) dan cetak ringkasan.
2
+ const text = process.env.SKILL_INPUT || process.argv.slice(2).join(' ');
3
+ const lines = text ? text.split(/\r?\n/).length : 0;
4
+ const words = (text.match(/\S+/g) || []).length;
5
+ console.log(JSON.stringify({ lines, words, chars: text.length }));