// DoAPI thin client — Node 18+ built-in fetch, no dependency. // // Usage: // export DOAPI_KEY="sk-doapi-..." # key do admin cap, hoac key dung thu // export DOAPI_BASE_URL="https://api.dotech.blog" # mac dinh // node examples/doapi_client.mjs // // import { DoAPIClient } from "./examples/doapi_client.mjs"; // const client = new DoAPIClient({ apiKey: "sk-doapi-..." }); // console.log(await client.chatText([{ role: "user", content: "xin chao" }])); // console.log(await client.usage()); // console.log(await client.listJobs()); // console.log(await client.estimate([{ role: "user", content: "xin chao" }])); // // Model goi lan dau nen la "doapi-default" (chay duoc ngay). Model // muse-agent / chatgpt-* chi chay khi provider tuong ung da duoc cau hinh. // SDK nay khong chua key, khong tu luu key: lay key qua admin // (/admin, CLI) hoac createTrialKey() — POST /v1/keys/trial, chi khi // admin da bat — roi tu gan key tra ve vao client (key chi hien 1 lan). export const DEFAULT_BASE_URL = "https://api.dotech.blog"; export const DEFAULT_MODEL = "doapi-default"; // DoAPIError: message giu nguyen message that cua server (nhu cu); // cach sua nam o .hint khi server tra error.hint (co tu v6.228). export class DoAPIError extends Error { constructor(status, message, retryAfter = null, hint = null) { super(`HTTP ${status}: ${message}` + (hint ? ` | Hint: ${hint}` : "")); this.status = status; this.message = message; this.retryAfter = retryAfter; this.hint = hint; } } export class DoAPIClient { constructor({ apiKey = process.env.DOAPI_KEY || "", adminToken = process.env.DOAPI_ADMIN_TOKEN || "", baseUrl = process.env.DOAPI_BASE_URL || DEFAULT_BASE_URL } = {}) { this.apiKey = apiKey; this.adminToken = adminToken; this.baseUrl = baseUrl.replace(/\/$/, ""); } async _request(method, path, body = undefined, auth = true, adminToken = undefined) { const headers = { "Content-Type": "application/json" }; if (adminToken !== undefined) { // Admin P3: auth bang header X-Admin-Token, KHONG phai // Bearer user (xem _admin_ok trong server.py: chi nhan // X-Admin-Token hoac ?token= token nay KHONG gui qua query // de khoi lo vao log URL. const token = adminToken || this.adminToken; if (!token) { throw new DoAPIError(0, "Thieu admin token: truyen adminToken " + "hoac dat bien moi truong DOAPI_ADMIN_TOKEN"); } headers["X-Admin-Token"] = token; } else if (auth) { if (!this.apiKey) { throw new DoAPIError(0, "Thieu API key: truyen apiKey hoac " + "dat bien moi truong DOAPI_KEY"); } headers.Authorization = `Bearer ${this.apiKey}`; } const resp = await fetch(this.baseUrl + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), }); const data = await resp.json().catch(() => ({})); if (!resp.ok) { const retryAfter = resp.headers.get("Retry-After"); throw new DoAPIError(resp.status, data.error?.message || JSON.stringify(data), retryAfter && /^\d+$/.test(retryAfter) ? Number(retryAfter) : null, data.error?.hint ?? null); } return data; } // Bien the cua _request tra ve text tho thay vi JSON, chi dung // cho route tra text (hien tai: CSV export admin): _request dung // resp.json() nen se tra {} rong tren body CSV. Auth giong nhanh // admin cua _request: header X-Admin-Token, KHONG Bearer, KHONG // gui token qua query; thieu token nem truoc khi gui. async _requestText(method, path, adminToken = undefined) { const token = adminToken || this.adminToken; if (!token) { throw new DoAPIError(0, "Thieu admin token: truyen adminToken " + "hoac dat bien moi truong DOAPI_ADMIN_TOKEN"); } const resp = await fetch(this.baseUrl + path, { method, headers: { "X-Admin-Token": token }, }); const text = await resp.text(); if (!resp.ok) { let message = text; let hint = null; try { const data = JSON.parse(text); message = data.error?.message || text; hint = data.error?.hint ?? null; } catch { /* body loi khong phai JSON: giu nguyen text */ } const retryAfter = resp.headers.get("Retry-After"); throw new DoAPIError(resp.status, message, retryAfter && /^\d+$/.test(retryAfter) ? Number(retryAfter) : null, hint); } return text; } health() { return this._request("GET", "/health", undefined, false); } models() { return this._request("GET", "/v1/models"); } // v6.345.0 (B36): chi cac model ao auto/* trong /v1/models. // Goi chat voi model="auto/cheap" (kem route={requires:{...}} // neu can) de gateway tu chon model that theo nang luc. async virtualModels() { const data = await this.models(); return (data.data || []).filter((m) => m && m.virtual); } chat(messages, model = DEFAULT_MODEL, extra = {}) { return this._request("POST", "/v1/chat/completions", { model, messages, ...extra }); } // v6.348.0 (B38): chat voi vong lap MCP chay tai gateway. // Gui mcpServers (vd ["doapi-builtin"]) thay cho tools — // gateway tu nap tool, goi model, thuc thi tool call va nap ket // qua lai toi da maxRounds vong (mac dinh 10, toi da 10); tra 1 // response chat chuan voi doapi.mcp_loop {servers, rounds, // tool_calls, tool_results, truncated, max_rounds, usage} + // header X-MCP-Loop. toolChoice ap dung cho vong 1, cac vong // sau ve auto. chatWithMcpServers(messages, servers, model = DEFAULT_MODEL, maxRounds = undefined, extra = {}) { const body = { model, messages, mcp_servers: [...servers] }; if (maxRounds !== undefined) body.mcp_max_rounds = maxRounds; return this._request("POST", "/v1/chat/completions", { ...body, ...extra }); } async chatText(messages, model = DEFAULT_MODEL, extra = {}) { const data = await this.chat(messages, model, extra); return data.choices[0].message.content; } // Usage cua chinh key dang goi (khong can admin). usage() { return this._request("GET", "/v1/usage"); } // Budget cua chinh key dang goi (chi key DB; master key tra 403). budget() { return this._request("GET", "/v1/keys/me/budget"); } // Tu giam budget cua chinh key (self-serve, chi key DB). // POST /v1/keys/me/budget, body {budget_usd} — chi duoc GIAM: // so huu han > 0 va nho hon cap hien tai (cap 0 = khong gioi han // thi bat ky so huu han > 0 nao cung la giam); tang, giu nguyen // hoac 0 tra 403/400; key chua duoc admin bat self_serve_budget // tra 403; khong reset spent. tightenBudget(budgetUsd) { return this._request("POST", "/v1/keys/me/budget", { budget_usd: budgetUsd }); } // --- Jobs / workers / system (v5.2/v5.3, da co trong OpenAPI // va Postman tu P2-9/P2-10; SDK them o P2-11) --- // Tao async job (scope jobs). Tra ve job co poll=/v1/jobs/{id}. createJob(messages, model = DEFAULT_MODEL, extra = {}) { return this._request("POST", "/v1/jobs", { model, messages, ...extra }); } // Lay 1 job (local hoac remote) theo id (scope read). getJob(jobId) { return this._request("GET", "/v1/jobs/" + encodeURIComponent(jobId)); } // Liet ke job local + remote (scope read, loc status/limit). listJobs({ status = undefined, limit = undefined } = {}) { const qs = new URLSearchParams(); if (status !== undefined) qs.set("status", status); if (limit !== undefined) qs.set("limit", String(limit)); const q = qs.toString(); return this._request("GET", "/v1/jobs" + (q ? "?" + q : "")); } // Huy job dang queued/running (scope jobs; job da xong tra 409). cancelJob(jobId) { return this._request("POST", "/v1/jobs/" + encodeURIComponent(jobId) + "/cancel", {}); } // Worker fleet registry (scope read). workers() { return this._request("GET", "/v1/workers"); } // Thong tin he thong: version, feature flags, counters (scope read). systemInfo() { return this._request("GET", "/v1/system"); } // Tao job cho worker local (scope jobs, tra 202 khi queued). createRemoteJob(messages, model = DEFAULT_MODEL, extra = {}) { return this._request("POST", "/v1/remote-jobs", { model, messages, ...extra }); } // --- Compare / estimate / rules / run-guard (P2-9) --- // Arena: cung prompt, chay song song nhieu provider (scope chat). compare(messages, extra = {}) { return this._request("POST", "/v1/compare", { messages, ...extra }); } // Uoc tinh token + chi phi TRUOC khi goi (scope chat, khong tru tien). estimate(messages, extra = {}) { return this._request("POST", "/v1/estimate", { messages, ...extra }); } // Doc rules cua 1 project (scope read). rules(project = "default") { return this._request("GET", "/v1/rules?project=" + encodeURIComponent(project)); } // Luu rules cho 1 project (scope prompts). saveRules(project, rules) { return this._request("POST", "/v1/rules", { project, rules }); } // Run-cap cua chinh key cho 1 session (scope read). runGuardUsage(sessionId) { return this._request("GET", "/v1/run-guard/usage?session_id=" + encodeURIComponent(sessionId)); } // --- Batches (v6.0, da co trong OpenAPI tu truoc; SDK them o // P2-12 vi P2-11 chi bo sung method da co trong Postman) --- // Tao batch toi da 50 chat request (scope jobs, tra 202). // Moi item phai co messages[]; poll getBatch de xem counts, // getBatchResults de xem ket qua tung item. createBatch(requests) { return this._request("POST", "/v1/batches", { requests }); } // Lay tom tat 1 batch: status + counts (scope read). getBatch(batchId) { return this._request("GET", "/v1/batches/" + encodeURIComponent(batchId)); } // Lay ket qua tung item cua 1 batch (scope read). getBatchResults(batchId) { return this._request("GET", "/v1/batches/" + encodeURIComponent(batchId) + "/results"); } // --- Trial key tu phuc vu (v6.208, da co trong OpenAPI tu P2-6 // va Postman tu truoc; SDK them o P2-13) --- // Xin 1 key dung thu tu phuc vu (KHONG can key truoc). // POST /v1/keys/trial, body {} — chi khi admin bat // DOAPI_TRIAL_KEYS_ENABLED=1, neu khong tra 403 kem hint // (xem DoAPIError.hint); khi bat tra 201 {key, trial: true, // quota: 50, budget_usd: 1.0, ...}, 1 IP chi 1 key / 24h // (vuot tra 429 kem Retry-After). SDK KHONG tu luu key: // tu gan key tra ve, vi du client.apiKey = data.key // (key chi hien 1 lan trong response). createTrialKey() { return this._request("POST", "/v1/keys/trial", {}, false); } // Trang thai thanh toan song (public, KHONG can key). // GET /v1/billing/status — billing_enabled=false, mode=demo, // pricing_published=true, tiers [starter 99.000d / pro 299.000d // / team 799.000d moi thang, kem quota/budget_usd/scopes], // payment manual (khong thu tien tu dong), trial {quota: 50, // budget_usd: 1.0, ...}. billingStatus() { return this._request("GET", "/v1/billing/status", undefined, false); } // Mo phong yeu cau nang cap (KHONG thu tien, KHONG doi key). // POST /v1/billing/upgrade-demo, body chi gom truong da truyen // (quota so nguyen duong, budgetUsd so duong; khong truyen thi {}); // tra 200 mode=demo, charges_nothing=true, payment_url=null. // Buoc tiep theo that: lien he admin tang quota/budget. upgradeDemo({ quota = undefined, budgetUsd = undefined } = {}) { const body = {}; if (quota !== undefined) body.quota = quota; if (budgetUsd !== undefined) body.budget_usd = budgetUsd; return this._request("POST", "/v1/billing/upgrade-demo", body, false); } // --- Admin P3 (v6.252, P2-26): 4 route van hanh ban hang da co // trong OpenAPI 80 path (P2-25) va Postman 62 item (P3-1/P3-2/P3-3) // nhung SDK chua co method nao goi chung. Auth RIENG: header // X-Admin-Token (truyen adminToken hoac dat DOAPI_ADMIN_TOKEN), // KHONG dung Bearer user; sai token tra 401. // Usage theo tung key chua thu hoi (admin). // GET /admin/api/keys/usage (P3-1); rows sap xep theo // total_requests giam dan, co near_budget khi dung >=80% cap; // chi tra key_prefix, khong tra secret. adminKeysUsage(adminToken) { return this._request("GET", "/admin/api/keys/usage", undefined, false, adminToken ?? this.adminToken); } // Quet canh bao quota bang tay (admin). // POST /admin/api/alerts/quota-check (P3-2), body {}; tra // {warned: [...], already_warned: [...]}. adminQuotaCheck(adminToken) { return this._request("POST", "/admin/api/alerts/quota-check", {}, false, adminToken ?? this.adminToken); } // Xuat backup dinh dang doapi-backup v1 (admin). // GET /admin/api/backup/export (P3-3); khong gom request log, // session, webhook secret. adminBackupExport(adminToken) { return this._request("GET", "/admin/api/backup/export", undefined, false, adminToken ?? this.adminToken); } // Khoi phuc tu backup do adminBackupExport tra ve (admin). // POST /admin/api/backup/restore (P3-3), body {backup, dry_run?}; // chi doi team + budget cua key dang song theo ten, muc hong // vao skipped, KHONG tao key moi hay nhap secret; luon chay // dryRun=true truoc khi khoi phuc that. adminBackupRestore(backup, adminToken, dryRun = undefined) { const body = { backup }; if (dryRun !== undefined) body.dry_run = dryRun; return this._request("POST", "/admin/api/backup/restore", body, false, adminToken ?? this.adminToken); } // Lich su budget cua 1 key (admin). // GET /admin/api/keys/{id}/budget-history (P2-30, noi P3-1); // tra budget hien tai + history moi nhat truoc (mac dinh // server 20 dong, truyen limit de doi); key da thu hoi van // doc duoc de audit, id khong ton tai tra 404. adminKeyBudgetHistory(keyId, { limit = undefined, adminToken = undefined } = {}) { let path = `/admin/api/keys/${keyId}/budget-history`; if (limit !== undefined) path += `?limit=${limit}`; return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // Xoay key cua 1 key (admin). // POST /admin/api/keys/{id}/rotate (P2-31, noi P3-1/P2-30); // tra key moi cung id, key moi chi hien 1 lan, key cu vo // hieu ngay; id khong ton tai hoac key da thu hoi tra 404. adminKeyRotate(keyId, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/rotate`, {}, false, adminToken ?? this.adminToken); } // Trang thai kill-switch hien tai + 20 event gan nhat (admin). // GET /admin/api/killswitch (P2-32, noi P2-31/P2-30); tra state // + events; sai admin token tra 401. Chi doc trang thai. // Thu hoi (vo hieu hoa vinh vien) 1 key (admin). // DELETE /admin/api/keys/{id} (P3-36, noi P3-35); tra // {revoked: id}; id khong hop le tra 400, id khong ton // tai tra 404, sai admin token tra 401. Khac rotate: khong // cap key moi; lich su cua key van doc duoc de audit. adminKeyRevoke(keyId, adminToken) { return this._request("DELETE", `/admin/api/keys/${keyId}`, undefined, false, adminToken ?? this.adminToken); } // Dat hoac xoa han dung cua 1 key (admin). // POST /admin/api/keys/{id}/expiry (v6.339.0, B30); body // {expires_at}: null/0 xoa han, epoch giay tuong lai dat han // moi; han qua khu / bool / khong phai so tra 400. Co hieu // luc ngay — call ke tiep cua key het han tra 401 "Key da // het han". Tra {id, expires_at, expired: false}. Khac // revoke: key het han van gia han lai duoc. adminSetKeyExpiry(keyId, expiresAt, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/expiry`, { expires_at: expiresAt }, false, adminToken ?? this.adminToken); } adminKillswitchStatus(adminToken) { return this._request("GET", "/admin/api/killswitch", undefined, false, adminToken ?? this.adminToken); } // Dong bang he thong — CANH BAO: chi goi khi admin chu dong // quyet dinh (L1, noi P2-32). POST /admin/api/killswitch/activate; // body chi gom field duoc truyen; scope vang mat server mac // dinh "module" (bat buoc co target khac rong), "global" chan // ca chat; khong truyen stage thi server tu chay invariant // stage roi moi dong bang. Sai token 401, stage sai kieu 400, // thieu bang chung/scope sai 422, dang dong bang san 409. // Ghi — dong bang that; test chi dung stub, KHONG goi that // len production. adminKillswitchActivate( { scope = undefined, target = undefined, note = undefined, stage = undefined, useLatestStage = undefined, fuzzTrials = undefined, adminToken = undefined } = {}) { const body = {}; if (scope !== undefined) body.scope = scope; if (target !== undefined) body.target = target; if (note !== undefined) body.note = note; if (stage !== undefined) body.stage = stage; if (useLatestStage !== undefined) body.use_latest_stage = useLatestStage; if (fuzzTrials !== undefined) body.fuzz_trials = fuzzTrials; return this._request("POST", "/admin/api/killswitch/activate", body, false, adminToken ?? this.adminToken); } // Nha khoa kill-switch (admin). POST /admin/api/killswitch/release; // body {note?}; khong dong bang tra 409, sai token tra 401. // Ghi — doi trang thai that; test chi dung stub, KHONG goi // that len production. adminKillswitchRelease(note = undefined, adminToken) { const body = {}; if (note !== undefined) body.note = note; return this._request("POST", "/admin/api/killswitch/release", body, false, adminToken ?? this.adminToken); } // Trang thai live cua invariants + shadow radar (admin). // GET /admin/api/invariants/live (P2-33, noi P2-32); tra // invariants + last_run + shadow_radar + kill_switch; sai admin // token tra 401. Chi doc — khong chay lai invariant. adminInvariantsLive(adminToken) { return this._request("GET", "/admin/api/invariants/live", undefined, false, adminToken ?? this.adminToken); } // Liet ke subscription webhook (admin). // GET /admin/api/webhooks (P3-04, noi P2-33); tra {data: [...]}, // secret day du khong tra o day, chi hien 1 lan luc tao. // Sai admin token tra 401. Chi doc. adminWebhooksList(adminToken) { return this._request("GET", "/admin/api/webhooks", undefined, false, adminToken ?? this.adminToken); } // Tao subscription webhook (admin). // POST /admin/api/webhooks (P3-04, noi P2-33); body {url, // events[], secret?, allow_private?}; url phai http(s)://, // events[] khong rong va chi gom event ho tro hoac '*'; // secret tra ve CHI HIEN 1 LAN. Tra 201; sai token tra 401. adminWebhookCreate(url, events, { secret = undefined, allowPrivate = undefined, adminToken = undefined } = {}) { const body = { url, events }; if (secret !== undefined) body.secret = secret; if (allowPrivate !== undefined) body.allow_private = allowPrivate; return this._request("POST", "/admin/api/webhooks", body, false, adminToken ?? this.adminToken); } // Bat/tat subscription webhook (admin). // POST /admin/api/webhooks/{id} (P3-04, noi P2-33); body // {active}; id khong ton tai tra 404, sai token tra 401. adminWebhookSetActive(webhookId, active, adminToken) { return this._request("POST", `/admin/api/webhooks/${webhookId}`, { active }, false, adminToken ?? this.adminToken); } // Xoa subscription webhook (admin). // DELETE /admin/api/webhooks/{id} (P3-04, noi P2-33); tra // {deleted: id}; id khong ton tai tra 404, sai token 401. adminWebhookDelete(webhookId, adminToken) { return this._request("DELETE", `/admin/api/webhooks/${webhookId}`, undefined, false, adminToken ?? this.adminToken); } // Ban su kien thu toi 1 subscription (admin). // POST /admin/api/webhooks/test (P3-04, noi P2-33); body // {subscription_id}; tra delivery_status, delivered, // signature_preview + timestamp; khong ton tai tra 404. adminWebhookTest(subscriptionId, adminToken) { return this._request("POST", "/admin/api/webhooks/test", { subscription_id: subscriptionId }, false, adminToken ?? this.adminToken); } // Phan tich luu luong theo provider/model/loi/gio trong ngay (admin). // GET /admin/api/analytics (P3-05, noi P3-04); tra by_provider, // top_models (toi da 8), errors_by_status, today_by_hour. // Sai admin token tra 401. Chi doc. adminAnalytics(adminToken) { return this._request("GET", "/admin/api/analytics", undefined, false, adminToken ?? this.adminToken); } // Thong ke tong quan gateway 14 ngay (admin). // GET /admin/api/stats (P3-05, noi P3-04); tra total_requests, // success_rate, today_requests, avg_latency_ms, est_cost_usd, // per_day, by_provider, by_key (top 10). Sai token tra 401. adminStats(adminToken) { return this._request("GET", "/admin/api/stats", undefined, false, adminToken ?? this.adminToken); } // Pheu ban hang cho admin (chi doc). // GET /admin/api/sales-funnel (L9, noi P3-05); tra // trials_issued_total, trials_active, trials_by_day (14 ngay, // ngay trong = 0), trials_converted + trial_conversion_rate, // active_keys_by_tier, active_paid_keys, active_untiered_keys, // unknown_tier_keys, estimated_monthly_revenue_vnd + revenue_note // (UOC TINH theo thang, KHONG phai doanh thu da thu). // Sai token tra 401. Chi doc. adminSalesFunnel(adminToken) { return this._request("GET", "/admin/api/sales-funnel", undefined, false, adminToken ?? this.adminToken); } // Chi phi theo tung khach hang cua 1 key (admin). // GET /admin/api/customer-spend (P3-06, noi P3-05); // ?key= bat buoc (thieu tra 400, key khong ton tai hoac da // thu hoi tra 404); khong co customerId tra danh sach // customers xep spent giam dan, chi tinh request thanh cong, // luu luong khong gan nhan khong xuat hien; co customerId // tra cap + spent + so request cua rieng khach do. // Sai token tra 401. Chi doc. adminCustomerSpend(key, customerId, adminToken) { let path = "/admin/api/customer-spend?key=" + encodeURIComponent(key); if (customerId !== undefined && customerId !== null) { path += "&customer_id=" + encodeURIComponent(customerId); } return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // Nhat ky request gan nhat cua gateway (admin). // GET /admin/api/requests (P3-07, noi P3-06); // ?limit= tuy chon (mac dinh server 50, toi da 500; // khong phai so hoac am deu fallback ve 50); tra // {data: [...]} xep id giam dan; key_name chi la nhan // dinh danh, khong phai key tho. Sai token tra 401. // Chi doc. adminRecentRequests(limit, adminToken) { let path = "/admin/api/requests"; if (limit !== undefined && limit !== null) { path += "?limit=" + encodeURIComponent(limit); } return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // Nhat ky webhook URL bi chan boi cong egress (admin). // GET /admin/api/egress-blocks (P3-08, noi P3-07); // ?limit= tuy chon (mac dinh server 50, toi da 500, // khong phai so fallback ve 50); tra {total, by_reason, // by_source, by_host, recent, suspected}. Moi entry chi // mang hostname + reason, khong bao gio mang URL day du // hay key tho. Sai token tra 401. Chi doc. adminEgressBlocks(limit, adminToken) { let path = "/admin/api/egress-blocks"; if (limit !== undefined && limit !== null) { path += "?limit=" + encodeURIComponent(limit); } return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // GET /admin/api/mcp/audit (P3-09, noi P3-08); // ?limit= tuy chon (mac dinh server 50, toi da 500, // khong phai so hoac am fallback ve 50); tra {data: // [{id, ts, key_name, tool, allowed, reason, // correlation_id}]} xep id giam dan, append-only. // key_name chi la nhan dinh danh, khong phai key tho. // Sai token tra 401. Chi doc. adminMcpAudit(limit, adminToken) { let path = "/admin/api/mcp/audit"; if (limit !== undefined && limit !== null) { path += "?limit=" + encodeURIComponent(limit); } return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // Danh muc tool MCP cua gateway (admin). // GET /admin/api/mcp/tools (P3-10, noi P3-09); // khong query param, khong body; tra {tools: [{name, tier, // description}]} — tier read/execute, chi bao cao tu van, // enforcement that la allowlist theo key. Sai token tra 401. // Chi doc. adminMcpTools(adminToken) { return this._request("GET", "/admin/api/mcp/tools", undefined, false, adminToken ?? this.adminToken); } // Liet ke toan bo key (admin). // GET /admin/api/keys (P3-11, noi P3-10); // khong query param, khong body; tra {data: [...]} xep id // tang dan, chi key_prefix khong key tho, key da thu hoi // van liet ke de audit. Sai token tra 401. Chi doc. adminListKeys(adminToken) { return this._request("GET", "/admin/api/keys", undefined, false, adminToken ?? this.adminToken); } // Trang thai san sang cua cac provider (admin). // GET /admin/api/providers (P3-12, noi P3-11); // khong query param, khong body; tra {data: [{name, ready, // note}]} cho mock/official/browser/muse, ready chi phan anh // cau hinh tai cho, khong goi provider. Sai token tra 401. // Chi doc. // Tao 1 key moi (admin). // POST /admin/api/keys (P3-38, noi P3-37); body chi gom field // duoc truyen trong opts {name, quota?, scopes?, budgetUsd?, // team?} — name bat buoc (thieu/rong tra 400), quota vang mat // mac dinh 0 = khong gioi han (am hoac khong phai so nguyen // tra 400), scopes vang mat la full access, budgetUsd vang mat // la 0 = khong gioi han, team vang mat la khong team. Tra 201 // {id, name, key, team, quota, scopes, ...} — key tho CHI HIEN // 1 LAN nay, server chi luu hash; SDK khong luu key, admin tu // luu ngay. Sai token tra 401. Ghi — tao key that, chi goi khi // admin chu dong cap key (test chi dung stub). adminCreateKey(name, { quota = undefined, scopes = undefined, budgetUsd = undefined, team = undefined, expiresAt = undefined, adminToken = undefined } = {}) { const body = { name }; if (quota !== undefined) body.quota = quota; if (scopes !== undefined) body.scopes = scopes; if (budgetUsd !== undefined) body.budget_usd = budgetUsd; if (team !== undefined) body.team = team; if (expiresAt !== undefined) body.expires_at = expiresAt; return this._request("POST", "/admin/api/keys", body, false, adminToken ?? this.adminToken); } adminProviders(adminToken) { return this._request("GET", "/admin/api/providers", undefined, false, adminToken ?? this.adminToken); } adminModelDeprecations(adminToken) { return this._request("GET", "/admin/api/model-deprecations", undefined, false, adminToken ?? this.adminToken); } adminSetModelDeprecation(deprecated, successor, adminToken, note = undefined, retirementDate = undefined) { const body = { deprecated, successor }; if (note !== undefined) body.note = note; if (retirementDate !== undefined) { body.retirement_date = retirementDate; } return this._request("POST", "/admin/api/model-deprecations", body, false, adminToken ?? this.adminToken); } adminModelDeprecationImpact(adminToken) { return this._request("GET", "/admin/api/model-deprecations/impact", undefined, false, adminToken ?? this.adminToken); } // GET /admin/api/model-deprecations/known (v6.377.0) — bang // nghi huu model chinh thuc cua OpenAI (snapshot 23/11/2026) // doi chieu voi DB song. Tra {snapshot_date, source, known: // [{model, shutdown_date, notice_date, openai_replacement, // registered, registered_successor, status, days_remaining}], // unregistered, advertised_not_listed, generated_at, note}. // Chi doc; sai token 401. adminKnownDeprecations(adminToken) { return this._request("GET", "/admin/api/model-deprecations/known", undefined, false, adminToken ?? this.adminToken); } adminModelAliases(adminToken) { return this._request("GET", "/admin/api/model-aliases", undefined, false, adminToken ?? this.adminToken); } adminSetModelAlias(alias, target, adminToken, note = undefined) { const body = { alias, target }; if (note !== undefined) body.note = note; return this._request("POST", "/admin/api/model-aliases", body, false, adminToken ?? this.adminToken); } adminDeleteModelAlias(alias, adminToken) { return this._request("DELETE", "/admin/api/model-aliases/" + alias, undefined, false, adminToken ?? this.adminToken); } adminSensitivityPolicies(adminToken) { return this._request("GET", "/admin/api/sensitivity-policies", undefined, false, adminToken ?? this.adminToken); } adminSetSensitivityPolicy(label, providers, adminToken, updatedBy = undefined) { const body = { label, providers: [...providers] }; if (updatedBy !== undefined) body.updated_by = updatedBy; return this._request("POST", "/admin/api/sensitivity-policies", body, false, adminToken ?? this.adminToken); } adminDeleteSensitivityPolicy(label, adminToken) { return this._request("DELETE", "/admin/api/sensitivity-policies/" + label, undefined, false, adminToken ?? this.adminToken); } adminMcpServers(status = undefined, adminToken) { const path = status === undefined ? "/admin/api/mcp-registry" : "/admin/api/mcp-registry?status=" + status; return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // v6.347.0 (B41): bang do tre thuc do theo (provider, model). // GET /admin/api/latency-stats — tra {stats: [{provider, model, // ewma_ms, samples, errors, last_seen, p50_ms, p95_ms}], // config: {alpha, buffer_ms, window, min_samples_for_p95}}. // p50/p95 null khi cua so bo nho rong (sau restart). adminLatencyStats(adminToken) { return this._request("GET", "/admin/api/latency-stats", undefined, false, adminToken ?? this.adminToken); } // v6.347.0 (B41): reset bang do tre + cua so bo nho. // DELETE /admin/api/latency-stats — tra {deleted: }. adminResetLatencyStats(adminToken) { return this._request("DELETE", "/admin/api/latency-stats", undefined, false, adminToken ?? this.adminToken); } // v6.359.0 (B15): bang xep hang model tu traffic that. // GET /admin/api/model-leaderboard — windowDays mac dinh 7 // (1..90), sai khoang tra 400. Tra {window_days, // window_start, window_end, generated_at, // reliable_min_turns, models: [{rank, provider, model, turns, // success_rate, p50_ms, p95_ms, ewma_ms, errors_lifetime, // est_spend_usd, est_tokens, usd_per_1k_tokens, reliable}], // note}. p50/p95 chi tren turn thanh cong; model < 10 turn // co reliable=false va xep sau model du mau. adminModelLeaderboard(adminToken, windowDays = 7) { const path = windowDays === undefined || windowDays === null ? "/admin/api/model-leaderboard" : `/admin/api/model-leaderboard?window_days=${windowDays}`; return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // GET /admin/api/route-health — khong tham so thi danh gia // route mac dinh (primary + DOAPI_FALLBACK, fallback bat); // providerOrder (mang ten provider) va/hoac allowFallbacks // (bool) de danh gia route de xuat truoc khi ghim. Tra // {providers, available, allow_fallbacks, warnings: [{code, // severity, message, provider?}], healthy}. Order chua // provider la tra 400, allowFallbacks khong phai true/false // tra 400. Sai admin token tra 401. Chi doc. adminRouteHealth(adminToken, providerOrder = undefined, allowFallbacks = undefined) { const qs = []; if (providerOrder !== undefined && providerOrder !== null) { qs.push("provider_order=" + providerOrder.join(",")); } if (allowFallbacks !== undefined && allowFallbacks !== null) { qs.push("allow_fallbacks=" + (allowFallbacks ? "true" : "false")); } const path = "/admin/api/route-health" + (qs.length ? "?" + qs.join("&") : ""); return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // GET /admin/api/usage/by-label — windowDays mac dinh 7 // (1..90), sai khoang tra 400. Tra {window_days, // window_start, window_end, generated_at, teams: // [{label, total_requests, success_requests, success_rate, // avg_latency_ms, est_prompt_tokens, est_completion_tokens, // est_spend_usd, key_count, top_models: [{provider, model, // turns}]}], customers: [cung dang], no_team, no_customer, // summary: {total_requests, success_requests, success_rate, // est_spend_usd, teams_count, customers_count, keys_count, // team_labeled_requests, customer_labeled_requests, // no_team_requests, no_customer_requests}, note}. Team gom // theo nhan HIEN TAI cua key; customer gom theo customer_id // ghi tren tung request. est_* la uoc tinh, khong phai hoa // don that. Sai admin token tra 401. Chi doc. adminUsageByLabel(adminToken, windowDays = 7) { const path = windowDays === undefined || windowDays === null ? "/admin/api/usage/by-label" : `/admin/api/usage/by-label?window_days=${windowDays}`; return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // GET /admin/api/performance-alerts (v6.372.0) — khong tham // so, khong body. Tra {day, baseline_days: 7, today: // {requests, errors, error_rate, success, p50_ms, p95_ms}, // baseline: {requests, requests_per_day, errors, error_rate, // success, p50_ms, p95_ms}, alerts: [{code, severity, // message, ...so lieu}], healthy, note, generated_at}. // Canh bao: traffic_spike (hom nay >= 2x trung binh ngay // baseline), error_rate_high (ti le loi hom nay >= 10% va // vuot baseline >= 10 diem phan tram), latency_high (p95 // hom nay >= 1.5x p95 baseline va vuot >= 500ms). Baseline // < 10 turn trong 7 ngay thi khong co canh bao nao (note // noi ro chua du du lieu). Sai admin token tra 401. Chi doc. adminPerformanceAlerts(adminToken) { return this._request("GET", "/admin/api/performance-alerts", undefined, false, adminToken ?? this.adminToken); } // Dat chinh sach luu tru audit rieng cho mot key (admin). // POST /admin/api/keys/{id}/audit-retention (v6.388.0, B69) // — body {audit_retention_days} int 1..3650, null = xoa ve // mac dinh chung. Tra {id, name, audit_retention_days, // effective_retention_days}. Sai dinh dang 400, sai admin // token 401, khong tim thay key 404. Chi ap cho bang // requests — mcp_audit append-only nen khong bao gio bi prune. adminSetKeyAuditRetention(keyId, auditRetentionDays, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/audit-retention`, { audit_retention_days: auditRetentionDays }, false, adminToken ?? this.adminToken); } // Xuat goi audit cua mot key (admin). // GET /admin/api/keys/{id}/audit-export (v6.388.0, B69) — // ?format=json|csv, ?window_days=7 (1..90). Tra {key_name, // window_days, window_start, window_end, generated_at, // retention_days, request_count, mcp_audit_count, row_count, // rows, sha256, merkle_root, note} — hoac chuoi CSV khi // format=csv. Chi truong audit-safe. Sai admin token 401, // khong tim thay key 404. adminAuditExport(keyId, adminToken, windowDays = 7, fmt = "json") { const qs = []; if (fmt !== undefined && fmt !== null) qs.push(`format=${fmt}`); if (windowDays !== undefined && windowDays !== null) { qs.push(`window_days=${windowDays}`); } const path = `/admin/api/keys/${keyId}/audit-export` + (qs.length ? `?${qs.join("&")}` : ""); return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // Chay prune log requests ngay theo chinh sach tung key (admin). // POST /admin/api/audit/prune (v6.388.0, B69) — khong body. // Tra {pruned_by_key, total_pruned, global_default_days, // note}. Chi prune bang requests — mcp_audit append-only. // Sai admin token 401. adminAuditPrune(adminToken) { return this._request("POST", "/admin/api/audit/prune", {}, false, adminToken ?? this.adminToken); } // GET /admin/api/sod-conflict-pairs (v6.400.0, B67) — {pairs, // count, mode enforce|report}; danh sach rong = chua khai bao // cap nao. Sai token 401. adminSodPairs(adminToken) { return this._request("GET", "/admin/api/sod-conflict-pairs", undefined, false, adminToken ?? this.adminToken); } // POST /admin/api/sod-conflict-pairs (v6.400.0, B67) — body // {tool_a, tool_b, declared_by?}; ca hai phai la tool gateway // dang phuc vu, khac nhau. Tra {tool_a, tool_b, declared_by, // declared_at, created, affected_keys}. Cap da co 200, // created=false; cap moi 201. Ten la 400, sai token 401. adminAddSodPair(toolA, toolB, declaredBy = undefined, adminToken = undefined) { const body = {tool_a: toolA, tool_b: toolB}; if (declaredBy !== undefined) body.declared_by = declaredBy; return this._request("POST", "/admin/api/sod-conflict-pairs", body, false, adminToken ?? this.adminToken); } // DELETE /admin/api/sod-conflict-pairs/{a}/{b} (v6.400.0, // B67) — tra {deleted: [tool_a, tool_b]}; cap chua khai bao // 404, sai token 401. adminRemoveSodPair(toolA, toolB, adminToken) { return this._request("DELETE", `/admin/api/sod-conflict-pairs/${toolA}/${toolB}`, undefined, false, adminToken ?? this.adminToken); } // GET /admin/api/allocations (v6.401.0, B36-b) — {allocations, // count}; team undefined = moi team; danh sach rong = chua // khai lich nao. Sai token 401, team sai 400. adminAllocations(team = undefined, adminToken = undefined) { const path = team === undefined ? "/admin/api/allocations" : `/admin/api/allocations?team=${team}`; return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // POST /admin/api/allocations (v6.401.0, B36-b) — body {team, // model, days?, start, end, priority?, created_by?}; model // phai la model that trong bang nang luc, start/end "HH:MM" // UTC (end exclusive, end <= start = khung qua nua dem). // Tra 201 + rule (kem id, created_at). Lich sai 400, sai // token 401. adminAddAllocation(team, model, start, end, opts = {}, adminToken = undefined) { const body = {team, model, start, end}; if (opts.days !== undefined) body.days = opts.days; if (opts.priority !== undefined) body.priority = opts.priority; if (opts.createdBy !== undefined) body.created_by = opts.createdBy; return this._request("POST", "/admin/api/allocations", body, false, adminToken ?? this.adminToken); } // DELETE /admin/api/allocations/{id} (v6.401.0, B36-b) — tra // {deleted: id}; id khong ton tai 404, sai token 401. adminRemoveAllocation(allocId, adminToken = undefined) { return this._request("DELETE", `/admin/api/allocations/${allocId}`, undefined, false, adminToken ?? this.adminToken); } // POST /admin/api/web-screen/open (v6.366.0) — mo phien man // hinh Chromium Muse web tren VPS (profile muse) de chu so // huu tu dang nhap qua /admin/web-login. Body tuy chon {url}. // Tra {open, url, state, detail}; sai token 401, trinh duyet // khong san sang 502. // GET /admin/api/agent-cards (v6.402.0, B58-a) — {agent_cards, // count}; danh sach rong nghia la chua dang ky agent nao. adminAgentCards(adminToken = undefined) { return this._request("GET", "/admin/api/agent-cards", undefined, false, adminToken ?? this.adminToken); } // POST /admin/api/agent-cards (v6.402.0, B58-a) — body la card // chuan A2A v1.0 (card v0.3 duoc chuan hoa ve mot interface). // Tra 201 + card public; ten trung 409, card sai 400. adminAddAgentCard(card, adminToken = undefined) { return this._request("POST", "/admin/api/agent-cards", card, false, adminToken ?? this.adminToken); } // DELETE /admin/api/agent-cards/{name} (v6.402.0, B58-a) — // tra {deleted: name}; khong ton tai 404. adminRemoveAgentCard(name, adminToken = undefined) { return this._request("DELETE", `/admin/api/agent-cards/${name}`, undefined, false, adminToken ?? this.adminToken); } // GET /a2a/cards (v6.402.0, B58-a) — catalog public, khong // can xac thuc; skill loc theo id skill hoac tag, q loc // chuoi con trong name/description/skill. a2aCards(skill = undefined, q = undefined) { const params = new URLSearchParams(); if (skill !== undefined) params.set("skill", skill); if (q !== undefined) params.set("q", q); const qs = params.toString(); return this._request("GET", "/a2a/cards" + (qs ? `?${qs}` : ""), undefined, false); } // GET /a2a/cards/{name} (v6.402.0, B58-a) — mot card public // theo name; khong ton tai 404. a2aCard(name) { return this._request("GET", `/a2a/cards/${name}`, undefined, false); } adminWebScreenOpen(adminToken, url = undefined) { const body = {}; if (url !== undefined) body.url = url; return this._request("POST", "/admin/api/web-screen/open", body, false, adminToken ?? this.adminToken); } // GET /admin/api/web-screen/status (v6.366.0) — {open, url, // idle_s, profile, profile_exists}; khong mo trinh duyet. adminWebScreenStatus(adminToken) { return this._request("GET", "/admin/api/web-screen/status", undefined, false, adminToken ?? this.adminToken); } // POST /admin/api/web-screen/input (v6.366.0) — action // {type: click|type|key|goto|reload, x, y, text, key, url}; // key allowlist, goto chi https, type toi da 2000 ky tu. adminWebScreenInput(action, adminToken) { return this._request("POST", "/admin/api/web-screen/input", action, false, adminToken ?? this.adminToken); } // POST /admin/api/web-screen/close (v6.366.0) — dong Chromium // phien man hinh, tra RAM; profile dang nhap tren dia giu // nguyen. Tra {open: false, closed}. adminWebScreenClose(adminToken) { return this._request("POST", "/admin/api/web-screen/close", {}, false, adminToken ?? this.adminToken); } adminRegisterMcpServer(name, endpoint, transport, environment, owner, tools = undefined, adminToken) { const body = { name, endpoint, transport, environment, owner }; if (tools !== undefined) body.tools = [...tools]; return this._request("POST", "/admin/api/mcp-registry", body, false, adminToken ?? this.adminToken); } adminMcpServer(name, adminToken) { return this._request("GET", "/admin/api/mcp-registry/" + name, undefined, false, adminToken ?? this.adminToken); } adminApproveMcpServer(name, adminToken, approvedBy = undefined, reviewIntervalDays = undefined) { const body = {}; if (approvedBy !== undefined) body.approved_by = approvedBy; if (reviewIntervalDays !== undefined) { body.review_interval_days = reviewIntervalDays; } return this._request("POST", "/admin/api/mcp-registry/" + name + "/approve", body, false, adminToken ?? this.adminToken); } adminRevokeMcpServer(name, adminToken, actor = undefined) { const body = {}; if (actor !== undefined) body.actor = actor; return this._request("POST", "/admin/api/mcp-registry/" + name + "/revoke", body, false, adminToken ?? this.adminToken); } adminGrantMcpServerAccess(name, keyName, adminToken, grantedBy = undefined) { const body = { key_name: keyName }; if (grantedBy !== undefined) body.granted_by = grantedBy; return this._request("POST", "/admin/api/mcp-registry/" + name + "/access", body, false, adminToken ?? this.adminToken); } adminRevokeMcpServerAccess(name, keyName, adminToken) { return this._request("DELETE", "/admin/api/mcp-registry/" + name + "/access/" + keyName, undefined, false, adminToken ?? this.adminToken); } adminMcpRegistryReviews(adminToken) { return this._request("GET", "/admin/api/mcp-registry/reviews", undefined, false, adminToken ?? this.adminToken); } adminReviewMcpServer(name, adminToken, reviewedBy = undefined, reviewIntervalDays = undefined) { const body = {}; if (reviewedBy !== undefined) body.reviewed_by = reviewedBy; if (reviewIntervalDays !== undefined) { body.review_interval_days = reviewIntervalDays; } return this._request("POST", "/admin/api/mcp-registry/" + name + "/review", body, false, adminToken ?? this.adminToken); } adminListShadowSightings(adminToken, status = undefined) { const path = status === undefined ? "/admin/api/mcp-shadow-sightings" : "/admin/api/mcp-shadow-sightings?status=" + status; return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } adminRecordShadowSighting(name, adminToken, opts = {}) { const body = { name }; for (const k of ["endpoint", "environment", "source", "observed_by", "note"]) { if (opts[k] !== undefined) body[k] = opts[k]; } return this._request("POST", "/admin/api/mcp-shadow-sightings", body, false, adminToken ?? this.adminToken); } adminResolveShadowSighting(sightingId, adminToken, resolvedBy = undefined, status = undefined) { const body = {}; if (resolvedBy !== undefined) body.resolved_by = resolvedBy; if (status !== undefined) body.status = status; return this._request("POST", "/admin/api/mcp-shadow-sightings/" + sightingId + "/resolve", body, false, adminToken ?? this.adminToken); } adminMcpToolFingerprints(adminToken) { return this._request("GET", "/admin/api/mcp-tools/fingerprints", undefined, false, adminToken ?? this.adminToken); } adminApproveMcpToolFingerprint(tool, adminToken, actor = undefined) { const body = {}; if (actor !== undefined) body.actor = actor; return this._request("POST", "/admin/api/mcp-tools/fingerprints/" + tool + "/approve", body, false, adminToken ?? this.adminToken); } adminProviderBudgets(adminToken) { return this._request("GET", "/admin/api/provider-budgets", undefined, false, adminToken ?? this.adminToken); } adminSetProviderBudget(provider, budgetUsd, adminToken) { return this._request("POST", "/admin/api/provider-budgets/" + provider, { budget_usd: budgetUsd }, false, adminToken ?? this.adminToken); } adminClearProviderBudget(provider, adminToken) { return this._request("DELETE", "/admin/api/provider-budgets/" + provider, undefined, false, adminToken ?? this.adminToken); } adminSetCustomerBudget(key, customerId, budgetUsd, adminToken) { return this._request("POST", "/admin/api/customer-budget", { key, customer_id: customerId, budget_usd: budgetUsd }, false, adminToken ?? this.adminToken); } adminRunGuardUsage(key, sessionId, adminToken) { const path = "/admin/api/run-guard/usage?key=" + encodeURIComponent(key) + "&session_id=" + encodeURIComponent(sessionId); return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // Xoa cache phan hoi cua gateway (admin). // POST /admin/api/cache/clear (P3-15, noi P3-14); // khong query param, body {} nhu dashboard gui (branch khong // doc body); tra {cleared: true}. Ghi — khong phai chi doc. // Sai token tra 401 (gate trung tam chay truoc branch); // POST khi DOAPI_DYNAMIC_CONFIG=0 tra 403 du token dung. adminCacheClear(adminToken) { return this._request("POST", "/admin/api/cache/clear", {}, false, adminToken ?? this.adminToken); } // Liet ke toan bo prompt template (admin). // GET /admin/api/templates (P3-16, noi P3-15); // khong query param, khong body; tra {data: [...]} xep theo // slug, moi row co id, slug, name, prompt, created_at. // Sai token tra 401. Chi doc. adminTemplatesList(adminToken) { return this._request("GET", "/admin/api/templates", undefined, false, adminToken ?? this.adminToken); } // Luu hoac cap nhat 1 prompt template (admin). // POST /admin/api/templates (P3-16, noi P3-15); // body {slug, prompt, name?}; name bo qua khi undefined thi // server mac dinh bang slug; tra {saved: slug}. Thieu slug // hoac prompt / slug/prompt/name sai kieu tra 400, sai token // tra 401, POST khi DOAPI_DYNAMIC_CONFIG=0 tra 403. adminTemplateSave(slug, prompt, adminToken, name = undefined) { const body = { slug, prompt }; if (name !== undefined) body.name = name; return this._request("POST", "/admin/api/templates", body, false, adminToken ?? this.adminToken); } // Xoa 1 prompt template theo slug (admin). // DELETE /admin/api/templates/{slug} (P3-16, noi P3-15); // tra {deleted: slug}; slug khong ton tai tra 404, sai token // tra 401, DELETE khi DOAPI_DYNAMIC_CONFIG=0 tra 403. adminTemplateDelete(slug, adminToken) { return this._request("DELETE", `/admin/api/templates/${slug}`, undefined, false, adminToken ?? this.adminToken); } // Xuat toan bo trang thai hien tai dang legacy export (admin). // GET /admin/api/export (P3-17, noi P3-16); // khong query param, khong body; tra {version, exported_at, // stats, keys, templates, cache} — keys chi la metadata // (key_prefix, khong key tho), cache la thong ke cache. Khac // adminBackupExport(): dang doapi-backup v1 moi la dang ma // POST /admin/api/backup/restore tieu thu; dang legacy nay la // dang ma nut export tren dashboard /admin tai xuong // (doapi-export.json) va restore van doc duoc. Sai token // tra 401. Chi doc. adminExport(adminToken) { return this._request("GET", "/admin/api/export", undefined, false, adminToken ?? this.adminToken); } // Liet ke ho chieu thay doi (admin). // GET /admin/api/passports (P3-18, noi P3-17); // tra {data: [...]} moi row co change_id, passport_hash, // prev_hash, created_at, author, tier, decision. // Sai token tra 401. Chi doc. adminPassportsList(adminToken) { return this._request("GET", "/admin/api/passports", undefined, false, adminToken ?? this.adminToken); } // Ghi 1 ho chieu thay doi moi (admin). // POST /admin/api/passports (P3-37, noi P3-36); body chi gom // field duoc truyen {author?, summary?, paths?, linesAdded?, // linesRemoved?, risk?, stages?, proofPlan?, disputedPoints?, // scopeLock?, approval?}; vang risk thi server mac dinh tier // MED; tra 201 ho chieu moi (200 neu da ton tai), MED/HIGH // duoc neo plan_hash vao cay Merkle, HIGH bat buoc approval // {ticket_id, signature} HMAC tren dung plan_hash, kill-switch // dang bat tra 423, sai kieu field tra 400, sai token tra 401. // Ghi — tao ho chieu that, chi goi khi admin chu dong quyet. adminPassportRecord(opts = {}, adminToken) { const body = {}; const map = { author: "author", summary: "summary", paths: "paths", linesAdded: "lines_added", linesRemoved: "lines_removed", risk: "risk", stages: "stages", proofPlan: "proof_plan", disputedPoints: "disputed_points", scopeLock: "scope_lock", approval: "approval" }; for (const [key, field] of Object.entries(map)) { if (opts[key] !== undefined) body[field] = opts[key]; } return this._request("POST", "/admin/api/passports", body, false, adminToken ?? this.adminToken); } // Kiem chung chuoi Merkle cua ho chieu (admin). // GET /admin/api/merkle (P3-18, noi P3-17); // tra {chain_ok, leaves, current_root, anchor, anchor_ok}. // Sai token tra 401. Chi doc. adminMerkleVerify(adminToken) { return this._request("GET", "/admin/api/merkle", undefined, false, adminToken ?? this.adminToken); } // Bang chung neo Merkle cua 1 ho chieu (admin). // GET /admin/api/passports/{change_id}/anchor-proof (P3-18, // noi P3-17); ho chieu MED/HIGH da neo tra anchored true kem // proof, khong MED/HIGH tra anchored false kem reason, // change_id khong ton tai tra 404. Sai token tra 401. Chi doc. adminPassportAnchorProof(changeId, adminToken) { return this._request("GET", `/admin/api/passports/${changeId}/anchor-proof`, undefined, false, adminToken ?? this.adminToken); } // Tong quan redteam goc admin (admin). // GET /admin/api/redteam (P3-18, noi P3-17); // tra {bounties, findings} — findings toi da 50 dong moi nhat. // Sai token tra 401. Chi doc. adminRedteam(adminToken) { return this._request("GET", "/admin/api/redteam", undefined, false, adminToken ?? this.adminToken); } // Dat hoac xoa allowlist model cua 1 key (admin). // POST /admin/api/keys/{id}/allowed-models (P3-19, noi P3-18); // body {allowed_models, allowlist_report_only?}; null xoa // allowlist, vang mat allowed_models thi giu nguyen list, // allowlist_report_only phai la bool neu co. Tra {id, // allowed_models, allowlist_report_only}. Sai token tra 401, // key khong ton tai tra 404. Ghi — khong phai chi doc. adminSetKeyAllowedModels(keyId, allowedModels, adminToken, allowlistReportOnly = undefined) { const body = { allowed_models: allowedModels }; if (allowlistReportOnly !== undefined) body.allowlist_report_only = allowlistReportOnly; return this._request("POST", `/admin/api/keys/${keyId}/allowed-models`, body, false, adminToken ?? this.adminToken); } // Dat hoac xoa egress allowlist cua 1 key (admin). // POST /admin/api/keys/{id}/egress-allowlist (P3-19, noi P3-18); // body {egress_allowlist} bat buoc; null xoa, list phai la // hostname / IP / CIDR hop le (entry xau tra 400). Tra {id, // egress_allowlist}. Sai token tra 401, key khong ton tai // tra 404. Ghi — khong phai chi doc. adminSetKeyEgressAllowlist(keyId, egressAllowlist, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/egress-allowlist`, { egress_allowlist: egressAllowlist }, false, adminToken ?? this.adminToken); } // Dat hoac xoa cap USD cua 1 key (admin). // POST /admin/api/keys/{id}/budget (P3-20, noi P3-19); // body {budget_usd}; null xoa cap ve 0 (khong gioi han), so // phai huu han va khong am, bool tra 400. Tra {id, // previous_budget_usd, budget_usd, spent_usd_est, // remaining_usd, self_serve_budget, budget_history}; spent // khong bao gio reset theo call nay. Sai token tra 401, key // khong ton tai tra 404. Ghi — khong phai chi doc. adminSetKeyBudget(keyId, budgetUsd, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/budget`, { budget_usd: budgetUsd }, false, adminToken ?? this.adminToken); } // Dat gioi han theo ngay (rpd/tpd) cua 1 key (admin). // POST /admin/api/keys/{id}/daily-limits (v6.404.0); body // {daily_requests, daily_tokens} — so nguyen >= 0; 0 = khong // gioi han; truong vang mat giu nguyen cap hien tai (it nhat // 1 truong phai co, khong thi nem truoc khi gui); truyen 0 de // xoa cap. Tra {id, daily_requests, daily_tokens, // requests_today, tokens_today, daily_requests_remaining, // daily_tokens_remaining, daily_resets_at}. Sai token tra 401, // key khong ton tai tra 404. Ghi — khong phai chi doc. adminSetKeyDailyLimits(keyId, dailyRequests, dailyTokens, adminToken) { const body = {}; if (dailyRequests !== undefined && dailyRequests !== null) body.daily_requests = dailyRequests; if (dailyTokens !== undefined && dailyTokens !== null) body.daily_tokens = dailyTokens; if (Object.keys(body).length === 0) throw new Error("can it nhat 1 trong 2 truong daily_requests / daily_tokens"); return this._request("POST", `/admin/api/keys/${keyId}/daily-limits`, body, false, adminToken ?? this.adminToken); } // Ap 1 tier cua bang gia A len 1 key (admin). // POST /admin/api/keys/{id}/tier (v6.287, P1-tiers); body // {tier} phai la starter, pro hoac team (khac tra 400) — server // copy quota/budget_usd/scopes tu bang TIERS, spent va // quota_used KHONG reset. Sai token tra 401, key khong ton tai // tra 404. Ghi — khong phai chi doc. adminApplyKeyTier(keyId, tier, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/tier`, { tier }, false, adminToken ?? this.adminToken); } // Chu ky tier cua 1 key (admin). // GET /admin/api/keys/{id}/tier-cycle (v6.297, L8; SDK them // o v6.303, P3-32 noi L8/L9); tra {id, tier, cycle, quota, // quota_used, budget_usd, budget_spent_usd_est, history} — // cycle null khi key chua co tier hoac da thu hoi, history // la cac chu ky da dong. Sai token tra 401, key khong ton // tai tra 404, id khong hop le tra 400. Chi doc. adminKeyTierCycle(keyId, adminToken) { return this._request("GET", `/admin/api/keys/${keyId}/tier-cycle`, undefined, false, adminToken ?? this.adminToken); } // Danh sach don payOS da dang ky (admin). // GET /admin/api/payos/orders (v6.296, L7; SDK them o v6.304, // P3-33 noi L7/L9): tra {data: [...], payos_enabled} de doi // soat. Sai token tra 401. Chi doc. adminPayosOrdersList(adminToken) { return this._request("GET", "/admin/api/payos/orders", undefined, false, adminToken ?? this.adminToken); } // Dang ky 1 don payOS truoc khi khach tra (admin). // POST /admin/api/payos/orders (v6.296, L7; SDK them o v6.304, // P3-33): body {key_id, tier, amount_vnd?} — amount_vnd vang // mat thi lay gia tier; tra 201 {orderCode, key_id, tier, // amount_vnd, status: "pending"}. KHONG tao link thanh toan, // KHONG thu tien — admin tu tao link tren dashboard payOS // voi dung orderCode tra ve. Sai token tra 401, key khong // ton tai tra 404, key_id/tier/amount_vnd sai tra 400. Ghi. adminPayosOrderCreate(keyId, tier, adminToken, amountVnd = undefined) { const body = { key_id: keyId, tier }; if (amountVnd !== undefined) body.amount_vnd = amountVnd; return this._request("POST", "/admin/api/payos/orders", body, false, adminToken ?? this.adminToken); } // Nhat ky webhook payOS, moi nhat truoc (admin). // GET /admin/api/payos/events (v6.296, L7; SDK them o v6.304, // P3-33 noi L7/L9): tra {data: [...]} cap 200 dong. Sai token // tra 401. Chi doc. adminPayosEvents(adminToken) { return this._request("GET", "/admin/api/payos/events", undefined, false, adminToken ?? this.adminToken); } // Chay thu chat o goc admin (khong can key user). // POST /admin/api/playground (SDK them o v6.305, P3-34): // body chi gom field duoc truyen {messages?, model?, text?} // — messages la danh sach {role, content} khong rong (sai // kieu tra 400), text la loi tat 1 luot; tra {reply, // provider, latency_ms}. Sai token tra 401. Ghi — chay chat // that qua provider, chi goi khi admin chu dong kiem tra. adminPlayground(messages, { model = undefined, text = undefined, adminToken = undefined } = {}) { const body = {}; if (messages !== undefined) body.messages = messages; if (model !== undefined) body.model = model; if (text !== undefined) body.text = text; return this._request("POST", "/admin/api/playground", body, false, adminToken ?? this.adminToken); } // Xuat nhat ky request gan nhat dang CSV (admin). // GET /admin/api/requests.csv (SDK them o v6.306, P3-35, noi // P3-07): tra CHUOI CSV text, khong phai JSON — dong dau la // header id,ts,key,provider,model,status,latency_ms, // prompt_chars,reply_chars,error; toi da 1000 dong moi nhat // (khong co tham so limit nhu ban JSON /admin/api/requests). // key chi la nhan dinh danh cua key, khong phai key tho. // Sai admin token tra 401. Chi doc. Vi tra text nen method nay // di qua _requestText, khong qua _request (JSON). adminRequestsCsv(adminToken) { return this._requestText("GET", "/admin/api/requests.csv", adminToken ?? this.adminToken); } // Bat/tat quyen tu giam budget cua 1 key (admin). // POST /admin/api/keys/{id}/self-serve-budget (P3-20, noi // P3-19); body {enabled} bat buoc phai la bool. Bat len chi mo // khoa POST /v1/keys/me/budget cho holder cua key do, khong // doi muc enforce nao. Tra {id, self_serve_budget}. Sai token // tra 401, key khong ton tai tra 404. Ghi — khong phai chi doc. adminSetKeySelfServeBudget(keyId, enabled, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/self-serve-budget`, { enabled }, false, adminToken ?? this.adminToken); } // Gan hoac go key khoi team (admin). // POST /admin/api/keys/{id}/team (P3-20, noi P3-19); // body {team}; null xoa ve khong team, team khac phai la ten // hop le [A-Za-z0-9_-] bat dau bang chu/so. Cap USD rieng cua // key (neu co) van ap dung chong len cap team. Tra {id, team}. // Sai token tra 401, key khong ton tai tra 404. Ghi — khong // phai chi doc. adminSetKeyTeam(keyId, team, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/team`, { team }, false, adminToken ?? this.adminToken); } // Dat hoac xoa danh sach tool MCP can duyet cua 1 key (admin). // POST /admin/api/keys/{id}/mcp-approval-tools (P3-20, noi // P3-19); body {mcp_approval_tools}; null xoa danh sach, list // phai la tap con cua cac ten tool MCP (entry la tra 400). // Tool trong danh sach chi chay khi co ticket HMAC mot lan. // Tra {id, mcp_approval_tools}. Sai token tra 401, key khong // ton tai tra 404. Ghi — khong phai chi doc. adminSetKeyMcpApprovalTools(keyId, mcpApprovalTools, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/mcp-approval-tools`, { mcp_approval_tools: mcpApprovalTools }, false, adminToken ?? this.adminToken); } // Dat guard chay theo session cua 1 key (admin). // POST /admin/api/keys/{id}/run-guard (P3-20, noi P3-19); // guard la object chi gom field muon doi: field vang mat thi // giu nguyen, field null/0 thi reset ve khong gioi han cho // field so (run_guard_mode null reset ve block, // downgrade_model null xoa ve tat). run_guard_mode phai la // block, warn hoac throttle; cac field so khong duoc am, khong // phai bool, phai huu han — sai tra 400. Sai token tra 401, // key khong ton tai tra 404. Ghi — khong phai chi doc. adminSetKeyRunGuard(keyId, guard, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/run-guard`, guard, false, adminToken ?? this.adminToken); } // Dat hoac xoa allowlist tool MCP cua 1 key (admin). // POST /admin/api/keys/{id}/mcp-tools (P3-21, noi // P3-20); body {mcp_tools}; null xoa ve khong gioi // han, list phai la tap con cua cac ten tool MCP // (entry la tra 400). Tra {id, mcp_tools}. Id khong // hop le tra 400, key khong ton tai tra 404, sai // token tra 401. Ghi — khong phai chi doc. adminSetKeyMcpTools(keyId, mcpTools, adminToken) { return this._request("POST", `/admin/api/keys/${keyId}/mcp-tools`, { mcp_tools: mcpTools }, false, adminToken ?? this.adminToken); } // Liet ke private deployment da dang ky (admin). // GET /admin/api/private-deployments (P3-22, noi P3-21); // tra {deployments: [...]} xep theo slug, moi row co slug, // provider, model, region, allowed_teams, created_at — chi la // thong tin dang ky, khong mang credential. Sai token tra 401. // Chi doc — khac POST cung path (dang ky deployment moi). adminPrivateDeploymentsList(adminToken) { return this._request("GET", "/admin/api/private-deployments", undefined, false, adminToken ?? this.adminToken); } // Dang ky private deployment moi (admin). // POST /admin/api/private-deployments (P3-27, noi P3-22); // body {slug, provider, model, region, allowed_teams}; provider // official/muse/browser/chatgpt/mock, region us/eu, allowed_teams // danh sach team khong rong. Tra 201 row dang ky, slug trung 409, // field sai 400, sai token 401. Ghi — tao moi, khac GET cung path. adminPrivateDeploymentsCreate(slug, provider, model, region, allowedTeams, adminToken) { return this._request("POST", "/admin/api/private-deployments", { slug, provider, model, region, allowed_teams: allowedTeams }, false, adminToken ?? this.adminToken); } // Bao cao chargeback/showback cua 1 team (admin). // GET /admin/api/teams/{team}/chargeback (P3-23, noi P3-22); // ?since=&until= tuy chon (epoch giay, nua mo [since, until)); // tra {team, period, budget_usd, spent_usd_est, remaining_usd, // utilization, requests, by_provider, by_key, by_model} — chi tinh // request thanh cong, chi doc, sai admin token tra 401. adminTeamChargeback(team, { since = undefined, until = undefined, adminToken = undefined } = {}) { let path = `/admin/api/teams/${team}/chargeback`; const params = []; if (since !== undefined && since !== null) params.push(`since=${since}`); if (until !== undefined && until !== null) params.push(`until=${until}`); if (params.length) path += "?" + params.join("&"); return this._request("GET", path, undefined, false, adminToken ?? this.adminToken); } // Cap + spend cua 1 team (admin). // GET /admin/api/teams/{team}/budget (P3-24, noi P3-23); // tra {team, budget_usd, spent_usd_est, boost_usd, // boost_expires_at, effective_budget_usd, period_budgets} — // budget_usd la cap co dinh goc (0 = khong gioi han), chi doc, // sai admin token tra 401. Khac POST cung path (dat cap). adminTeamBudget(team, adminToken) { return this._request("GET", `/admin/api/teams/${team}/budget`, undefined, false, adminToken ?? this.adminToken); } // Dat hoac xoa cap USD cua 1 team (admin). // POST /admin/api/teams/{team}/budget (P3-24, noi P3-23); // body chi gom field duoc truyen trong opts: budgetUsd (null // hoac 0 xoa cap co dinh ve 0, so phai huu han khong am, bool // tra 400; spent khong reset), boostUsd (so can kem // boostExpiresAt epoch tuong lai, null khong kem expiry thi // xoa boost, vang mat thi giu nguyen), periodBudgets (object // hourly/daily/weekly/monthly; null/0 xoa cap ky do, so > 0 // dat cap). Chi truyen boost/period thi base cap giu nguyen. // Goi khong truyen field nao thi nem loi truoc khi gui vi // POST rong tren server se xoa cap co dinh ve 0. Tra {team, // previous_budget_usd, budget_usd, spent_usd_est, boost_usd, // boost_expires_at, effective_budget_usd, remaining_usd_est, // period_budgets}. Ghi — khong phai chi doc. adminSetTeamBudget(team, { budgetUsd = undefined, boostUsd = undefined, boostExpiresAt = undefined, periodBudgets = undefined, adminToken = undefined } = {}) { const body = {}; if (budgetUsd !== undefined) body.budget_usd = budgetUsd; if (boostUsd !== undefined) body.boost_usd = boostUsd; if (boostExpiresAt !== undefined) body.boost_expires_at = boostExpiresAt; if (periodBudgets !== undefined) body.period_budgets = periodBudgets; if (!Object.keys(body).length) { throw new DoAPIError(0, "adminSetTeamBudget can it nhat mot " + "trong budgetUsd/boostUsd/periodBudgets: POST rong se xoa " + "cap co dinh cua team ve 0"); } return this._request("POST", `/admin/api/teams/${team}/budget`, body, false, adminToken ?? this.adminToken); } // Cap ticket phe duyet HMAC cho mot plan (admin). // POST /admin/api/approvals/ticket (P3-25, noi P3-24); // body chi gom field duoc truyen trong opts (planHash, // proofPlan, paths, risk, tier, scopeLock, actor). It nhat // phai co planHash hoac proofPlan — goi khong ca hai thi // nem loi truoc khi gui vi ticket cho plan rong khong co // y nghia. Tra 201 {ticket_id, plan_hash, issued_at, // expires_at, signing_payload, note} — ticket song 10 phut, // dung 1 lan, chi cho dung plan_hash nay; sai admin token // tra 401, field sai kieu tra 400, plan khong hop le 422. adminApprovalTicket({ planHash = undefined, proofPlan = undefined, paths = undefined, risk = undefined, tier = undefined, scopeLock = undefined, actor = undefined, adminToken = undefined } = {}) { const body = {}; if (planHash !== undefined) body.plan_hash = planHash; if (proofPlan !== undefined) body.proof_plan = proofPlan; if (paths !== undefined) body.paths = paths; if (risk !== undefined) body.risk = risk; if (tier !== undefined) body.tier = tier; if (scopeLock !== undefined) body.scope_lock = scopeLock; if (actor !== undefined) body.actor = actor; if (planHash === undefined && proofPlan === undefined) { throw new DoAPIError(0, "adminApprovalTicket can it nhat " + "mot trong planHash/proofPlan: ticket cho plan rong " + "khong co y nghia"); } return this._request("POST", "/admin/api/approvals/ticket", body, false, adminToken ?? this.adminToken); } // Kiem tra chu ky HMAC cua mot approval ticket (admin). // POST /admin/api/approvals/verify (P3-25, noi P3-24); // body {ticket_id, signature?, plan_hash?}. Tra 200 {valid, // reason, ticket?}; ticket khong ton tai cung tra 200 // valid=false, KHONG tieu thu ticket. ticket_id dict/list // hoac signature khong phai chuoi tra 400, sai token 401. adminApprovalVerify(ticketId, { signature = undefined, planHash = undefined, adminToken = undefined } = {}) { const body = { ticket_id: ticketId }; if (signature !== undefined) body.signature = signature; if (planHash !== undefined) body.plan_hash = planHash; return this._request("POST", "/admin/api/approvals/verify", body, false, adminToken ?? this.adminToken); } // Neo root Merkle hien tai (admin). // POST /admin/api/merkle/anchor (P3-26, noi P3-25); // khong can body, tra row neo {id, created_at, leaf_count, // root, prev_root}. Sai token tra 401. Ghi — tao neo moi. adminMerkleAnchor(adminToken) { return this._request("POST", "/admin/api/merkle/anchor", {}, false, adminToken ?? this.adminToken); } // Phai mon von tin cay duong (admin). // POST /admin/api/trust/decay (P3-26, noi P3-25); // body {} thi server mac dinh percent=10, clamp 1..50, // bool/khong phai so tra 400. Tra {decayed, percent}. // Chi von DUONG bi phai. Sai token tra 401. Ghi. adminTrustDecay(percent, adminToken) { const body = {}; if (percent !== undefined) body.percent = percent; return this._request("POST", "/admin/api/trust/decay", body, false, adminToken ?? this.adminToken); } // Cap ticket phe duyet MCP mot lan cho 1 tool + 1 key (admin). // POST /admin/api/mcp/approvals/ticket (P3-28, noi P3-27); // body {tool, key_name, actor?}; tool phai la 1 trong // doapi_chat/doapi_summarize/doapi_search_codebase/doapi_usage, // key_name phai la key dang song, actor vang mat mac dinh admin. // Tra 201 {ticket_id, plan_hash, tool, key_name, definition, // definitionHash, issued_at, expires_at, signing_payload, note}; // ticket song 10 phut, dung 1 lan. Tool la tra 400, key khong // ton tai tra 404, actor dict/list tra 400, sai token tra 401. adminMcpApprovalTicket(tool, keyName, { actor = undefined, adminToken = undefined } = {}) { const body = { tool, key_name: keyName }; if (actor !== undefined) body.actor = actor; return this._request("POST", "/admin/api/mcp/approvals/ticket", body, false, adminToken ?? this.adminToken); } // Chay kiem tra shadow-mode day du (admin). // POST /admin/api/shadow/run (P3-29, noi P3-28); khong can // body. Tra bao cao shadow so stage hien tai voi ho chieu // baseline moi nhat; chua co ho chieu thi comparable=false // van 200. Sai token tra 401. Chi doc. adminShadowRun(adminToken) { return this._request("POST", "/admin/api/shadow/run", {}, false, adminToken ?? this.adminToken); } // Chay stage bat bien ngay, ghi ket qua (admin). // POST /admin/api/invariants/run (P3-29, noi P3-28); // body {fuzz_trials?} (vang mat server mac dinh 10, clamp // 0..40, bool tra 400). Ghi stage cho dashboard + phat // su kien invariant.stage. Sai token tra 401. Ghi. adminInvariantsRun( { fuzzTrials = undefined, adminToken = undefined } = {}) { const body = {}; if (fuzzTrials !== undefined) body.fuzz_trials = fuzzTrials; return this._request("POST", "/admin/api/invariants/run", body, false, adminToken ?? this.adminToken); } // Soan thao luat tu mo ta bang ngon ngu tu nhien (admin). // POST /admin/api/lawforge/draft (P3-30, noi P3-29); // body {description} (khong phai chuoi tra 400, thieu/rong // tra 422, provider loi tra 502). De xuat chi o trang thai // proposed, tra 201 neu tao moi khong thi 200. Sai token // tra 401. Ghi — goi provider LLM nen ton chi phi. adminLawforgeDraft(description, adminToken) { return this._request("POST", "/admin/api/lawforge/draft", { description }, false, adminToken ?? this.adminToken); } // Chay mo phong redteam vao ban sandbox (admin). // POST /admin/api/redteam/simulate (P3-30, noi P3-29); // khong can body (subprocess toi da 240s, qua thoi gian // tra 504). Escape tu dong nop de xuat luat. Sai token // tra 401. Ghi — escape co the nop de xuat that. adminRedteamSimulate(adminToken) { return this._request("POST", "/admin/api/redteam/simulate", {}, false, adminToken ?? this.adminToken); } // --- Suy luan / tim kiem co ban (da co trong OpenAPI 76 path tu // truoc; SDK them o P2-15 vi ca 2 SDK va Postman 33 item deu // chua co method/item nao goi chung) --- // Hoan thanh van ban kieu ghost-text (scope chat). // POST /v1/completions, body {model, prompt, suffix?}; chi chay // tren model NHANH (official/mock) — provider web tra 422. completions(prompt, { suffix = undefined, model = DEFAULT_MODEL } = {}) { const body = { model, prompt }; if (suffix !== undefined) body.suffix = suffix; return this._request("POST", "/v1/completions", body); } // Embedding tu vung cuc bo TF-IDF 256 chieu (scope chat). // POST /v1/embeddings, body {input, project?, model?}; input la // chuoi hoac list chuoi (toi da 100). KHONG phai embedding neural. embeddings(input, { project = undefined, model = undefined } = {}) { const body = { input }; if (project !== undefined) body.project = project; if (model !== undefined) body.model = model; return this._request("POST", "/v1/embeddings", body); } // Decisions API kieu LiteLLM/OpenAI (scope chat). // POST /v1/decisions, body {input, questions, engine}; questions // la list {name, type: boolean/choice/score, options?}; engine // rule (mac dinh) hoac provider. Chi tra dap an co kieu. decisions(input, questions, { engine = "rule" } = {}) { return this._request("POST", "/v1/decisions", { input, questions, engine }); } // Quet PII / secret / blocklist (scope chat). // POST /v1/moderate, body {text, blocklist?}. moderate(text, { blocklist = undefined } = {}) { const body = { text }; if (blocklist !== undefined) body.blocklist = blocklist; return this._request("POST", "/v1/moderate", body); } // Xep hang lai tai lieu bang TF-IDF cosine (scope chat). // POST /v1/rerank, body {query, documents, top_n?}. rerank(query, documents, { topN = undefined } = {}) { const body = { query, documents }; if (topN !== undefined) body.top_n = topN; return this._request("POST", "/v1/rerank", body); } // Tim kiem trong project da index truoc (scope chat). // POST /v1/search, body {query, project?, top_k?}; project mac // dinh default, top_k mac dinh 5 (toi da 20). search(query, { project = undefined, topK = undefined } = {}) { const body = { query }; if (project !== undefined) body.project = project; if (topK !== undefined) body.top_k = topK; return this._request("POST", "/v1/search", body); } // Index file vao 1 project (scope chat) de search()/listConcepts() // sau do co du lieu. POST /v1/index, body {files: [{path, content}], // project?}; files rong tra 400, project/duong dan khong hop le 400. indexProject(files, { project = undefined } = {}) { const body = { files }; if (project !== undefined) body.project = project; return this._request("POST", "/v1/index", body); } // --- Sessions + Prompt library (v6.3, da co trong OpenAPI; // SDK them o P2-16) --- listSessions() { return this._request("GET", "/v1/sessions"); } getSession(sessionId) { return this._request("GET", "/v1/sessions/" + encodeURIComponent(sessionId)); } forkSession(sessionId, { newId = undefined } = {}) { const body = {}; if (newId !== undefined) body.new_id = newId; return this._request("POST", "/v1/sessions/" + encodeURIComponent(sessionId) + "/fork", body); } compactSession(sessionId, { keepLast = undefined } = {}) { const body = {}; if (keepLast !== undefined) body.keep_last = keepLast; return this._request("POST", "/v1/sessions/" + encodeURIComponent(sessionId) + "/compact", body); } shareSession(sessionId) { return this._request("POST", "/v1/sessions/" + encodeURIComponent(sessionId) + "/share", {}); } revokeSessionShare(sessionId) { return this._request("DELETE", "/v1/sessions/" + encodeURIComponent(sessionId) + "/share"); } deleteSession(sessionId) { return this._request("DELETE", "/v1/sessions/" + encodeURIComponent(sessionId)); } listPrompts() { return this._request("GET", "/v1/prompts"); } getPrompt(promptId) { return this._request("GET", "/v1/prompts/" + encodeURIComponent(promptId)); } createPrompt(name, body) { return this._request("POST", "/v1/prompts", { name, body }); } updatePrompt(promptId, { name = undefined, body = undefined } = {}) { const payload = {}; if (name !== undefined) payload.name = name; if (body !== undefined) payload.body = body; return this._request("PUT", "/v1/prompts/" + encodeURIComponent(promptId), payload); } deletePrompt(promptId) { return this._request("DELETE", "/v1/prompts/" + encodeURIComponent(promptId)); } renderPrompt(promptId, { variables = undefined } = {}) { const body = {}; if (variables !== undefined) body.variables = variables; return this._request("POST", "/v1/prompts/" + encodeURIComponent(promptId) + "/render", body); } // Lich su version cua 1 prompt (scope prompts). // GET /v1/prompts/{id}/versions (v6.350.0, B42-P): tra {data: // [{prompt_id, version, name, body, created_at}, ...] tang dan, // current_version}. Version bat bien — PUT tao version moi. listPromptVersions(promptId) { return this._request("GET", "/v1/prompts/" + encodeURIComponent(promptId) + "/versions"); } // Lay 1 version cu the (scope prompts); khong ton tai tra 404. getPromptVersion(promptId, version) { return this._request("GET", "/v1/prompts/" + encodeURIComponent(promptId) + "/versions/" + Number(version)); } // Rollback ve version cu (scope prompts): POST // /v1/prompts/{id}/rollback {version} — tao version MOI copy // noi dung cu, lich su khong sua; tra prompt sau rollback. rollbackPrompt(promptId, version) { return this._request("POST", "/v1/prompts/" + encodeURIComponent(promptId) + "/rollback", { version: Number(version) }); } promptGallery() { return this._request("GET", "/v1/prompts/gallery"); } importPromptGallery(galleryId) { return this._request("POST", "/v1/prompts/import", { gallery_id: galleryId }); } // Skills Hub (v6.352.0, B42-S): thu vien skill dung chung cua // gateway (scope prompts). Skill moi LUON pending; chi skill // approved moi dung duoc trong chat (skills: ["name"] hoac // ["name@2"] de ghim version). listSkills(status = undefined) { const q = status !== undefined ? "?status=" + encodeURIComponent(status) : ""; return this._request("GET", "/v1/skills" + q); } getSkill(skillId) { return this._request("GET", "/v1/skills/" + encodeURIComponent(skillId)); } createSkill(name, description, content) { return this._request("POST", "/v1/skills", { name, description, content }); } importSkill(name, description, content) { return this._request("POST", "/v1/skills/import", { name, description, content }); } updateSkill(skillId, { description = undefined, content = undefined } = {}) { const payload = {}; if (description !== undefined) payload.description = description; if (content !== undefined) payload.content = content; return this._request("PUT", "/v1/skills/" + encodeURIComponent(skillId), payload); } // Lich su version cua 1 skill (scope prompts); version bat bien. listSkillVersions(skillId) { return this._request("GET", "/v1/skills/" + encodeURIComponent(skillId) + "/versions"); } getSkillVersion(skillId, version) { return this._request("GET", "/v1/skills/" + encodeURIComponent(skillId) + "/versions/" + Number(version)); } // Rollback ve version cu: tao version MOI copy noi dung cu. rollbackSkill(skillId, version) { return this._request("POST", "/v1/skills/" + encodeURIComponent(skillId) + "/rollback", { version: Number(version) }); } approveSkill(skillId, approvedBy = undefined) { const body = {}; if (approvedBy !== undefined) body.approved_by = approvedBy; return this._request("POST", "/v1/skills/" + encodeURIComponent(skillId) + "/approve", body); } revokeSkill(skillId, actor = undefined) { const body = {}; if (actor !== undefined) body.actor = actor; return this._request("POST", "/v1/skills/" + encodeURIComponent(skillId) + "/revoke", body); } // Chat kem skill tu hub: skills ["name"] hoac ["name@2"]. chatWithSkills(messages, skills, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, skills: [...skills] }); } // Chat voi PII duoc che khoi phuc duoc (v6.354.0, B32-C): // gateway thay PII bang placeholder truoc khi gui provider // roi khoi phuc gia tri goc trong response. chatWithMaskedPii(messages, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, mask_pii: true }); } // Quet PII trong response (v6.355.0, B32-D): chi bao cao // (doapi.response_pii + header X-DoAPI-Response-PII + event // pii.response_detected), khong chan, khong che them. chatWithResponsePiiScan(messages, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, scan_response_pii: true }); } // v6.356.0 (total_timeout): chat co ngan sach thoi gian toan // request — het han tra HTTP 408 + event request.total_timeout. chatWithTotalTimeout(messages, totalTimeout, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, total_timeout: totalTimeout }); } // v6.357.0 (mid-stream fallback): stream co fallback giua chung // — stream live dut vi loi provider thi gateway tiep tuc tren // provider ke trong provider_order; switch bao bang SSE comment // ': doapi stream-fallback -> ' + event stream.fallback. chatWithMidStreamFallback(messages, providerOrder, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, provider_order: providerOrder, mid_stream_fallback: true }); } // v6.358.0 (B1 remainder): auto-router live-switch — gateway // phan loai prompt, xep hang models theo spend noi bo, roi chuyen // THAT turn sang model duoc de xuat (truoc moi gate: allowlist / // deprecation / budget / downgrade / sensitivity). Response mang // doapi.auto_router.live {switched, from_model, to_model, reason} // + header X-DoAPI-Auto-Router ("from->to", chi khi that su chuyen). chatWithAutoRouterLive(messages, models, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, auto_router: { enabled: true, live: true, models } }); } // v6.365.0 (B48): chat voi policy dinh tuyen provider — gui // provider_sort ("price" | "latency" | "value" | "throughput") // va/hoac provider_max_price (so > 0, USD / 1M token); gateway // xep/loc chuoi thu provider sau khi resolve, truoc outage // reorder; response mang doapi.provider_policy {sort, max_price, // chain, filtered_out} + header X-DoAPI-Provider-Policy. // v6.369.0: sort=value xep theo EWMA throughput do that chia // cho chan gia dat nhat; sort=throughput xep theo EWMA // throughput giam dan; sort + provider_order cung luc la 400. chatWithProviderPolicy(messages, { sort = undefined, maxPrice = undefined } = {}, model = DEFAULT_MODEL, extra = {}) { const body = { ...extra }; if (sort !== undefined) body.provider_sort = sort; if (maxPrice !== undefined) body.provider_max_price = maxPrice; return this.chat(messages, model, body); } // v6.367.0 (B46): chat voi nen prompt "light" — gateway nen // prompt ngay truoc khi goi provider (cat trailing whitespace, // gom dong trang thua, bo message trung lap lien tiep; message // tool / content khong phai chuoi giu nguyen) roi bao cao trong // doapi.prompt_compression {level, messages_before/after, // duplicates_removed, chars_before/after, chars_saved, // est_tokens_saved} + header X-DoAPI-Prompt-Compression. // Turn co nen bo qua ResponseCache; budget pre-flight van tinh // tren prompt goc (huong bao thu). Muc khac "light" la 400. chatWithPromptCompression(messages, level = "light", model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, prompt_compression: level }); } // v6.378.0 (B2/B56): chat voi semantic cache — gui // semantic_cache: true; gateway tra response da luu khi prompt // moi gan giong prompt da tra loi (cosine TF-IDF >= 0.97 mac // dinh), khong goi provider. Chi khi co master // DOAPI_SEMANTIC_CACHE=1; chi duong buffered. Hit mang // doapi.semantic_cache {similarity, matched_prompt_sha256}. chatWithSemanticCache(messages, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, semantic_cache: true }); } // v6.374.0 (B44 remainder): chat voi danh tinh agent — gui // agent_id + task_token (task token dtk_... da mint cho agent // do); gateway xac thuc danh tinh truoc moi provider call, // token sai la 403 agent_not_allowed; model yeu cau phai nam // trong allowed_models cua agent (rong = khong gioi han), khong // thi 403 agent_model_not_allowed — dat canh gate allowlist cua // key (B99), ca hai phai vuot. Response mang doapi.agent // {agent_id, allowed_models} + header X-DoAPI-Agent. // v6.383.0 (B12): truyen run_token + session_id qua extra tuy // chon — turn bi gan vao dung session da mint run token (sai // session / het han / thu hoi la 403 agent_run_not_allowed); // khong truyen thi dung luong B44 cu (agent_id + task_token). chatWithAgent(messages, agentId, taskToken, model = DEFAULT_MODEL, extra = {}) { return this.chat(messages, model, { ...extra, agent_id: agentId, task_token: taskToken }); } // Concept map cua 1 project da index (scope read). listConcepts(project = "default") { return this._request("GET", "/v1/concepts?project=" + encodeURIComponent(project)); } // Trace 1 run: cost span tung buoc (scope read; session khong // phai cua key tra 404). getRunTrace(sessionId) { return this._request("GET", "/v1/runs/" + encodeURIComponent(sessionId) + "/trace"); } // Chay 1 util 1-click tren chat (scope chat): summarize, translate, // rewrite, explain, marketing, test, document, fixerror, commit. // Body {text, ...extra}; ten khac tra 404, thieu text tra 400. runUtil(name, text, extra = {}) { return this._request("POST", "/v1/utils/" + encodeURIComponent(name), { text, ...extra }); } // Cac red-team bounty dang mo (scope read). listBounties() { return this._request("GET", "/v1/redteam/bounties"); } // Nop 1 red-team finding (scope chat): body {module, check_spec, // finder?, bounty_id?}; diem chi khi Executor xac minh live. submitFinding(module, checkSpec, { finder = undefined, bountyId = undefined } = {}) { const body = { module, check_spec: checkSpec }; if (finder !== undefined) body.finder = finder; if (bountyId !== undefined) body.bounty_id = bountyId; return this._request("POST", "/v1/redteam/findings", body); } // --- SSE streams (v6.246, P2-20) --- // Hai route SSE la 2 route /v1 cuoi cung chua co trong SDK: truoc // day SDK JSON (qua _request) khong goi duoc chung vi chung tra // stream text/event-stream, khong phai 1 JSON. Hai method duoi // day dung rieng cho stream, khong dung _request. async *_stream(path, { maxEvents = undefined } = {}) { if (!this.apiKey) { throw new DoAPIError(0, "Thieu API key: truyen apiKey hoac " + "dat bien moi truong DOAPI_KEY"); } const resp = await fetch(this.baseUrl + path, { method: "GET", headers: { Authorization: `Bearer ${this.apiKey}`, Accept: "text/event-stream" }, }); if (!resp.ok) { const data = await resp.json().catch(() => ({})); const retryAfter = resp.headers.get("Retry-After"); throw new DoAPIError(resp.status, data.error?.message || JSON.stringify(data), retryAfter && /^\d+$/.test(retryAfter) ? Number(retryAfter) : null, data.error?.hint ?? null); } // Moi event la 1 khoi "event: " + "data: " + dong // trang; dong ": heartbeat" moi 15s bi bo qua. Dict yield ra // la JSON trong data (tu mang "type"). Stream job dong khi // gap event terminal; stream /v1/events mo toi da 600s phia // server, nen caller thuong truyen maxEvents hoac break som. const parseBlock = (block) => { const dataLines = []; for (const line of block.split("\n")) { if (line.startsWith(":")) continue; if (line.startsWith("data:")) { dataLines.push(line.slice(5).replace(/^ /, "")); } } return dataLines.length ? JSON.parse(dataLines.join("\n")) : null; }; const reader = resp.body.getReader(); const decoder = new TextDecoder(); let buffer = ""; let count = 0; while (true) { const { done, value } = await reader.read(); if (value) { buffer += decoder.decode(value, { stream: true }) .replace(/\r\n/g, "\n"); } if (done) { buffer += decoder.decode(); break; } let idx; while ((idx = buffer.indexOf("\n\n")) !== -1) { const ev = parseBlock(buffer.slice(0, idx)); buffer = buffer.slice(idx + 2); if (ev !== null) { yield ev; count++; if (maxEvents !== undefined && count >= maxEvents) return; } } } if (buffer.trim() !== "") { const ev = parseBlock(buffer); if (ev !== null) yield ev; } } // Stream event cua chinh key dang goi (scope read). // GET /v1/events — snapshot dau tien la {type: "stream.ready", // data: {key}}; sau do la chat.completed, job.*, quota.warning, // ... cua chinh key; stream mo toi da 600s phia server. streamEvents({ maxEvents = undefined } = {}) { return this._stream("/v1/events", { maxEvents }); } // Stream event truc tiep cua 1 job (scope read). // GET /v1/jobs/{id}/events — snapshot dau tien la // {type: "job.snapshot", data: {status, job}}; stream tu dong // dong khi gap event terminal; job khong ton tai tra 404. streamJobEvents(jobId, { maxEvents = undefined } = {}) { return this._stream("/v1/jobs/" + encodeURIComponent(jobId) + "/events", { maxEvents }); } } const isMain = process.argv[1] && import.meta.url === new URL(`file://${process.argv[1]}`).href; if (isMain) { const client = new DoAPIClient(); if (!client.apiKey) { console.error("Thieu DOAPI_KEY. Lay key qua admin (/admin, CLI) hoac " + "POST /v1/keys/trial khi admin da bat, roi chay lai."); process.exit(2); } console.log(await client.chatText([{ role: "user", content: "xin chao" }])); }