File size: 5,072 Bytes
84aa3bf
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
/**
 * @license
 * Copyright 2026 Google LLC
 * SPDX-License-Identifier: Apache-2.0
 */

import type { CommandModule } from 'yargs';
import fs from 'node:fs';
import { spawn, type ChildProcess } from 'node:child_process';
import { debugLogger } from '@google/gemini-cli-core';
import { exitCli } from '../utils.js';
import { getLogFilePath } from './constants.js';

export async function readLastLines(
  filePath: string,
  count: number,
): Promise<string> {
  if (count <= 0) {
    return '';
  }

  const CHUNK_SIZE = 64 * 1024;
  const fileHandle = await fs.promises.open(filePath, fs.constants.O_RDONLY);

  try {
    const stats = await fileHandle.stat();
    if (stats.size === 0) {
      return '';
    }

    const chunks: Buffer[] = [];
    let totalBytes = 0;
    let newlineCount = 0;
    let position = stats.size;

    while (position > 0 && newlineCount <= count) {
      const readSize = Math.min(CHUNK_SIZE, position);
      position -= readSize;

      const buffer = Buffer.allocUnsafe(readSize);
      const { bytesRead } = await fileHandle.read(
        buffer,
        0,
        readSize,
        position,
      );

      if (bytesRead === 0) {
        break;
      }

      const chunk =
        bytesRead === readSize ? buffer : buffer.subarray(0, bytesRead);
      chunks.unshift(chunk);
      totalBytes += chunk.length;

      for (const byte of chunk) {
        if (byte === 0x0a) {
          newlineCount += 1;
        }
      }
    }

    const content = Buffer.concat(chunks, totalBytes).toString('utf-8');
    const lines = content.split('\n');

    if (position > 0 && lines.length > 0) {
      const boundary = Buffer.allocUnsafe(1);
      const { bytesRead } = await fileHandle.read(boundary, 0, 1, position - 1);
      if (bytesRead === 1 && boundary[0] !== 0x0a) {
        lines.shift();
      }
    }

    if (lines.length > 0 && lines[lines.length - 1] === '') {
      lines.pop();
    }

    if (lines.length === 0) {
      return '';
    }

    return lines.slice(-count).join('\n') + '\n';
  } finally {
    await fileHandle.close();
  }
}

interface LogsArgs {
  lines?: number;
  follow?: boolean;
}

function waitForChild(child: ChildProcess): Promise<number> {
  return new Promise((resolve, reject) => {
    child.once('error', reject);
    child.once('close', (code) => resolve(code ?? 1));
  });
}

async function runTail(logPath: string, lines: number, follow: boolean) {
  const tailArgs = follow
    ? ['-f', '-n', String(lines), logPath]
    : ['-n', String(lines), logPath];
  const child = spawn('tail', tailArgs, { stdio: 'inherit' });

  if (!follow) {
    return waitForChild(child);
  }

  const handleSigint = () => {
    child.kill('SIGTERM');
  };
  process.once('SIGINT', handleSigint);

  try {
    return await waitForChild(child);
  } finally {
    process.off('SIGINT', handleSigint);
  }
}

export const logsCommand: CommandModule<object, LogsArgs> = {
  command: 'logs',
  describe: 'View LiteRT-LM server logs',
  builder: (yargs) =>
    yargs
      .option('lines', {
        alias: 'n',
        type: 'number',
        description: 'Show the last N lines and exit (omit to follow live)',
      })
      .option('follow', {
        alias: 'f',
        type: 'boolean',
        description:
          'Follow log output (defaults to true when --lines is omitted)',
      }),
  handler: async (argv) => {
    const logPath = getLogFilePath();

    try {
      await fs.promises.access(logPath, fs.constants.F_OK);
    } catch {
      debugLogger.log(`No log file found at ${logPath}`);
      debugLogger.log(
        'Is the LiteRT server running? Start it with: gemini gemma start',
      );
      await exitCli(1);
      return;
    }

    const lines = argv.lines;
    const follow = argv.follow ?? lines === undefined;
    const requestedLines = lines ?? 20;

    if (follow && process.platform === 'win32') {
      debugLogger.log(
        'Live log following is not supported on Windows. Use --lines N to view recent logs.',
      );
      await exitCli(1);
      return;
    }

    if (process.platform === 'win32') {
      process.stdout.write(await readLastLines(logPath, requestedLines));
      await exitCli(0);
      return;
    }

    try {
      if (follow) {
        debugLogger.log(`Tailing ${logPath} (Ctrl+C to stop)\n`);
      }
      const exitCode = await runTail(logPath, requestedLines, follow);
      await exitCli(exitCode);
    } catch (error) {
      if (
        error instanceof Error &&
        'code' in error &&
        error.code === 'ENOENT'
      ) {
        if (!follow) {
          process.stdout.write(await readLastLines(logPath, requestedLines));
          await exitCli(0);
        } else {
          debugLogger.error(
            '"tail" command not found. Use --lines N to view recent logs without tail.',
          );
          await exitCli(1);
        }
      } else {
        debugLogger.error(
          `Failed to read log output: ${error instanceof Error ? error.message : String(error)}`,
        );
        await exitCli(1);
      }
    }
  },
};