@aivin-labs/cli 1.0.75 → 1.0.78

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.
@@ -5,6 +5,7 @@ import { execFile, spawn } from 'child_process';
5
5
  import { DeviceErrorCode, REMOTE_CONFIG_DIR, ToolGroup } from './constants.mjs';
6
6
  import { DeviceToolError, agentEnv } from './sandbox.mjs';
7
7
  import { CLAUDE_ADAPTER, findAgentBinary } from './codingAgents.mjs';
8
+ import { readConnector } from './lightcodeAgent.mjs';
8
9
  import { MEMBER_LLM_AGENTS, MEMBER_LLM_DIR, createSignInChecker, memberSpawnArgs } from './localLlmMembers.mjs';
9
10
 
10
11
  /**
@@ -237,7 +238,18 @@ export const ANTIGRAVITY_LLM = Object.freeze({
237
238
  args: () => ['acp', '--disable-telemetry'],
238
239
  });
239
240
 
240
- export const DEFAULT_LLM_ADAPTERS = Object.freeze([CLAUDE_LLM, CODEX_LLM, ANTIGRAVITY_LLM]);
241
+ export const LIGHTCODE_LLM = Object.freeze({
242
+ id: 'lightcode',
243
+ label: 'LightCode',
244
+ kind: 'http',
245
+ dynamic: true,
246
+ find() {
247
+ const conn = readConnector();
248
+ return conn ? { bin: `http://127.0.0.1:${conn.port}`, version: conn.app_version || null, connector: conn } : null;
249
+ },
250
+ });
251
+
252
+ export const DEFAULT_LLM_ADAPTERS = Object.freeze([CLAUDE_LLM, CODEX_LLM, ANTIGRAVITY_LLM, LIGHTCODE_LLM]);
241
253
 
242
254
  /** Câu báo hết hạn mức agy gửi như một đoạn trả lời bình thường. */
243
255
  const AGY_QUOTA_RE = /^\s*⚠?\s*(individual )?quota reached/i;
@@ -245,7 +257,7 @@ const AGY_QUOTA_RE = /^\s*⚠?\s*(individual )?quota reached/i;
245
257
  // ------------------------------------------------------------------------------------------------------------------------------------------
246
258
 
247
259
  export function createLocalLlm({
248
- adapters = DEFAULT_LLM_ADAPTERS, spawnImpl = spawn, dir = LLM_DIR, now = Date.now, idleMs = WARM_IDLE_MS, version = versionOf,
260
+ adapters = DEFAULT_LLM_ADAPTERS, spawnImpl = spawn, fetchImpl = globalThis.fetch, dir = LLM_DIR, now = Date.now, idleMs = WARM_IDLE_MS, version = versionOf,
249
261
  warmPerKey = WARM_PER_KEY, maxWarmProcs = MAX_WARM_PROCS,
250
262
  // Máy tính tổ chức: lời gọi nào cũng phải mang tài khoản thành viên (`ctx.runAs`) — agent chạy dưới tài khoản đó, không bao giờ bằng root.
251
263
  memberMode = false, memberDir = MEMBER_LLM_DIR, signIn: signInOverride,
@@ -255,6 +267,17 @@ export function createLocalLlm({
255
267
  const probes = new Map();
256
268
  const versions = new Map();
257
269
  const binOf = (a) => {
270
+ if (a.dynamic) {
271
+ try {
272
+ const hit = a.find() || null;
273
+ found.set(a.id, hit);
274
+ if (hit?.version) versions.set(a.id, hit.version);
275
+ return hit;
276
+ } catch {
277
+ found.set(a.id, null);
278
+ return null;
279
+ }
280
+ }
258
281
  if (!found.has(a.id)) { try { found.set(a.id, a.find() || null); } catch { found.set(a.id, null); } }
259
282
  return found.get(a.id);
260
283
  };
@@ -423,8 +446,106 @@ export function createLocalLlm({
423
446
  return { adapter, model, effort };
424
447
  }
425
448
 
449
+ async function completeViaLightcodeHttp(adapter, args, ctx) {
450
+ const info = binOf(adapter);
451
+ const conn = info?.connector;
452
+ if (!conn?.port || !conn?.key) throw failed('LightCode is not running on this computer', DeviceErrorCode.NOT_FOUND);
453
+ const startedAt = now();
454
+ const timeoutMs = Math.min(Number(args.timeout_ms) || ctx.timeoutMs || DEFAULT_TIMEOUT_MS, 10 * 60_000);
455
+ const ctrl = new AbortController();
456
+ const timer = setTimeout(() => ctrl.abort(), timeoutMs);
457
+ const onOuterAbort = () => ctrl.abort();
458
+ ctx.signal?.addEventListener?.('abort', onOuterAbort, { once: true });
459
+ try {
460
+ const res = await fetchImpl(`http://127.0.0.1:${conn.port}/connector/v1/complete`, {
461
+ method: 'POST',
462
+ headers: { 'Content-Type': 'application/json', Authorization: `Bearer ${conn.key}` },
463
+ body: JSON.stringify({
464
+ ...(args.prompt ? { prompt: String(args.prompt) } : {}),
465
+ ...(args.system ? { system: String(args.system) } : {}),
466
+ ...(Array.isArray(args.messages) ? { messages: args.messages } : {}),
467
+ ...(args.json_schema ? { json_schema: args.json_schema } : {}),
468
+ ...(args.provider ? { provider: String(args.provider) } : {}),
469
+ ...(args.model && args.model !== 'auto' ? { model: String(args.model) } : {}),
470
+ ...(args.effort ? { effort: String(args.effort) } : {}),
471
+ timeout_ms: timeoutMs,
472
+ stream: true,
473
+ }),
474
+ signal: ctrl.signal,
475
+ });
476
+ if (res.status === 429) {
477
+ const errBody = await res.json().catch(() => ({}));
478
+ throw failed(errBody?.error || 'All LightCode accounts are out of quota', QUOTA_ERROR);
479
+ }
480
+ if (!res.ok) {
481
+ const errBody = await res.json().catch(() => ({}));
482
+ if (errBody?.code === 'quota_exceeded') throw failed(errBody?.error || 'All LightCode accounts are out of quota', QUOTA_ERROR);
483
+ throw failed(errBody?.error || `LightCode answered ${res.status}`);
484
+ }
485
+ const decoder = new TextDecoder();
486
+ let buf = '';
487
+ let accText = '';
488
+ let finalMsg = null;
489
+ let ttft = null;
490
+ const handleLine = (line) => {
491
+ const s = line.trim();
492
+ if (!s) return;
493
+ let msg;
494
+ try { msg = JSON.parse(s); } catch { return; }
495
+ if (msg?.type === 'delta' && typeof msg.text === 'string') {
496
+ if (ttft === null) ttft = now() - startedAt;
497
+ accText += msg.text;
498
+ if (typeof ctx.onOutput === 'function') { try { ctx.onOutput(msg.text); } catch { /* bỏ qua */ } }
499
+ } else if (msg?.type === 'result') {
500
+ finalMsg = msg;
501
+ }
502
+ };
503
+ if (res.body) {
504
+ for await (const chunk of res.body) {
505
+ if (ctrl.signal.aborted) break;
506
+ buf += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
507
+ const lines = buf.split('\n');
508
+ buf = lines.pop() ?? '';
509
+ for (const line of lines) handleLine(line);
510
+ }
511
+ if (buf.trim()) handleLine(buf);
512
+ } else {
513
+ finalMsg = await res.json().catch(() => null);
514
+ }
515
+ if (finalMsg && !finalMsg.ok) {
516
+ if (finalMsg.code === 'quota_exceeded') {
517
+ const resetNote = finalMsg.reset_at ? ` (resets at ${finalMsg.reset_at})` : '';
518
+ throw failed(`${finalMsg.error || 'All LightCode accounts are out of quota'}${resetNote}`, QUOTA_ERROR);
519
+ }
520
+ throw failed(finalMsg.error || 'LightCode completion failed');
521
+ }
522
+ const text = typeof finalMsg?.text === 'string' ? finalMsg.text : accText;
523
+ if (!text && finalMsg?.json === undefined) throw failed('LightCode returned an empty answer');
524
+ return {
525
+ text,
526
+ ...(finalMsg?.json !== undefined ? { json: finalMsg.json } : {}),
527
+ agent: 'lightcode',
528
+ model: finalMsg?.model || args.model || 'auto',
529
+ ...(finalMsg?.provider ? { provider: finalMsg.provider } : {}),
530
+ ...(finalMsg?.account ? { account: finalMsg.account } : {}),
531
+ ...(finalMsg?.usage ? { usage: finalMsg.usage } : {}),
532
+ duration_ms: now() - startedAt,
533
+ ...(ttft !== null ? { ttft_ms: ttft } : {}),
534
+ };
535
+ } catch (e) {
536
+ if (e instanceof DeviceToolError) throw e;
537
+ if (ctx.signal?.aborted) throw failed('Cancelled', DeviceErrorCode.CANCELLED);
538
+ if (ctrl.signal.aborted) throw failed(`LightCode timed out after ${timeoutMs} ms`, DeviceErrorCode.TIMEOUT);
539
+ throw failed(`LightCode: ${e?.message || e}`);
540
+ } finally {
541
+ clearTimeout(timer);
542
+ ctx.signal?.removeEventListener?.('abort', onOuterAbort);
543
+ }
544
+ }
545
+
426
546
  async function complete(args = {}, ctx = {}) {
427
547
  const { adapter, model, effort } = validate(args);
548
+ if (adapter.kind === 'http') return completeViaLightcodeHttp(adapter, { ...args, model, effort }, ctx);
428
549
  const account = accountOf(ctx);
429
550
  await assertSignedIn(adapter, account);
430
551
  const content = renderRequest(args, { withBase: adapter.kind !== 'stream' });
@@ -542,6 +663,7 @@ export function createLocalLlm({
542
663
  /** BE báo trước agent / model sắp dùng (người dùng vừa chọn máy này) → khởi động sẵn. Máy tổ chức: chỉ khi thành viên đã đăng nhập. */
543
664
  prewarm: (args = {}, ctx = {}) => {
544
665
  const { adapter, model, effort } = validate(args);
666
+ if (adapter.kind === 'http') return Promise.resolve({ warm: [] });
545
667
  const account = accountOf(ctx);
546
668
  const warmNow = () => {
547
669
  keepWarm(adapter, { model, effort, account });