-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathquery.ts
More file actions
82 lines (66 loc) · 2.17 KB
/
query.ts
File metadata and controls
82 lines (66 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import path from "node:path";
import os from "node:os";
import type { Crumb } from "../../types.js";
import { CrumbStore } from "../../collector/store.js";
import { formatCrumbPretty, formatCrumbJson } from "../format.js";
import { getFlag, hasFlag } from "../args.js";
export async function query(args: string[]): Promise<void> {
const ns = getFlag(args, "--ns");
const tag = getFlag(args, "--tag");
const since = getFlag(args, "--since");
const session = getFlag(args, "--session");
const match = getFlag(args, "--match");
const json = hasFlag(args, "--json");
const limit = parseInt(getFlag(args, "--limit") ?? "100", 10);
const store = new CrumbStore(path.join(os.homedir(), ".agentcrumbs"));
const allCrumbs = store.readAll();
let filtered = allCrumbs;
if (since) {
const cutoff = parseSince(since);
filtered = filtered.filter((c) => new Date(c.ts).getTime() >= cutoff);
}
if (ns) {
const pattern = new RegExp(`^${ns.replace(/\*/g, ".*")}$`);
filtered = filtered.filter((c) => pattern.test(c.ns));
}
if (tag) {
filtered = filtered.filter((c) => c.tags?.includes(tag));
}
if (session) {
filtered = filtered.filter((c) => c.sid === session);
}
if (match) {
filtered = filtered.filter((c) => JSON.stringify(c).includes(match));
}
const results = filtered.slice(-limit);
if (results.length === 0) {
process.stderr.write("No crumbs found matching filters.\n");
return;
}
for (const crumb of results) {
if (json) {
process.stdout.write(formatCrumbJson(crumb) + "\n");
} else {
process.stdout.write(formatCrumbPretty(crumb) + "\n");
}
}
process.stderr.write(`\n${results.length} crumbs found.\n`);
}
function parseSince(since: string): number {
const match = since.match(/^(\d+)(s|m|h|d)$/);
if (!match) {
process.stderr.write(
`Invalid --since format: "${since}". Use Ns, Nm, Nh, or Nd.\n`
);
process.exit(1);
}
const value = parseInt(match[1]!, 10);
const unit = match[2]!;
const multipliers: Record<string, number> = {
s: 1000,
m: 60 * 1000,
h: 60 * 60 * 1000,
d: 24 * 60 * 60 * 1000,
};
return Date.now() - value * multipliers[unit]!;
}