@kenhkl/agent-gate 0.4.1 → 0.5.0

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.
package/dist/cli.js CHANGED
@@ -44,42 +44,257 @@ var init_cjs_shims = __esm({
44
44
  }
45
45
  });
46
46
 
47
- // src/v3/storage/db.ts
48
- var db_exports = {};
49
- __export(db_exports, {
50
- closeDb: () => closeDb,
51
- getDb: () => getDb
47
+ // src/shared/storage/json-storage.ts
48
+ var json_storage_exports = {};
49
+ __export(json_storage_exports, {
50
+ JsonStorage: () => JsonStorage
52
51
  });
53
- function getDb(dbPath) {
54
- if (db) return db;
55
- const path2 = dbPath || getDefaultDbPath();
56
- const dir2 = (0, import_path.dirname)(path2);
57
- if (!(0, import_fs.existsSync)(dir2)) (0, import_fs.mkdirSync)(dir2, { recursive: true });
58
- db = new import_better_sqlite3.default(path2);
59
- db.pragma("journal_mode = WAL");
60
- db.exec(SCHEMA);
61
- return db;
52
+ function nowISO() {
53
+ return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, "");
62
54
  }
63
- function getDefaultDbPath() {
55
+ function getDefaultDataDir() {
64
56
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
65
57
  const xdgData = process.env.XDG_DATA_HOME || (0, import_path.join)(home, ".local", "share");
66
- return (0, import_path.join)(xdgData, "agent_gate", "agent_gate_ts.db");
58
+ return (0, import_path.join)(xdgData, "agent_gate", "storage");
67
59
  }
68
- function closeDb() {
69
- if (db) {
70
- db.close();
71
- db = null;
72
- }
73
- }
74
- var import_better_sqlite3, import_fs, import_path, db, SCHEMA;
75
- var init_db = __esm({
76
- "src/v3/storage/db.ts"() {
60
+ var import_fs, import_path, JsonStorage;
61
+ var init_json_storage = __esm({
62
+ "src/shared/storage/json-storage.ts"() {
77
63
  "use strict";
78
64
  init_cjs_shims();
79
- import_better_sqlite3 = __toESM(require("better-sqlite3"));
80
65
  import_fs = require("fs");
81
66
  import_path = require("path");
82
- db = null;
67
+ JsonStorage = class {
68
+ dataDir;
69
+ agentsPath;
70
+ sessionsPath;
71
+ toolCallsDir;
72
+ nextId;
73
+ constructor(dataDir) {
74
+ this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
75
+ this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
76
+ this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
77
+ this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
78
+ if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
79
+ if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
80
+ this.nextId = this.recoverNextId();
81
+ }
82
+ /** 扫描所有 tool_calls 文件,找到最大 id + 1 */
83
+ recoverNextId() {
84
+ let maxId = 0;
85
+ try {
86
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
87
+ for (const file of files) {
88
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
89
+ for (const r of records) {
90
+ if (r.id > maxId) maxId = r.id;
91
+ }
92
+ }
93
+ } catch {
94
+ }
95
+ return maxId + 1;
96
+ }
97
+ readJsonFile(path2, fallback2) {
98
+ try {
99
+ if (!(0, import_fs.existsSync)(path2)) return fallback2;
100
+ return JSON.parse((0, import_fs.readFileSync)(path2, "utf-8"));
101
+ } catch {
102
+ return fallback2;
103
+ }
104
+ }
105
+ /** 原子写入:先写 .tmp 再 rename */
106
+ writeJsonFile(path2, data) {
107
+ const dir2 = (0, import_path.dirname)(path2);
108
+ if (!(0, import_fs.existsSync)(dir2)) (0, import_fs.mkdirSync)(dir2, { recursive: true });
109
+ const tmp = path2 + ".tmp";
110
+ (0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
111
+ (0, import_fs.renameSync)(tmp, path2);
112
+ }
113
+ loadAgents() {
114
+ const raw = this.readJsonFile(this.agentsPath, {});
115
+ return new Map(Object.entries(raw));
116
+ }
117
+ saveAgents(agents) {
118
+ this.writeJsonFile(this.agentsPath, Object.fromEntries(agents));
119
+ }
120
+ loadSessions() {
121
+ const raw = this.readJsonFile(this.sessionsPath, {});
122
+ return new Map(Object.entries(raw));
123
+ }
124
+ saveSessions(sessions) {
125
+ this.writeJsonFile(this.sessionsPath, Object.fromEntries(sessions));
126
+ }
127
+ loadToolCalls(sessionId) {
128
+ return this.readJsonFile(
129
+ (0, import_path.join)(this.toolCallsDir, `${sessionId}.json`),
130
+ []
131
+ );
132
+ }
133
+ saveToolCalls(sessionId, records) {
134
+ this.writeJsonFile((0, import_path.join)(this.toolCallsDir, `${sessionId}.json`), records);
135
+ }
136
+ getOrCreateAgent(agentType, hostname, version2 = "") {
137
+ const agents = this.loadAgents();
138
+ const id = `${agentType}:${hostname}`;
139
+ const existing = agents.get(id);
140
+ if (existing) {
141
+ existing.last_seen_at = nowISO();
142
+ if (version2) existing.agent_version = version2;
143
+ } else {
144
+ agents.set(id, {
145
+ id,
146
+ agent_type: agentType,
147
+ agent_version: version2,
148
+ hostname,
149
+ registered_at: nowISO(),
150
+ last_seen_at: nowISO()
151
+ });
152
+ }
153
+ this.saveAgents(agents);
154
+ return id;
155
+ }
156
+ getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
157
+ const sessions = this.loadSessions();
158
+ if (!sessions.has(sessionId)) {
159
+ sessions.set(sessionId, {
160
+ id: sessionId,
161
+ agent_id: agentId,
162
+ cwd,
163
+ user_prompt: prompt,
164
+ os_type: osType,
165
+ status: "active",
166
+ created_at: nowISO(),
167
+ ended_at: null,
168
+ tool_call_count: 0
169
+ });
170
+ this.saveSessions(sessions);
171
+ }
172
+ }
173
+ getNextSeq(sessionId) {
174
+ const records = this.loadToolCalls(sessionId);
175
+ if (records.length === 0) return 1;
176
+ return Math.max(...records.map((r) => r.seq)) + 1;
177
+ }
178
+ insertToolCall(record) {
179
+ const records = this.loadToolCalls(record.session_id);
180
+ const id = this.nextId++;
181
+ records.push({ ...record, id, called_at: nowISO() });
182
+ this.saveToolCalls(record.session_id, records);
183
+ return id;
184
+ }
185
+ getActionHistory(sessionId, limit = 100) {
186
+ const records = this.loadToolCalls(sessionId);
187
+ const sorted = [...records].sort((a, b) => a.seq - b.seq);
188
+ const slice = sorted.slice(-limit);
189
+ return slice.map((r) => ({ action_type: r.action_type, action_detail: r.action_detail }));
190
+ }
191
+ queryToolCalls(params) {
192
+ const sessions = this.loadSessions();
193
+ const agents = this.loadAgents();
194
+ let allRecords = [];
195
+ if (params.sessionId) {
196
+ const records = this.loadToolCalls(params.sessionId);
197
+ allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
198
+ } else {
199
+ try {
200
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
201
+ for (const file of files) {
202
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
203
+ allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
204
+ }
205
+ } catch {
206
+ }
207
+ }
208
+ if (params.decision) {
209
+ allRecords = allRecords.filter((r) => r.decision === params.decision);
210
+ }
211
+ allRecords.sort((a, b) => b.called_at.localeCompare(a.called_at));
212
+ const offset = params.offset || 0;
213
+ const limit = params.limit || 50;
214
+ return allRecords.slice(offset, offset + limit);
215
+ }
216
+ enrichRecord(record, sessions, agents) {
217
+ const session = sessions.get(record.session_id);
218
+ const agentId = session?.agent_id;
219
+ const agent = agentId ? agents.get(agentId) : void 0;
220
+ return {
221
+ ...record,
222
+ agent_type: agent?.agent_type || "",
223
+ agent_version: agent?.agent_version || "",
224
+ hostname: agent?.hostname || ""
225
+ };
226
+ }
227
+ getAgentsList() {
228
+ const agents = this.loadAgents();
229
+ const sessions = this.loadSessions();
230
+ const result = [];
231
+ for (const agent of agents.values()) {
232
+ let sessionCount = 0;
233
+ let callCount = 0;
234
+ for (const session of sessions.values()) {
235
+ if (session.agent_id === agent.id) {
236
+ sessionCount++;
237
+ const records = this.loadToolCalls(session.id);
238
+ callCount += records.length;
239
+ }
240
+ }
241
+ result.push({
242
+ agent_type: agent.agent_type,
243
+ hostname: agent.hostname,
244
+ version: agent.agent_version,
245
+ session_count: sessionCount,
246
+ call_count: callCount
247
+ });
248
+ }
249
+ result.sort((a, b) => b.call_count - a.call_count);
250
+ return result.slice(0, 20);
251
+ }
252
+ getTimeline(limit = 100) {
253
+ const buckets = /* @__PURE__ */ new Map();
254
+ try {
255
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
256
+ for (const file of files) {
257
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
258
+ for (const r of records) {
259
+ const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
260
+ const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
261
+ if (r.decision === "Allow") bucket.allow++;
262
+ else bucket.deny++;
263
+ buckets.set(minute, bucket);
264
+ }
265
+ }
266
+ } catch {
267
+ }
268
+ const result = [];
269
+ for (const [time, counts] of buckets) {
270
+ result.push({ time, ...counts });
271
+ }
272
+ result.sort((a, b) => b.time.localeCompare(a.time));
273
+ return result.slice(0, limit);
274
+ }
275
+ close() {
276
+ }
277
+ };
278
+ }
279
+ });
280
+
281
+ // src/shared/storage/sqlite-storage.ts
282
+ var sqlite_storage_exports = {};
283
+ __export(sqlite_storage_exports, {
284
+ SqliteStorage: () => SqliteStorage
285
+ });
286
+ function getDefaultDbPath() {
287
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
288
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
289
+ return (0, import_path2.join)(xdgData, "agent_gate", "agent_gate_ts.db");
290
+ }
291
+ var import_fs2, import_path2, SCHEMA, SqliteStorage;
292
+ var init_sqlite_storage = __esm({
293
+ "src/shared/storage/sqlite-storage.ts"() {
294
+ "use strict";
295
+ init_cjs_shims();
296
+ import_fs2 = require("fs");
297
+ import_path2 = require("path");
83
298
  SCHEMA = `
84
299
  CREATE TABLE IF NOT EXISTS agents (
85
300
  id TEXT PRIMARY KEY,
@@ -126,10 +341,219 @@ CREATE TABLE IF NOT EXISTS tool_calls (
126
341
  CREATE INDEX IF NOT EXISTS idx_tool_calls_session_seq ON tool_calls(session_id, seq);
127
342
  CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, called_at);
128
343
  `;
344
+ SqliteStorage = class {
345
+ db;
346
+ constructor(dbPath) {
347
+ let Database;
348
+ try {
349
+ Database = require("better-sqlite3");
350
+ } catch {
351
+ throw new Error(
352
+ "better-sqlite3 is not installed. Use AGENT_GATE_STORAGE=json for environments without native modules."
353
+ );
354
+ }
355
+ const path2 = dbPath || getDefaultDbPath();
356
+ const dir2 = (0, import_path2.dirname)(path2);
357
+ if (!(0, import_fs2.existsSync)(dir2)) (0, import_fs2.mkdirSync)(dir2, { recursive: true });
358
+ this.db = new Database(path2);
359
+ this.db.pragma("journal_mode = WAL");
360
+ this.db.exec(SCHEMA);
361
+ }
362
+ static isAvailable() {
363
+ try {
364
+ require.resolve("better-sqlite3");
365
+ return true;
366
+ } catch {
367
+ return false;
368
+ }
369
+ }
370
+ getOrCreateAgent(agentType, hostname, version2 = "") {
371
+ const id = `${agentType}:${hostname}`;
372
+ this.db.prepare(
373
+ "INSERT OR IGNORE INTO agents (id, agent_type, agent_version, hostname) VALUES (?, ?, ?, ?)"
374
+ ).run(id, agentType, version2, hostname);
375
+ this.db.prepare("UPDATE agents SET last_seen_at = datetime('now') WHERE id = ?").run(id);
376
+ return id;
377
+ }
378
+ getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
379
+ this.db.prepare(
380
+ "INSERT OR IGNORE INTO sessions (id, agent_id, cwd, user_prompt, os_type) VALUES (?, ?, ?, ?, ?)"
381
+ ).run(sessionId, agentId, cwd, prompt, osType);
382
+ }
383
+ getNextSeq(sessionId) {
384
+ const row = this.db.prepare(
385
+ "SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
386
+ ).get(sessionId);
387
+ return row.next;
388
+ }
389
+ insertToolCall(record) {
390
+ const result = this.db.prepare(`
391
+ INSERT INTO tool_calls (session_id, seq, tool_name, command, description, cwd,
392
+ action_type, action_detail, decision, risk_level, risk_type, violated_layers,
393
+ reason, confidence, analysis_duration_ms)
394
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
395
+ `).run(
396
+ record.session_id,
397
+ record.seq,
398
+ record.tool_name,
399
+ record.command,
400
+ record.description,
401
+ record.cwd,
402
+ record.action_type,
403
+ record.action_detail,
404
+ record.decision,
405
+ record.risk_level,
406
+ record.risk_type,
407
+ record.violated_layers,
408
+ record.reason,
409
+ record.confidence,
410
+ record.analysis_duration_ms
411
+ );
412
+ return Number(result.lastInsertRowid);
413
+ }
414
+ getActionHistory(sessionId, limit = 100) {
415
+ const rows = this.db.prepare(
416
+ "SELECT action_type, action_detail FROM tool_calls WHERE session_id = ? ORDER BY seq DESC LIMIT ?"
417
+ ).all(sessionId, limit);
418
+ return rows.reverse();
419
+ }
420
+ queryToolCalls(params) {
421
+ const conditions = [];
422
+ const values = [];
423
+ if (params.sessionId) {
424
+ conditions.push("tc.session_id = ?");
425
+ values.push(params.sessionId);
426
+ }
427
+ if (params.decision) {
428
+ conditions.push("tc.decision = ?");
429
+ values.push(params.decision);
430
+ }
431
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
432
+ const limit = params.limit || 50;
433
+ const offset = params.offset || 0;
434
+ return this.db.prepare(
435
+ `SELECT tc.*, a.agent_type, a.agent_version, a.hostname
436
+ FROM tool_calls tc
437
+ LEFT JOIN sessions s ON tc.session_id = s.id
438
+ LEFT JOIN agents a ON s.agent_id = a.id
439
+ ${where} ORDER BY tc.called_at DESC LIMIT ? OFFSET ?`
440
+ ).all(...values, limit, offset);
441
+ }
442
+ getAgentsList() {
443
+ return this.db.prepare(`
444
+ SELECT a.agent_type, a.hostname, a.agent_version as version,
445
+ COUNT(DISTINCT s.id) as session_count,
446
+ COUNT(tc.id) as call_count
447
+ FROM agents a
448
+ LEFT JOIN sessions s ON s.agent_id = a.id
449
+ LEFT JOIN tool_calls tc ON tc.session_id = s.id
450
+ GROUP BY a.id
451
+ ORDER BY call_count DESC
452
+ LIMIT 20
453
+ `).all();
454
+ }
455
+ getTimeline(limit = 100) {
456
+ const rows = this.db.prepare(`
457
+ SELECT strftime('%Y-%m-%dT%H:%M', called_at) as time,
458
+ SUM(CASE WHEN decision='Allow' THEN 1 ELSE 0 END) as allow,
459
+ SUM(CASE WHEN decision='Deny' THEN 1 ELSE 0 END) as deny
460
+ FROM tool_calls
461
+ GROUP BY strftime('%Y-%m-%dT%H:%M', called_at)
462
+ ORDER BY time DESC
463
+ LIMIT ?
464
+ `).all(limit);
465
+ return rows.map((r) => {
466
+ const d = /* @__PURE__ */ new Date(r.time + ":00Z");
467
+ const year = d.getFullYear();
468
+ const month = String(d.getMonth() + 1).padStart(2, "0");
469
+ const day = String(d.getDate()).padStart(2, "0");
470
+ const hours = String(d.getHours()).padStart(2, "0");
471
+ const minutes = String(d.getMinutes()).padStart(2, "0");
472
+ return { ...r, time: `${year}-${month}-${day}T${hours}:${minutes}` };
473
+ });
474
+ }
475
+ close() {
476
+ if (this.db) {
477
+ this.db.close();
478
+ }
479
+ }
480
+ };
481
+ }
482
+ });
483
+
484
+ // src/shared/storage/db.ts
485
+ var db_exports = {};
486
+ __export(db_exports, {
487
+ closeDb: () => closeDb,
488
+ createStorage: () => createStorage,
489
+ getDb: () => getDb,
490
+ getStorage: () => getStorage
491
+ });
492
+ function createStorage(opts) {
493
+ if (storage) return storage;
494
+ const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
495
+ if (backend === "json") {
496
+ const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
497
+ storage = new JsonStorage2(opts?.dataDir);
498
+ console.log("[AgentGate] Storage: JSON files");
499
+ } else {
500
+ try {
501
+ require.resolve("better-sqlite3");
502
+ } catch {
503
+ console.error(
504
+ "[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
505
+ );
506
+ process.exit(1);
507
+ }
508
+ const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
509
+ storage = new SqliteStorage2(opts?.dbPath);
510
+ console.log("[AgentGate] Storage: SQLite");
511
+ }
512
+ return storage;
513
+ }
514
+ function getStorage() {
515
+ return storage;
516
+ }
517
+ function getDb(dbPath) {
518
+ if (rawDb) return rawDb;
519
+ try {
520
+ const Database = require("better-sqlite3");
521
+ const { existsSync: existsSync6, mkdirSync: mkdirSync3 } = require("fs");
522
+ const { join: join3, dirname: dirname3 } = require("path");
523
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
524
+ const xdgData = process.env.XDG_DATA_HOME || join3(home, ".local", "share");
525
+ const defaultPath = join3(xdgData, "agent_gate", "agent_gate_ts.db");
526
+ const path2 = dbPath || defaultPath;
527
+ const dir2 = dirname3(path2);
528
+ if (!existsSync6(dir2)) mkdirSync3(dir2, { recursive: true });
529
+ rawDb = new Database(path2);
530
+ rawDb.pragma("journal_mode = WAL");
531
+ return rawDb;
532
+ } catch {
533
+ throw new Error("better-sqlite3 is not available. Use AGENT_GATE_STORAGE=json.");
534
+ }
535
+ }
536
+ function closeDb() {
537
+ if (storage) {
538
+ storage.close();
539
+ storage = null;
540
+ }
541
+ if (rawDb) {
542
+ rawDb.close();
543
+ rawDb = null;
544
+ }
545
+ }
546
+ var storage, rawDb;
547
+ var init_db = __esm({
548
+ "src/shared/storage/db.ts"() {
549
+ "use strict";
550
+ init_cjs_shims();
551
+ storage = null;
552
+ rawDb = null;
129
553
  }
130
554
  });
131
555
 
132
- // src/v3/moss-client.ts
556
+ // src/shared/moss-client.ts
133
557
  var moss_client_exports = {};
134
558
  __export(moss_client_exports, {
135
559
  callAgentMoss: () => callAgentMoss,
@@ -168,7 +592,7 @@ function failClosedResponse(reason) {
168
592
  }
169
593
  var DEFAULT_MOSS_URL, mossUrl;
170
594
  var init_moss_client = __esm({
171
- "src/v3/moss-client.ts"() {
595
+ "src/shared/moss-client.ts"() {
172
596
  "use strict";
173
597
  init_cjs_shims();
174
598
  DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
@@ -176,10 +600,10 @@ var init_moss_client = __esm({
176
600
  }
177
601
  });
178
602
 
179
- // src/v3/models.ts
603
+ // src/shared/models.ts
180
604
  var import_zod, AgentGateInputSchema, AgentGateResponseSchema, HealthResponseSchema;
181
605
  var init_models = __esm({
182
- "src/v3/models.ts"() {
606
+ "src/shared/models.ts"() {
183
607
  "use strict";
184
608
  init_cjs_shims();
185
609
  import_zod = require("zod");
@@ -233,7 +657,7 @@ var init_models = __esm({
233
657
  }
234
658
  });
235
659
 
236
- // src/v3/normalizer.ts
660
+ // src/shared/normalizer.ts
237
661
  function normalize(input, systemContext) {
238
662
  const actionHistory = input.action_history.map((h) => ({
239
663
  action_type: h.action_type,
@@ -262,13 +686,13 @@ function normalize(input, systemContext) {
262
686
  };
263
687
  }
264
688
  var init_normalizer = __esm({
265
- "src/v3/normalizer.ts"() {
689
+ "src/shared/normalizer.ts"() {
266
690
  "use strict";
267
691
  init_cjs_shims();
268
692
  }
269
693
  });
270
694
 
271
- // src/v1/collector/system-info.ts
695
+ // src/shared/collector/system-info.ts
272
696
  async function collectSystemInfo() {
273
697
  try {
274
698
  return {
@@ -285,14 +709,14 @@ async function collectSystemInfo() {
285
709
  }
286
710
  var import_os;
287
711
  var init_system_info = __esm({
288
- "src/v1/collector/system-info.ts"() {
712
+ "src/shared/collector/system-info.ts"() {
289
713
  "use strict";
290
714
  init_cjs_shims();
291
715
  import_os = __toESM(require("os"));
292
716
  }
293
717
  });
294
718
 
295
- // src/v1/collector/process-info.ts
719
+ // src/shared/collector/process-info.ts
296
720
  async function collectProcessInfo() {
297
721
  try {
298
722
  return {
@@ -306,13 +730,13 @@ async function collectProcessInfo() {
306
730
  }
307
731
  }
308
732
  var init_process_info = __esm({
309
- "src/v1/collector/process-info.ts"() {
733
+ "src/shared/collector/process-info.ts"() {
310
734
  "use strict";
311
735
  init_cjs_shims();
312
736
  }
313
737
  });
314
738
 
315
- // src/v1/collector/user-info.ts
739
+ // src/shared/collector/user-info.ts
316
740
  async function collectUserInfo() {
317
741
  try {
318
742
  const userInfo = import_os2.default.userInfo();
@@ -328,14 +752,14 @@ async function collectUserInfo() {
328
752
  }
329
753
  var import_os2;
330
754
  var init_user_info = __esm({
331
- "src/v1/collector/user-info.ts"() {
755
+ "src/shared/collector/user-info.ts"() {
332
756
  "use strict";
333
757
  init_cjs_shims();
334
758
  import_os2 = __toESM(require("os"));
335
759
  }
336
760
  });
337
761
 
338
- // src/v1/collector/index.ts
762
+ // src/shared/collector/index.ts
339
763
  async function collectSystemContext() {
340
764
  const [os3, proc, user] = await Promise.all([
341
765
  collectSystemInfo(),
@@ -345,7 +769,7 @@ async function collectSystemContext() {
345
769
  return { os: os3, process: proc, user };
346
770
  }
347
771
  var init_collector = __esm({
348
- "src/v1/collector/index.ts"() {
772
+ "src/shared/collector/index.ts"() {
349
773
  "use strict";
350
774
  init_cjs_shims();
351
775
  init_system_info();
@@ -354,7 +778,7 @@ var init_collector = __esm({
354
778
  }
355
779
  });
356
780
 
357
- // src/v3/cache.ts
781
+ // src/shared/cache.ts
358
782
  function cacheKey(sessionId, cwd, command) {
359
783
  return `${sessionId}|${cwd}|${command}`;
360
784
  }
@@ -376,7 +800,7 @@ function setCache(key, result) {
376
800
  }
377
801
  var MAX_SIZE, TTL_MS, cache;
378
802
  var init_cache = __esm({
379
- "src/v3/cache.ts"() {
803
+ "src/shared/cache.ts"() {
380
804
  "use strict";
381
805
  init_cjs_shims();
382
806
  MAX_SIZE = 500;
@@ -385,120 +809,40 @@ var init_cache = __esm({
385
809
  }
386
810
  });
387
811
 
388
- // src/v3/storage/repository.ts
389
- function getOrCreateAgent(agentType, hostname, version2 = "") {
390
- const db2 = getDb();
391
- const id = `${agentType}:${hostname}`;
392
- db2.prepare(`
393
- INSERT OR IGNORE INTO agents (id, agent_type, agent_version, hostname) VALUES (?, ?, ?, ?)
394
- `).run(id, agentType, version2, hostname);
395
- db2.prepare("UPDATE agents SET last_seen_at = datetime('now') WHERE id = ?").run(id);
396
- return id;
812
+ // src/shared/storage/repository.ts
813
+ function store() {
814
+ return createStorage();
815
+ }
816
+ function getOrCreateAgent(agentType, hostname, version2) {
817
+ return store().getOrCreateAgent(agentType, hostname, version2);
397
818
  }
398
- function getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
399
- const db2 = getDb();
400
- db2.prepare(`
401
- INSERT OR IGNORE INTO sessions (id, agent_id, cwd, user_prompt, os_type) VALUES (?, ?, ?, ?, ?)
402
- `).run(sessionId, agentId, cwd, prompt, osType);
819
+ function getOrCreateSession(sessionId, agentId, cwd, prompt, osType) {
820
+ store().getOrCreateSession(sessionId, agentId, cwd, prompt, osType);
403
821
  }
404
822
  function getNextSeq(sessionId) {
405
- const db2 = getDb();
406
- const row = db2.prepare("SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?").get(sessionId);
407
- return row.next;
823
+ return store().getNextSeq(sessionId);
408
824
  }
409
825
  function insertToolCall(record) {
410
- const db2 = getDb();
411
- const result = db2.prepare(`
412
- INSERT INTO tool_calls (session_id, seq, tool_name, command, description, cwd,
413
- action_type, action_detail, decision, risk_level, risk_type, violated_layers,
414
- reason, confidence, analysis_duration_ms)
415
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
416
- `).run(
417
- record.session_id,
418
- record.seq,
419
- record.tool_name,
420
- record.command,
421
- record.description,
422
- record.cwd,
423
- record.action_type,
424
- record.action_detail,
425
- record.decision,
426
- record.risk_level,
427
- record.risk_type,
428
- record.violated_layers,
429
- record.reason,
430
- record.confidence,
431
- record.analysis_duration_ms
432
- );
433
- return Number(result.lastInsertRowid);
826
+ return store().insertToolCall(record);
434
827
  }
435
828
  function queryToolCalls(params) {
436
- const db2 = getDb();
437
- const conditions = [];
438
- const values = [];
439
- if (params.sessionId) {
440
- conditions.push("tc.session_id = ?");
441
- values.push(params.sessionId);
442
- }
443
- if (params.decision) {
444
- conditions.push("tc.decision = ?");
445
- values.push(params.decision);
446
- }
447
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
448
- const limit = params.limit || 50;
449
- const offset = params.offset || 0;
450
- return db2.prepare(
451
- `SELECT tc.*, a.agent_type, a.agent_version, a.hostname
452
- FROM tool_calls tc
453
- LEFT JOIN sessions s ON tc.session_id = s.id
454
- LEFT JOIN agents a ON s.agent_id = a.id
455
- ${where} ORDER BY tc.called_at DESC LIMIT ? OFFSET ?`
456
- ).all(...values, limit, offset);
829
+ return store().queryToolCalls(params);
457
830
  }
458
831
  function getAgentsList() {
459
- const db2 = getDb();
460
- return db2.prepare(`
461
- SELECT a.agent_type, a.hostname, a.agent_version as version,
462
- COUNT(DISTINCT s.id) as session_count,
463
- COUNT(tc.id) as call_count
464
- FROM agents a
465
- LEFT JOIN sessions s ON s.agent_id = a.id
466
- LEFT JOIN tool_calls tc ON tc.session_id = s.id
467
- GROUP BY a.id
468
- ORDER BY call_count DESC
469
- LIMIT 20
470
- `).all();
832
+ return store().getAgentsList();
471
833
  }
472
- function getTimeline(limit = 100) {
473
- const db2 = getDb();
474
- const rows = db2.prepare(`
475
- SELECT strftime('%Y-%m-%dT%H:%M', called_at) as time,
476
- SUM(CASE WHEN decision='Allow' THEN 1 ELSE 0 END) as allow,
477
- SUM(CASE WHEN decision='Deny' THEN 1 ELSE 0 END) as deny
478
- FROM tool_calls
479
- GROUP BY strftime('%Y-%m-%dT%H:%M', called_at)
480
- ORDER BY time DESC
481
- LIMIT ?
482
- `).all(limit);
483
- return rows.map((r) => {
484
- const d = /* @__PURE__ */ new Date(r.time + ":00Z");
485
- const year = d.getFullYear();
486
- const month = String(d.getMonth() + 1).padStart(2, "0");
487
- const day = String(d.getDate()).padStart(2, "0");
488
- const hours = String(d.getHours()).padStart(2, "0");
489
- const minutes = String(d.getMinutes()).padStart(2, "0");
490
- return { ...r, time: `${year}-${month}-${day}T${hours}:${minutes}` };
491
- });
834
+ function getTimeline(limit) {
835
+ return store().getTimeline(limit);
492
836
  }
493
837
  var init_repository = __esm({
494
- "src/v3/storage/repository.ts"() {
838
+ "src/shared/storage/repository.ts"() {
495
839
  "use strict";
496
840
  init_cjs_shims();
497
841
  init_db();
498
842
  }
499
843
  });
500
844
 
501
- // src/v3/routes.ts
845
+ // src/v1/routes.ts
502
846
  async function healthRoute(c) {
503
847
  return c.json(HealthResponseSchema.parse({}));
504
848
  }
@@ -587,7 +931,7 @@ async function timelineRoute(c) {
587
931
  return c.json(rows);
588
932
  }
589
933
  var init_routes = __esm({
590
- "src/v3/routes.ts"() {
934
+ "src/v1/routes.ts"() {
591
935
  "use strict";
592
936
  init_cjs_shims();
593
937
  init_models();
@@ -599,7 +943,7 @@ var init_routes = __esm({
599
943
  }
600
944
  });
601
945
 
602
- // src/v3/server.ts
946
+ // src/v1/server.ts
603
947
  var server_exports = {};
604
948
  __export(server_exports, {
605
949
  createApp: () => createApp
@@ -619,21 +963,21 @@ function createApp() {
619
963
  return app;
620
964
  }
621
965
  async function dashboardRoute(c) {
622
- const { readFileSync: readFileSync4, existsSync: existsSync5 } = await import("fs");
623
- const { resolve, dirname: dirname2 } = await import("path");
966
+ const { readFileSync: readFileSync5, existsSync: existsSync6 } = await import("fs");
967
+ const { resolve, dirname: dirname3 } = await import("path");
624
968
  const { fileURLToPath } = await import("url");
625
- const __dirname = dirname2(fileURLToPath(importMetaUrl));
969
+ const __dirname = dirname3(fileURLToPath(importMetaUrl));
626
970
  const paths = [
627
971
  resolve(__dirname, "dashboard.html"),
628
- resolve(__dirname, "../src/dashboard.html")
972
+ resolve(__dirname, "../src/v1/dashboard.html")
629
973
  ];
630
- const htmlPath = paths.find((p) => existsSync5(p)) || paths[0];
631
- const html = readFileSync4(htmlPath, "utf-8");
974
+ const htmlPath = paths.find((p) => existsSync6(p)) || paths[0];
975
+ const html = readFileSync5(htmlPath, "utf-8");
632
976
  return c.html(html);
633
977
  }
634
978
  var import_hono, import_cors, import_logger;
635
979
  var init_server = __esm({
636
- "src/v3/server.ts"() {
980
+ "src/v1/server.ts"() {
637
981
  "use strict";
638
982
  init_cjs_shims();
639
983
  import_hono = require("hono");
@@ -13286,26 +13630,26 @@ var require_pkcs1 = __commonJS({
13286
13630
  var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
13287
13631
  var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);
13288
13632
  var dbMask = rsa_mgf1(seed, keyLength - md.digestLength - 1, mgf1Md);
13289
- var db2 = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);
13290
- var lHashPrime = db2.substring(0, md.digestLength);
13633
+ var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);
13634
+ var lHashPrime = db.substring(0, md.digestLength);
13291
13635
  var error = y !== "\0";
13292
13636
  for (var i = 0; i < md.digestLength; ++i) {
13293
13637
  error |= lHash.charAt(i) !== lHashPrime.charAt(i);
13294
13638
  }
13295
13639
  var in_ps = 1;
13296
13640
  var index2 = md.digestLength;
13297
- for (var j = md.digestLength; j < db2.length; j++) {
13298
- var code = db2.charCodeAt(j);
13641
+ for (var j = md.digestLength; j < db.length; j++) {
13642
+ var code = db.charCodeAt(j);
13299
13643
  var is_0 = code & 1 ^ 1;
13300
13644
  var error_mask = in_ps ? 65534 : 0;
13301
13645
  error |= code & error_mask;
13302
13646
  in_ps = in_ps & is_0;
13303
13647
  index2 += in_ps;
13304
13648
  }
13305
- if (error || db2.charCodeAt(index2) !== 1) {
13649
+ if (error || db.charCodeAt(index2) !== 1) {
13306
13650
  throw new Error("Invalid RSAES-OAEP padding.");
13307
13651
  }
13308
- return db2.substring(index2 + 1);
13652
+ return db.substring(index2 + 1);
13309
13653
  };
13310
13654
  function rsa_mgf1(seed, maskLength, hash) {
13311
13655
  if (!hash) {
@@ -15889,12 +16233,12 @@ var require_pss = __commonJS({
15889
16233
  ps.fillWithByte(0, emLen - sLen - hLen - 2);
15890
16234
  ps.putByte(1);
15891
16235
  ps.putBytes(salt);
15892
- var db2 = ps.getBytes();
16236
+ var db = ps.getBytes();
15893
16237
  var maskLen = emLen - hLen - 1;
15894
16238
  var dbMask = mgf.generate(h, maskLen);
15895
16239
  var maskedDB = "";
15896
16240
  for (i = 0; i < maskLen; i++) {
15897
- maskedDB += String.fromCharCode(db2.charCodeAt(i) ^ dbMask.charCodeAt(i));
16241
+ maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));
15898
16242
  }
15899
16243
  var mask = 65280 >> 8 * emLen - emBits & 255;
15900
16244
  maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1);
@@ -15919,21 +16263,21 @@ var require_pss = __commonJS({
15919
16263
  throw new Error("Bits beyond keysize not zero as expected.");
15920
16264
  }
15921
16265
  var dbMask = mgf.generate(h, maskLen);
15922
- var db2 = "";
16266
+ var db = "";
15923
16267
  for (i = 0; i < maskLen; i++) {
15924
- db2 += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));
16268
+ db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));
15925
16269
  }
15926
- db2 = String.fromCharCode(db2.charCodeAt(0) & ~mask) + db2.substr(1);
16270
+ db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);
15927
16271
  var checkLen = emLen - hLen - sLen - 2;
15928
16272
  for (i = 0; i < checkLen; i++) {
15929
- if (db2.charCodeAt(i) !== 0) {
16273
+ if (db.charCodeAt(i) !== 0) {
15930
16274
  throw new Error("Leftmost octets not zero as expected");
15931
16275
  }
15932
16276
  }
15933
- if (db2.charCodeAt(checkLen) !== 1) {
16277
+ if (db.charCodeAt(checkLen) !== 1) {
15934
16278
  throw new Error("Inconsistent PSS signature, 0x01 marker not found");
15935
16279
  }
15936
- var salt = db2.substr(-sLen);
16280
+ var salt = db.substr(-sLen);
15937
16281
  var m_ = new forge.util.ByteBuffer();
15938
16282
  m_.fillWithByte(0, 8);
15939
16283
  m_.putBytes(mHash);
@@ -24287,14 +24631,14 @@ var require_find_made = __commonJS({
24287
24631
  "../node_modules/mkdirp/lib/find-made.js"(exports2, module2) {
24288
24632
  "use strict";
24289
24633
  init_cjs_shims();
24290
- var { dirname: dirname2 } = require("path");
24634
+ var { dirname: dirname3 } = require("path");
24291
24635
  var findMade = (opts, parent2, path2 = void 0) => {
24292
24636
  if (path2 === parent2)
24293
24637
  return Promise.resolve();
24294
24638
  return opts.statAsync(parent2).then(
24295
24639
  (st) => st.isDirectory() ? path2 : void 0,
24296
24640
  // will fail later
24297
- (er) => er.code === "ENOENT" ? findMade(opts, dirname2(parent2), parent2) : void 0
24641
+ (er) => er.code === "ENOENT" ? findMade(opts, dirname3(parent2), parent2) : void 0
24298
24642
  );
24299
24643
  };
24300
24644
  var findMadeSync = (opts, parent2, path2 = void 0) => {
@@ -24303,7 +24647,7 @@ var require_find_made = __commonJS({
24303
24647
  try {
24304
24648
  return opts.statSync(parent2).isDirectory() ? path2 : void 0;
24305
24649
  } catch (er) {
24306
- return er.code === "ENOENT" ? findMadeSync(opts, dirname2(parent2), parent2) : void 0;
24650
+ return er.code === "ENOENT" ? findMadeSync(opts, dirname3(parent2), parent2) : void 0;
24307
24651
  }
24308
24652
  };
24309
24653
  module2.exports = { findMade, findMadeSync };
@@ -24315,10 +24659,10 @@ var require_mkdirp_manual = __commonJS({
24315
24659
  "../node_modules/mkdirp/lib/mkdirp-manual.js"(exports2, module2) {
24316
24660
  "use strict";
24317
24661
  init_cjs_shims();
24318
- var { dirname: dirname2 } = require("path");
24662
+ var { dirname: dirname3 } = require("path");
24319
24663
  var mkdirpManual = (path2, opts, made) => {
24320
24664
  opts.recursive = false;
24321
- const parent2 = dirname2(path2);
24665
+ const parent2 = dirname3(path2);
24322
24666
  if (parent2 === path2) {
24323
24667
  return opts.mkdirAsync(path2, opts).catch((er) => {
24324
24668
  if (er.code !== "EISDIR")
@@ -24341,7 +24685,7 @@ var require_mkdirp_manual = __commonJS({
24341
24685
  });
24342
24686
  };
24343
24687
  var mkdirpManualSync = (path2, opts, made) => {
24344
- const parent2 = dirname2(path2);
24688
+ const parent2 = dirname3(path2);
24345
24689
  opts.recursive = false;
24346
24690
  if (parent2 === path2) {
24347
24691
  try {
@@ -24378,12 +24722,12 @@ var require_mkdirp_native = __commonJS({
24378
24722
  "../node_modules/mkdirp/lib/mkdirp-native.js"(exports2, module2) {
24379
24723
  "use strict";
24380
24724
  init_cjs_shims();
24381
- var { dirname: dirname2 } = require("path");
24725
+ var { dirname: dirname3 } = require("path");
24382
24726
  var { findMade, findMadeSync } = require_find_made();
24383
24727
  var { mkdirpManual, mkdirpManualSync } = require_mkdirp_manual();
24384
24728
  var mkdirpNative = (path2, opts) => {
24385
24729
  opts.recursive = true;
24386
- const parent2 = dirname2(path2);
24730
+ const parent2 = dirname3(path2);
24387
24731
  if (parent2 === path2)
24388
24732
  return opts.mkdirAsync(path2, opts);
24389
24733
  return findMade(opts, path2).then((made) => opts.mkdirAsync(path2, opts).then(() => made).catch((er) => {
@@ -24395,7 +24739,7 @@ var require_mkdirp_native = __commonJS({
24395
24739
  };
24396
24740
  var mkdirpNativeSync = (path2, opts) => {
24397
24741
  opts.recursive = true;
24398
- const parent2 = dirname2(path2);
24742
+ const parent2 = dirname3(path2);
24399
24743
  if (parent2 === path2)
24400
24744
  return opts.mkdirSync(path2, opts);
24401
24745
  const made = findMadeSync(opts, path2);
@@ -27044,11 +27388,11 @@ var init_trigger = __esm({
27044
27388
  });
27045
27389
 
27046
27390
  // src/v3/proxy/storage.ts
27047
- function initProxySchema(db2) {
27048
- db2.exec(PROXY_SCHEMA_SQL);
27391
+ function initProxySchema(db) {
27392
+ db.exec(PROXY_SCHEMA_SQL);
27049
27393
  }
27050
- function insertProxyEvent(db2, event) {
27051
- const stmt = db2.prepare(`
27394
+ function insertProxyEvent(db, event) {
27395
+ const stmt = db.prepare(`
27052
27396
  INSERT INTO v3_proxy_events
27053
27397
  (session_id, event_type, tool_name, tool_call_id, arguments_raw,
27054
27398
  target_command, target_path, model, agent_type, system_prompt, user_prompt,
@@ -27313,44 +27657,44 @@ load();setInterval(load,5000);
27313
27657
  });
27314
27658
  }
27315
27659
  _serveStats(res) {
27316
- const db2 = this._options.db;
27317
- if (!db2) {
27660
+ const db = this._options.db;
27661
+ if (!db) {
27318
27662
  this._json(res, { error: "no database" });
27319
27663
  return;
27320
27664
  }
27321
27665
  try {
27322
- const totalEvents = db2.prepare("SELECT COUNT(*) FROM v3_proxy_events").get()["COUNT(*)"] || 0;
27323
- const totalSessions = db2.prepare("SELECT COUNT(DISTINCT session_id) FROM v3_proxy_events").get()["COUNT(DISTINCT session_id)"] || 0;
27324
- const totalTriggers = db2.prepare("SELECT COUNT(*) FROM v2_trigger_matches").get()["COUNT(*)"] || 0;
27325
- const uniqueTools = db2.prepare("SELECT COUNT(DISTINCT tool_name) FROM v3_proxy_events").get()["COUNT(DISTINCT tool_name)"] || 0;
27666
+ const totalEvents = db.prepare("SELECT COUNT(*) FROM v3_proxy_events").get()["COUNT(*)"] || 0;
27667
+ const totalSessions = db.prepare("SELECT COUNT(DISTINCT session_id) FROM v3_proxy_events").get()["COUNT(DISTINCT session_id)"] || 0;
27668
+ const totalTriggers = db.prepare("SELECT COUNT(*) FROM v2_trigger_matches").get()["COUNT(*)"] || 0;
27669
+ const uniqueTools = db.prepare("SELECT COUNT(DISTINCT tool_name) FROM v3_proxy_events").get()["COUNT(DISTINCT tool_name)"] || 0;
27326
27670
  this._json(res, { total_events: totalEvents, total_sessions: totalSessions, total_triggers: totalTriggers, unique_tools: uniqueTools });
27327
27671
  } catch {
27328
27672
  this._json(res, { error: "query failed" });
27329
27673
  }
27330
27674
  }
27331
27675
  _serveEvents(req, res) {
27332
- const db2 = this._options.db;
27333
- if (!db2) {
27676
+ const db = this._options.db;
27677
+ if (!db) {
27334
27678
  this._json(res, { events: [] });
27335
27679
  return;
27336
27680
  }
27337
27681
  try {
27338
27682
  const url = new import_node_url.URL(req.url || "/", `http://${req.headers.host}`);
27339
27683
  const limit = parseInt(url.searchParams.get("limit") || "50");
27340
- const rows = db2.prepare("SELECT session_id, tool_name, target_command, agent_type, captured_at FROM v3_proxy_events ORDER BY captured_at DESC LIMIT ?").all(limit);
27684
+ const rows = db.prepare("SELECT session_id, tool_name, target_command, agent_type, captured_at FROM v3_proxy_events ORDER BY captured_at DESC LIMIT ?").all(limit);
27341
27685
  this._json(res, { events: rows });
27342
27686
  } catch {
27343
27687
  this._json(res, { events: [] });
27344
27688
  }
27345
27689
  }
27346
27690
  _serveSessions(res) {
27347
- const db2 = this._options.db;
27348
- if (!db2) {
27691
+ const db = this._options.db;
27692
+ if (!db) {
27349
27693
  this._json(res, { sessions: [] });
27350
27694
  return;
27351
27695
  }
27352
27696
  try {
27353
- const rows = db2.prepare("SELECT session_id, agent_type, COUNT(*) as event_count, GROUP_CONCAT(DISTINCT tool_name) as tools FROM v3_proxy_events GROUP BY session_id ORDER BY MAX(captured_at) DESC LIMIT 20").all();
27697
+ const rows = db.prepare("SELECT session_id, agent_type, COUNT(*) as event_count, GROUP_CONCAT(DISTINCT tool_name) as tools FROM v3_proxy_events GROUP BY session_id ORDER BY MAX(captured_at) DESC LIMIT 20").all();
27354
27698
  this._json(res, { sessions: rows });
27355
27699
  } catch {
27356
27700
  this._json(res, { sessions: [] });
@@ -28500,6 +28844,50 @@ load();setInterval(load,5000);
28500
28844
  });
28501
28845
 
28502
28846
  // src/v3/pty/wrapper.ts
28847
+ async function scanProcesses() {
28848
+ const isWin = process.platform === "win32";
28849
+ const cmd = isWin ? "wmic" : "ps";
28850
+ const args = isWin ? ["process", "get", "ProcessId,ParentProcessId,Name,CommandLine", "/format:csv"] : ["-eo", "pid,ppid,comm,args"];
28851
+ try {
28852
+ const { execFile } = await import("child_process");
28853
+ return new Promise((resolve) => {
28854
+ execFile(cmd, args, { timeout: 5e3 }, (err, stdout) => {
28855
+ if (err || !stdout) {
28856
+ resolve([]);
28857
+ return;
28858
+ }
28859
+ const procs = [];
28860
+ const lines = stdout.trim().split("\n");
28861
+ for (const line of lines) {
28862
+ if (isWin) {
28863
+ const parts = line.split(",").map((p) => p.trim().replace(/"/g, ""));
28864
+ if (parts.length >= 4 && parts[1] && parts[2] && parts[3]) {
28865
+ const ppid = parseInt(parts[2], 10);
28866
+ const pid = parseInt(parts[3], 10);
28867
+ if (pid > 0 && ppid >= 0) {
28868
+ procs.push({ pid, ppid, name: parts[1], cmd: parts[4] || parts[1] });
28869
+ }
28870
+ }
28871
+ } else {
28872
+ const trimmed = line.trim();
28873
+ if (!trimmed) continue;
28874
+ const parts = trimmed.split(/\s+/);
28875
+ if (parts.length >= 4) {
28876
+ const pid = parseInt(parts[0], 10);
28877
+ const ppid = parseInt(parts[1], 10);
28878
+ if (pid > 0 && ppid >= 0) {
28879
+ procs.push({ pid, ppid, name: parts[2], cmd: parts.slice(3).join(" ") });
28880
+ }
28881
+ }
28882
+ }
28883
+ }
28884
+ resolve(procs);
28885
+ });
28886
+ });
28887
+ } catch {
28888
+ return [];
28889
+ }
28890
+ }
28503
28891
  var pty, import_events, PTYWrapper;
28504
28892
  var init_wrapper = __esm({
28505
28893
  "src/v3/pty/wrapper.ts"() {
@@ -28513,6 +28901,7 @@ var init_wrapper = __esm({
28513
28901
  isRunning = false;
28514
28902
  trackedPids = /* @__PURE__ */ new Set();
28515
28903
  processMonitorInterval = null;
28904
+ lastKnownChildren = /* @__PURE__ */ new Map();
28516
28905
  constructor(options = {}) {
28517
28906
  super();
28518
28907
  this.options = options;
@@ -28561,7 +28950,40 @@ var init_wrapper = __esm({
28561
28950
  if (!this.isRunning || !this.ptyProcess) {
28562
28951
  return;
28563
28952
  }
28564
- }, 100);
28953
+ try {
28954
+ const allProcs = await scanProcesses();
28955
+ const mainPid = this.ptyProcess.pid;
28956
+ const newChildren = [];
28957
+ for (const proc of allProcs) {
28958
+ if (this.trackedPids.has(proc.ppid) && !this.trackedPids.has(proc.pid) && !this.lastKnownChildren.has(proc.pid)) {
28959
+ newChildren.push(proc);
28960
+ this.trackedPids.add(proc.pid);
28961
+ this.lastKnownChildren.set(proc.pid, proc);
28962
+ }
28963
+ }
28964
+ for (const child of newChildren) {
28965
+ const procInfo = {
28966
+ pid: child.pid,
28967
+ command: child.name,
28968
+ args: child.cmd.split(" ").slice(1),
28969
+ timestamp: Date.now()
28970
+ };
28971
+ this.emit("process_create", procInfo);
28972
+ if (this.options.onProcessCreate) {
28973
+ this.options.onProcessCreate(procInfo.pid, procInfo.command, procInfo.args);
28974
+ }
28975
+ console.log(`[PTY] New subprocess: PID=${child.pid} cmd=${child.cmd}`);
28976
+ }
28977
+ for (const [pid] of this.lastKnownChildren) {
28978
+ if (!allProcs.some((p) => p.pid === pid)) {
28979
+ this.lastKnownChildren.delete(pid);
28980
+ this.trackedPids.delete(pid);
28981
+ }
28982
+ }
28983
+ } catch (err) {
28984
+ console.debug(`[PTY] Process scan failed:`, err);
28985
+ }
28986
+ }, 500);
28565
28987
  }
28566
28988
  stopProcessMonitor() {
28567
28989
  if (this.processMonitorInterval) {
@@ -28584,6 +29006,15 @@ var init_wrapper = __esm({
28584
29006
  this.ptyProcess.kill(signal);
28585
29007
  }
28586
29008
  }
29009
+ /** Kill process and all tracked children. */
29010
+ killTree(signal = "SIGTERM") {
29011
+ for (const pid of this.trackedPids) {
29012
+ try {
29013
+ process.kill(pid, signal);
29014
+ } catch {
29015
+ }
29016
+ }
29017
+ }
28587
29018
  get pid() {
28588
29019
  return this.ptyProcess?.pid;
28589
29020
  }
@@ -28614,8 +29045,9 @@ var init_output_parser = __esm({
28614
29045
  agentType: "claude-code"
28615
29046
  },
28616
29047
  // OpenCode: [TOOL_CALL] name {...}
29048
+ // Supports nested JSON via balanced-brace pattern
28617
29049
  {
28618
- pattern: /\[TOOL_CALL\]\s+(\w+)\s+(\{.*?\})/gs,
29050
+ pattern: /\[TOOL_CALL\]\s+(\w+)\s+(\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\})/gs,
28619
29051
  agentType: "opencode"
28620
29052
  },
28621
29053
  // OpenInterpreter: $ command
@@ -28624,8 +29056,9 @@ var init_output_parser = __esm({
28624
29056
  agentType: "openinterpreter"
28625
29057
  },
28626
29058
  // AutoGPT: [NEXT_ACTION] {"name": "...", "parameters": {...}}
29059
+ // Supports nested JSON via balanced-brace pattern
28627
29060
  {
28628
- pattern: /\[NEXT_ACTION\]\s+(\{.*?\})/gs,
29061
+ pattern: /\[NEXT_ACTION\]\s+(\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\})/gs,
28629
29062
  agentType: "autogpt"
28630
29063
  },
28631
29064
  // Generic Bash execution (Chinese)
@@ -28924,7 +29357,7 @@ async function main() {
28924
29357
  const args = process.argv.slice(2);
28925
29358
  const command = args[0];
28926
29359
  if (!command || command === "--help" || command === "-h") {
28927
- console.log(`AgentGate - AI Agent Data Collection & Security Analysis Gateway (TS v0.3.0)
29360
+ console.log(`AgentGate - AI Agent Data Collection & Security Analysis Gateway (TS v0.5.0)
28928
29361
 
28929
29362
  Commands:
28930
29363
  start Start AgentGate with specified layers (unified)
@@ -28951,6 +29384,7 @@ Server options:
28951
29384
  --host <host> Listen host (default: 127.0.0.1)
28952
29385
  --port <port> Listen port (default: 9100)
28953
29386
  --db-path <path> SQLite database path override
29387
+ (or set AGENT_GATE_STORAGE=json + AGENT_GATE_DATA_DIR=<dir> for JSON storage)
28954
29388
  --moss-url <url> AgentMoss service URL (default: http://127.0.0.1:9090)
28955
29389
 
28956
29390
  Proxy options:
@@ -28994,10 +29428,9 @@ Run options:
28994
29428
  else if (args[i] === "--moss-url" && args[i + 1]) mossUrl2 = args[++i];
28995
29429
  }
28996
29430
  mossUrl2 = mossUrl2 || process.env.MOSS_URL;
28997
- if (dbPath) {
28998
- const { getDb: getDb2 } = await Promise.resolve().then(() => (init_db(), db_exports));
28999
- getDb2(dbPath);
29000
- }
29431
+ const dataDir = process.env.AGENT_GATE_DATA_DIR;
29432
+ const { createStorage: createStorage2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29433
+ createStorage2({ dbPath, dataDir });
29001
29434
  if (mossUrl2) {
29002
29435
  const { setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
29003
29436
  setMossUrl2(mossUrl2);
@@ -29032,10 +29465,10 @@ Run options:
29032
29465
  if (envLevel && !args.includes("--level")) level = parseInt(envLevel, 10);
29033
29466
  const envDeny = process.env.AGENT_GATE_DENY_ACTION;
29034
29467
  if (envDeny && !args.includes("--deny-action")) denyAction = envDeny;
29035
- let db2;
29468
+ let db;
29036
29469
  if (dbPath) {
29037
29470
  const { getDb: getDb2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29038
- db2 = getDb2(dbPath);
29471
+ db = getDb2(dbPath);
29039
29472
  }
29040
29473
  const { ProxyServer: ProxyServer2 } = await Promise.resolve().then(() => (init_server2(), server_exports2));
29041
29474
  const { PhaseCoordinator: PhaseCoordinator2 } = await Promise.resolve().then(() => (init_coordinator(), coordinator_exports));
@@ -29057,7 +29490,7 @@ Run options:
29057
29490
  triggerEngine,
29058
29491
  whitelistEngine,
29059
29492
  privacyFilter,
29060
- db: db2,
29493
+ db,
29061
29494
  onBlock: (sid, matches) => {
29062
29495
  if (denyAction === "block") {
29063
29496
  console.warn(`[AgentGate] AgentMoss DENY (blocking): session=${sid.slice(0, 8)} rule=${matches[0]?.rule.name ?? "unknown"}`);
@@ -29075,7 +29508,7 @@ Run options:
29075
29508
  port,
29076
29509
  interceptHosts: interceptHosts.split(",").map((h) => h.trim()),
29077
29510
  rulesPath,
29078
- db: db2,
29511
+ db,
29079
29512
  coordinator
29080
29513
  });
29081
29514
  await server.start();
@@ -29127,10 +29560,10 @@ Run options:
29127
29560
  process.exit(1);
29128
29561
  }
29129
29562
  console.log(`[Gateway] Loaded ${modelRoutes.length} routes from ${configPath}`);
29130
- let db2;
29563
+ let db;
29131
29564
  if (dbPath) {
29132
29565
  const { getDb: getDb2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29133
- db2 = getDb2(dbPath);
29566
+ db = getDb2(dbPath);
29134
29567
  }
29135
29568
  const { GatewayServer: GatewayServer2 } = await Promise.resolve().then(() => (init_server3(), server_exports3));
29136
29569
  const { PhaseCoordinator: PhaseCoordinator2 } = await Promise.resolve().then(() => (init_coordinator(), coordinator_exports));
@@ -29152,7 +29585,7 @@ Run options:
29152
29585
  triggerEngine,
29153
29586
  whitelistEngine,
29154
29587
  privacyFilter,
29155
- db: db2,
29588
+ db,
29156
29589
  onBlock: (sid, matches) => {
29157
29590
  if (denyAction === "block") {
29158
29591
  console.warn(`[AgentGate] AgentMoss DENY (blocking): session=${sid.slice(0, 8)} rule=${matches[0]?.rule.name ?? "unknown"}`);
@@ -29174,7 +29607,7 @@ Run options:
29174
29607
  api_base: r.api_base,
29175
29608
  api_key: r.api_key
29176
29609
  })),
29177
- db: db2,
29610
+ db,
29178
29611
  rulesPath,
29179
29612
  coordinator
29180
29613
  });
@@ -29198,8 +29631,8 @@ Run options:
29198
29631
  if (args[i] === "--retention-days" && args[i + 1]) retentionDays = parseInt(args[++i], 10);
29199
29632
  }
29200
29633
  const { getDb: getDb2, closeDb: closeDb2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29201
- const db2 = getDb2();
29202
- const result = db2.prepare(
29634
+ const db = getDb2();
29635
+ const result = db.prepare(
29203
29636
  `DELETE FROM tool_calls WHERE called_at < datetime('now', '-${retentionDays} days')`
29204
29637
  ).run();
29205
29638
  console.log(`Cleaned ${result.changes} old records (retention: ${retentionDays} days)`);