File size: 5,807 Bytes
d739b1b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
/** CLI ๊ตฌ์กฐํ™” ์ถœ๋ ฅ๊ณผ ์‚ฌ์šฉ๋Ÿ‰ ์ •๊ทœํ™”. ๊ณ„์•ฝ: docs/specs/runtime-usage.md v1.0.0 */
const valid = value => typeof value === 'number' && Number.isFinite(value) && value >= 0;
const token = value => valid(value) && Number.isSafeInteger(value) ? value : null;
const { isStorageBusy, storageBusyError } = require('./cli-storage-error');
const { providerHttpError } = require('./cli-provider-error');

function jsonOutputArgs(cli, args, { streamJson = false } = {}) {
  const stream = cli === 'claude' && streamJson;
  const flag = cli === 'claude' ? '--output-format' : ['opencode', 'codeagent'].includes(cli) ? '--format' : null;
  if (!flag) return [...args];
  // ์ค‘๋ณต ํ”Œ๋ž˜๊ทธ์˜ CLI๋ณ„ ์šฐ์„ ์ˆœ์œ„์— ๊ธฐ๋Œ€์ง€ ์•Š๊ณ  ๋ž˜ํผ์˜ ์ถœ๋ ฅ ๊ณ„์•ฝ์„ ํ•˜๋‚˜๋กœ ๊ณ ์ •ํ•œ๋‹ค.
  const result = [];
  for (let i = 0; i < args.length; i++) {
    if (args[i] === '--') throw new Error('CLI argument separator is incompatible with managed output');
    if (args[i] === flag) {
      if (!args[i + 1] || args[i + 1].startsWith('-')) throw new Error('Missing CLI output format');
      i++;
    } else if (!args[i].startsWith(flag + '=')) {
      if (stream && args[i] === '--verbose') continue;
      result.push(args[i]);
    }
  }
  return [...result, flag, stream ? 'stream-json' : 'json', ...(stream ? ['--verbose'] : [])];
}

function parseCliOutput(cli, stdout, { streamJson = false } = {}) {
  const usage = { costUsd: null, costSource: 'unknown', totalTokens: null, tokenSource: 'unknown', reports: [] };
  if (!['claude', 'opencode', 'codeagent'].includes(cli)) return { text: stdout, usage, error: null };
  let events, error = null;
  try {
    // Claude --verbose๋Š” JSON ๋ฐฐ์—ด, ์ผ๋ฐ˜ json์€ ์ตœ์ข… result ๊ฐ์ฒด๋ฅผ ๋ฐ˜ํ™˜ํ•  ์ˆ˜ ์žˆ๋‹ค.
    if (cli === 'claude' && streamJson) {
      ({ events, error } = require('./claude-stream-output').claudeStreamOutput(stdout));
    } else if (cli === 'claude') {
      const parsed = JSON.parse(stdout); events = Array.isArray(parsed) ? parsed : [parsed];
    } else events = stdout.split('\n').filter(line => line.trim()).map(line => JSON.parse(line));
  } catch {
    error = new Error('Invalid ' + cli + ' JSON output');
    // ์ข…๋ฃŒ/์ถœ๋ ฅ ์ œํ•œ์œผ๋กœ ๋งˆ์ง€๋ง‰ ์ค„์ด ์ž˜๋ ค๋„ ์ด๋ฏธ ์™„๋ฃŒ๋œ OpenCode step์˜ ์‚ฌ์šฉ๋Ÿ‰์€ ๋ณด์กดํ•œ๋‹ค.
    events = cli === 'claude' ? [] : stdout.split('\n').flatMap(line => {
      try { return [JSON.parse(line)]; } catch { return []; }
    });
  }
  const seen = new Map(), messages = []; let result = null;
  for (const event of events) {
    if (!event || typeof event !== 'object') { error ||= new Error('Invalid CLI event'); continue; }
    if (cli === 'claude') {
      if (event.type !== 'result') continue;
      if (result && JSON.stringify(result) !== JSON.stringify(event)) { error ||= new Error('Conflicting Claude results'); continue; }
      if (result) continue;
      result = event;
      const u = event.usage || {};
      const fields = [u.input_tokens, u.output_tokens, u.cache_read_input_tokens ?? 0, u.cache_creation_input_tokens ?? 0].map(token);
      const total = fields.every(x => x !== null) ? fields.reduce((a, b) => a + b, 0) : null;
      usage.reports.push({ id: event.uuid || event.session_id || 'result', costUsd: valid(event.total_cost_usd) ? event.total_cost_usd : null,
        totalTokens: token(total), inputTokens: fields[0], outputTokens: fields[1], cacheReadTokens: fields[2], cacheWriteTokens: fields[3] });
      if (event.is_error || event.subtype !== 'success') error ||= new Error('Claude reported an execution error');
    } else {
      if (event.type === 'error') {
        // ์‚ฌ์šฉ์ž text ์ด๋ฒคํŠธ๋Š” ๊ฒ€์‚ฌํ•˜์ง€ ์•Š๋Š”๋‹ค. ์ €์žฅ ์˜ค๋ฅ˜๋Š” ํŒŒ์‹ฑ ์˜ค๋ฅ˜๋ณด๋‹ค ์šฐ์„ ํ•ด ์žฌ์‹œ๋„๋ฅผ ์ฐจ๋‹จํ•œ๋‹ค.
        if (isStorageBusy(JSON.stringify(event.error))) error = storageBusyError();
        else error ||= providerHttpError(event.error) || new Error('OpenCode reported an execution error');
      }
      if (event.type === 'text' && typeof event.part?.text === 'string') messages.push(event.part.text);
      if (event.type !== 'step_finish') continue;
      const part = event.part || {}, id = part.id;
      if (typeof id !== 'string' || !id) { error ||= new Error('Missing OpenCode usage event ID'); continue; }
      if (seen.has(id)) {
        if (seen.get(id) !== JSON.stringify(part)) error ||= new Error('Conflicting OpenCode usage event');
        continue;
      }
      seen.set(id, JSON.stringify(part));
      const t = part.tokens || {};
      // provider๋ณ„ ์บ์‹œ/์ถ”๋ก  ์ค‘๋ณต ์˜๋ฏธ๋ฅผ ์ถ”์ธกํ•˜์ง€ ์•Š๋Š”๋‹ค. total์ด ์—†์œผ๋ฉด ํ•ฉ๊ณ„๋Š” ๋ฏธ์ƒ์ด๋‹ค.
      usage.reports.push({ id, costUsd: valid(part.cost) ? part.cost : null, totalTokens: token(t.total),
        inputTokens: token(t.input), outputTokens: token(t.output), reasoningTokens: token(t.reasoning),
        cacheReadTokens: token(t.cache?.read), cacheWriteTokens: token(t.cache?.write) });
    }
  }
  if (usage.reports.length) {
    const costs = usage.reports.map(r => r.costUsd), totals = usage.reports.map(r => r.totalTokens);
    const knownCost = costs.filter(c => c !== null).reduce((a, b) => a + b, 0);
    usage.reportedCostUsd = valid(knownCost) ? knownCost : null;
    if (costs.every(c => c !== null) && valid(knownCost)) { usage.costUsd = knownCost; usage.costSource = 'cli_reported'; }
    const sum = totals.every(t => t !== null) ? totals.reduce((a, b) => a + b, 0) : null;
    if (token(sum) !== null) { usage.totalTokens = sum; usage.tokenSource = 'cli_reported'; }
  }
  if (cli === 'claude' && (!result || typeof result.result !== 'string')) error ||= new Error('Missing Claude text result');
  return { text: cli === 'claude' ? result?.result || '' : messages.join('\n'), usage, error };
}
module.exports = { jsonOutputArgs, parseCliOutput };