@agentknight/sdk 0.9.55 → 0.9.57
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/LICENSE +201 -201
- package/dist/chunks/{acp-adapter-HUNUQGUF.js → acp-adapter-WYDK3PLS.js} +4 -3
- package/dist/chunks/chunk-3LEPYV7Y.js +72 -0
- package/dist/chunks/{chunk-L3A736SO.js → chunk-7ZYBES47.js} +2 -66
- package/dist/chunks/{chunk-NTFNQYQ3.js → chunk-DAKDVZ7X.js} +2 -2
- package/dist/chunks/{chunk-HFVA7ZOD.js → chunk-EDZPP6SJ.js} +2 -2
- package/dist/chunks/{chunk-5J7BK2Y7.js → chunk-IPJWNGNK.js} +1 -1
- package/dist/chunks/{chunk-K5CMKBW6.js → chunk-KBI5IWPR.js} +183 -51
- package/dist/chunks/chunk-LT5ULDVT.js +1217 -0
- package/dist/chunks/{chunk-6ZPE7VIE.js → chunk-OOCAIULD.js} +28 -1223
- package/dist/chunks/{chunk-Z5STULMQ.js → chunk-USI66MEF.js} +1 -1
- package/dist/chunks/{chunk-E7QL4CBT.js → chunk-WPVH7HKC.js} +1 -1
- package/dist/chunks/chunk-ZLKFFKAX.js +571 -0
- package/dist/chunks/{claude-adapter-G6YTPXRP.js → claude-adapter-GCH36EZ6.js} +4 -3
- package/dist/chunks/{codex-adapter-ELYJE2A2.js → codex-adapter-CXD4SVCE.js} +4 -3
- package/dist/chunks/{copilot-adapter-TU2GDFYP.js → copilot-adapter-SYFGOAGE.js} +471 -636
- package/dist/chunks/{managed-agent-adapter-KEXZFLGA.js → managed-agent-adapter-ODCNYYO6.js} +14 -6
- package/dist/chunks/{pi-adapter-5BFIJTPD.js → pi-adapter-XLY46UDL.js} +4 -3
- package/dist/configuration.js +4 -3
- package/dist/index.d.ts +51 -0
- package/dist/index.js +62 -34
- package/dist/runtime.js +2 -2
- package/dist/session-analytics-worker.js +474 -0
- package/package.json +1 -1
|
@@ -0,0 +1,474 @@
|
|
|
1
|
+
import {
|
|
2
|
+
AnalyticsCommandSchema,
|
|
3
|
+
AnalyticsEventSchema,
|
|
4
|
+
openSessionEventLog
|
|
5
|
+
} from "./chunks/chunk-ZLKFFKAX.js";
|
|
6
|
+
import "./chunks/chunk-LT5ULDVT.js";
|
|
7
|
+
import "./chunks/chunk-IPJWNGNK.js";
|
|
8
|
+
import {
|
|
9
|
+
SessionOperationError
|
|
10
|
+
} from "./chunks/chunk-7ZYBES47.js";
|
|
11
|
+
import {
|
|
12
|
+
SessionAnalyticsResultSchema,
|
|
13
|
+
SessionSkillInfoSchema
|
|
14
|
+
} from "./chunks/chunk-KBI5IWPR.js";
|
|
15
|
+
|
|
16
|
+
// src/session-analytics-worker.ts
|
|
17
|
+
import { parentPort, workerData, isMainThread as isMainThread2 } from "node:worker_threads";
|
|
18
|
+
import { z as z2 } from "zod";
|
|
19
|
+
|
|
20
|
+
// src/session-analytics-store.ts
|
|
21
|
+
import { createHash } from "node:crypto";
|
|
22
|
+
import { chmod, lstat, mkdir, open, realpath } from "node:fs/promises";
|
|
23
|
+
import { join } from "node:path";
|
|
24
|
+
import { DatabaseSync } from "node:sqlite";
|
|
25
|
+
import { isMainThread } from "node:worker_threads";
|
|
26
|
+
import { z } from "zod";
|
|
27
|
+
|
|
28
|
+
// src/session-keywords.ts
|
|
29
|
+
var segmenter = new Intl.Segmenter(["zh", "en"], { granularity: "word" });
|
|
30
|
+
var particles = new Set("\u7684\u4E86\u548C\u4E0E\u662F\u5728\u6709\u628A\u5C06\u5BF9\u5230\u4E5F\u5C31\u90FD\u5F88\u6700\u518D\u8FD9\u90A3\u7B49\u8FD8\u53CA\u8BA9\u7ED9\u88AB\u5E76\u4ECE\u4E3A\u4F7F\u4E8E\u4F46\u4E48\u5462\u5427\u554A\u5417");
|
|
31
|
+
var stopwords = new Set("a an and are as at be been being but by can could did do does for from had has have how i if in into is it its just like may me more most my no not of on or our please should so some than that the their them then there these they this those to too up us use using very was we were what when where which who why will with would you your yes ok okay also about all any make get let need want help \u4E00\u4E2A \u4E00\u4E0B \u4E00\u4E9B \u4E00\u76F4 \u4E00\u8D77 \u4E00\u822C \u4E00\u5B9A \u4E0A\u9762 \u4E0B\u9762 \u4E0D\u8981 \u4E0D\u662F \u4E0D\u80FD \u4E0D\u7528 \u4E0D\u8FC7 \u4E4B\u524D \u4E4B\u540E \u4EC0\u4E48 \u4EE5\u4E0A \u4EE5\u4E0B \u4ED6\u4EEC \u4EE5\u540E \u4EE5\u53CA \u4F46\u662F \u4F60\u4EEC \u4F60\u7684 \u8FD9\u4E2A \u8FD9\u4E9B \u90A3\u4E2A \u90A3\u4E9B \u53EF\u4EE5 \u53EF\u80FD \u56E0\u4E3A \u6240\u4EE5 \u5982\u4F55 \u5982\u679C \u5DF2\u7ECF \u5E94\u8BE5 \u6211\u4EEC \u6211\u7684 \u6216\u8005 \u65F6\u5019 \u662F\u5426 \u73B0\u5728 \u7136\u540E \u81EA\u5DF1 \u8FD8\u6709 \u8FD9\u91CC \u8FD9\u6837 \u90A3\u6837 \u9700\u8981 \u600E\u4E48 \u4E3A\u4EC0\u4E48 \u8BF7\u95EE \u5E2E\u6211 \u80FD\u591F \u8FDB\u884C \u6CA1\u6709 \u76EE\u524D \u5176\u4E2D \u5BF9\u4E8E \u901A\u8FC7 \u5173\u4E8E \u6839\u636E \u770B\u5230 \u770B\u770B \u4F7F\u7528 \u8BF7\u6C42 \u5904\u7406 \u5F00\u59CB \u7EE7\u7EED \u5B8C\u6210".split(/\s+/u));
|
|
32
|
+
function messageKeywords(content) {
|
|
33
|
+
const truncated = content.length > 8192;
|
|
34
|
+
const excerpt = truncated ? content.slice(0, 8192).replace(/[\p{L}\p{M}\p{N}_]+$/u, "") : content;
|
|
35
|
+
const text = excerpt.replace(/<(system_reminder|system-reminder|environment_context|environment_details|context|instructions|user_message|attachment)(?:\s[^>]*)?>[\s\S]*?(?:<\/\1>|$)/giu, " ").replace(/(```|~~~)[\s\S]*?(?:\1|$)/gu, " ").replace(/`[^`\n]*(?:`|$)/gu, " ").replace(/^\s*>.*$/gmu, " ").replace(/\b[a-z][a-z\d+.-]*:\/\/[^\s<>]+|\bwww\.[^\s<>]+/giu, " ").replace(/\b[^\s@]+@[^\s@]+\.[^\s@]+/gu, " ").replace(/(?:[a-z]:[\\/]|(?:~|\.{1,2})?\/)[^\s<>,。;]+/giu, " ").replace(/\b(?:password|passwd|secret|token|api[_-]?key|authorization)\s*[:=]\s*\S+/giu, " ").replace(/\b[\w.-]+\.(?:kt|java|ts|tsx|js|json|md|yaml|yml|py|log)\b/giu, " ").normalize("NFKC").toLowerCase();
|
|
36
|
+
const terms = /* @__PURE__ */ new Set();
|
|
37
|
+
let unsegmented = "";
|
|
38
|
+
const flush = () => {
|
|
39
|
+
const characters = [...unsegmented];
|
|
40
|
+
for (let index = 1; index < characters.length; index += 1) {
|
|
41
|
+
const term = `${characters[index - 1]}${characters[index]}`;
|
|
42
|
+
if (!stopwords.has(term)) terms.add(term);
|
|
43
|
+
}
|
|
44
|
+
unsegmented = "";
|
|
45
|
+
};
|
|
46
|
+
for (const { segment, isWordLike } of segmenter.segment(text)) {
|
|
47
|
+
if (new RegExp("^\\p{Script=Han}$", "u").test(segment) && !particles.has(segment)) {
|
|
48
|
+
unsegmented += segment;
|
|
49
|
+
} else {
|
|
50
|
+
flush();
|
|
51
|
+
if (isWordLike && new RegExp("^\\p{L}[\\p{L}\\p{M}]{1,23}$", "u").test(segment) && !stopwords.has(segment)) terms.add(segment);
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
flush();
|
|
55
|
+
return { terms, truncated };
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// src/session-analytics-store.ts
|
|
59
|
+
var RETENTION_MS = 30 * 24 * 60 * 60 * 1e3;
|
|
60
|
+
var MAX_RECORDS = 5e4;
|
|
61
|
+
var INDEX_BYTES = 8 * 1024 * 1024;
|
|
62
|
+
var KEYWORD_VERSION = 1;
|
|
63
|
+
var Count = z.number().int().nonnegative().max(Number.MAX_SAFE_INTEGER);
|
|
64
|
+
var Usage = z.object({
|
|
65
|
+
id: z.string().min(1).max(2048),
|
|
66
|
+
timestamp: z.iso.datetime({ offset: true }),
|
|
67
|
+
model: z.string().min(1).max(256),
|
|
68
|
+
inputTokens: Count.optional(),
|
|
69
|
+
outputTokens: Count.optional(),
|
|
70
|
+
cacheReadTokens: Count.optional()
|
|
71
|
+
});
|
|
72
|
+
var SessionRow = z.object({
|
|
73
|
+
started_at: z.number(),
|
|
74
|
+
observed_since: z.number(),
|
|
75
|
+
dropped: z.number(),
|
|
76
|
+
gap_since: z.number().nullable(),
|
|
77
|
+
usage_lost: z.number().nullable(),
|
|
78
|
+
history_lost: z.number().nullable(),
|
|
79
|
+
fingerprint: z.string().nullable(),
|
|
80
|
+
head_hash: z.string().nullable(),
|
|
81
|
+
head_bytes: z.number(),
|
|
82
|
+
offset: z.number(),
|
|
83
|
+
skipping: z.number(),
|
|
84
|
+
indexed_at: z.number().nullable(),
|
|
85
|
+
skills: z.string().nullable(),
|
|
86
|
+
skills_at: z.string().nullable()
|
|
87
|
+
});
|
|
88
|
+
var ReceiptRow = z.object({
|
|
89
|
+
kind: z.enum(["user", "assistant", "usage"]),
|
|
90
|
+
occurred_at: z.number(),
|
|
91
|
+
manual: z.number(),
|
|
92
|
+
model: z.string().nullable(),
|
|
93
|
+
input: z.number().nullable(),
|
|
94
|
+
output: z.number().nullable(),
|
|
95
|
+
cache: z.number().nullable(),
|
|
96
|
+
keywords: z.string().nullable(),
|
|
97
|
+
shortened: z.number()
|
|
98
|
+
});
|
|
99
|
+
var AnalyticsStore = class {
|
|
100
|
+
#directory;
|
|
101
|
+
#database;
|
|
102
|
+
#prunedAt = 0;
|
|
103
|
+
#seen = /* @__PURE__ */ new Set();
|
|
104
|
+
constructor(directory) {
|
|
105
|
+
if (isMainThread) throw new Error("Analytics storage must run in a background worker");
|
|
106
|
+
this.#directory = directory;
|
|
107
|
+
}
|
|
108
|
+
async #db() {
|
|
109
|
+
if (this.#database !== void 0) return this.#database;
|
|
110
|
+
await mkdir(this.#directory, { recursive: true, mode: 448 });
|
|
111
|
+
const root = await lstat(this.#directory);
|
|
112
|
+
if (!root.isDirectory() || root.isSymbolicLink()) throw new Error("Analytics directory must not be a symbolic link");
|
|
113
|
+
const path = join(await realpath(this.#directory), "analytics.sqlite");
|
|
114
|
+
for (const suffix of ["", "-wal", "-shm"]) {
|
|
115
|
+
try {
|
|
116
|
+
const info = await lstat(`${path}${suffix}`);
|
|
117
|
+
if (info.isSymbolicLink() || !info.isFile()) throw new Error("Invalid analytics database file");
|
|
118
|
+
} catch (error) {
|
|
119
|
+
if (!(error instanceof Error) || !("code" in error) || error.code !== "ENOENT") throw error;
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
const file = await open(path, "a", 384);
|
|
123
|
+
await file.close();
|
|
124
|
+
await chmod(path, 384);
|
|
125
|
+
const db = new DatabaseSync(path);
|
|
126
|
+
try {
|
|
127
|
+
db.exec("PRAGMA busy_timeout=5000; PRAGMA journal_mode=WAL; PRAGMA synchronous=FULL; PRAGMA foreign_keys=ON; PRAGMA secure_delete=ON;");
|
|
128
|
+
const version = z.object({ user_version: z.number() }).parse(db.prepare("PRAGMA user_version").get()).user_version;
|
|
129
|
+
if (version > 1) throw new Error("Analytics database requires a newer PC Agent");
|
|
130
|
+
db.exec(`
|
|
131
|
+
BEGIN IMMEDIATE;
|
|
132
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
133
|
+
id TEXT PRIMARY KEY, started_at INTEGER NOT NULL, observed_since INTEGER NOT NULL,
|
|
134
|
+
dropped INTEGER NOT NULL DEFAULT 0, gap_since INTEGER,
|
|
135
|
+
usage_lost INTEGER, history_lost INTEGER, fingerprint TEXT, head_hash TEXT, head_bytes INTEGER NOT NULL DEFAULT 0,
|
|
136
|
+
offset INTEGER NOT NULL DEFAULT 0, skipping INTEGER NOT NULL DEFAULT 0, indexed_at INTEGER,
|
|
137
|
+
skills TEXT, skills_at TEXT
|
|
138
|
+
);
|
|
139
|
+
CREATE TABLE IF NOT EXISTS receipts (
|
|
140
|
+
session TEXT NOT NULL REFERENCES sessions(id) ON DELETE CASCADE,
|
|
141
|
+
kind TEXT NOT NULL, identity TEXT NOT NULL, occurred_at INTEGER NOT NULL, event_id TEXT NOT NULL,
|
|
142
|
+
source TEXT, source_session TEXT, agent_id TEXT, manual INTEGER NOT NULL DEFAULT 0,
|
|
143
|
+
model TEXT, input INTEGER, output INTEGER, cache INTEGER,
|
|
144
|
+
keywords TEXT, shortened INTEGER NOT NULL DEFAULT 0, keyword_version INTEGER,
|
|
145
|
+
PRIMARY KEY(session,kind,identity)
|
|
146
|
+
);
|
|
147
|
+
CREATE INDEX IF NOT EXISTS receipts_time ON receipts(occurred_at);
|
|
148
|
+
CREATE INDEX IF NOT EXISTS receipts_session_time ON receipts(session,occurred_at);
|
|
149
|
+
CREATE UNIQUE INDEX IF NOT EXISTS receipts_message_event ON receipts(session,kind,event_id)
|
|
150
|
+
WHERE kind IN ('user','assistant');
|
|
151
|
+
PRAGMA user_version=1;
|
|
152
|
+
COMMIT;
|
|
153
|
+
`);
|
|
154
|
+
this.#database = db;
|
|
155
|
+
return db;
|
|
156
|
+
} catch (error) {
|
|
157
|
+
db.close();
|
|
158
|
+
throw error;
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
#key(sessionId) {
|
|
162
|
+
return createHash("sha256").update(sessionId).digest("hex");
|
|
163
|
+
}
|
|
164
|
+
#transaction(db, work) {
|
|
165
|
+
db.exec("BEGIN IMMEDIATE");
|
|
166
|
+
try {
|
|
167
|
+
const result = work();
|
|
168
|
+
db.exec("COMMIT");
|
|
169
|
+
return result;
|
|
170
|
+
} catch (error) {
|
|
171
|
+
db.exec("ROLLBACK");
|
|
172
|
+
throw error;
|
|
173
|
+
}
|
|
174
|
+
}
|
|
175
|
+
async #session(sessionId) {
|
|
176
|
+
const db = await this.#db(), key = this.#key(sessionId);
|
|
177
|
+
if (!this.#seen.has(key)) {
|
|
178
|
+
const now = Date.now();
|
|
179
|
+
db.prepare(`INSERT INTO sessions(id,started_at,observed_since) VALUES(?,?,?)
|
|
180
|
+
ON CONFLICT(id) DO UPDATE SET observed_since=excluded.observed_since`).run(key, now, now);
|
|
181
|
+
this.#seen.add(key);
|
|
182
|
+
}
|
|
183
|
+
const row = SessionRow.parse(db.prepare("SELECT * FROM sessions WHERE id=?").get(key));
|
|
184
|
+
return { db, key, row };
|
|
185
|
+
}
|
|
186
|
+
#event(db, key, event) {
|
|
187
|
+
const time = Date.parse(event.timestamp);
|
|
188
|
+
if (time < Date.now() - RETENTION_MS) return;
|
|
189
|
+
if (event.type === "assistant.usage") {
|
|
190
|
+
const accounting = z.object({ sourceSessionId: z.string(), usageId: z.string() }).optional().parse(event.data.accounting);
|
|
191
|
+
const callId = event.data.apiCallId ?? event.id;
|
|
192
|
+
const identity2 = accounting === void 0 ? event.agentId === void 0 ? callId : JSON.stringify([event.agentId, callId]) : JSON.stringify([accounting.sourceSessionId, accounting.usageId]);
|
|
193
|
+
const value = Usage.parse({ ...event.data, id: identity2, timestamp: event.timestamp });
|
|
194
|
+
db.prepare(`INSERT INTO receipts(session,kind,identity,occurred_at,event_id,source_session,agent_id,model,input,output,cache)
|
|
195
|
+
VALUES(?,'usage',?,?,?,?,?,?,?,?,?)
|
|
196
|
+
ON CONFLICT(session,kind,identity) DO UPDATE SET
|
|
197
|
+
input=COALESCE(receipts.input,excluded.input), output=COALESCE(receipts.output,excluded.output),
|
|
198
|
+
cache=COALESCE(receipts.cache,excluded.cache)`).run(
|
|
199
|
+
key,
|
|
200
|
+
value.id,
|
|
201
|
+
time,
|
|
202
|
+
event.id,
|
|
203
|
+
accounting?.sourceSessionId ?? null,
|
|
204
|
+
event.agentId ?? null,
|
|
205
|
+
value.model,
|
|
206
|
+
value.inputTokens ?? null,
|
|
207
|
+
value.outputTokens ?? null,
|
|
208
|
+
value.cacheReadTokens ?? null
|
|
209
|
+
);
|
|
210
|
+
return;
|
|
211
|
+
}
|
|
212
|
+
if (event.agentId !== void 0) return;
|
|
213
|
+
if (event.type === "session.skills_loaded") {
|
|
214
|
+
const skills = z.array(SessionSkillInfoSchema).max(512).parse(event.data.skills);
|
|
215
|
+
const timestamp = new Date(time).toISOString();
|
|
216
|
+
db.prepare("UPDATE sessions SET skills=?,skills_at=? WHERE id=? AND (skills_at IS NULL OR skills_at<=?)").run(JSON.stringify(skills), timestamp, key, timestamp);
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
const user = event.type === "user.message";
|
|
220
|
+
if (user ? event.data.isAutopilotContinuation === true || event.data.source === "tool" : event.type !== "assistant.message" || event.data.parentToolCallId !== void 0 || typeof event.data.content !== "string" || event.data.content.trim().length === 0) return;
|
|
221
|
+
const manual = user && (event.data.source === void 0 || event.data.source === "user" || event.data.source === "mobile");
|
|
222
|
+
const keywords = manual && typeof event.data.content === "string" ? messageKeywords(event.data.content) : void 0;
|
|
223
|
+
const identity = typeof event.data.messageId === "string" ? event.data.messageId : event.id;
|
|
224
|
+
db.prepare(`INSERT OR IGNORE INTO receipts(
|
|
225
|
+
session,kind,identity,occurred_at,event_id,source,manual,keywords,shortened,keyword_version)
|
|
226
|
+
VALUES(?,?,?,?,?,?,?,?,?,?)`).run(
|
|
227
|
+
key,
|
|
228
|
+
user ? "user" : "assistant",
|
|
229
|
+
identity,
|
|
230
|
+
time,
|
|
231
|
+
event.id,
|
|
232
|
+
typeof event.data.source === "string" ? event.data.source : null,
|
|
233
|
+
manual ? 1 : 0,
|
|
234
|
+
keywords === void 0 ? null : JSON.stringify([...keywords.terms].slice(0, 128)),
|
|
235
|
+
keywords !== void 0 && (keywords.truncated || keywords.terms.size > 128) ? 1 : 0,
|
|
236
|
+
keywords === void 0 ? null : KEYWORD_VERSION
|
|
237
|
+
);
|
|
238
|
+
}
|
|
239
|
+
async observe(observations, gaps) {
|
|
240
|
+
const sessions = /* @__PURE__ */ new Map();
|
|
241
|
+
for (const id of /* @__PURE__ */ new Set([...observations.map((item) => item.sessionId), ...gaps.map((item) => item.sessionId)])) {
|
|
242
|
+
sessions.set(id, await this.#session(id));
|
|
243
|
+
}
|
|
244
|
+
const db = await this.#db();
|
|
245
|
+
this.#transaction(db, () => {
|
|
246
|
+
for (const item of observations) {
|
|
247
|
+
const session = sessions.get(item.sessionId);
|
|
248
|
+
if (session === void 0) throw new Error("Missing analytics session");
|
|
249
|
+
this.#event(db, session.key, item.event);
|
|
250
|
+
}
|
|
251
|
+
for (const gap of gaps) {
|
|
252
|
+
const session = sessions.get(gap.sessionId);
|
|
253
|
+
if (session === void 0) throw new Error("Missing analytics session");
|
|
254
|
+
db.prepare("UPDATE sessions SET dropped=dropped+?,gap_since=MIN(COALESCE(gap_since,?),?) WHERE id=?").run(gap.count, gap.since, gap.since, session.key);
|
|
255
|
+
}
|
|
256
|
+
this.#prune(db);
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
#prune(db) {
|
|
260
|
+
if (Date.now() - this.#prunedAt < 6e4) return;
|
|
261
|
+
const cutoff = Date.now() - RETENTION_MS;
|
|
262
|
+
const overflow = z.object({ count: z.number() }).parse(db.prepare("SELECT COUNT(*) AS count FROM receipts").get()).count - MAX_RECORDS;
|
|
263
|
+
const lost = z.array(z.object({ session: z.string(), kind: z.string(), latest: z.number() })).parse(db.prepare(`
|
|
264
|
+
SELECT session,kind,MAX(occurred_at) AS latest FROM receipts
|
|
265
|
+
WHERE occurred_at<? OR rowid IN (SELECT rowid FROM receipts ORDER BY occurred_at LIMIT ?)
|
|
266
|
+
GROUP BY session,kind`).all(cutoff, Math.max(0, overflow)));
|
|
267
|
+
for (const item of lost) {
|
|
268
|
+
const column = item.kind === "usage" ? "usage_lost" : "history_lost";
|
|
269
|
+
db.prepare(`UPDATE sessions SET ${column}=MAX(COALESCE(${column},?),?) WHERE id=?`).run(item.latest, item.latest, item.session);
|
|
270
|
+
}
|
|
271
|
+
db.prepare(`DELETE FROM receipts WHERE occurred_at<? OR rowid IN (
|
|
272
|
+
SELECT rowid FROM receipts ORDER BY occurred_at LIMIT ?)`).run(cutoff, Math.max(0, overflow));
|
|
273
|
+
this.#prunedAt = Date.now();
|
|
274
|
+
}
|
|
275
|
+
async index(sessionId, environment, allowMissingEventLog) {
|
|
276
|
+
const { db, key, row } = await this.#session(sessionId);
|
|
277
|
+
const file = await openSessionEventLog(sessionId, environment, { allowMissingEventLog: () => allowMissingEventLog });
|
|
278
|
+
if (file === void 0) return { complete: true, catchUp: false };
|
|
279
|
+
try {
|
|
280
|
+
const info = await file.stat();
|
|
281
|
+
const fingerprint = `${info.dev}:${info.ino}:${info.birthtimeMs}`;
|
|
282
|
+
const head = Buffer.alloc(Math.min(256, info.size));
|
|
283
|
+
const headRead = await file.read(head, 0, head.length, 0);
|
|
284
|
+
const headHash = createHash("sha256").update(head.subarray(0, headRead.bytesRead)).digest("hex");
|
|
285
|
+
const previousHash = createHash("sha256").update(head.subarray(0, Math.min(row.head_bytes, headRead.bytesRead))).digest("hex");
|
|
286
|
+
const changed = row.fingerprint !== null && (row.fingerprint !== fingerprint || info.size < row.offset || row.head_bytes > 0 && row.head_hash !== null && row.head_hash !== previousHash);
|
|
287
|
+
if (!changed && row.fingerprint !== null && row.offset === info.size) {
|
|
288
|
+
return { complete: true, catchUp: false };
|
|
289
|
+
}
|
|
290
|
+
let offset = changed ? 0 : row.offset, skipping = changed ? false : row.skipping === 1;
|
|
291
|
+
const start = offset, budget = Math.min(INDEX_BYTES, info.size - offset);
|
|
292
|
+
const data = Buffer.alloc(budget);
|
|
293
|
+
const { bytesRead } = await file.read(data, 0, budget, offset);
|
|
294
|
+
const observations = [];
|
|
295
|
+
let cursor = 0, gap = changed ? Date.now() : row.history_lost;
|
|
296
|
+
while (cursor < bytesRead) {
|
|
297
|
+
const end = data.indexOf(10, cursor);
|
|
298
|
+
if (end < 0 || end >= bytesRead) break;
|
|
299
|
+
if (!skipping) {
|
|
300
|
+
const text = data.subarray(cursor, end).toString("utf8").trim();
|
|
301
|
+
if (text.length > 0) observations.push(AnalyticsEventSchema.parse(JSON.parse(text)));
|
|
302
|
+
}
|
|
303
|
+
skipping = false;
|
|
304
|
+
cursor = end + 1;
|
|
305
|
+
}
|
|
306
|
+
offset += cursor;
|
|
307
|
+
if (cursor === 0 && bytesRead === INDEX_BYTES && info.size - start > INDEX_BYTES) {
|
|
308
|
+
offset += bytesRead;
|
|
309
|
+
skipping = true;
|
|
310
|
+
gap = Date.now();
|
|
311
|
+
}
|
|
312
|
+
this.#transaction(db, () => {
|
|
313
|
+
for (const event of observations) this.#event(db, key, event);
|
|
314
|
+
db.prepare(`UPDATE sessions SET offset=?,fingerprint=?,head_hash=?,head_bytes=?,skipping=?,
|
|
315
|
+
indexed_at=?,history_lost=? WHERE id=?`).run(
|
|
316
|
+
offset,
|
|
317
|
+
fingerprint,
|
|
318
|
+
headHash,
|
|
319
|
+
headRead.bytesRead,
|
|
320
|
+
skipping ? 1 : 0,
|
|
321
|
+
Date.now(),
|
|
322
|
+
gap,
|
|
323
|
+
key
|
|
324
|
+
);
|
|
325
|
+
this.#prune(db);
|
|
326
|
+
});
|
|
327
|
+
return { complete: offset === info.size, catchUp: start + bytesRead < info.size };
|
|
328
|
+
} finally {
|
|
329
|
+
await file.close();
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
async read(sessionId, request, environment, allowMissingEventLog) {
|
|
333
|
+
const since = Date.parse(request.since), until = Date.parse(request.until);
|
|
334
|
+
if (!(until > since) || until - since > 8 * 24 * 60 * 60 * 1e3 || until > Date.now() + 6e4) {
|
|
335
|
+
throw new SessionOperationError("ANALYTICS_INVALID", "Invalid analytics time window");
|
|
336
|
+
}
|
|
337
|
+
let formatter;
|
|
338
|
+
try {
|
|
339
|
+
formatter = new Intl.DateTimeFormat("en-CA", { timeZone: request.timeZone, year: "numeric", month: "2-digit", day: "2-digit" });
|
|
340
|
+
} catch (cause) {
|
|
341
|
+
throw new SessionOperationError("ANALYTICS_INVALID", "Invalid analytics time zone", { cause });
|
|
342
|
+
}
|
|
343
|
+
const { complete } = await this.index(sessionId, environment, allowMissingEventLog);
|
|
344
|
+
const { db, key, row } = await this.#session(sessionId);
|
|
345
|
+
const records = z.array(ReceiptRow).parse(db.prepare(
|
|
346
|
+
"SELECT * FROM receipts WHERE session=? AND occurred_at>=? AND occurred_at<? ORDER BY occurred_at"
|
|
347
|
+
).all(key, since, until));
|
|
348
|
+
const days = /* @__PURE__ */ new Map();
|
|
349
|
+
const users = /* @__PURE__ */ new Map();
|
|
350
|
+
let usageTruncated = since < row.observed_since || row.usage_lost !== null && row.usage_lost >= since || row.gap_since !== null && row.gap_since < until;
|
|
351
|
+
for (const record of records) {
|
|
352
|
+
const date = formatter.format(record.occurred_at);
|
|
353
|
+
let bucket = days.get(date);
|
|
354
|
+
if (bucket === void 0) {
|
|
355
|
+
bucket = { date, messages: 0, models: [] };
|
|
356
|
+
days.set(date, bucket);
|
|
357
|
+
}
|
|
358
|
+
if (record.kind !== "usage") {
|
|
359
|
+
bucket.messages++;
|
|
360
|
+
if (record.kind === "user" && record.manual === 1) {
|
|
361
|
+
let user = users.get(date);
|
|
362
|
+
if (user === void 0) {
|
|
363
|
+
user = { messages: 0, keywords: /* @__PURE__ */ new Map(), shortened: false };
|
|
364
|
+
users.set(date, user);
|
|
365
|
+
}
|
|
366
|
+
user.messages++;
|
|
367
|
+
user.shortened ||= record.shortened === 1;
|
|
368
|
+
for (const term of z.array(z.string()).parse(JSON.parse(record.keywords ?? "[]"))) {
|
|
369
|
+
user.keywords.set(term, (user.keywords.get(term) ?? 0) + 1);
|
|
370
|
+
}
|
|
371
|
+
}
|
|
372
|
+
continue;
|
|
373
|
+
}
|
|
374
|
+
if (record.input === null || record.output === null) {
|
|
375
|
+
usageTruncated = true;
|
|
376
|
+
continue;
|
|
377
|
+
}
|
|
378
|
+
const modelName = record.model;
|
|
379
|
+
if (modelName === null) throw new Error("Usage receipt has no model");
|
|
380
|
+
let model = bucket.models.find((item) => item.model === modelName);
|
|
381
|
+
if (model === void 0) {
|
|
382
|
+
model = {
|
|
383
|
+
model: modelName,
|
|
384
|
+
calls: 0,
|
|
385
|
+
inputTokens: 0,
|
|
386
|
+
outputTokens: 0,
|
|
387
|
+
...record.cache === null ? {} : { cacheReadTokens: 0 }
|
|
388
|
+
};
|
|
389
|
+
bucket.models.push(model);
|
|
390
|
+
}
|
|
391
|
+
model.calls++;
|
|
392
|
+
model.inputTokens += record.input;
|
|
393
|
+
model.outputTokens += record.output;
|
|
394
|
+
if (model.cacheReadTokens !== void 0 && record.cache !== null) model.cacheReadTokens += record.cache;
|
|
395
|
+
else delete model.cacheReadTokens;
|
|
396
|
+
}
|
|
397
|
+
return SessionAnalyticsResultSchema.parse({
|
|
398
|
+
sampledAt: (/* @__PURE__ */ new Date()).toISOString(),
|
|
399
|
+
days: [...days.values()].sort((a, b) => a.date.localeCompare(b.date)),
|
|
400
|
+
historyTruncated: !complete || row.history_lost !== null && row.history_lost >= since || row.gap_since !== null && row.gap_since < until,
|
|
401
|
+
usageTruncated,
|
|
402
|
+
userActivity: [...users].sort(([a], [b]) => a.localeCompare(b)).map(([date, value]) => ({
|
|
403
|
+
date,
|
|
404
|
+
messages: value.messages,
|
|
405
|
+
keywords: [...value.keywords].sort(([a, x], [b, y]) => y - x || a.localeCompare(b)).slice(0, 48).map(([term, messages]) => ({ term, messages })),
|
|
406
|
+
keywordsTruncated: value.shortened || value.keywords.size > 48
|
|
407
|
+
})),
|
|
408
|
+
...row.skills === null ? {} : { skills: JSON.parse(row.skills) },
|
|
409
|
+
...row.skills_at === null ? {} : { skillsSampledAt: row.skills_at },
|
|
410
|
+
coverage: {
|
|
411
|
+
recordingStartedAt: new Date(row.started_at).toISOString(),
|
|
412
|
+
usageObservedSince: new Date(row.observed_since).toISOString(),
|
|
413
|
+
...row.indexed_at === null ? {} : { historyIndexedAt: new Date(row.indexed_at).toISOString() },
|
|
414
|
+
droppedEvents: row.dropped,
|
|
415
|
+
usageSource: "observed"
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
}
|
|
419
|
+
async remove(sessionId) {
|
|
420
|
+
const db = await this.#db();
|
|
421
|
+
db.prepare("DELETE FROM sessions WHERE id=?").run(this.#key(sessionId));
|
|
422
|
+
this.#seen.delete(this.#key(sessionId));
|
|
423
|
+
db.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
424
|
+
}
|
|
425
|
+
close() {
|
|
426
|
+
if (this.#database !== void 0) {
|
|
427
|
+
this.#database.exec("PRAGMA wal_checkpoint(TRUNCATE)");
|
|
428
|
+
this.#database.close();
|
|
429
|
+
this.#database = void 0;
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
};
|
|
433
|
+
|
|
434
|
+
// src/session-analytics-worker.ts
|
|
435
|
+
if (isMainThread2 || parentPort === null) throw new Error("Analytics storage requires a background worker");
|
|
436
|
+
var port = parentPort;
|
|
437
|
+
var settings = z2.object({ directory: z2.string() }).parse(workerData);
|
|
438
|
+
var store = new AnalyticsStore(settings.directory);
|
|
439
|
+
var pending = Promise.resolve();
|
|
440
|
+
port.on("message", (value) => {
|
|
441
|
+
pending = pending.then(async () => {
|
|
442
|
+
const { id, command } = z2.object({ id: z2.number().int(), command: AnalyticsCommandSchema }).parse(value);
|
|
443
|
+
try {
|
|
444
|
+
let result;
|
|
445
|
+
switch (command.operation) {
|
|
446
|
+
case "observe":
|
|
447
|
+
result = await store.observe(command.observations, command.gaps);
|
|
448
|
+
break;
|
|
449
|
+
case "index":
|
|
450
|
+
result = await store.index(command.sessionId, command.environment, command.allowMissingEventLog);
|
|
451
|
+
break;
|
|
452
|
+
case "read":
|
|
453
|
+
result = await store.read(command.sessionId, command.request, command.environment, command.allowMissingEventLog);
|
|
454
|
+
break;
|
|
455
|
+
case "remove":
|
|
456
|
+
result = await store.remove(command.sessionId);
|
|
457
|
+
break;
|
|
458
|
+
case "close":
|
|
459
|
+
store.close();
|
|
460
|
+
break;
|
|
461
|
+
}
|
|
462
|
+
port.postMessage({ id, result });
|
|
463
|
+
} catch (error) {
|
|
464
|
+
port.postMessage({ id, error: {
|
|
465
|
+
code: error instanceof SessionOperationError ? error.code : "ANALYTICS_UNAVAILABLE",
|
|
466
|
+
message: error instanceof SessionOperationError ? error.message : error instanceof Error && error.message.includes("symbolic link") ? "Analytics paths must not be symbolic links" : "Background analytics storage or history indexing failed; check the PC Agent data directory"
|
|
467
|
+
} });
|
|
468
|
+
}
|
|
469
|
+
}).catch((error) => {
|
|
470
|
+
setImmediate(() => {
|
|
471
|
+
throw error;
|
|
472
|
+
});
|
|
473
|
+
});
|
|
474
|
+
});
|