@kenhkl/agent-gate 0.4.2 → 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.
package/dist/cli.js CHANGED
@@ -44,42 +44,270 @@ 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/version.ts
48
+ var import_module, require2, pkg, version;
49
+ var init_version = __esm({
50
+ "src/version.ts"() {
51
+ "use strict";
52
+ init_cjs_shims();
53
+ import_module = require("module");
54
+ require2 = (0, import_module.createRequire)(importMetaUrl);
55
+ pkg = require2("../../package.json");
56
+ version = pkg.version;
57
+ }
52
58
  });
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;
59
+
60
+ // src/shared/storage/json-storage.ts
61
+ var json_storage_exports = {};
62
+ __export(json_storage_exports, {
63
+ JsonStorage: () => JsonStorage
64
+ });
65
+ function nowISO() {
66
+ return (/* @__PURE__ */ new Date()).toISOString().replace("T", " ").replace(/\.\d+Z$/, "");
62
67
  }
63
- function getDefaultDbPath() {
68
+ function getDefaultDataDir() {
64
69
  const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
65
70
  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");
71
+ return (0, import_path.join)(xdgData, "agent_gate", "storage");
67
72
  }
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"() {
73
+ var import_fs, import_path, JsonStorage;
74
+ var init_json_storage = __esm({
75
+ "src/shared/storage/json-storage.ts"() {
77
76
  "use strict";
78
77
  init_cjs_shims();
79
- import_better_sqlite3 = __toESM(require("better-sqlite3"));
80
78
  import_fs = require("fs");
81
79
  import_path = require("path");
82
- db = null;
80
+ JsonStorage = class {
81
+ dataDir;
82
+ agentsPath;
83
+ sessionsPath;
84
+ toolCallsDir;
85
+ nextId;
86
+ constructor(dataDir) {
87
+ this.dataDir = dataDir || process.env.AGENT_GATE_DATA_DIR || getDefaultDataDir();
88
+ this.agentsPath = (0, import_path.join)(this.dataDir, "agents.json");
89
+ this.sessionsPath = (0, import_path.join)(this.dataDir, "sessions.json");
90
+ this.toolCallsDir = (0, import_path.join)(this.dataDir, "tool_calls");
91
+ if (!(0, import_fs.existsSync)(this.dataDir)) (0, import_fs.mkdirSync)(this.dataDir, { recursive: true });
92
+ if (!(0, import_fs.existsSync)(this.toolCallsDir)) (0, import_fs.mkdirSync)(this.toolCallsDir, { recursive: true });
93
+ this.nextId = this.recoverNextId();
94
+ }
95
+ /** 扫描所有 tool_calls 文件,找到最大 id + 1 */
96
+ recoverNextId() {
97
+ let maxId = 0;
98
+ try {
99
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
100
+ for (const file of files) {
101
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
102
+ for (const r of records) {
103
+ if (r.id > maxId) maxId = r.id;
104
+ }
105
+ }
106
+ } catch {
107
+ }
108
+ return maxId + 1;
109
+ }
110
+ readJsonFile(path2, fallback2) {
111
+ try {
112
+ if (!(0, import_fs.existsSync)(path2)) return fallback2;
113
+ return JSON.parse((0, import_fs.readFileSync)(path2, "utf-8"));
114
+ } catch {
115
+ return fallback2;
116
+ }
117
+ }
118
+ /** 原子写入:先写 .tmp 再 rename */
119
+ writeJsonFile(path2, data) {
120
+ const dir2 = (0, import_path.dirname)(path2);
121
+ if (!(0, import_fs.existsSync)(dir2)) (0, import_fs.mkdirSync)(dir2, { recursive: true });
122
+ const tmp = path2 + ".tmp";
123
+ (0, import_fs.writeFileSync)(tmp, JSON.stringify(data, null, 2), "utf-8");
124
+ (0, import_fs.renameSync)(tmp, path2);
125
+ }
126
+ loadAgents() {
127
+ const raw = this.readJsonFile(this.agentsPath, {});
128
+ return new Map(Object.entries(raw));
129
+ }
130
+ saveAgents(agents) {
131
+ this.writeJsonFile(this.agentsPath, Object.fromEntries(agents));
132
+ }
133
+ loadSessions() {
134
+ const raw = this.readJsonFile(this.sessionsPath, {});
135
+ return new Map(Object.entries(raw));
136
+ }
137
+ saveSessions(sessions) {
138
+ this.writeJsonFile(this.sessionsPath, Object.fromEntries(sessions));
139
+ }
140
+ loadToolCalls(sessionId) {
141
+ return this.readJsonFile(
142
+ (0, import_path.join)(this.toolCallsDir, `${sessionId}.json`),
143
+ []
144
+ );
145
+ }
146
+ saveToolCalls(sessionId, records) {
147
+ this.writeJsonFile((0, import_path.join)(this.toolCallsDir, `${sessionId}.json`), records);
148
+ }
149
+ getOrCreateAgent(agentType, hostname, version3 = "") {
150
+ const agents = this.loadAgents();
151
+ const id = `${agentType}:${hostname}`;
152
+ const existing = agents.get(id);
153
+ if (existing) {
154
+ existing.last_seen_at = nowISO();
155
+ if (version3) existing.agent_version = version3;
156
+ } else {
157
+ agents.set(id, {
158
+ id,
159
+ agent_type: agentType,
160
+ agent_version: version3,
161
+ hostname,
162
+ registered_at: nowISO(),
163
+ last_seen_at: nowISO()
164
+ });
165
+ }
166
+ this.saveAgents(agents);
167
+ return id;
168
+ }
169
+ getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
170
+ const sessions = this.loadSessions();
171
+ if (!sessions.has(sessionId)) {
172
+ sessions.set(sessionId, {
173
+ id: sessionId,
174
+ agent_id: agentId,
175
+ cwd,
176
+ user_prompt: prompt,
177
+ os_type: osType,
178
+ status: "active",
179
+ created_at: nowISO(),
180
+ ended_at: null,
181
+ tool_call_count: 0
182
+ });
183
+ this.saveSessions(sessions);
184
+ }
185
+ }
186
+ getNextSeq(sessionId) {
187
+ const records = this.loadToolCalls(sessionId);
188
+ if (records.length === 0) return 1;
189
+ return Math.max(...records.map((r) => r.seq)) + 1;
190
+ }
191
+ insertToolCall(record) {
192
+ const records = this.loadToolCalls(record.session_id);
193
+ const id = this.nextId++;
194
+ records.push({ ...record, id, called_at: nowISO() });
195
+ this.saveToolCalls(record.session_id, records);
196
+ return id;
197
+ }
198
+ getActionHistory(sessionId, limit = 100) {
199
+ const records = this.loadToolCalls(sessionId);
200
+ const sorted = [...records].sort((a, b) => a.seq - b.seq);
201
+ const slice = sorted.slice(-limit);
202
+ return slice.map((r) => ({ action_type: r.action_type, action_detail: r.action_detail }));
203
+ }
204
+ queryToolCalls(params) {
205
+ const sessions = this.loadSessions();
206
+ const agents = this.loadAgents();
207
+ let allRecords = [];
208
+ if (params.sessionId) {
209
+ const records = this.loadToolCalls(params.sessionId);
210
+ allRecords = records.map((r) => this.enrichRecord(r, sessions, agents));
211
+ } else {
212
+ try {
213
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
214
+ for (const file of files) {
215
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
216
+ allRecords.push(...records.map((r) => this.enrichRecord(r, sessions, agents)));
217
+ }
218
+ } catch {
219
+ }
220
+ }
221
+ if (params.decision) {
222
+ allRecords = allRecords.filter((r) => r.decision === params.decision);
223
+ }
224
+ allRecords.sort((a, b) => b.called_at.localeCompare(a.called_at));
225
+ const offset = params.offset || 0;
226
+ const limit = params.limit || 50;
227
+ return allRecords.slice(offset, offset + limit);
228
+ }
229
+ enrichRecord(record, sessions, agents) {
230
+ const session = sessions.get(record.session_id);
231
+ const agentId = session?.agent_id;
232
+ const agent = agentId ? agents.get(agentId) : void 0;
233
+ return {
234
+ ...record,
235
+ agent_type: agent?.agent_type || "",
236
+ agent_version: agent?.agent_version || "",
237
+ hostname: agent?.hostname || ""
238
+ };
239
+ }
240
+ getAgentsList() {
241
+ const agents = this.loadAgents();
242
+ const sessions = this.loadSessions();
243
+ const result = [];
244
+ for (const agent of agents.values()) {
245
+ let sessionCount = 0;
246
+ let callCount = 0;
247
+ for (const session of sessions.values()) {
248
+ if (session.agent_id === agent.id) {
249
+ sessionCount++;
250
+ const records = this.loadToolCalls(session.id);
251
+ callCount += records.length;
252
+ }
253
+ }
254
+ result.push({
255
+ agent_type: agent.agent_type,
256
+ hostname: agent.hostname,
257
+ version: agent.agent_version,
258
+ session_count: sessionCount,
259
+ call_count: callCount
260
+ });
261
+ }
262
+ result.sort((a, b) => b.call_count - a.call_count);
263
+ return result.slice(0, 20);
264
+ }
265
+ getTimeline(limit = 100) {
266
+ const buckets = /* @__PURE__ */ new Map();
267
+ try {
268
+ const files = (0, import_fs.readdirSync)(this.toolCallsDir).filter((f) => f.endsWith(".json"));
269
+ for (const file of files) {
270
+ const records = this.readJsonFile((0, import_path.join)(this.toolCallsDir, file), []);
271
+ for (const r of records) {
272
+ const minute = r.called_at.replace(/(\d{4}-\d{2}-\d{2}) (\d{2}:\d{2}):\d{2}/, "$1T$2");
273
+ const bucket = buckets.get(minute) || { allow: 0, deny: 0 };
274
+ if (r.decision === "Allow") bucket.allow++;
275
+ else bucket.deny++;
276
+ buckets.set(minute, bucket);
277
+ }
278
+ }
279
+ } catch {
280
+ }
281
+ const result = [];
282
+ for (const [time, counts] of buckets) {
283
+ result.push({ time, ...counts });
284
+ }
285
+ result.sort((a, b) => b.time.localeCompare(a.time));
286
+ return result.slice(0, limit);
287
+ }
288
+ close() {
289
+ }
290
+ };
291
+ }
292
+ });
293
+
294
+ // src/shared/storage/sqlite-storage.ts
295
+ var sqlite_storage_exports = {};
296
+ __export(sqlite_storage_exports, {
297
+ SqliteStorage: () => SqliteStorage
298
+ });
299
+ function getDefaultDbPath() {
300
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
301
+ const xdgData = process.env.XDG_DATA_HOME || (0, import_path2.join)(home, ".local", "share");
302
+ return (0, import_path2.join)(xdgData, "agent_gate", "agent_gate_ts.db");
303
+ }
304
+ var import_fs2, import_path2, SCHEMA, SqliteStorage;
305
+ var init_sqlite_storage = __esm({
306
+ "src/shared/storage/sqlite-storage.ts"() {
307
+ "use strict";
308
+ init_cjs_shims();
309
+ import_fs2 = require("fs");
310
+ import_path2 = require("path");
83
311
  SCHEMA = `
84
312
  CREATE TABLE IF NOT EXISTS agents (
85
313
  id TEXT PRIMARY KEY,
@@ -126,13 +354,223 @@ CREATE TABLE IF NOT EXISTS tool_calls (
126
354
  CREATE INDEX IF NOT EXISTS idx_tool_calls_session_seq ON tool_calls(session_id, seq);
127
355
  CREATE INDEX IF NOT EXISTS idx_tool_calls_decision ON tool_calls(decision, called_at);
128
356
  `;
357
+ SqliteStorage = class {
358
+ db;
359
+ constructor(dbPath) {
360
+ let Database;
361
+ try {
362
+ Database = require("better-sqlite3");
363
+ } catch {
364
+ throw new Error(
365
+ "better-sqlite3 is not installed. Use AGENT_GATE_STORAGE=json for environments without native modules."
366
+ );
367
+ }
368
+ const path2 = dbPath || getDefaultDbPath();
369
+ const dir2 = (0, import_path2.dirname)(path2);
370
+ if (!(0, import_fs2.existsSync)(dir2)) (0, import_fs2.mkdirSync)(dir2, { recursive: true });
371
+ this.db = new Database(path2);
372
+ this.db.pragma("journal_mode = WAL");
373
+ this.db.exec(SCHEMA);
374
+ }
375
+ static isAvailable() {
376
+ try {
377
+ require.resolve("better-sqlite3");
378
+ return true;
379
+ } catch {
380
+ return false;
381
+ }
382
+ }
383
+ getOrCreateAgent(agentType, hostname, version3 = "") {
384
+ const id = `${agentType}:${hostname}`;
385
+ this.db.prepare(
386
+ "INSERT OR IGNORE INTO agents (id, agent_type, agent_version, hostname) VALUES (?, ?, ?, ?)"
387
+ ).run(id, agentType, version3, hostname);
388
+ this.db.prepare("UPDATE agents SET last_seen_at = datetime('now') WHERE id = ?").run(id);
389
+ return id;
390
+ }
391
+ getOrCreateSession(sessionId, agentId, cwd = "", prompt = "", osType = "") {
392
+ this.db.prepare(
393
+ "INSERT OR IGNORE INTO sessions (id, agent_id, cwd, user_prompt, os_type) VALUES (?, ?, ?, ?, ?)"
394
+ ).run(sessionId, agentId, cwd, prompt, osType);
395
+ }
396
+ getNextSeq(sessionId) {
397
+ const row = this.db.prepare(
398
+ "SELECT COALESCE(MAX(seq), 0) + 1 as next FROM tool_calls WHERE session_id = ?"
399
+ ).get(sessionId);
400
+ return row.next;
401
+ }
402
+ insertToolCall(record) {
403
+ const result = this.db.prepare(`
404
+ INSERT INTO tool_calls (session_id, seq, tool_name, command, description, cwd,
405
+ action_type, action_detail, decision, risk_level, risk_type, violated_layers,
406
+ reason, confidence, analysis_duration_ms)
407
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
408
+ `).run(
409
+ record.session_id,
410
+ record.seq,
411
+ record.tool_name,
412
+ record.command,
413
+ record.description,
414
+ record.cwd,
415
+ record.action_type,
416
+ record.action_detail,
417
+ record.decision,
418
+ record.risk_level,
419
+ record.risk_type,
420
+ record.violated_layers,
421
+ record.reason,
422
+ record.confidence,
423
+ record.analysis_duration_ms
424
+ );
425
+ return Number(result.lastInsertRowid);
426
+ }
427
+ getActionHistory(sessionId, limit = 100) {
428
+ const rows = this.db.prepare(
429
+ "SELECT action_type, action_detail FROM tool_calls WHERE session_id = ? ORDER BY seq DESC LIMIT ?"
430
+ ).all(sessionId, limit);
431
+ return rows.reverse();
432
+ }
433
+ queryToolCalls(params) {
434
+ const conditions = [];
435
+ const values = [];
436
+ if (params.sessionId) {
437
+ conditions.push("tc.session_id = ?");
438
+ values.push(params.sessionId);
439
+ }
440
+ if (params.decision) {
441
+ conditions.push("tc.decision = ?");
442
+ values.push(params.decision);
443
+ }
444
+ const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
445
+ const limit = params.limit || 50;
446
+ const offset = params.offset || 0;
447
+ return this.db.prepare(
448
+ `SELECT tc.*, a.agent_type, a.agent_version, a.hostname
449
+ FROM tool_calls tc
450
+ LEFT JOIN sessions s ON tc.session_id = s.id
451
+ LEFT JOIN agents a ON s.agent_id = a.id
452
+ ${where} ORDER BY tc.called_at DESC LIMIT ? OFFSET ?`
453
+ ).all(...values, limit, offset);
454
+ }
455
+ getAgentsList() {
456
+ return this.db.prepare(`
457
+ SELECT a.agent_type, a.hostname, a.agent_version as version,
458
+ COUNT(DISTINCT s.id) as session_count,
459
+ COUNT(tc.id) as call_count
460
+ FROM agents a
461
+ LEFT JOIN sessions s ON s.agent_id = a.id
462
+ LEFT JOIN tool_calls tc ON tc.session_id = s.id
463
+ GROUP BY a.id
464
+ ORDER BY call_count DESC
465
+ LIMIT 20
466
+ `).all();
467
+ }
468
+ getTimeline(limit = 100) {
469
+ const rows = this.db.prepare(`
470
+ SELECT strftime('%Y-%m-%dT%H:%M', called_at) as time,
471
+ SUM(CASE WHEN decision='Allow' THEN 1 ELSE 0 END) as allow,
472
+ SUM(CASE WHEN decision='Deny' THEN 1 ELSE 0 END) as deny
473
+ FROM tool_calls
474
+ GROUP BY strftime('%Y-%m-%dT%H:%M', called_at)
475
+ ORDER BY time DESC
476
+ LIMIT ?
477
+ `).all(limit);
478
+ return rows.map((r) => {
479
+ const d = /* @__PURE__ */ new Date(r.time + ":00Z");
480
+ const year = d.getFullYear();
481
+ const month = String(d.getMonth() + 1).padStart(2, "0");
482
+ const day = String(d.getDate()).padStart(2, "0");
483
+ const hours = String(d.getHours()).padStart(2, "0");
484
+ const minutes = String(d.getMinutes()).padStart(2, "0");
485
+ return { ...r, time: `${year}-${month}-${day}T${hours}:${minutes}` };
486
+ });
487
+ }
488
+ close() {
489
+ if (this.db) {
490
+ this.db.close();
491
+ }
492
+ }
493
+ };
494
+ }
495
+ });
496
+
497
+ // src/shared/storage/db.ts
498
+ var db_exports = {};
499
+ __export(db_exports, {
500
+ closeDb: () => closeDb,
501
+ createStorage: () => createStorage,
502
+ getDb: () => getDb,
503
+ getStorage: () => getStorage
504
+ });
505
+ function createStorage(opts) {
506
+ if (storage) return storage;
507
+ const backend = (process.env.AGENT_GATE_STORAGE || "sqlite").toLowerCase();
508
+ if (backend === "json") {
509
+ const { JsonStorage: JsonStorage2 } = (init_json_storage(), __toCommonJS(json_storage_exports));
510
+ storage = new JsonStorage2(opts?.dataDir);
511
+ console.log("[AgentGate] Storage: JSON files");
512
+ } else {
513
+ try {
514
+ require.resolve("better-sqlite3");
515
+ } catch {
516
+ console.error(
517
+ "[AgentGate] better-sqlite3 is not installed. Set AGENT_GATE_STORAGE=json or install better-sqlite3."
518
+ );
519
+ process.exit(1);
520
+ }
521
+ const { SqliteStorage: SqliteStorage2 } = (init_sqlite_storage(), __toCommonJS(sqlite_storage_exports));
522
+ storage = new SqliteStorage2(opts?.dbPath);
523
+ console.log("[AgentGate] Storage: SQLite");
524
+ }
525
+ return storage;
526
+ }
527
+ function getStorage() {
528
+ return storage;
529
+ }
530
+ function getDb(dbPath) {
531
+ if (rawDb) return rawDb;
532
+ try {
533
+ const Database = require("better-sqlite3");
534
+ const { existsSync: existsSync6, mkdirSync: mkdirSync3 } = require("fs");
535
+ const { join: join3, dirname: dirname3 } = require("path");
536
+ const home = process.env.HOME || process.env.USERPROFILE || "/tmp";
537
+ const xdgData = process.env.XDG_DATA_HOME || join3(home, ".local", "share");
538
+ const defaultPath = join3(xdgData, "agent_gate", "agent_gate_ts.db");
539
+ const path2 = dbPath || defaultPath;
540
+ const dir2 = dirname3(path2);
541
+ if (!existsSync6(dir2)) mkdirSync3(dir2, { recursive: true });
542
+ rawDb = new Database(path2);
543
+ rawDb.pragma("journal_mode = WAL");
544
+ return rawDb;
545
+ } catch {
546
+ throw new Error("better-sqlite3 is not available. Use AGENT_GATE_STORAGE=json.");
547
+ }
548
+ }
549
+ function closeDb() {
550
+ if (storage) {
551
+ storage.close();
552
+ storage = null;
553
+ }
554
+ if (rawDb) {
555
+ rawDb.close();
556
+ rawDb = null;
557
+ }
558
+ }
559
+ var storage, rawDb;
560
+ var init_db = __esm({
561
+ "src/shared/storage/db.ts"() {
562
+ "use strict";
563
+ init_cjs_shims();
564
+ storage = null;
565
+ rawDb = null;
129
566
  }
130
567
  });
131
568
 
132
- // src/v3/moss-client.ts
569
+ // src/shared/moss-client.ts
133
570
  var moss_client_exports = {};
134
571
  __export(moss_client_exports, {
135
572
  callAgentMoss: () => callAgentMoss,
573
+ fetchMossHealth: () => fetchMossHealth,
136
574
  setMossUrl: () => setMossUrl
137
575
  });
138
576
  function setMossUrl(url) {
@@ -156,6 +594,23 @@ async function callAgentMoss(request) {
156
594
  return failClosedResponse("AgentMoss service unavailable");
157
595
  }
158
596
  }
597
+ async function fetchMossHealth() {
598
+ try {
599
+ const resp = await fetch(`${mossUrl}/api/v1/health`, {
600
+ signal: AbortSignal.timeout(3e3)
601
+ });
602
+ if (!resp.ok) {
603
+ return { moss_version: "N/A", moss_status: "error" };
604
+ }
605
+ const data = await resp.json();
606
+ return {
607
+ moss_version: data.version || "unknown",
608
+ moss_status: data.status || "unknown"
609
+ };
610
+ } catch {
611
+ return { moss_version: "N/A", moss_status: "unreachable" };
612
+ }
613
+ }
159
614
  function failClosedResponse(reason) {
160
615
  return {
161
616
  decision: "Deny",
@@ -168,7 +623,7 @@ function failClosedResponse(reason) {
168
623
  }
169
624
  var DEFAULT_MOSS_URL, mossUrl;
170
625
  var init_moss_client = __esm({
171
- "src/v3/moss-client.ts"() {
626
+ "src/shared/moss-client.ts"() {
172
627
  "use strict";
173
628
  init_cjs_shims();
174
629
  DEFAULT_MOSS_URL = "http://127.0.0.1:9090";
@@ -176,13 +631,14 @@ var init_moss_client = __esm({
176
631
  }
177
632
  });
178
633
 
179
- // src/v3/models.ts
634
+ // src/shared/models.ts
180
635
  var import_zod, AgentGateInputSchema, AgentGateResponseSchema, HealthResponseSchema;
181
636
  var init_models = __esm({
182
- "src/v3/models.ts"() {
637
+ "src/shared/models.ts"() {
183
638
  "use strict";
184
639
  init_cjs_shims();
185
640
  import_zod = require("zod");
641
+ init_version();
186
642
  AgentGateInputSchema = import_zod.z.object({
187
643
  agent_type: import_zod.z.string().describe("Agent identifier, e.g. opendesk, claude-code"),
188
644
  agent_version: import_zod.z.string().default("0.1.0"),
@@ -228,12 +684,14 @@ var init_models = __esm({
228
684
  });
229
685
  HealthResponseSchema = import_zod.z.object({
230
686
  status: import_zod.z.string().default("healthy"),
231
- version: import_zod.z.string().default("0.2.2")
687
+ version: import_zod.z.string().default(version),
688
+ moss_version: import_zod.z.string().default("N/A"),
689
+ moss_status: import_zod.z.string().default("unknown")
232
690
  });
233
691
  }
234
692
  });
235
693
 
236
- // src/v3/normalizer.ts
694
+ // src/shared/normalizer.ts
237
695
  function normalize(input, systemContext) {
238
696
  const actionHistory = input.action_history.map((h) => ({
239
697
  action_type: h.action_type,
@@ -262,13 +720,13 @@ function normalize(input, systemContext) {
262
720
  };
263
721
  }
264
722
  var init_normalizer = __esm({
265
- "src/v3/normalizer.ts"() {
723
+ "src/shared/normalizer.ts"() {
266
724
  "use strict";
267
725
  init_cjs_shims();
268
726
  }
269
727
  });
270
728
 
271
- // src/v1/collector/system-info.ts
729
+ // src/shared/collector/system-info.ts
272
730
  async function collectSystemInfo() {
273
731
  try {
274
732
  return {
@@ -285,14 +743,14 @@ async function collectSystemInfo() {
285
743
  }
286
744
  var import_os;
287
745
  var init_system_info = __esm({
288
- "src/v1/collector/system-info.ts"() {
746
+ "src/shared/collector/system-info.ts"() {
289
747
  "use strict";
290
748
  init_cjs_shims();
291
749
  import_os = __toESM(require("os"));
292
750
  }
293
751
  });
294
752
 
295
- // src/v1/collector/process-info.ts
753
+ // src/shared/collector/process-info.ts
296
754
  async function collectProcessInfo() {
297
755
  try {
298
756
  return {
@@ -306,13 +764,13 @@ async function collectProcessInfo() {
306
764
  }
307
765
  }
308
766
  var init_process_info = __esm({
309
- "src/v1/collector/process-info.ts"() {
767
+ "src/shared/collector/process-info.ts"() {
310
768
  "use strict";
311
769
  init_cjs_shims();
312
770
  }
313
771
  });
314
772
 
315
- // src/v1/collector/user-info.ts
773
+ // src/shared/collector/user-info.ts
316
774
  async function collectUserInfo() {
317
775
  try {
318
776
  const userInfo = import_os2.default.userInfo();
@@ -328,14 +786,14 @@ async function collectUserInfo() {
328
786
  }
329
787
  var import_os2;
330
788
  var init_user_info = __esm({
331
- "src/v1/collector/user-info.ts"() {
789
+ "src/shared/collector/user-info.ts"() {
332
790
  "use strict";
333
791
  init_cjs_shims();
334
792
  import_os2 = __toESM(require("os"));
335
793
  }
336
794
  });
337
795
 
338
- // src/v1/collector/index.ts
796
+ // src/shared/collector/index.ts
339
797
  async function collectSystemContext() {
340
798
  const [os3, proc, user] = await Promise.all([
341
799
  collectSystemInfo(),
@@ -345,7 +803,7 @@ async function collectSystemContext() {
345
803
  return { os: os3, process: proc, user };
346
804
  }
347
805
  var init_collector = __esm({
348
- "src/v1/collector/index.ts"() {
806
+ "src/shared/collector/index.ts"() {
349
807
  "use strict";
350
808
  init_cjs_shims();
351
809
  init_system_info();
@@ -354,7 +812,7 @@ var init_collector = __esm({
354
812
  }
355
813
  });
356
814
 
357
- // src/v3/cache.ts
815
+ // src/shared/cache.ts
358
816
  function cacheKey(sessionId, cwd, command) {
359
817
  return `${sessionId}|${cwd}|${command}`;
360
818
  }
@@ -376,7 +834,7 @@ function setCache(key, result) {
376
834
  }
377
835
  var MAX_SIZE, TTL_MS, cache;
378
836
  var init_cache = __esm({
379
- "src/v3/cache.ts"() {
837
+ "src/shared/cache.ts"() {
380
838
  "use strict";
381
839
  init_cjs_shims();
382
840
  MAX_SIZE = 500;
@@ -385,122 +843,48 @@ var init_cache = __esm({
385
843
  }
386
844
  });
387
845
 
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;
846
+ // src/shared/storage/repository.ts
847
+ function store() {
848
+ return createStorage();
849
+ }
850
+ function getOrCreateAgent(agentType, hostname, version3) {
851
+ return store().getOrCreateAgent(agentType, hostname, version3);
397
852
  }
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);
853
+ function getOrCreateSession(sessionId, agentId, cwd, prompt, osType) {
854
+ store().getOrCreateSession(sessionId, agentId, cwd, prompt, osType);
403
855
  }
404
856
  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;
857
+ return store().getNextSeq(sessionId);
408
858
  }
409
859
  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);
860
+ return store().insertToolCall(record);
434
861
  }
435
862
  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);
863
+ return store().queryToolCalls(params);
457
864
  }
458
865
  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();
866
+ return store().getAgentsList();
471
867
  }
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
- });
868
+ function getTimeline(limit) {
869
+ return store().getTimeline(limit);
492
870
  }
493
871
  var init_repository = __esm({
494
- "src/v3/storage/repository.ts"() {
872
+ "src/shared/storage/repository.ts"() {
495
873
  "use strict";
496
874
  init_cjs_shims();
497
875
  init_db();
498
876
  }
499
877
  });
500
878
 
501
- // src/v3/routes.ts
879
+ // src/v1/routes.ts
502
880
  async function healthRoute(c) {
503
- return c.json(HealthResponseSchema.parse({}));
881
+ const mossHealth = await fetchMossHealth();
882
+ return c.json({
883
+ status: "healthy",
884
+ version,
885
+ moss_version: mossHealth.moss_version,
886
+ moss_status: mossHealth.moss_status
887
+ });
504
888
  }
505
889
  async function analyzeRoute(c) {
506
890
  const t0 = performance.now();
@@ -587,7 +971,7 @@ async function timelineRoute(c) {
587
971
  return c.json(rows);
588
972
  }
589
973
  var init_routes = __esm({
590
- "src/v3/routes.ts"() {
974
+ "src/v1/routes.ts"() {
591
975
  "use strict";
592
976
  init_cjs_shims();
593
977
  init_models();
@@ -596,10 +980,11 @@ var init_routes = __esm({
596
980
  init_moss_client();
597
981
  init_cache();
598
982
  init_repository();
983
+ init_version();
599
984
  }
600
985
  });
601
986
 
602
- // src/v3/server.ts
987
+ // src/v1/server.ts
603
988
  var server_exports = {};
604
989
  __export(server_exports, {
605
990
  createApp: () => createApp
@@ -619,21 +1004,21 @@ function createApp() {
619
1004
  return app;
620
1005
  }
621
1006
  async function dashboardRoute(c) {
622
- const { readFileSync: readFileSync4, existsSync: existsSync5 } = await import("fs");
623
- const { resolve, dirname: dirname2 } = await import("path");
1007
+ const { readFileSync: readFileSync5, existsSync: existsSync6 } = await import("fs");
1008
+ const { resolve, dirname: dirname3 } = await import("path");
624
1009
  const { fileURLToPath } = await import("url");
625
- const __dirname = dirname2(fileURLToPath(importMetaUrl));
1010
+ const __dirname = dirname3(fileURLToPath(importMetaUrl));
626
1011
  const paths = [
627
1012
  resolve(__dirname, "dashboard.html"),
628
- resolve(__dirname, "../src/dashboard.html")
1013
+ resolve(__dirname, "../src/v1/dashboard.html")
629
1014
  ];
630
- const htmlPath = paths.find((p) => existsSync5(p)) || paths[0];
631
- const html = readFileSync4(htmlPath, "utf-8");
1015
+ const htmlPath = paths.find((p) => existsSync6(p)) || paths[0];
1016
+ const html = readFileSync5(htmlPath, "utf-8");
632
1017
  return c.html(html);
633
1018
  }
634
1019
  var import_hono, import_cors, import_logger;
635
1020
  var init_server = __esm({
636
- "src/v3/server.ts"() {
1021
+ "src/v1/server.ts"() {
637
1022
  "use strict";
638
1023
  init_cjs_shims();
639
1024
  import_hono = require("hono");
@@ -6000,7 +6385,7 @@ var require_websocket_server = __commonJS({
6000
6385
  socket.on("error", socketOnError);
6001
6386
  const key = req.headers["sec-websocket-key"];
6002
6387
  const upgrade = req.headers.upgrade;
6003
- const version2 = +req.headers["sec-websocket-version"];
6388
+ const version3 = +req.headers["sec-websocket-version"];
6004
6389
  if (req.method !== "GET") {
6005
6390
  const message = "Invalid HTTP method";
6006
6391
  abortHandshakeOrEmitwsClientError(this, req, socket, 405, message);
@@ -6016,7 +6401,7 @@ var require_websocket_server = __commonJS({
6016
6401
  abortHandshakeOrEmitwsClientError(this, req, socket, 400, message);
6017
6402
  return;
6018
6403
  }
6019
- if (version2 !== 13 && version2 !== 8) {
6404
+ if (version3 !== 13 && version3 !== 8) {
6020
6405
  const message = "Missing or invalid Sec-WebSocket-Version header";
6021
6406
  abortHandshakeOrEmitwsClientError(this, req, socket, 400, message, {
6022
6407
  "Sec-WebSocket-Version": "13, 8"
@@ -6060,7 +6445,7 @@ var require_websocket_server = __commonJS({
6060
6445
  }
6061
6446
  if (this.options.verifyClient) {
6062
6447
  const info = {
6063
- origin: req.headers[`${version2 === 8 ? "sec-websocket-origin" : "origin"}`],
6448
+ origin: req.headers[`${version3 === 8 ? "sec-websocket-origin" : "origin"}`],
6064
6449
  secure: !!(req.socket.authorized || req.socket.encrypted),
6065
6450
  req
6066
6451
  };
@@ -13286,26 +13671,26 @@ var require_pkcs1 = __commonJS({
13286
13671
  var seedMask = rsa_mgf1(maskedDB, md.digestLength, mgf1Md);
13287
13672
  var seed = forge.util.xorBytes(maskedSeed, seedMask, maskedSeed.length);
13288
13673
  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);
13674
+ var db = forge.util.xorBytes(maskedDB, dbMask, maskedDB.length);
13675
+ var lHashPrime = db.substring(0, md.digestLength);
13291
13676
  var error = y !== "\0";
13292
13677
  for (var i = 0; i < md.digestLength; ++i) {
13293
13678
  error |= lHash.charAt(i) !== lHashPrime.charAt(i);
13294
13679
  }
13295
13680
  var in_ps = 1;
13296
13681
  var index2 = md.digestLength;
13297
- for (var j = md.digestLength; j < db2.length; j++) {
13298
- var code = db2.charCodeAt(j);
13682
+ for (var j = md.digestLength; j < db.length; j++) {
13683
+ var code = db.charCodeAt(j);
13299
13684
  var is_0 = code & 1 ^ 1;
13300
13685
  var error_mask = in_ps ? 65534 : 0;
13301
13686
  error |= code & error_mask;
13302
13687
  in_ps = in_ps & is_0;
13303
13688
  index2 += in_ps;
13304
13689
  }
13305
- if (error || db2.charCodeAt(index2) !== 1) {
13690
+ if (error || db.charCodeAt(index2) !== 1) {
13306
13691
  throw new Error("Invalid RSAES-OAEP padding.");
13307
13692
  }
13308
- return db2.substring(index2 + 1);
13693
+ return db.substring(index2 + 1);
13309
13694
  };
13310
13695
  function rsa_mgf1(seed, maskLength, hash) {
13311
13696
  if (!hash) {
@@ -15889,12 +16274,12 @@ var require_pss = __commonJS({
15889
16274
  ps.fillWithByte(0, emLen - sLen - hLen - 2);
15890
16275
  ps.putByte(1);
15891
16276
  ps.putBytes(salt);
15892
- var db2 = ps.getBytes();
16277
+ var db = ps.getBytes();
15893
16278
  var maskLen = emLen - hLen - 1;
15894
16279
  var dbMask = mgf.generate(h, maskLen);
15895
16280
  var maskedDB = "";
15896
16281
  for (i = 0; i < maskLen; i++) {
15897
- maskedDB += String.fromCharCode(db2.charCodeAt(i) ^ dbMask.charCodeAt(i));
16282
+ maskedDB += String.fromCharCode(db.charCodeAt(i) ^ dbMask.charCodeAt(i));
15898
16283
  }
15899
16284
  var mask = 65280 >> 8 * emLen - emBits & 255;
15900
16285
  maskedDB = String.fromCharCode(maskedDB.charCodeAt(0) & ~mask) + maskedDB.substr(1);
@@ -15919,21 +16304,21 @@ var require_pss = __commonJS({
15919
16304
  throw new Error("Bits beyond keysize not zero as expected.");
15920
16305
  }
15921
16306
  var dbMask = mgf.generate(h, maskLen);
15922
- var db2 = "";
16307
+ var db = "";
15923
16308
  for (i = 0; i < maskLen; i++) {
15924
- db2 += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));
16309
+ db += String.fromCharCode(maskedDB.charCodeAt(i) ^ dbMask.charCodeAt(i));
15925
16310
  }
15926
- db2 = String.fromCharCode(db2.charCodeAt(0) & ~mask) + db2.substr(1);
16311
+ db = String.fromCharCode(db.charCodeAt(0) & ~mask) + db.substr(1);
15927
16312
  var checkLen = emLen - hLen - sLen - 2;
15928
16313
  for (i = 0; i < checkLen; i++) {
15929
- if (db2.charCodeAt(i) !== 0) {
16314
+ if (db.charCodeAt(i) !== 0) {
15930
16315
  throw new Error("Leftmost octets not zero as expected");
15931
16316
  }
15932
16317
  }
15933
- if (db2.charCodeAt(checkLen) !== 1) {
16318
+ if (db.charCodeAt(checkLen) !== 1) {
15934
16319
  throw new Error("Inconsistent PSS signature, 0x01 marker not found");
15935
16320
  }
15936
- var salt = db2.substr(-sLen);
16321
+ var salt = db.substr(-sLen);
15937
16322
  var m_ = new forge.util.ByteBuffer();
15938
16323
  m_.fillWithByte(0, 8);
15939
16324
  m_.putBytes(mHash);
@@ -19424,14 +19809,14 @@ var require_tls = __commonJS({
19424
19809
  c.version = c.session.version = session.version;
19425
19810
  c.session.sp = session.sp;
19426
19811
  } else {
19427
- var version2;
19812
+ var version3;
19428
19813
  for (var i = 1; i < tls.SupportedVersions.length; ++i) {
19429
- version2 = tls.SupportedVersions[i];
19430
- if (version2.minor <= msg.version.minor) {
19814
+ version3 = tls.SupportedVersions[i];
19815
+ if (version3.minor <= msg.version.minor) {
19431
19816
  break;
19432
19817
  }
19433
19818
  }
19434
- c.version = { major: version2.major, minor: version2.minor };
19819
+ c.version = { major: version3.major, minor: version3.minor };
19435
19820
  c.session.version = c.version;
19436
19821
  }
19437
19822
  if (session !== null) {
@@ -19602,8 +19987,8 @@ var require_tls = __commonJS({
19602
19987
  try {
19603
19988
  var sp = c.session.sp;
19604
19989
  sp.pre_master_secret = privateKey.decrypt(msg.enc_pre_master_secret);
19605
- var version2 = c.session.clientHelloVersion;
19606
- if (version2.major !== sp.pre_master_secret.charCodeAt(0) || version2.minor !== sp.pre_master_secret.charCodeAt(1)) {
19990
+ var version3 = c.session.clientHelloVersion;
19991
+ if (version3.major !== sp.pre_master_secret.charCodeAt(0) || version3.minor !== sp.pre_master_secret.charCodeAt(1)) {
19607
19992
  throw new Error("TLS version rollback attack detected.");
19608
19993
  }
19609
19994
  } catch (ex) {
@@ -24287,14 +24672,14 @@ var require_find_made = __commonJS({
24287
24672
  "../node_modules/mkdirp/lib/find-made.js"(exports2, module2) {
24288
24673
  "use strict";
24289
24674
  init_cjs_shims();
24290
- var { dirname: dirname2 } = require("path");
24675
+ var { dirname: dirname3 } = require("path");
24291
24676
  var findMade = (opts, parent2, path2 = void 0) => {
24292
24677
  if (path2 === parent2)
24293
24678
  return Promise.resolve();
24294
24679
  return opts.statAsync(parent2).then(
24295
24680
  (st) => st.isDirectory() ? path2 : void 0,
24296
24681
  // will fail later
24297
- (er) => er.code === "ENOENT" ? findMade(opts, dirname2(parent2), parent2) : void 0
24682
+ (er) => er.code === "ENOENT" ? findMade(opts, dirname3(parent2), parent2) : void 0
24298
24683
  );
24299
24684
  };
24300
24685
  var findMadeSync = (opts, parent2, path2 = void 0) => {
@@ -24303,7 +24688,7 @@ var require_find_made = __commonJS({
24303
24688
  try {
24304
24689
  return opts.statSync(parent2).isDirectory() ? path2 : void 0;
24305
24690
  } catch (er) {
24306
- return er.code === "ENOENT" ? findMadeSync(opts, dirname2(parent2), parent2) : void 0;
24691
+ return er.code === "ENOENT" ? findMadeSync(opts, dirname3(parent2), parent2) : void 0;
24307
24692
  }
24308
24693
  };
24309
24694
  module2.exports = { findMade, findMadeSync };
@@ -24315,10 +24700,10 @@ var require_mkdirp_manual = __commonJS({
24315
24700
  "../node_modules/mkdirp/lib/mkdirp-manual.js"(exports2, module2) {
24316
24701
  "use strict";
24317
24702
  init_cjs_shims();
24318
- var { dirname: dirname2 } = require("path");
24703
+ var { dirname: dirname3 } = require("path");
24319
24704
  var mkdirpManual = (path2, opts, made) => {
24320
24705
  opts.recursive = false;
24321
- const parent2 = dirname2(path2);
24706
+ const parent2 = dirname3(path2);
24322
24707
  if (parent2 === path2) {
24323
24708
  return opts.mkdirAsync(path2, opts).catch((er) => {
24324
24709
  if (er.code !== "EISDIR")
@@ -24341,7 +24726,7 @@ var require_mkdirp_manual = __commonJS({
24341
24726
  });
24342
24727
  };
24343
24728
  var mkdirpManualSync = (path2, opts, made) => {
24344
- const parent2 = dirname2(path2);
24729
+ const parent2 = dirname3(path2);
24345
24730
  opts.recursive = false;
24346
24731
  if (parent2 === path2) {
24347
24732
  try {
@@ -24378,12 +24763,12 @@ var require_mkdirp_native = __commonJS({
24378
24763
  "../node_modules/mkdirp/lib/mkdirp-native.js"(exports2, module2) {
24379
24764
  "use strict";
24380
24765
  init_cjs_shims();
24381
- var { dirname: dirname2 } = require("path");
24766
+ var { dirname: dirname3 } = require("path");
24382
24767
  var { findMade, findMadeSync } = require_find_made();
24383
24768
  var { mkdirpManual, mkdirpManualSync } = require_mkdirp_manual();
24384
24769
  var mkdirpNative = (path2, opts) => {
24385
24770
  opts.recursive = true;
24386
- const parent2 = dirname2(path2);
24771
+ const parent2 = dirname3(path2);
24387
24772
  if (parent2 === path2)
24388
24773
  return opts.mkdirAsync(path2, opts);
24389
24774
  return findMade(opts, path2).then((made) => opts.mkdirAsync(path2, opts).then(() => made).catch((er) => {
@@ -24395,7 +24780,7 @@ var require_mkdirp_native = __commonJS({
24395
24780
  };
24396
24781
  var mkdirpNativeSync = (path2, opts) => {
24397
24782
  opts.recursive = true;
24398
- const parent2 = dirname2(path2);
24783
+ const parent2 = dirname3(path2);
24399
24784
  if (parent2 === path2)
24400
24785
  return opts.mkdirSync(path2, opts);
24401
24786
  const made = findMadeSync(opts, path2);
@@ -24419,8 +24804,8 @@ var require_use_native = __commonJS({
24419
24804
  "use strict";
24420
24805
  init_cjs_shims();
24421
24806
  var fs2 = require("fs");
24422
- var version2 = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version;
24423
- var versArr = version2.replace(/^v/, "").split(".");
24807
+ var version3 = process.env.__TESTING_MKDIRP_NODE_VERSION__ || process.version;
24808
+ var versArr = version3.replace(/^v/, "").split(".");
24424
24809
  var hasNative = +versArr[0] > 10 || +versArr[0] === 10 && +versArr[1] >= 12;
24425
24810
  var useNative = !hasNative ? () => false : (opts) => opts.mkdir === fs2.mkdir;
24426
24811
  var useNativeSync = !hasNative ? () => false : (opts) => opts.mkdirSync === fs2.mkdirSync;
@@ -25022,7 +25407,7 @@ function stringToBytes(str) {
25022
25407
  }
25023
25408
  return bytes;
25024
25409
  }
25025
- function v35(name, version2, hashfunc) {
25410
+ function v35(name, version3, hashfunc) {
25026
25411
  function generateUUID(value, namespace, buf, offset) {
25027
25412
  var _namespace;
25028
25413
  if (typeof value === "string") {
@@ -25038,7 +25423,7 @@ function v35(name, version2, hashfunc) {
25038
25423
  bytes.set(namespace);
25039
25424
  bytes.set(value, namespace.length);
25040
25425
  bytes = hashfunc(bytes);
25041
- bytes[6] = bytes[6] & 15 | version2;
25426
+ bytes[6] = bytes[6] & 15 | version3;
25042
25427
  bytes[8] = bytes[8] & 63 | 128;
25043
25428
  if (buf) {
25044
25429
  offset = offset || 0;
@@ -25187,19 +25572,19 @@ var init_nil = __esm({
25187
25572
  });
25188
25573
 
25189
25574
  // ../node_modules/uuid/dist/esm-node/version.js
25190
- function version(uuid) {
25575
+ function version2(uuid) {
25191
25576
  if (!validate_default(uuid)) {
25192
25577
  throw TypeError("Invalid UUID");
25193
25578
  }
25194
25579
  return parseInt(uuid.slice(14, 15), 16);
25195
25580
  }
25196
25581
  var version_default;
25197
- var init_version = __esm({
25582
+ var init_version2 = __esm({
25198
25583
  "../node_modules/uuid/dist/esm-node/version.js"() {
25199
25584
  "use strict";
25200
25585
  init_cjs_shims();
25201
25586
  init_validate();
25202
- version_default = version;
25587
+ version_default = version2;
25203
25588
  }
25204
25589
  });
25205
25590
 
@@ -25225,7 +25610,7 @@ var init_esm_node = __esm({
25225
25610
  init_v4();
25226
25611
  init_v5();
25227
25612
  init_nil();
25228
- init_version();
25613
+ init_version2();
25229
25614
  init_validate();
25230
25615
  init_stringify();
25231
25616
  init_parse();
@@ -27044,11 +27429,11 @@ var init_trigger = __esm({
27044
27429
  });
27045
27430
 
27046
27431
  // src/v3/proxy/storage.ts
27047
- function initProxySchema(db2) {
27048
- db2.exec(PROXY_SCHEMA_SQL);
27432
+ function initProxySchema(db) {
27433
+ db.exec(PROXY_SCHEMA_SQL);
27049
27434
  }
27050
- function insertProxyEvent(db2, event) {
27051
- const stmt = db2.prepare(`
27435
+ function insertProxyEvent(db, event) {
27436
+ const stmt = db.prepare(`
27052
27437
  INSERT INTO v3_proxy_events
27053
27438
  (session_id, event_type, tool_name, tool_call_id, arguments_raw,
27054
27439
  target_command, target_path, model, agent_type, system_prompt, user_prompt,
@@ -27313,44 +27698,44 @@ load();setInterval(load,5000);
27313
27698
  });
27314
27699
  }
27315
27700
  _serveStats(res) {
27316
- const db2 = this._options.db;
27317
- if (!db2) {
27701
+ const db = this._options.db;
27702
+ if (!db) {
27318
27703
  this._json(res, { error: "no database" });
27319
27704
  return;
27320
27705
  }
27321
27706
  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;
27707
+ const totalEvents = db.prepare("SELECT COUNT(*) FROM v3_proxy_events").get()["COUNT(*)"] || 0;
27708
+ const totalSessions = db.prepare("SELECT COUNT(DISTINCT session_id) FROM v3_proxy_events").get()["COUNT(DISTINCT session_id)"] || 0;
27709
+ const totalTriggers = db.prepare("SELECT COUNT(*) FROM v2_trigger_matches").get()["COUNT(*)"] || 0;
27710
+ const uniqueTools = db.prepare("SELECT COUNT(DISTINCT tool_name) FROM v3_proxy_events").get()["COUNT(DISTINCT tool_name)"] || 0;
27326
27711
  this._json(res, { total_events: totalEvents, total_sessions: totalSessions, total_triggers: totalTriggers, unique_tools: uniqueTools });
27327
27712
  } catch {
27328
27713
  this._json(res, { error: "query failed" });
27329
27714
  }
27330
27715
  }
27331
27716
  _serveEvents(req, res) {
27332
- const db2 = this._options.db;
27333
- if (!db2) {
27717
+ const db = this._options.db;
27718
+ if (!db) {
27334
27719
  this._json(res, { events: [] });
27335
27720
  return;
27336
27721
  }
27337
27722
  try {
27338
27723
  const url = new import_node_url.URL(req.url || "/", `http://${req.headers.host}`);
27339
27724
  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);
27725
+ 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
27726
  this._json(res, { events: rows });
27342
27727
  } catch {
27343
27728
  this._json(res, { events: [] });
27344
27729
  }
27345
27730
  }
27346
27731
  _serveSessions(res) {
27347
- const db2 = this._options.db;
27348
- if (!db2) {
27732
+ const db = this._options.db;
27733
+ if (!db) {
27349
27734
  this._json(res, { sessions: [] });
27350
27735
  return;
27351
27736
  }
27352
27737
  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();
27738
+ 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
27739
  this._json(res, { sessions: rows });
27355
27740
  } catch {
27356
27741
  this._json(res, { sessions: [] });
@@ -28500,6 +28885,50 @@ load();setInterval(load,5000);
28500
28885
  });
28501
28886
 
28502
28887
  // src/v3/pty/wrapper.ts
28888
+ async function scanProcesses() {
28889
+ const isWin = process.platform === "win32";
28890
+ const cmd = isWin ? "wmic" : "ps";
28891
+ const args = isWin ? ["process", "get", "ProcessId,ParentProcessId,Name,CommandLine", "/format:csv"] : ["-eo", "pid,ppid,comm,args"];
28892
+ try {
28893
+ const { execFile } = await import("child_process");
28894
+ return new Promise((resolve) => {
28895
+ execFile(cmd, args, { timeout: 5e3 }, (err, stdout) => {
28896
+ if (err || !stdout) {
28897
+ resolve([]);
28898
+ return;
28899
+ }
28900
+ const procs = [];
28901
+ const lines = stdout.trim().split("\n");
28902
+ for (const line of lines) {
28903
+ if (isWin) {
28904
+ const parts = line.split(",").map((p) => p.trim().replace(/"/g, ""));
28905
+ if (parts.length >= 4 && parts[1] && parts[2] && parts[3]) {
28906
+ const ppid = parseInt(parts[2], 10);
28907
+ const pid = parseInt(parts[3], 10);
28908
+ if (pid > 0 && ppid >= 0) {
28909
+ procs.push({ pid, ppid, name: parts[1], cmd: parts[4] || parts[1] });
28910
+ }
28911
+ }
28912
+ } else {
28913
+ const trimmed = line.trim();
28914
+ if (!trimmed) continue;
28915
+ const parts = trimmed.split(/\s+/);
28916
+ if (parts.length >= 4) {
28917
+ const pid = parseInt(parts[0], 10);
28918
+ const ppid = parseInt(parts[1], 10);
28919
+ if (pid > 0 && ppid >= 0) {
28920
+ procs.push({ pid, ppid, name: parts[2], cmd: parts.slice(3).join(" ") });
28921
+ }
28922
+ }
28923
+ }
28924
+ }
28925
+ resolve(procs);
28926
+ });
28927
+ });
28928
+ } catch {
28929
+ return [];
28930
+ }
28931
+ }
28503
28932
  var pty, import_events, PTYWrapper;
28504
28933
  var init_wrapper = __esm({
28505
28934
  "src/v3/pty/wrapper.ts"() {
@@ -28513,6 +28942,7 @@ var init_wrapper = __esm({
28513
28942
  isRunning = false;
28514
28943
  trackedPids = /* @__PURE__ */ new Set();
28515
28944
  processMonitorInterval = null;
28945
+ lastKnownChildren = /* @__PURE__ */ new Map();
28516
28946
  constructor(options = {}) {
28517
28947
  super();
28518
28948
  this.options = options;
@@ -28561,7 +28991,40 @@ var init_wrapper = __esm({
28561
28991
  if (!this.isRunning || !this.ptyProcess) {
28562
28992
  return;
28563
28993
  }
28564
- }, 100);
28994
+ try {
28995
+ const allProcs = await scanProcesses();
28996
+ const mainPid = this.ptyProcess.pid;
28997
+ const newChildren = [];
28998
+ for (const proc of allProcs) {
28999
+ if (this.trackedPids.has(proc.ppid) && !this.trackedPids.has(proc.pid) && !this.lastKnownChildren.has(proc.pid)) {
29000
+ newChildren.push(proc);
29001
+ this.trackedPids.add(proc.pid);
29002
+ this.lastKnownChildren.set(proc.pid, proc);
29003
+ }
29004
+ }
29005
+ for (const child of newChildren) {
29006
+ const procInfo = {
29007
+ pid: child.pid,
29008
+ command: child.name,
29009
+ args: child.cmd.split(" ").slice(1),
29010
+ timestamp: Date.now()
29011
+ };
29012
+ this.emit("process_create", procInfo);
29013
+ if (this.options.onProcessCreate) {
29014
+ this.options.onProcessCreate(procInfo.pid, procInfo.command, procInfo.args);
29015
+ }
29016
+ console.log(`[PTY] New subprocess: PID=${child.pid} cmd=${child.cmd}`);
29017
+ }
29018
+ for (const [pid] of this.lastKnownChildren) {
29019
+ if (!allProcs.some((p) => p.pid === pid)) {
29020
+ this.lastKnownChildren.delete(pid);
29021
+ this.trackedPids.delete(pid);
29022
+ }
29023
+ }
29024
+ } catch (err) {
29025
+ console.debug(`[PTY] Process scan failed:`, err);
29026
+ }
29027
+ }, 500);
28565
29028
  }
28566
29029
  stopProcessMonitor() {
28567
29030
  if (this.processMonitorInterval) {
@@ -28584,6 +29047,15 @@ var init_wrapper = __esm({
28584
29047
  this.ptyProcess.kill(signal);
28585
29048
  }
28586
29049
  }
29050
+ /** Kill process and all tracked children. */
29051
+ killTree(signal = "SIGTERM") {
29052
+ for (const pid of this.trackedPids) {
29053
+ try {
29054
+ process.kill(pid, signal);
29055
+ } catch {
29056
+ }
29057
+ }
29058
+ }
28587
29059
  get pid() {
28588
29060
  return this.ptyProcess?.pid;
28589
29061
  }
@@ -28614,8 +29086,9 @@ var init_output_parser = __esm({
28614
29086
  agentType: "claude-code"
28615
29087
  },
28616
29088
  // OpenCode: [TOOL_CALL] name {...}
29089
+ // Supports nested JSON via balanced-brace pattern
28617
29090
  {
28618
- pattern: /\[TOOL_CALL\]\s+(\w+)\s+(\{.*?\})/gs,
29091
+ pattern: /\[TOOL_CALL\]\s+(\w+)\s+(\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\})/gs,
28619
29092
  agentType: "opencode"
28620
29093
  },
28621
29094
  // OpenInterpreter: $ command
@@ -28624,8 +29097,9 @@ var init_output_parser = __esm({
28624
29097
  agentType: "openinterpreter"
28625
29098
  },
28626
29099
  // AutoGPT: [NEXT_ACTION] {"name": "...", "parameters": {...}}
29100
+ // Supports nested JSON via balanced-brace pattern
28627
29101
  {
28628
- pattern: /\[NEXT_ACTION\]\s+(\{.*?\})/gs,
29102
+ pattern: /\[NEXT_ACTION\]\s+(\{[^{}]*(?:\{[^{}]*(?:\{[^{}]*\}[^{}]*)*\}[^{}]*)*\})/gs,
28629
29103
  agentType: "autogpt"
28630
29104
  },
28631
29105
  // Generic Bash execution (Chinese)
@@ -28920,11 +29394,12 @@ var init_launcher = __esm({
28920
29394
  init_cjs_shims();
28921
29395
  var import_node_fs4 = require("fs");
28922
29396
  var import_yaml3 = require("yaml");
29397
+ init_version();
28923
29398
  async function main() {
28924
29399
  const args = process.argv.slice(2);
28925
29400
  const command = args[0];
28926
29401
  if (!command || command === "--help" || command === "-h") {
28927
- console.log(`AgentGate - AI Agent Data Collection & Security Analysis Gateway (TS v0.3.0)
29402
+ console.log(`AgentGate - AI Agent Data Collection & Security Analysis Gateway (TS v${version})
28928
29403
 
28929
29404
  Commands:
28930
29405
  start Start AgentGate with specified layers (unified)
@@ -28951,6 +29426,7 @@ Server options:
28951
29426
  --host <host> Listen host (default: 127.0.0.1)
28952
29427
  --port <port> Listen port (default: 9100)
28953
29428
  --db-path <path> SQLite database path override
29429
+ (or set AGENT_GATE_STORAGE=json + AGENT_GATE_DATA_DIR=<dir> for JSON storage)
28954
29430
  --moss-url <url> AgentMoss service URL (default: http://127.0.0.1:9090)
28955
29431
 
28956
29432
  Proxy options:
@@ -28994,10 +29470,9 @@ Run options:
28994
29470
  else if (args[i] === "--moss-url" && args[i + 1]) mossUrl2 = args[++i];
28995
29471
  }
28996
29472
  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
- }
29473
+ const dataDir = process.env.AGENT_GATE_DATA_DIR;
29474
+ const { createStorage: createStorage2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29475
+ createStorage2({ dbPath, dataDir });
29001
29476
  if (mossUrl2) {
29002
29477
  const { setMossUrl: setMossUrl2 } = await Promise.resolve().then(() => (init_moss_client(), moss_client_exports));
29003
29478
  setMossUrl2(mossUrl2);
@@ -29032,10 +29507,10 @@ Run options:
29032
29507
  if (envLevel && !args.includes("--level")) level = parseInt(envLevel, 10);
29033
29508
  const envDeny = process.env.AGENT_GATE_DENY_ACTION;
29034
29509
  if (envDeny && !args.includes("--deny-action")) denyAction = envDeny;
29035
- let db2;
29510
+ let db;
29036
29511
  if (dbPath) {
29037
29512
  const { getDb: getDb2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29038
- db2 = getDb2(dbPath);
29513
+ db = getDb2(dbPath);
29039
29514
  }
29040
29515
  const { ProxyServer: ProxyServer2 } = await Promise.resolve().then(() => (init_server2(), server_exports2));
29041
29516
  const { PhaseCoordinator: PhaseCoordinator2 } = await Promise.resolve().then(() => (init_coordinator(), coordinator_exports));
@@ -29057,7 +29532,7 @@ Run options:
29057
29532
  triggerEngine,
29058
29533
  whitelistEngine,
29059
29534
  privacyFilter,
29060
- db: db2,
29535
+ db,
29061
29536
  onBlock: (sid, matches) => {
29062
29537
  if (denyAction === "block") {
29063
29538
  console.warn(`[AgentGate] AgentMoss DENY (blocking): session=${sid.slice(0, 8)} rule=${matches[0]?.rule.name ?? "unknown"}`);
@@ -29075,7 +29550,7 @@ Run options:
29075
29550
  port,
29076
29551
  interceptHosts: interceptHosts.split(",").map((h) => h.trim()),
29077
29552
  rulesPath,
29078
- db: db2,
29553
+ db,
29079
29554
  coordinator
29080
29555
  });
29081
29556
  await server.start();
@@ -29127,10 +29602,10 @@ Run options:
29127
29602
  process.exit(1);
29128
29603
  }
29129
29604
  console.log(`[Gateway] Loaded ${modelRoutes.length} routes from ${configPath}`);
29130
- let db2;
29605
+ let db;
29131
29606
  if (dbPath) {
29132
29607
  const { getDb: getDb2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29133
- db2 = getDb2(dbPath);
29608
+ db = getDb2(dbPath);
29134
29609
  }
29135
29610
  const { GatewayServer: GatewayServer2 } = await Promise.resolve().then(() => (init_server3(), server_exports3));
29136
29611
  const { PhaseCoordinator: PhaseCoordinator2 } = await Promise.resolve().then(() => (init_coordinator(), coordinator_exports));
@@ -29152,7 +29627,7 @@ Run options:
29152
29627
  triggerEngine,
29153
29628
  whitelistEngine,
29154
29629
  privacyFilter,
29155
- db: db2,
29630
+ db,
29156
29631
  onBlock: (sid, matches) => {
29157
29632
  if (denyAction === "block") {
29158
29633
  console.warn(`[AgentGate] AgentMoss DENY (blocking): session=${sid.slice(0, 8)} rule=${matches[0]?.rule.name ?? "unknown"}`);
@@ -29174,7 +29649,7 @@ Run options:
29174
29649
  api_base: r.api_base,
29175
29650
  api_key: r.api_key
29176
29651
  })),
29177
- db: db2,
29652
+ db,
29178
29653
  rulesPath,
29179
29654
  coordinator
29180
29655
  });
@@ -29198,8 +29673,8 @@ Run options:
29198
29673
  if (args[i] === "--retention-days" && args[i + 1]) retentionDays = parseInt(args[++i], 10);
29199
29674
  }
29200
29675
  const { getDb: getDb2, closeDb: closeDb2 } = await Promise.resolve().then(() => (init_db(), db_exports));
29201
- const db2 = getDb2();
29202
- const result = db2.prepare(
29676
+ const db = getDb2();
29677
+ const result = db.prepare(
29203
29678
  `DELETE FROM tool_calls WHERE called_at < datetime('now', '-${retentionDays} days')`
29204
29679
  ).run();
29205
29680
  console.log(`Cleaned ${result.changes} old records (retention: ${retentionDays} days)`);