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
package/dist/hub.js
ADDED
|
@@ -0,0 +1,318 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
|
|
3
|
+
if (k2 === undefined) k2 = k;
|
|
4
|
+
var desc = Object.getOwnPropertyDescriptor(m, k);
|
|
5
|
+
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
|
|
6
|
+
desc = { enumerable: true, get: function() { return m[k]; } };
|
|
7
|
+
}
|
|
8
|
+
Object.defineProperty(o, k2, desc);
|
|
9
|
+
}) : (function(o, m, k, k2) {
|
|
10
|
+
if (k2 === undefined) k2 = k;
|
|
11
|
+
o[k2] = m[k];
|
|
12
|
+
}));
|
|
13
|
+
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
|
|
14
|
+
Object.defineProperty(o, "default", { enumerable: true, value: v });
|
|
15
|
+
}) : function(o, v) {
|
|
16
|
+
o["default"] = v;
|
|
17
|
+
});
|
|
18
|
+
var __importStar = (this && this.__importStar) || (function () {
|
|
19
|
+
var ownKeys = function(o) {
|
|
20
|
+
ownKeys = Object.getOwnPropertyNames || function (o) {
|
|
21
|
+
var ar = [];
|
|
22
|
+
for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
|
|
23
|
+
return ar;
|
|
24
|
+
};
|
|
25
|
+
return ownKeys(o);
|
|
26
|
+
};
|
|
27
|
+
return function (mod) {
|
|
28
|
+
if (mod && mod.__esModule) return mod;
|
|
29
|
+
var result = {};
|
|
30
|
+
if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
|
|
31
|
+
__setModuleDefault(result, mod);
|
|
32
|
+
return result;
|
|
33
|
+
};
|
|
34
|
+
})();
|
|
35
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
36
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
37
|
+
};
|
|
38
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
39
|
+
exports.mcpList = exports.sourceOf = void 0;
|
|
40
|
+
exports.searchRepos = searchRepos;
|
|
41
|
+
exports.listSkills = listSkills;
|
|
42
|
+
exports.installSkill = installSkill;
|
|
43
|
+
exports.checkUpdates = checkUpdates;
|
|
44
|
+
exports.updateSkill = updateSkill;
|
|
45
|
+
exports.mcpSearch = mcpSearch;
|
|
46
|
+
exports.mcpInstall = mcpInstall;
|
|
47
|
+
exports.mcpToggle = mcpToggle;
|
|
48
|
+
exports.mcpRemove = mcpRemove;
|
|
49
|
+
exports.applyMcp = applyMcp;
|
|
50
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
51
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
52
|
+
const config_1 = require("./config");
|
|
53
|
+
const store_1 = require("./store");
|
|
54
|
+
const logs_1 = require("./logs");
|
|
55
|
+
const util_1 = require("./util");
|
|
56
|
+
const skills = __importStar(require("./skills"));
|
|
57
|
+
const API = (process.env.GITHUB_API || 'https://api.github.com').replace(/\/+$/, '');
|
|
58
|
+
const RAW = (process.env.GITHUB_RAW || 'https://raw.githubusercontent.com').replace(/\/+$/, '');
|
|
59
|
+
const REG = (process.env.MCP_REGISTRY || 'https://registry.modelcontextprotocol.io/v0.1').replace(/\/+$/, '');
|
|
60
|
+
const UA = { 'User-Agent': 'ChatNUS-Hub', Accept: 'application/vnd.github+json' };
|
|
61
|
+
const auth = () => (process.env.GITHUB_TOKEN ? { Authorization: 'Bearer ' + process.env.GITHUB_TOKEN } : {});
|
|
62
|
+
const REPO = /^[\w.-]{1,100}\/[\w.-]{1,100}$/;
|
|
63
|
+
async function gh(p) {
|
|
64
|
+
const r = await fetch(API + p, { headers: { ...UA, ...auth() }, signal: AbortSignal.timeout(20000) });
|
|
65
|
+
if (r.status === 403 || r.status === 429)
|
|
66
|
+
throw new Error('Batas API GitHub tercapai (tanpa login ±10 pencarian/menit). Set GITHUB_TOKEN di .env untuk batas lebih longgar.');
|
|
67
|
+
if (r.status === 404)
|
|
68
|
+
throw new Error('Repo / path tidak ditemukan di GitHub');
|
|
69
|
+
if (!r.ok)
|
|
70
|
+
throw new Error('GitHub HTTP ' + r.status);
|
|
71
|
+
return r.json();
|
|
72
|
+
}
|
|
73
|
+
const mapRepo = (x) => ({ repo: x.full_name, description: x.description || '', stars: x.stargazers_count || 0, url: x.html_url, pushed: x.pushed_at, branch: x.default_branch, topics: x.topics || [], license: x.license?.spdx_id || '' });
|
|
74
|
+
/** Cari repo di GitHub secara langsung (topik skill / MCP), atau terima owner/repo & URL GitHub. */
|
|
75
|
+
async function searchRepos(q, kind) {
|
|
76
|
+
q = String(q || '').trim();
|
|
77
|
+
const d = /^(?:https?:\/\/github\.com\/)?([\w.-]+)\/([\w.-]+?)(?:\.git)?\/?$/.exec(q);
|
|
78
|
+
if (d && !/\s/.test(q)) {
|
|
79
|
+
try {
|
|
80
|
+
return [mapRepo(await gh('/repos/' + d[1] + '/' + d[2]))];
|
|
81
|
+
}
|
|
82
|
+
catch { /* lanjut ke pencarian */ }
|
|
83
|
+
}
|
|
84
|
+
const topics = kind === 'mcp' ? ['mcp-server'] : ['agent-skills', 'claude-skills'];
|
|
85
|
+
const res = await Promise.allSettled(topics.map(t => gh('/search/repositories?q=' + encodeURIComponent((q ? q + ' ' : '') + 'topic:' + t) + '&sort=stars&order=desc&per_page=15')));
|
|
86
|
+
const seen = new Map();
|
|
87
|
+
let err = '';
|
|
88
|
+
for (const r of res) {
|
|
89
|
+
if (r.status === 'fulfilled')
|
|
90
|
+
for (const it of r.value.items || [])
|
|
91
|
+
seen.set(it.full_name, mapRepo(it));
|
|
92
|
+
else
|
|
93
|
+
err = (0, util_1.errMsg)(r.reason);
|
|
94
|
+
}
|
|
95
|
+
if (!seen.size && err)
|
|
96
|
+
throw new Error(err);
|
|
97
|
+
return [...seen.values()].sort((a, b) => b.stars - a.stars).slice(0, 25);
|
|
98
|
+
}
|
|
99
|
+
async function tree(repo, branch) {
|
|
100
|
+
if (!REPO.test(repo))
|
|
101
|
+
throw new Error('Format repo harus owner/nama');
|
|
102
|
+
const b = branch || (await gh('/repos/' + repo)).default_branch;
|
|
103
|
+
const t = await gh('/repos/' + repo + '/git/trees/' + encodeURIComponent(b) + '?recursive=1');
|
|
104
|
+
return { branch: b, entries: (t.tree || []), truncated: !!t.truncated };
|
|
105
|
+
}
|
|
106
|
+
/** Semua SKILL.md di dalam repo. */
|
|
107
|
+
async function listSkills(repo, branch) {
|
|
108
|
+
const t = await tree(repo, branch);
|
|
109
|
+
const found = t.entries.filter(e => e.type === 'blob' && /(^|\/)SKILL\.md$/i.test(e.path)).slice(0, 150).map(e => {
|
|
110
|
+
const dir = e.path.replace(/\/?SKILL\.md$/i, '');
|
|
111
|
+
return { dir, name: node_path_1.default.basename(dir) || repo.split('/')[1], sha: e.sha, installed: node_fs_1.default.existsSync(node_path_1.default.join(config_1.SKILLS_DIR, skills.safeName(node_path_1.default.basename(dir) || repo.split('/')[1]), 'SKILL.md')) };
|
|
112
|
+
});
|
|
113
|
+
return { branch: t.branch, truncated: t.truncated, skills: found };
|
|
114
|
+
}
|
|
115
|
+
const SRC = '.nus-source.json';
|
|
116
|
+
const readSrc = (d) => { try {
|
|
117
|
+
return JSON.parse(node_fs_1.default.readFileSync(node_path_1.default.join(d, SRC), 'utf8'));
|
|
118
|
+
}
|
|
119
|
+
catch {
|
|
120
|
+
return null;
|
|
121
|
+
} };
|
|
122
|
+
/** Pasang skill dari GitHub: unduh SKILL.md + berkas pendamping (batas ukuran), catat sumbernya untuk pembaruan. */
|
|
123
|
+
async function installSkill(repo, dir, branch, force = false) {
|
|
124
|
+
if (!/^[\w ./-]{0,200}$/.test(dir) || dir.split('/').includes('..') || dir.startsWith('/'))
|
|
125
|
+
throw new Error('Path skill tidak valid');
|
|
126
|
+
const t = await tree(repo, branch), pre = dir ? dir.replace(/\/+$/, '') + '/' : '';
|
|
127
|
+
const skillMd = t.entries.find(e => e.type === 'blob' && e.path.toLowerCase() === (pre + 'skill.md'));
|
|
128
|
+
if (!skillMd)
|
|
129
|
+
throw new Error('SKILL.md tidak ada di ' + (dir || 'root repo'));
|
|
130
|
+
let files = t.entries.filter(e => e.type === 'blob' && e.path.startsWith(pre) && !e.path.split('/').includes('..') && !/(^|\/)(\.git|node_modules)(\/|$)/.test(e.path) && (e.size || 0) <= 300000);
|
|
131
|
+
if (!dir)
|
|
132
|
+
files = files.filter(e => e.path.split('/').length <= 3);
|
|
133
|
+
files = files.slice(0, 40);
|
|
134
|
+
if (files.reduce((n, e) => n + (e.size || 0), 0) > 2e6)
|
|
135
|
+
throw new Error('Skill terlalu besar (>2 MB)');
|
|
136
|
+
const raw = async (p) => {
|
|
137
|
+
const r = await fetch(RAW + '/' + repo + '/' + encodeURIComponent(t.branch) + '/' + p.split('/').map(encodeURIComponent).join('/'), { headers: { 'User-Agent': 'ChatNUS-Hub', ...auth() }, signal: AbortSignal.timeout(20000) });
|
|
138
|
+
if (!r.ok)
|
|
139
|
+
throw new Error('Gagal mengunduh ' + p + ' (HTTP ' + r.status + ')');
|
|
140
|
+
return Buffer.from(await r.arrayBuffer());
|
|
141
|
+
};
|
|
142
|
+
const md = (await raw(skillMd.path)).toString('utf8');
|
|
143
|
+
const fm = /^---\r?\n([\s\S]*?)\r?\n---/.exec(md), nm = fm && /^name\s*:\s*["']?([^"'\r\n]+)/m.exec(fm[1]);
|
|
144
|
+
const name = skills.safeName((nm && nm[1].trim()) || node_path_1.default.basename(dir) || repo.split('/')[1]);
|
|
145
|
+
if (!skills.validName(name))
|
|
146
|
+
throw new Error('Nama skill tidak valid: ' + name);
|
|
147
|
+
const target = node_path_1.default.join(config_1.SKILLS_DIR, name), old = readSrc(target);
|
|
148
|
+
if (node_fs_1.default.existsSync(target) && !force && !(old && old.repo === repo && old.dir === dir))
|
|
149
|
+
throw new Error('Sudah ada skill lokal bernama "' + name + '". Hapus dulu atau pakai nama lain.');
|
|
150
|
+
node_fs_1.default.mkdirSync(target, { recursive: true });
|
|
151
|
+
const scripts = [];
|
|
152
|
+
for (const e of files) {
|
|
153
|
+
const rel = e.path.slice(pre.length);
|
|
154
|
+
const dest = node_path_1.default.resolve(target, rel);
|
|
155
|
+
if (dest !== target && !dest.startsWith(target + node_path_1.default.sep))
|
|
156
|
+
continue; // anti path traversal
|
|
157
|
+
node_fs_1.default.mkdirSync(node_path_1.default.dirname(dest), { recursive: true });
|
|
158
|
+
node_fs_1.default.writeFileSync(dest, e.path === skillMd.path ? Buffer.from(md) : await raw(e.path));
|
|
159
|
+
if (/\.(js|mjs|py|sh|ps1|cmd|bat|exe)$/i.test(rel))
|
|
160
|
+
scripts.push(rel);
|
|
161
|
+
}
|
|
162
|
+
if (node_path_1.default.basename(skillMd.path) !== 'SKILL.md')
|
|
163
|
+
node_fs_1.default.renameSync(node_path_1.default.join(target, node_path_1.default.basename(skillMd.path)), node_path_1.default.join(target, 'SKILL.md'));
|
|
164
|
+
node_fs_1.default.writeFileSync(node_path_1.default.join(target, SRC), JSON.stringify({ repo, dir, branch: t.branch, sha: skillMd.sha, installedAt: new Date().toISOString() }, null, 2));
|
|
165
|
+
(0, logs_1.clog)('OK', 'hub', 'Skill terpasang dari GitHub: ' + name + ' (' + repo + ')' + (scripts.length ? ' · berisi skrip: ' + scripts.join(', ') : ''));
|
|
166
|
+
return { name, files: files.length, scripts, sha: skillMd.sha };
|
|
167
|
+
}
|
|
168
|
+
/** Cek pembaruan realtime: bandingkan SHA SKILL.md terpasang dengan GitHub. */
|
|
169
|
+
async function checkUpdates() {
|
|
170
|
+
const out = [], byRepo = new Map();
|
|
171
|
+
for (const s of skills.list()) {
|
|
172
|
+
const src = readSrc(node_path_1.default.join(config_1.SKILLS_DIR, s.name));
|
|
173
|
+
if (src)
|
|
174
|
+
byRepo.set(src.repo, [...(byRepo.get(src.repo) || []), { name: s.name, dir: src.dir, sha: src.sha, branch: src.branch }]);
|
|
175
|
+
}
|
|
176
|
+
for (const [repo, arr] of byRepo) {
|
|
177
|
+
try {
|
|
178
|
+
const t = await tree(repo, arr[0].branch);
|
|
179
|
+
for (const a of arr) {
|
|
180
|
+
const e = t.entries.find(x => x.path.toLowerCase() === ((a.dir ? a.dir + '/' : '') + 'skill.md'));
|
|
181
|
+
out.push({ name: a.name, repo, update: !!e && e.sha !== a.sha });
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
catch (e) {
|
|
185
|
+
for (const a of arr)
|
|
186
|
+
out.push({ name: a.name, repo, update: false, error: (0, util_1.errMsg)(e) });
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
return out;
|
|
190
|
+
}
|
|
191
|
+
const sourceOf = (name) => readSrc(node_path_1.default.join(config_1.SKILLS_DIR, name));
|
|
192
|
+
exports.sourceOf = sourceOf;
|
|
193
|
+
async function updateSkill(name) {
|
|
194
|
+
const s = (0, exports.sourceOf)(name);
|
|
195
|
+
if (!s)
|
|
196
|
+
throw new Error('Skill ini bukan dari GitHub');
|
|
197
|
+
return installSkill(s.repo, s.dir, s.branch, true);
|
|
198
|
+
}
|
|
199
|
+
const store = (0, store_1.open)('mcp.json', { servers: {}, applied: [] });
|
|
200
|
+
const win = process.platform === 'win32';
|
|
201
|
+
async function mcpSearch(q, cursor) {
|
|
202
|
+
const r = await fetch(REG + '/servers?limit=20' + (q ? '&search=' + encodeURIComponent(q) : '') + (cursor ? '&cursor=' + encodeURIComponent(cursor) : ''), { headers: { 'User-Agent': 'ChatNUS-Hub' }, signal: AbortSignal.timeout(20000) });
|
|
203
|
+
if (!r.ok)
|
|
204
|
+
throw new Error('Registry MCP HTTP ' + r.status);
|
|
205
|
+
const j = await r.json(), seen = new Set();
|
|
206
|
+
const servers = (j.servers || []).map((x) => x.server || x).filter((s) => s && s.name && !seen.has(s.name) && seen.add(s.name)).map((s) => ({
|
|
207
|
+
name: s.name, title: s.title || '', description: s.description || '', version: s.version || '', repo: s.repository?.url || '',
|
|
208
|
+
packages: (s.packages || []).map((p) => ({ type: p.registryType, id: p.identifier, version: p.version || '', transport: p.transport?.type || 'stdio',
|
|
209
|
+
env: (p.environmentVariables || []).map((e) => ({ name: e.name, desc: e.description || '', required: !!e.isRequired, secret: !!e.isSecret, def: e.default || '' })) })),
|
|
210
|
+
remotes: (s.remotes || []).map((x) => ({ type: x.type, url: x.url, headers: (x.headers || []).map((h) => ({ name: h.name, desc: h.description || '', required: !!h.isRequired, secret: !!h.isSecret })) })),
|
|
211
|
+
installed: !!store.data.servers[mcpKey(s.name)]
|
|
212
|
+
}));
|
|
213
|
+
return { servers, next: j.metadata?.nextCursor || '' };
|
|
214
|
+
}
|
|
215
|
+
const mcpKey = (n) => String(n).split('/').pop().toLowerCase().replace(/[^a-z0-9_-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40) || 'mcp';
|
|
216
|
+
async function mcpInstall(name, pick, env) {
|
|
217
|
+
const r = await mcpSearch(name), s = r.servers.find((x) => x.name === name);
|
|
218
|
+
if (!s)
|
|
219
|
+
throw new Error('Server tidak ditemukan di registry: ' + name);
|
|
220
|
+
const key = mcpKey(name), safeEnv = {};
|
|
221
|
+
const okKey = pick.kind === 'remote' ? /^[A-Za-z0-9_-]{1,60}$/ : /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
222
|
+
for (const [k, v] of Object.entries(env || {}))
|
|
223
|
+
if (okKey.test(k) && String(v) !== '')
|
|
224
|
+
safeEnv[k] = String(v);
|
|
225
|
+
let m;
|
|
226
|
+
if (pick.kind === 'remote') {
|
|
227
|
+
const rm = s.remotes[pick.index];
|
|
228
|
+
if (!rm)
|
|
229
|
+
throw new Error('Remote tidak ada');
|
|
230
|
+
m = { name: key, kind: 'remote', url: rm.url, env: {}, headers: Object.fromEntries(Object.entries(safeEnv)), enabled: true, repo: s.repo, version: s.version };
|
|
231
|
+
}
|
|
232
|
+
else {
|
|
233
|
+
const p = s.packages[pick.index];
|
|
234
|
+
if (!p)
|
|
235
|
+
throw new Error('Paket tidak ada');
|
|
236
|
+
for (const e of p.env)
|
|
237
|
+
if (e.required && !safeEnv[e.name] && !e.def)
|
|
238
|
+
throw new Error('Variabel wajib belum diisi: ' + e.name);
|
|
239
|
+
let cmd, args;
|
|
240
|
+
if (p.type === 'npm') {
|
|
241
|
+
cmd = 'npx';
|
|
242
|
+
args = ['-y', p.id + (p.version ? '@' + p.version : '')];
|
|
243
|
+
}
|
|
244
|
+
else if (p.type === 'pypi') {
|
|
245
|
+
cmd = 'uvx';
|
|
246
|
+
args = [p.id + (p.version ? '==' + p.version : '')];
|
|
247
|
+
}
|
|
248
|
+
else if (p.type === 'oci') {
|
|
249
|
+
cmd = 'docker';
|
|
250
|
+
args = ['run', '-i', '--rm', ...Object.keys(safeEnv).flatMap(k => ['-e', k]), p.id];
|
|
251
|
+
}
|
|
252
|
+
else
|
|
253
|
+
throw new Error('Jenis paket belum didukung: ' + p.type);
|
|
254
|
+
if (win && p.type !== 'oci') {
|
|
255
|
+
args = ['/c', cmd, ...args];
|
|
256
|
+
cmd = 'cmd';
|
|
257
|
+
} // npx/uvx di Windows butuh cmd /c
|
|
258
|
+
m = { name: key, kind: 'local', command: cmd, args, env: safeEnv, enabled: true, repo: s.repo, version: p.version || s.version };
|
|
259
|
+
}
|
|
260
|
+
store.data.servers[key] = m;
|
|
261
|
+
store.save();
|
|
262
|
+
applyMcp();
|
|
263
|
+
(0, logs_1.clog)('OK', 'hub', 'MCP dipasang: ' + key + ' (' + name + ')');
|
|
264
|
+
return key;
|
|
265
|
+
}
|
|
266
|
+
const mcpList = () => Object.values(store.data.servers).map(m => ({ ...m, env: Object.fromEntries(Object.entries(m.env).map(([k, v]) => [k, (0, util_1.mask)(v)])), headers: m.headers ? Object.fromEntries(Object.entries(m.headers).map(([k, v]) => [k, (0, util_1.mask)(v)])) : undefined }));
|
|
267
|
+
exports.mcpList = mcpList;
|
|
268
|
+
function mcpToggle(key, on) { const m = store.data.servers[key]; if (!m)
|
|
269
|
+
return false; m.enabled = on; store.save(); applyMcp(); return true; }
|
|
270
|
+
function mcpRemove(key) { if (!store.data.servers[key])
|
|
271
|
+
return false; delete store.data.servers[key]; store.save(); applyMcp(); return true; }
|
|
272
|
+
const readJson = (f) => { try {
|
|
273
|
+
return JSON.parse(node_fs_1.default.readFileSync(f, 'utf8').replace(/^\uFEFF/, ''));
|
|
274
|
+
}
|
|
275
|
+
catch {
|
|
276
|
+
return null;
|
|
277
|
+
} };
|
|
278
|
+
function writeJson(f, o) { try {
|
|
279
|
+
if (node_fs_1.default.existsSync(f))
|
|
280
|
+
node_fs_1.default.copyFileSync(f, f + '.nus-bak');
|
|
281
|
+
}
|
|
282
|
+
catch { /* ok */ } node_fs_1.default.writeFileSync(f, JSON.stringify(o, null, 2) + '\n'); }
|
|
283
|
+
/** Terapkan MCP aktif ke opencode.json (mcp) dan .mcp.json (mcpServers) di workspace; yang dilepas dihapus. */
|
|
284
|
+
function applyMcp(cwd) {
|
|
285
|
+
const dir = cwd && node_fs_1.default.existsSync(cwd) ? cwd : config_1.ROOT, on = Object.values(store.data.servers).filter(m => m.enabled), touched = [];
|
|
286
|
+
const prev = store.data.applied;
|
|
287
|
+
const oc = node_path_1.default.join(dir, 'opencode.json'), cl = node_path_1.default.join(dir, '.mcp.json');
|
|
288
|
+
if (node_fs_1.default.existsSync(oc) || on.length) {
|
|
289
|
+
const o = readJson(oc) ?? (node_fs_1.default.existsSync(oc) ? undefined : {});
|
|
290
|
+
if (o !== undefined && o !== null) { // jangan timpa file yang tidak valid
|
|
291
|
+
o.mcp = o.mcp || {};
|
|
292
|
+
for (const n of prev)
|
|
293
|
+
delete o.mcp[n];
|
|
294
|
+
for (const m of on)
|
|
295
|
+
o.mcp[m.name] = m.kind === 'remote' ? { type: 'remote', url: m.url, enabled: true, ...(m.headers && Object.keys(m.headers).length ? { headers: m.headers } : {}) }
|
|
296
|
+
: { type: 'local', command: [m.command, ...(m.args || [])], enabled: true, ...(Object.keys(m.env).length ? { environment: m.env } : {}) };
|
|
297
|
+
if (!Object.keys(o.mcp).length)
|
|
298
|
+
delete o.mcp;
|
|
299
|
+
writeJson(oc, o);
|
|
300
|
+
touched.push(oc);
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
if (node_fs_1.default.existsSync(cl) || on.length) {
|
|
304
|
+
const o = readJson(cl) ?? (node_fs_1.default.existsSync(cl) ? undefined : {});
|
|
305
|
+
if (o !== undefined && o !== null) {
|
|
306
|
+
o.mcpServers = o.mcpServers || {};
|
|
307
|
+
for (const n of prev)
|
|
308
|
+
delete o.mcpServers[n];
|
|
309
|
+
for (const m of on)
|
|
310
|
+
o.mcpServers[m.name] = m.kind === 'remote' ? { type: 'http', url: m.url, ...(m.headers && Object.keys(m.headers).length ? { headers: m.headers } : {}) } : { command: m.command, args: m.args || [], ...(Object.keys(m.env).length ? { env: m.env } : {}) };
|
|
311
|
+
writeJson(cl, o);
|
|
312
|
+
touched.push(cl);
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
store.data.applied = on.map(m => m.name);
|
|
316
|
+
store.save();
|
|
317
|
+
return touched;
|
|
318
|
+
}
|
package/dist/logs.js
ADDED
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.lvOf = exports.bootTime = exports.subscribe = exports.clear = exports.lastId = exports.since = void 0;
|
|
7
|
+
exports.clog = clog;
|
|
8
|
+
exports.hookConsole = hookConsole;
|
|
9
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
10
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
11
|
+
const config_1 = require("./config");
|
|
12
|
+
const util_1 = require("./util");
|
|
13
|
+
const FILE = node_path_1.default.join(config_1.DATA_DIR, 'logs.ndjson');
|
|
14
|
+
const rows = [];
|
|
15
|
+
const subs = new Set();
|
|
16
|
+
let seq = 0;
|
|
17
|
+
// Riwayat: muat 800 baris terakhir dari sesi sebelumnya
|
|
18
|
+
try {
|
|
19
|
+
const tail = node_fs_1.default.readFileSync(FILE, 'utf8').split('\n').filter(Boolean).slice(-800);
|
|
20
|
+
for (const l of tail) {
|
|
21
|
+
try {
|
|
22
|
+
const r = JSON.parse(l);
|
|
23
|
+
rows.push(r);
|
|
24
|
+
seq = Math.max(seq, r.id);
|
|
25
|
+
}
|
|
26
|
+
catch { /* baris rusak */ }
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
catch { /* belum ada */ }
|
|
30
|
+
function clog(lv, tag, msg) {
|
|
31
|
+
for (const line of (0, util_1.stripAnsi)(String(msg)).split(/\r?\n|\r/)) {
|
|
32
|
+
if (!line.trim())
|
|
33
|
+
continue;
|
|
34
|
+
const r = { id: ++seq, t: Date.now(), lv, tag, msg: line.slice(0, 2000) };
|
|
35
|
+
rows.push(r);
|
|
36
|
+
subs.forEach(f => { try {
|
|
37
|
+
f(r);
|
|
38
|
+
}
|
|
39
|
+
catch { /* pelanggan putus */ } });
|
|
40
|
+
node_fs_1.default.appendFile(FILE, JSON.stringify(r) + '\n', () => { });
|
|
41
|
+
}
|
|
42
|
+
while (rows.length > 3000)
|
|
43
|
+
rows.shift();
|
|
44
|
+
try {
|
|
45
|
+
if (node_fs_1.default.statSync(FILE).size > 4e6)
|
|
46
|
+
node_fs_1.default.renameSync(FILE, FILE + '.1');
|
|
47
|
+
}
|
|
48
|
+
catch { /* ok */ }
|
|
49
|
+
}
|
|
50
|
+
function hookConsole() {
|
|
51
|
+
const l = console.log.bind(console), w = console.warn.bind(console), e = console.error.bind(console);
|
|
52
|
+
console.log = (...a) => { l(...a); clog('I', 'server', a.join(' ')); };
|
|
53
|
+
console.warn = (...a) => { w(...a); clog('W', 'server', a.join(' ')); };
|
|
54
|
+
console.error = (...a) => { e(...a); clog('E', 'server', a.join(' ')); };
|
|
55
|
+
}
|
|
56
|
+
const since = (n, max = 600) => rows.filter(r => r.id > n).slice(-max);
|
|
57
|
+
exports.since = since;
|
|
58
|
+
const lastId = () => seq;
|
|
59
|
+
exports.lastId = lastId;
|
|
60
|
+
const clear = () => { rows.length = 0; try {
|
|
61
|
+
node_fs_1.default.writeFileSync(FILE, '');
|
|
62
|
+
}
|
|
63
|
+
catch { /* ok */ } };
|
|
64
|
+
exports.clear = clear;
|
|
65
|
+
const subscribe = (f) => { subs.add(f); return () => subs.delete(f); };
|
|
66
|
+
exports.subscribe = subscribe;
|
|
67
|
+
exports.bootTime = config_1.BOOT;
|
|
68
|
+
const lvOf = (l, d) => /\b(error|err!|fatal|failed|gagal|traceback|exception|not found|tidak ditemukan)\b/i.test(l) ? 'E' : d;
|
|
69
|
+
exports.lvOf = lvOf;
|
package/dist/meter.js
ADDED
|
@@ -0,0 +1,104 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.subscribe = exports.snapshot = exports.newId = exports.estTokens = exports.TokCounter = exports.totals = void 0;
|
|
7
|
+
exports.begin = begin;
|
|
8
|
+
exports.tick = tick;
|
|
9
|
+
exports.end = end;
|
|
10
|
+
exports.merge = merge;
|
|
11
|
+
const node_crypto_1 = __importDefault(require("node:crypto"));
|
|
12
|
+
const live = new Map();
|
|
13
|
+
const subs = new Set();
|
|
14
|
+
const done = new Set();
|
|
15
|
+
exports.totals = { req: 0, pt: 0, ct: 0, since: Date.now() };
|
|
16
|
+
const lastTick = new Map();
|
|
17
|
+
const isCJK = (c) => (c >= 0x4e00 && c <= 0x9fff) || (c >= 0x3040 && c <= 0x30ff) || (c >= 0xac00 && c <= 0xd7af);
|
|
18
|
+
/** Perkiraan token bertahap (logika sama dengan sidecar Go): kata ≈ 1 token/4 huruf, tanda baca & CJK ≈ 1/karakter. */
|
|
19
|
+
class TokCounter {
|
|
20
|
+
n = 0;
|
|
21
|
+
run = 0;
|
|
22
|
+
flush() { if (this.run > 0) {
|
|
23
|
+
this.n += Math.ceil(this.run / 4);
|
|
24
|
+
this.run = 0;
|
|
25
|
+
} }
|
|
26
|
+
add(s) {
|
|
27
|
+
for (const ch of s) {
|
|
28
|
+
const c = ch.codePointAt(0);
|
|
29
|
+
if (isCJK(c)) {
|
|
30
|
+
this.flush();
|
|
31
|
+
this.n++;
|
|
32
|
+
}
|
|
33
|
+
else if (/[\p{L}\p{N}]/u.test(ch))
|
|
34
|
+
this.run++;
|
|
35
|
+
else if (/\s/.test(ch))
|
|
36
|
+
this.flush();
|
|
37
|
+
else {
|
|
38
|
+
this.flush();
|
|
39
|
+
this.n++;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
}
|
|
43
|
+
total() { return this.n + Math.ceil(this.run / 4); }
|
|
44
|
+
}
|
|
45
|
+
exports.TokCounter = TokCounter;
|
|
46
|
+
const estTokens = (s) => { const t = new TokCounter(); t.add(s); return t.total(); };
|
|
47
|
+
exports.estTokens = estTokens;
|
|
48
|
+
const newId = () => node_crypto_1.default.randomBytes(6).toString('hex');
|
|
49
|
+
exports.newId = newId;
|
|
50
|
+
const emit = (l) => { subs.forEach(f => { try {
|
|
51
|
+
f(l);
|
|
52
|
+
}
|
|
53
|
+
catch { /* pelanggan putus */ } }); };
|
|
54
|
+
function finishTotals(l) {
|
|
55
|
+
if (done.has(l.id))
|
|
56
|
+
return;
|
|
57
|
+
done.add(l.id);
|
|
58
|
+
exports.totals.req++;
|
|
59
|
+
exports.totals.pt += l.pt;
|
|
60
|
+
exports.totals.ct += l.ct;
|
|
61
|
+
setTimeout(() => { live.delete(l.id); done.delete(l.id); lastTick.delete(l.id); }, 10000).unref?.();
|
|
62
|
+
}
|
|
63
|
+
function begin(x, src = 'node') {
|
|
64
|
+
const l = { ...x, state: 'run', ct: 0, tps: 0, t0: Date.now(), src };
|
|
65
|
+
live.set(l.id, l);
|
|
66
|
+
emit(l);
|
|
67
|
+
}
|
|
68
|
+
function tick(id, ct) {
|
|
69
|
+
const l = live.get(id), now = Date.now();
|
|
70
|
+
if (!l || now - (lastTick.get(id) || 0) < 250)
|
|
71
|
+
return;
|
|
72
|
+
lastTick.set(id, now);
|
|
73
|
+
l.ct = ct;
|
|
74
|
+
l.tps = ct / Math.max(0.001, (now - l.t0) / 1000);
|
|
75
|
+
emit(l);
|
|
76
|
+
}
|
|
77
|
+
function end(id, pt, ct, ok = true) {
|
|
78
|
+
const l = live.get(id);
|
|
79
|
+
if (!l)
|
|
80
|
+
return;
|
|
81
|
+
l.pt = pt;
|
|
82
|
+
l.ct = ct;
|
|
83
|
+
l.state = ok ? 'done' : 'err';
|
|
84
|
+
l.tps = ct / Math.max(0.001, (Date.now() - l.t0) / 1000);
|
|
85
|
+
finishTotals(l);
|
|
86
|
+
emit(l);
|
|
87
|
+
}
|
|
88
|
+
/** Peristiwa dari sidecar Go. */
|
|
89
|
+
function merge(events) {
|
|
90
|
+
for (const e of events) {
|
|
91
|
+
if (!e || typeof e.id !== 'string')
|
|
92
|
+
continue;
|
|
93
|
+
const l = { id: e.id, model: String(e.model || ''), provider: String(e.provider || ''), state: e.state === 'done' || e.state === 'err' ? e.state : 'run',
|
|
94
|
+
pt: +e.pt || 0, ct: +e.ct || 0, tps: +e.tps || 0, t0: +e.t0 || Date.now(), src: 'go' };
|
|
95
|
+
live.set(l.id, l);
|
|
96
|
+
if (l.state !== 'run')
|
|
97
|
+
finishTotals(l);
|
|
98
|
+
emit(l);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
const snapshot = () => ({ live: [...live.values()], totals: exports.totals });
|
|
102
|
+
exports.snapshot = snapshot;
|
|
103
|
+
const subscribe = (f) => { subs.add(f); return () => subs.delete(f); };
|
|
104
|
+
exports.subscribe = subscribe;
|
package/dist/platform.js
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
1
|
+
"use strict";
|
|
2
|
+
var __importDefault = (this && this.__importDefault) || function (mod) {
|
|
3
|
+
return (mod && mod.__esModule) ? mod : { "default": mod };
|
|
4
|
+
};
|
|
5
|
+
Object.defineProperty(exports, "__esModule", { value: true });
|
|
6
|
+
exports.wslHas = void 0;
|
|
7
|
+
exports.detectEnv = detectEnv;
|
|
8
|
+
exports.winBash = winBash;
|
|
9
|
+
exports.wslList = wslList;
|
|
10
|
+
exports.probe = probe;
|
|
11
|
+
exports.refreshPath = refreshPath;
|
|
12
|
+
exports.which = which;
|
|
13
|
+
const node_fs_1 = __importDefault(require("node:fs"));
|
|
14
|
+
const node_os_1 = __importDefault(require("node:os"));
|
|
15
|
+
const node_path_1 = __importDefault(require("node:path"));
|
|
16
|
+
const node_child_process_1 = require("node:child_process");
|
|
17
|
+
const config_1 = require("./config");
|
|
18
|
+
function detectEnv() {
|
|
19
|
+
const p = process.platform;
|
|
20
|
+
const termux = /com\.termux/.test(process.env.PREFIX || '') || !!process.env.TERMUX_VERSION || node_fs_1.default.existsSync('/data/data/com.termux');
|
|
21
|
+
let wsl = false;
|
|
22
|
+
if (p === 'linux') {
|
|
23
|
+
try {
|
|
24
|
+
wsl = /microsoft/i.test(node_fs_1.default.readFileSync('/proc/version', 'utf8'));
|
|
25
|
+
}
|
|
26
|
+
catch { /* bukan WSL */ }
|
|
27
|
+
}
|
|
28
|
+
let user = '', home = '';
|
|
29
|
+
try {
|
|
30
|
+
user = node_os_1.default.userInfo().username;
|
|
31
|
+
home = node_os_1.default.homedir();
|
|
32
|
+
}
|
|
33
|
+
catch { /* ok */ }
|
|
34
|
+
const shell = p === 'win32' ? (process.env.ComSpec || 'cmd.exe') : (process.env.SHELL || '/bin/sh');
|
|
35
|
+
const base = shell.split(/[\\/]/).pop().toLowerCase();
|
|
36
|
+
const shellKind = p === 'win32' ? 'cmd' : base.includes('zsh') ? 'zsh' : base.includes('bash') ? 'bash' : 'sh';
|
|
37
|
+
const osName = termux ? 'android' : p === 'win32' ? 'windows' : p === 'darwin' ? 'macos' : 'linux';
|
|
38
|
+
const pkg = termux ? 'pkg' : p === 'win32' ? 'winget' : p === 'darwin' ? 'brew' : node_fs_1.default.existsSync('/usr/bin/apt') ? 'apt' : node_fs_1.default.existsSync('/usr/bin/dnf') ? 'dnf' : node_fs_1.default.existsSync('/usr/bin/pacman') ? 'pacman' : 'apt';
|
|
39
|
+
return {
|
|
40
|
+
ok: true, name: 'ChatNUS Backend', root: config_1.ROOT, v: 4, platform: p, arch: process.arch, node: process.version,
|
|
41
|
+
shell, shellKind, termux, wsl, os: osName, pkg, rel: node_os_1.default.release(), host: node_os_1.default.hostname(), user, home, up: Math.round((Date.now() - config_1.BOOT) / 1000)
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
/** Cek biner ada di PATH tanpa shell-injection (nama divalidasi). */
|
|
45
|
+
function whichOnce(bin) {
|
|
46
|
+
return new Promise(ok => {
|
|
47
|
+
if (!/^[\w.@+-]{1,64}$/.test(bin))
|
|
48
|
+
return ok(null);
|
|
49
|
+
const win = process.platform === 'win32';
|
|
50
|
+
const p = win ? (0, node_child_process_1.spawn)('where', [bin], { windowsHide: true }) : (0, node_child_process_1.spawn)('sh', ['-c', 'command -v "$1"', 'sh', bin]);
|
|
51
|
+
let out = '';
|
|
52
|
+
p.stdout.on('data', c => (out += c));
|
|
53
|
+
p.on('error', () => ok(null));
|
|
54
|
+
p.on('close', code => ok(code === 0 && out.trim() ? out.trim().split(/\r?\n/)[0] : null));
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
// ---------- Windows: deteksi WSL / Git Bash untuk installer berbasis bash ----------
|
|
58
|
+
const sh = (cmd, args, ms = 15000) => new Promise(ok => {
|
|
59
|
+
let out = '';
|
|
60
|
+
const c = (0, node_child_process_1.spawn)(cmd, args, { windowsHide: true });
|
|
61
|
+
const t = setTimeout(() => { try {
|
|
62
|
+
c.kill();
|
|
63
|
+
}
|
|
64
|
+
catch { /* ok */ } ok({ code: null, out }); }, ms);
|
|
65
|
+
c.stdout.on('data', d => (out += d));
|
|
66
|
+
c.on('error', () => { clearTimeout(t); ok({ code: null, out }); });
|
|
67
|
+
c.on('close', code => { clearTimeout(t); ok({ code, out: out.replace(/\0/g, '') }); });
|
|
68
|
+
});
|
|
69
|
+
let wbCache = null;
|
|
70
|
+
function winBash() {
|
|
71
|
+
if (process.platform !== 'win32')
|
|
72
|
+
return Promise.resolve(null);
|
|
73
|
+
if (wbCache && Date.now() - wbCache.t < 60000)
|
|
74
|
+
return wbCache.v;
|
|
75
|
+
const v = (async () => {
|
|
76
|
+
const w = await sh('wsl.exe', ['-e', 'sh', '-c', 'echo ok']);
|
|
77
|
+
if (w.code === 0 && /ok/.test(w.out))
|
|
78
|
+
return { kind: 'wsl' };
|
|
79
|
+
const c = [process.env.ProgramFiles, process.env['ProgramFiles(x86)'], process.env.LOCALAPPDATA && process.env.LOCALAPPDATA + '\\Programs']
|
|
80
|
+
.filter(Boolean).map(b => b + '\\Git\\bin\\bash.exe').find(f => node_fs_1.default.existsSync(f));
|
|
81
|
+
return c ? { kind: 'gitbash', path: c } : null;
|
|
82
|
+
})();
|
|
83
|
+
wbCache = { t: Date.now(), v };
|
|
84
|
+
return v;
|
|
85
|
+
}
|
|
86
|
+
/** Daftar biner yang ada di dalam WSL (satu panggilan untuk semua). */
|
|
87
|
+
async function wslList(bins) {
|
|
88
|
+
const ok = bins.filter(b => /^[\w.@+-]{1,64}$/.test(b));
|
|
89
|
+
const r = await sh('wsl.exe', ['-e', 'bash', '-lc', 'for b in ' + ok.join(' ') + '; do command -v "$b" >/dev/null 2>&1 && echo "$b"; done']);
|
|
90
|
+
return new Set(r.out.split(/\r?\n/).map(s => s.trim()).filter(Boolean));
|
|
91
|
+
}
|
|
92
|
+
const wslHas = async (bin) => (await wslList([bin])).has(bin);
|
|
93
|
+
exports.wslHas = wslHas;
|
|
94
|
+
/** Ada di PATH, atau (Windows) ada di dalam WSL. */
|
|
95
|
+
async function probe(bin) {
|
|
96
|
+
const w = await which(bin);
|
|
97
|
+
if (w)
|
|
98
|
+
return w;
|
|
99
|
+
if (process.platform === 'win32' && (await winBash())?.kind === 'wsl' && (await (0, exports.wslHas)(bin)))
|
|
100
|
+
return 'wsl:' + bin;
|
|
101
|
+
return null;
|
|
102
|
+
}
|
|
103
|
+
/** Muat ulang PATH Windows dari registri (installer baru mengubah PATH, proses ini masih memakai yang lama). */
|
|
104
|
+
let pathAt = 0;
|
|
105
|
+
async function refreshPath() {
|
|
106
|
+
if (process.platform !== 'win32' || Date.now() - pathAt < 5000)
|
|
107
|
+
return;
|
|
108
|
+
pathAt = Date.now();
|
|
109
|
+
const r = await sh('powershell.exe', ['-NoProfile', '-NonInteractive', '-Command',
|
|
110
|
+
"[Environment]::GetEnvironmentVariable('Path','Machine')+';'+[Environment]::GetEnvironmentVariable('Path','User')"], 10000);
|
|
111
|
+
const ex = (s) => s.replace(/%([^%]+)%/g, (m, n) => process.env[n] || m);
|
|
112
|
+
const cur = (process.env.PATH || process.env.Path || '').split(';').filter(Boolean), seen = new Set(cur.map(x => x.toLowerCase()));
|
|
113
|
+
for (const e of r.out.split(';').map(s => ex(s.trim())).filter(Boolean))
|
|
114
|
+
if (!seen.has(e.toLowerCase())) {
|
|
115
|
+
cur.push(e);
|
|
116
|
+
seen.add(e.toLowerCase());
|
|
117
|
+
}
|
|
118
|
+
process.env.PATH = cur.join(';');
|
|
119
|
+
}
|
|
120
|
+
function knownDirs() {
|
|
121
|
+
const la = process.env.LOCALAPPDATA, ap = process.env.APPDATA, hm = node_os_1.default.homedir();
|
|
122
|
+
return [la && node_path_1.default.join(la, 'hermes', 'bin'), ap && node_path_1.default.join(ap, 'npm'), node_path_1.default.join(hm, '.local', 'bin'), la && node_path_1.default.join(la, 'Programs', 'opencode')].filter(Boolean);
|
|
123
|
+
}
|
|
124
|
+
async function which(bin) {
|
|
125
|
+
const r = await whichOnce(bin);
|
|
126
|
+
if (r || process.platform !== 'win32')
|
|
127
|
+
return r;
|
|
128
|
+
await refreshPath();
|
|
129
|
+
const r2 = await whichOnce(bin);
|
|
130
|
+
if (r2)
|
|
131
|
+
return r2;
|
|
132
|
+
for (const d of knownDirs())
|
|
133
|
+
for (const e of ['.exe', '.cmd', '.bat']) {
|
|
134
|
+
const f = node_path_1.default.join(d, bin + e);
|
|
135
|
+
if (node_fs_1.default.existsSync(f))
|
|
136
|
+
return f;
|
|
137
|
+
}
|
|
138
|
+
return null;
|
|
139
|
+
}
|