@anthonyhan/token-pilot 0.5.0 → 0.5.1

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.
@@ -3,6 +3,7 @@
3
3
  import { promises as fs } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import os from 'node:os';
6
+ import { forEachLine } from './lines.js';
6
7
  const HOME = os.homedir();
7
8
  const PROJECTS_DIR = path.join(HOME, '.claude', 'projects');
8
9
  async function* walkJsonl(dir) {
@@ -116,32 +117,28 @@ function grabTitle(line, out) {
116
117
  }
117
118
  // 解析单个 jsonl 文件:文件内按 message.id 去重(取 totalTokens 最大),附会话标题
118
119
  async function readFileEvents(file, sinceMs = 0) {
119
- let content;
120
+ const byId = new Map();
121
+ const titleBySession = new Map();
120
122
  try {
121
- content = await fs.readFile(file, 'utf8');
123
+ await forEachLine(file, (line, i) => {
124
+ if (!line.trim())
125
+ return;
126
+ // 顺手抓会话标题(首条用户文本消息),成本只是一次子串判断
127
+ if (line.includes('"type":"user"') && line.includes('"content"')) {
128
+ grabTitle(line, titleBySession);
129
+ }
130
+ const ev = parseLine(line, file, i);
131
+ if (!ev || ev.timestamp < sinceMs)
132
+ return;
133
+ const prev = byId.get(ev.eventId);
134
+ if (!prev || ev.usage.totalTokens > prev.usage.totalTokens) {
135
+ byId.set(ev.eventId, ev);
136
+ }
137
+ });
122
138
  }
123
139
  catch {
124
140
  return [];
125
141
  }
126
- const byId = new Map();
127
- const titleBySession = new Map();
128
- const lines = content.split('\n');
129
- for (let i = 0; i < lines.length; i++) {
130
- const line = lines[i];
131
- if (!line.trim())
132
- continue;
133
- // 顺手抓会话标题(首条用户文本消息),成本只是一次子串判断
134
- if (line.includes('"type":"user"') && line.includes('"content"')) {
135
- grabTitle(line, titleBySession);
136
- }
137
- const ev = parseLine(line, file, i);
138
- if (!ev || ev.timestamp < sinceMs)
139
- continue;
140
- const prev = byId.get(ev.eventId);
141
- if (!prev || ev.usage.totalTokens > prev.usage.totalTokens) {
142
- byId.set(ev.eventId, ev);
143
- }
144
- }
145
142
  const events = [...byId.values()];
146
143
  for (const ev of events) {
147
144
  const t = titleBySession.get(ev.sessionId);
@@ -158,57 +155,55 @@ async function listFiles() {
158
155
  }
159
156
  // 内容流:tool_use(assistant)与 tool_result(user)只取尺寸与目标路径,不落内容
160
157
  async function readFileContentEvents(file, sinceMs = 0) {
161
- let content;
162
- try {
163
- content = await fs.readFile(file, 'utf8');
164
- }
165
- catch {
166
- return [];
167
- }
168
158
  const events = [];
169
159
  const sessionId = path.basename(file, '.jsonl');
170
- for (const line of content.split('\n')) {
171
- if (!line.includes('tool_use') && !line.includes('tool_result'))
172
- continue;
173
- let d;
174
- try {
175
- d = JSON.parse(line);
176
- }
177
- catch {
178
- continue;
179
- }
180
- const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
181
- if (ts < sinceMs)
182
- continue;
183
- const items = d.message?.content;
184
- if (!Array.isArray(items))
185
- continue;
186
- for (const c of items) {
187
- if (!c || typeof c !== 'object')
188
- continue;
189
- const cc = c;
190
- if (d.type === 'assistant' && cc.type === 'tool_use') {
191
- const input = cc.input;
192
- events.push({
193
- agent: 'claude-code',
194
- sessionId,
195
- timestamp: ts,
196
- kind: 'tool_use',
197
- tool: cc.name,
198
- targetPath: input?.file_path ?? input?.path,
199
- sizeBytes: cc.input ? JSON.stringify(cc.input).length : 0,
200
- });
160
+ try {
161
+ await forEachLine(file, (line) => {
162
+ if (!line.includes('tool_use') && !line.includes('tool_result'))
163
+ return;
164
+ let d;
165
+ try {
166
+ d = JSON.parse(line);
201
167
  }
202
- else if (d.type === 'user' && cc.type === 'tool_result') {
203
- events.push({
204
- agent: 'claude-code',
205
- sessionId,
206
- timestamp: ts,
207
- kind: 'tool_result',
208
- sizeBytes: cc.content ? JSON.stringify(cc.content).length : 0,
209
- });
168
+ catch {
169
+ return;
210
170
  }
211
- }
171
+ const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
172
+ if (ts < sinceMs)
173
+ return;
174
+ const items = d.message?.content;
175
+ if (!Array.isArray(items))
176
+ return;
177
+ for (const c of items) {
178
+ if (!c || typeof c !== 'object')
179
+ continue;
180
+ const cc = c;
181
+ if (d.type === 'assistant' && cc.type === 'tool_use') {
182
+ const input = cc.input;
183
+ events.push({
184
+ agent: 'claude-code',
185
+ sessionId,
186
+ timestamp: ts,
187
+ kind: 'tool_use',
188
+ tool: cc.name,
189
+ targetPath: input?.file_path ?? input?.path,
190
+ sizeBytes: cc.input ? JSON.stringify(cc.input).length : 0,
191
+ });
192
+ }
193
+ else if (d.type === 'user' && cc.type === 'tool_result') {
194
+ events.push({
195
+ agent: 'claude-code',
196
+ sessionId,
197
+ timestamp: ts,
198
+ kind: 'tool_result',
199
+ sizeBytes: cc.content ? JSON.stringify(cc.content).length : 0,
200
+ });
201
+ }
202
+ }
203
+ });
204
+ }
205
+ catch {
206
+ return [];
212
207
  }
213
208
  return events;
214
209
  }
@@ -3,6 +3,7 @@
3
3
  import { promises as fs } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import os from 'node:os';
6
+ import { forEachLine } from './lines.js';
6
7
  const HOME = os.homedir();
7
8
  const SESSIONS_DIR = path.join(HOME, '.codex', 'sessions');
8
9
  async function* walkJsonl(dir) {
@@ -61,23 +62,19 @@ function parseLine(line, file, lineNo) {
61
62
  };
62
63
  }
63
64
  async function readFileEvents(file, sinceMs = 0) {
64
- let content;
65
+ const events = [];
65
66
  try {
66
- content = await fs.readFile(file, 'utf8');
67
+ await forEachLine(file, (line, lineNo) => {
68
+ if (!line.trim())
69
+ return;
70
+ const ev = parseLine(line, file, lineNo);
71
+ if (ev && ev.timestamp >= sinceMs)
72
+ events.push(ev);
73
+ });
67
74
  }
68
75
  catch {
69
76
  return [];
70
77
  }
71
- const events = [];
72
- const lines = content.split('\n');
73
- for (let i = 0; i < lines.length; i++) {
74
- const line = lines[i];
75
- if (!line.trim())
76
- continue;
77
- const ev = parseLine(line, file, i);
78
- if (ev && ev.timestamp >= sinceMs)
79
- events.push(ev);
80
- }
81
78
  return events;
82
79
  }
83
80
  async function listFiles() {
@@ -123,41 +120,39 @@ export const codexAdapter = {
123
120
  };
124
121
  // 内容流:response_item 的 function_call / function_call_output,只取尺寸
125
122
  export async function readCodexContentEvents(file, sinceMs = 0) {
126
- let content;
123
+ const events = [];
124
+ const sessionId = path.basename(file, '.jsonl');
127
125
  try {
128
- content = await fs.readFile(file, 'utf8');
126
+ await forEachLine(file, (line) => {
127
+ if (!line.includes('function_call'))
128
+ return;
129
+ let d;
130
+ try {
131
+ d = JSON.parse(line);
132
+ }
133
+ catch {
134
+ return;
135
+ }
136
+ const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
137
+ if (ts < sinceMs)
138
+ return;
139
+ const p = d.payload;
140
+ if (p?.type === 'function_call') {
141
+ events.push({
142
+ agent: 'codex', sessionId, timestamp: ts, kind: 'tool_use',
143
+ tool: p.name, sizeBytes: (p.arguments ?? '').length,
144
+ });
145
+ }
146
+ else if (p?.type === 'function_call_output') {
147
+ events.push({
148
+ agent: 'codex', sessionId, timestamp: ts, kind: 'tool_result',
149
+ sizeBytes: (p.output ?? '').length,
150
+ });
151
+ }
152
+ });
129
153
  }
130
154
  catch {
131
155
  return [];
132
156
  }
133
- const events = [];
134
- const sessionId = path.basename(file, '.jsonl');
135
- for (const line of content.split('\n')) {
136
- if (!line.includes('function_call'))
137
- continue;
138
- let d;
139
- try {
140
- d = JSON.parse(line);
141
- }
142
- catch {
143
- continue;
144
- }
145
- const ts = d.timestamp ? new Date(d.timestamp).getTime() : 0;
146
- if (ts < sinceMs)
147
- continue;
148
- const p = d.payload;
149
- if (p?.type === 'function_call') {
150
- events.push({
151
- agent: 'codex', sessionId, timestamp: ts, kind: 'tool_use',
152
- tool: p.name, sizeBytes: (p.arguments ?? '').length,
153
- });
154
- }
155
- else if (p?.type === 'function_call_output') {
156
- events.push({
157
- agent: 'codex', sessionId, timestamp: ts, kind: 'tool_result',
158
- sizeBytes: (p.output ?? '').length,
159
- });
160
- }
161
- }
162
157
  return events;
163
158
  }
@@ -8,6 +8,7 @@ import { promisify } from 'node:util';
8
8
  import { promises as fs } from 'node:fs';
9
9
  import path from 'node:path';
10
10
  import os from 'node:os';
11
+ import { forEachZstdLine } from './lines.js';
11
12
  const execFileP = promisify(execFile);
12
13
  const HOME = os.homedir();
13
14
  const SESSIONS_DIR = path.join(HOME, '.dsh', 'sessions');
@@ -95,22 +96,19 @@ function providerFromModel(model) {
95
96
  return 'unknown';
96
97
  }
97
98
  async function readFileEvents(file, sinceMs = 0) {
98
- let content;
99
+ const events = [];
99
100
  try {
100
- const r = await execFileP('zstd', ['-dc', file], { timeout: 60_000, maxBuffer: 512 * 1024 * 1024 });
101
- content = r.stdout;
101
+ await forEachZstdLine(file, (line) => {
102
+ if (!line.trim())
103
+ return;
104
+ const ev = parseLine(line, file);
105
+ if (ev && ev.timestamp >= sinceMs)
106
+ events.push(ev);
107
+ });
102
108
  }
103
109
  catch {
104
110
  return [];
105
111
  }
106
- const events = [];
107
- for (const line of content.split('\n')) {
108
- if (!line.trim())
109
- continue;
110
- const ev = parseLine(line, file);
111
- if (ev && ev.timestamp >= sinceMs)
112
- events.push(ev);
113
- }
114
112
  // 同 seq 的流式快照去重(取最大 totalTokens)
115
113
  const byId = new Map();
116
114
  for (const ev of events) {
@@ -3,6 +3,7 @@
3
3
  import { promises as fs } from 'node:fs';
4
4
  import path from 'node:path';
5
5
  import os from 'node:os';
6
+ import { forEachLine } from './lines.js';
6
7
  const HOME = os.homedir();
7
8
  const SESSIONS_DIR = path.join(HOME, '.kimi-code', 'sessions');
8
9
  async function* walkJsonl(dir) {
@@ -59,23 +60,19 @@ function parseLine(line, file, lineNo) {
59
60
  };
60
61
  }
61
62
  async function readFileEvents(file, sinceMs = 0) {
62
- let content;
63
+ const events = [];
63
64
  try {
64
- content = await fs.readFile(file, 'utf8');
65
+ await forEachLine(file, (line, i) => {
66
+ if (!line.trim())
67
+ return;
68
+ const ev = parseLine(line, file, i);
69
+ if (ev && ev.timestamp >= sinceMs)
70
+ events.push(ev);
71
+ });
65
72
  }
66
73
  catch {
67
74
  return [];
68
75
  }
69
- const events = [];
70
- const lines = content.split('\n');
71
- for (let i = 0; i < lines.length; i++) {
72
- const line = lines[i];
73
- if (!line.trim())
74
- continue;
75
- const ev = parseLine(line, file, i);
76
- if (ev && ev.timestamp >= sinceMs)
77
- events.push(ev);
78
- }
79
76
  return events;
80
77
  }
81
78
  async function listFiles() {
@@ -121,45 +118,43 @@ export const kimiCodeAdapter = {
121
118
  };
122
119
  // 内容流:agent.message.appended 里的 toolCalls / role=tool 结果,只取尺寸
123
120
  export async function readKimiContentEvents(file, sinceMs = 0) {
124
- let content;
125
- try {
126
- content = await fs.readFile(file, 'utf8');
127
- }
128
- catch {
129
- return [];
130
- }
131
121
  const events = [];
132
122
  const sessionId = path.basename(path.dirname(path.dirname(file)));
133
- for (const line of content.split('\n')) {
134
- if (!line.includes('agent.message.appended'))
135
- continue;
136
- let d;
137
- try {
138
- d = JSON.parse(line);
139
- }
140
- catch {
141
- continue;
142
- }
143
- const ts = d.time ?? 0;
144
- if (ts < sinceMs)
145
- continue;
146
- const msg = d.message?.message;
147
- if (!msg)
148
- continue;
149
- if (Array.isArray(msg.toolCalls)) {
150
- for (const tc of msg.toolCalls) {
123
+ try {
124
+ await forEachLine(file, (line) => {
125
+ if (!line.includes('agent.message.appended'))
126
+ return;
127
+ let d;
128
+ try {
129
+ d = JSON.parse(line);
130
+ }
131
+ catch {
132
+ return;
133
+ }
134
+ const ts = d.time ?? 0;
135
+ if (ts < sinceMs)
136
+ return;
137
+ const msg = d.message?.message;
138
+ if (!msg)
139
+ return;
140
+ if (Array.isArray(msg.toolCalls)) {
141
+ for (const tc of msg.toolCalls) {
142
+ events.push({
143
+ agent: 'kimi-code', sessionId, timestamp: ts, kind: 'tool_use',
144
+ tool: tc.name, sizeBytes: (tc.arguments ?? '').length,
145
+ });
146
+ }
147
+ }
148
+ if (msg.role === 'tool' && msg.content) {
151
149
  events.push({
152
- agent: 'kimi-code', sessionId, timestamp: ts, kind: 'tool_use',
153
- tool: tc.name, sizeBytes: (tc.arguments ?? '').length,
150
+ agent: 'kimi-code', sessionId, timestamp: ts, kind: 'tool_result',
151
+ sizeBytes: JSON.stringify(msg.content).length,
154
152
  });
155
153
  }
156
- }
157
- if (msg.role === 'tool' && msg.content) {
158
- events.push({
159
- agent: 'kimi-code', sessionId, timestamp: ts, kind: 'tool_result',
160
- sizeBytes: JSON.stringify(msg.content).length,
161
- });
162
- }
154
+ });
155
+ }
156
+ catch {
157
+ return [];
163
158
  }
164
159
  return events;
165
160
  }
@@ -0,0 +1,50 @@
1
+ // 大日志逐行读取工具
2
+ //
3
+ // 教训:一个 281MB 的 rollout 直接 readFile + split('\n') 会同时持有
4
+ // 整文件字符串、行数组和解析对象;采集器又并发开 32 个文件,4GB 堆会被打爆。
5
+ // 这里统一用流式行读取,内存上限降到「单行 + 单文件解析结果」。
6
+ import { createReadStream } from 'node:fs';
7
+ import { createInterface } from 'node:readline';
8
+ import { spawn } from 'node:child_process';
9
+ export async function forEachLine(file, onLine) {
10
+ const stream = createReadStream(file, { encoding: 'utf8' });
11
+ const rl = createInterface({ input: stream, crlfDelay: Infinity });
12
+ let lineNo = 0;
13
+ try {
14
+ for await (const line of rl)
15
+ onLine(line, lineNo++);
16
+ }
17
+ finally {
18
+ rl.close();
19
+ stream.destroy();
20
+ }
21
+ }
22
+ export async function forEachZstdLine(file, onLine) {
23
+ const child = spawn('zstd', ['-dc', file], { stdio: ['ignore', 'pipe', 'pipe'] });
24
+ if (!child.stdout)
25
+ throw new Error('zstd stdout unavailable');
26
+ const exited = new Promise((resolve, reject) => {
27
+ child.once('error', reject);
28
+ child.once('close', (code) => {
29
+ if (code === 0)
30
+ resolve();
31
+ else
32
+ reject(new Error(`zstd exited ${code ?? 'unknown'}`));
33
+ });
34
+ });
35
+ const rl = createInterface({ input: child.stdout, crlfDelay: Infinity });
36
+ let lineNo = 0;
37
+ try {
38
+ for await (const line of rl)
39
+ onLine(line, lineNo++);
40
+ await exited;
41
+ }
42
+ finally {
43
+ rl.close();
44
+ child.stdout.destroy();
45
+ try {
46
+ child.kill();
47
+ }
48
+ catch { /* 已退出 */ }
49
+ }
50
+ }
@@ -67,7 +67,7 @@ export const opencodeAdapter = {
67
67
  db = new DatabaseSync(file, { readOnly: true });
68
68
  const rows = db.prepare(`SELECT id, session_id, time_created, data FROM message
69
69
  WHERE time_created >= ? AND json_extract(data,'$.tokens') IS NOT NULL
70
- AND json_extract(data,'$.role') = 'assistant'`).all(sinceMs);
70
+ AND json_extract(data,'$.role') = 'assistant'`).iterate(sinceMs);
71
71
  for (const r of rows) {
72
72
  const ev = toEvent(r.id, r.session_id, r.time_created, r.data);
73
73
  if (ev)
@@ -96,7 +96,7 @@ export async function readOpencodeContentEvents(file, sinceMs = 0) {
96
96
  try {
97
97
  db = new DatabaseSync(file, { readOnly: true });
98
98
  const rows = db.prepare(`SELECT p.session_id AS sid, p.time_created AS ts, p.data AS data
99
- FROM part p WHERE p.time_created >= ? AND json_extract(p.data,'$.type') = 'tool'`).all(sinceMs);
99
+ FROM part p WHERE p.time_created >= ? AND json_extract(p.data,'$.type') = 'tool'`).iterate(sinceMs);
100
100
  for (const r of rows) {
101
101
  let d;
102
102
  try {
@@ -4,6 +4,7 @@
4
4
  import { promises as fs } from 'node:fs';
5
5
  import path from 'node:path';
6
6
  import os from 'node:os';
7
+ import { forEachLine } from './lines.js';
7
8
  const HOME = os.homedir();
8
9
  const SESSIONS_DIR = path.join(HOME, '.pi', 'agent', 'sessions');
9
10
  async function* walkJsonl(dir) {
@@ -58,23 +59,19 @@ function parseLine(line, file, lineNo) {
58
59
  };
59
60
  }
60
61
  async function readFileEvents(file, sinceMs = 0) {
61
- let content;
62
+ const events = [];
62
63
  try {
63
- content = await fs.readFile(file, 'utf8');
64
+ await forEachLine(file, (line, i) => {
65
+ if (!line.trim())
66
+ return;
67
+ const ev = parseLine(line, file, i);
68
+ if (ev && ev.timestamp >= sinceMs)
69
+ events.push(ev);
70
+ });
64
71
  }
65
72
  catch {
66
73
  return [];
67
74
  }
68
- const events = [];
69
- const lines = content.split('\n');
70
- for (let i = 0; i < lines.length; i++) {
71
- const line = lines[i];
72
- if (!line.trim())
73
- continue;
74
- const ev = parseLine(line, file, i);
75
- if (ev && ev.timestamp >= sinceMs)
76
- events.push(ev);
77
- }
78
75
  return events;
79
76
  }
80
77
  async function listFiles() {
@@ -5,6 +5,7 @@
5
5
  import { promises as fs } from 'node:fs';
6
6
  import path from 'node:path';
7
7
  import os from 'node:os';
8
+ import { forEachLine } from './lines.js';
8
9
  const HOME = os.homedir();
9
10
  const ROOTS = [
10
11
  [path.join(HOME, '.workbuddy', 'traces'), 'workbuddy'],
@@ -82,21 +83,19 @@ function providerFromModel(model) {
82
83
  return 'unknown';
83
84
  }
84
85
  async function readFileEvents(file, sinceMs, agent) {
85
- let content;
86
+ const events = [];
86
87
  try {
87
- content = await fs.readFile(file, 'utf8');
88
+ await forEachLine(file, (line) => {
89
+ if (!line.trim())
90
+ return;
91
+ const ev = parseTraceEnd(line, file, agent);
92
+ if (ev && ev.timestamp >= sinceMs)
93
+ events.push(ev);
94
+ });
88
95
  }
89
96
  catch {
90
97
  return [];
91
98
  }
92
- const events = [];
93
- for (const line of content.split('\n')) {
94
- if (!line.trim())
95
- continue;
96
- const ev = parseTraceEnd(line, file, agent);
97
- if (ev && ev.timestamp >= sinceMs)
98
- events.push(ev);
99
- }
100
99
  return events;
101
100
  }
102
101
  function makeAdapter(root, agentId, displayName) {
@@ -19,8 +19,12 @@ import { workbuddyAdapter, workbuddyAiAdapter } from '../adapters/workbuddy.js';
19
19
  import { CONFIG_DIR } from './config.js';
20
20
  export const ALL_ADAPTERS = [claudeCodeAdapter, codexAdapter, kimiCodeAdapter, opencodeAdapter, piAdapter, volcArkAdapter, dshAdapter, workbuddyAdapter, workbuddyAiAdapter];
21
21
  const CACHE_PATH = path.join(CONFIG_DIR, 'events-cache.json');
22
- /** 同时打开的文件数上限。SSD 上 32 已经能吃到 IO 带宽,再高只是徒增内存峰值。 */
23
- const FILE_CONCURRENCY = 32;
22
+ /**
23
+ * 同时打开的文件数上限。
24
+ * 这里从 32 降到 4:用户的 rollout / trace 里有 100–300MB 单文件,
25
+ * 32 路并发会把「整文件读取 + 行数组」叠加到数 GB;流式读取后 4 路足够。
26
+ */
27
+ const FILE_CONCURRENCY = 4;
24
28
  /** 限并发的 map,保持结果顺序无关(本项目只关心副作用) */
25
29
  async function mapWithConcurrency(items, limit, fn) {
26
30
  let cursor = 0;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@anthonyhan/token-pilot",
3
- "version": "0.5.0",
3
+ "version": "0.5.1",
4
4
  "description": "你所有 AI 工具的本地账单 + 预算控制器 — 只读本地日志,零入侵,不出本机",
5
5
  "type": "module",
6
6
  "bin": {