kibi-agent-core 0.9.1 → 0.11.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/CHANGELOG.md CHANGED
@@ -1,5 +1,29 @@
1
1
  # kibi-agent-core
2
2
 
3
+ ## 0.11.0
4
+
5
+ ### Minor Changes
6
+
7
+ - 43d4366: Usage telemetry data is cleaner and more complete. Telemetry is now off when the home directory lies inside the temp directory, as eval, packaging and end-to-end harnesses set it, so each harness run no longer counts as a new install; Kibi's own eval and packed-test sandboxes also set `KIBI_TELEMETRY=0`. Events now name the host agent from `CLAUDECODE`, `CURSOR_AGENT`, `CODEX_SANDBOX`, `GEMINI_CLI`, `OPENCODE`, `AI_AGENT` or the MCP client name, carry a hashed host session id in every host, and say whether they come from a hosted cloud workspace. Failed CLI commands and MCP tool results now carry a fixed error category: the result's error code (for example `upsert_dry_run_invalid`), the failing `kibi doctor` checks, or the `kibi migrate` approval problem. `kibi migrate --apply-safe` now prints the current plan hash when the approved hash is missing or out of date.
8
+
9
+ Hooks in Claude Code, Codex, Cursor, ZCode and OpenCode now all send the anonymous `kibi_hook` event (before, only Claude Code did, and only in diagnostic mode for the others), and each hook remembers, as hashes in `telemetry-sessions.json`, which host session last ran in the workspace. CLI and MCP events take the session id from `KIBI_SESSION_ID`, `CLAUDE_CODE_SESSION_ID` or `CODEX_THREAD_ID` when the host exposes one, and otherwise from that workspace marker (at most 30 minutes old), so events from Cursor and OpenCode sessions, which expose no session variable, can be grouped too. Every host's hook also sends the queue when it is due, and right away at the end of a turn.
10
+
11
+ ### Patch Changes
12
+
13
+ - ce41f02: Agents now keep a signoff in the pull request it approves. The guidance used to time the signoff as an end-of-work step and said only that an agent must never set `approved_by` itself, so agents often opened the pull request first and then carried the person's answer in a separate follow-up pull request.
14
+ - kibi-usage 2.37.0, kibi-decisions 1.5.0 and kibi-commit-review 1.4.0 (and the signoff-views resource) say to ask for the signoff before opening or merging the pull request, and to record the person's answer (their name in `approved_by` or a `*_waiver_approved_by` field, their words in `origin.ref` or `approval_ref`) on the same branch and pull request. Writing down an answer the person gave is not self-approval. A pull request that only carries a signoff, firmness or waiver approval is ruled out.
15
+ - The stop-hook signoff reminder (Claude Code, Codex, Cursor, ZCode) adds the same rule. So do the `agent-requirement-unapproved` check action, the `dimension_unrepresented` repair hint and the waiver lines of `kibi proof explain`.
16
+
17
+ ## 0.10.0
18
+
19
+ ### Minor Changes
20
+
21
+ - d89c1d2: Kibi now sends anonymous usage statistics, so its maintainers can see which operations people use, how long they take and how they fail, including in cloud and ephemeral environments where the local diagnostic log is lost. Only fixed names, statuses, durations, error categories, versions and platform are sent. Code, paths, queries, KB content and repository names never are. Turn it off with `kibi telemetry disable`, `KIBI_TELEMETRY=0` or `DO_NOT_TRACK=1`. It is also off in CI and test runs.
22
+ - kibi-agent-core adds `usage-telemetry`, a shared queue and batch sender for PostHog, with a random install id, hashed session ids and no person profiles.
23
+ - kibi-mcp records one `kibi_operation` event per tool call, sends the queue every minute and on shutdown, and prints a one-time notice to stderr.
24
+ - kibi-cli records one event per command, adds `kibi telemetry status|enable|disable`, and prints the one-time notice.
25
+ - kibi-claude records one `kibi_hook` event per hook decision and sends the queue from the Stop hook.
26
+
3
27
  ## 0.9.1
4
28
 
5
29
  ### Patch Changes
@@ -260,7 +260,7 @@ export function claimSignoffReminder(session, workspaceRoot) {
260
260
  export function signoffReminder() {
261
261
  return [
262
262
  "Kibi: this session recorded or changed requirements, and the person has not seen them as a signoff view.",
263
- "Before reporting the work done or asking to commit, run `kibi signoff` and put its output in the reply unchanged; a requirement the agent wrote waits for the person's approval, so ask for it with this view, never in your own words. When replies go through a messaging tool, pass the output there as the message text, and share `.kb/briefs/signoff/latest.html` only as a rendered page (the Artifact tool in Claude apps), never as an attached file, which chat apps show as raw source (kibi-decisions, resources/signoff-views.md).",
263
+ "Before reporting the work done, asking to commit, or opening or merging the pull request, run `kibi signoff` and put its output in the reply unchanged; a requirement the agent wrote waits for the person's approval, so ask for it with this view, never in your own words. When they answer, record their answer on the same branch and push it to the same pull request, never to a separate one. When replies go through a messaging tool, pass the output there as the message text, and share `.kb/briefs/signoff/latest.html` only as a rendered page (the Artifact tool in Claude apps), never as an attached file, which chat apps show as raw source (kibi-decisions, resources/signoff-views.md).",
264
264
  ].join("\n");
265
265
  }
266
266
  function readSettled(file) {
@@ -35,6 +35,8 @@ export declare function hookTelemetryEnabled(env?: NodeJS.ProcessEnv): boolean;
35
35
  export type HookUsageRow = {
36
36
  /** Host agent, e.g. `claude-code`, `cursor`, `codex`, `zcode`, `opencode`. */
37
37
  host: string;
38
+ /** Adapter npm package; defaults to `kibi-<host>` (`kibi-claude` for Claude Code). */
39
+ packageName?: string | undefined;
38
40
  /** Version of the adapter package that wrote the row, when known. */
39
41
  packageVersion?: string | null | undefined;
40
42
  workspaceRoot: string;
@@ -44,7 +46,15 @@ export type HookUsageRow = {
44
46
  trace: HookTrace;
45
47
  startedAt: Date;
46
48
  };
47
- /** Append one hook row to `.kb/usage.log` when the operator opted in. */
49
+ /**
50
+ * Whether a host should build hook traces at all: for the opt-in
51
+ * `.kb/usage.log` rows or for anonymous usage telemetry.
52
+ */
53
+ export declare function hookTracesWanted(env?: NodeJS.ProcessEnv): boolean;
54
+ /**
55
+ * Record one hook decision: an anonymous summary event (unless telemetry is
56
+ * off) and, when the operator opted in, the detailed `.kb/usage.log` row.
57
+ */
48
58
  export declare function appendHookUsage(row: HookUsageRow, env?: NodeJS.ProcessEnv): void;
49
59
  /**
50
60
  * Trace for a tool call that ran a Kibi operation through MCP or the
@@ -59,6 +69,17 @@ export declare function kbUsageTrace(toolName: string | undefined, toolInput: un
59
69
  export declare function editTraces(relativePaths: readonly string[], requirementIdsFor: (relativePath: string) => string[]): HookTrace[];
60
70
  /** Append one row per trace, sharing the call's host, session and tool. */
61
71
  export declare function appendHookUsageRows(row: Omit<HookUsageRow, "trace">, traces: readonly HookTrace[], env?: NodeJS.ProcessEnv): void;
72
+ /**
73
+ * End-of-hook bookkeeping every host runs: remember the host session for the
74
+ * workspace, so CLI and MCP events from that workspace can carry it, and send
75
+ * the anonymous telemetry queue when it is due, or always at the end of a
76
+ * turn. Never throws.
77
+ */
78
+ export declare function finishHookTelemetry(input: {
79
+ readonly event: string;
80
+ readonly workspaceRoot: string | undefined;
81
+ readonly sessionId: string | undefined;
82
+ }, env?: NodeJS.ProcessEnv): Promise<void>;
62
83
  /**
63
84
  * Version of the adapter package whose `package.json` sits at
64
85
  * `packageJsonPath`, or null when it cannot be read.
@@ -4,6 +4,7 @@ import fs from "node:fs";
4
4
  import path from "node:path";
5
5
  import { hostKbOperation } from "./kb-mcp-tools.js";
6
6
  import { classifyPath } from "./path-policy.js";
7
+ import { flushTelemetry, recordHookTelemetry, rememberHookSession, telemetryEnabled, } from "./usage-telemetry.js";
7
8
  // implements REQ-claude-hook-usage-telemetry-v2, REQ-kibi-telemetry-acceptance-gate-v2
8
9
  /** Hook actions the acceptance report reads; hosts emit these names. */
9
10
  export const HOOK_ACTION_EDITED = "edited";
@@ -15,9 +16,38 @@ export function hookTelemetryEnabled(env = process.env) {
15
16
  return value === "1" || value === "true";
16
17
  }
17
18
  // implements REQ-claude-hook-usage-telemetry-v2
18
- /** Append one hook row to `.kb/usage.log` when the operator opted in. */
19
+ /**
20
+ * Whether a host should build hook traces at all: for the opt-in
21
+ * `.kb/usage.log` rows or for anonymous usage telemetry.
22
+ */
23
+ export function hookTracesWanted(env = process.env) {
24
+ return hookTelemetryEnabled(env) || telemetryEnabled(env);
25
+ }
26
+ function adapterPackage(host) {
27
+ return host === "claude-code" ? "kibi-claude" : `kibi-${host}`;
28
+ }
29
+ // implements REQ-claude-hook-usage-telemetry-v2, REQ-kibi-anonymous-usage-telemetry
30
+ /**
31
+ * Record one hook decision: an anonymous summary event (unless telemetry is
32
+ * off) and, when the operator opted in, the detailed `.kb/usage.log` row.
33
+ */
19
34
  export function appendHookUsage(row, env = process.env) {
20
- if (!hookTelemetryEnabled(env) || row.trace.action === undefined)
35
+ if (row.trace.action === undefined)
36
+ return;
37
+ recordHookTelemetry({
38
+ packageName: row.packageName ?? adapterPackage(row.host),
39
+ packageVersion: row.packageVersion,
40
+ host: row.host,
41
+ sessionId: row.sessionId,
42
+ }, {
43
+ hookEvent: row.event,
44
+ hookAction: row.trace.action,
45
+ pathKind: row.trace.pathKind,
46
+ kbOperation: row.trace.kbOperation,
47
+ kbUsedBefore: row.trace.kbUsedBefore,
48
+ requirementCount: row.trace.requirementIds?.length,
49
+ }, env);
50
+ if (!hookTelemetryEnabled(env))
21
51
  return;
22
52
  const finishedAt = new Date();
23
53
  const { trace } = row;
@@ -85,11 +115,32 @@ export function editTraces(relativePaths, requirementIdsFor) {
85
115
  // implements REQ-claude-hook-usage-telemetry-v2
86
116
  /** Append one row per trace, sharing the call's host, session and tool. */
87
117
  export function appendHookUsageRows(row, traces, env = process.env) {
88
- if (!hookTelemetryEnabled(env))
118
+ if (!hookTracesWanted(env))
89
119
  return;
90
120
  for (const trace of traces)
91
121
  appendHookUsage({ ...row, trace }, env);
92
122
  }
123
+ /** Host events that end a turn or a session: the queue is sent right away. */
124
+ const TURN_END_EVENTS = new Set(["stop", "sessionend"]);
125
+ // implements REQ-kibi-anonymous-usage-telemetry
126
+ /**
127
+ * End-of-hook bookkeeping every host runs: remember the host session for the
128
+ * workspace, so CLI and MCP events from that workspace can carry it, and send
129
+ * the anonymous telemetry queue when it is due, or always at the end of a
130
+ * turn. Never throws.
131
+ */
132
+ export async function finishHookTelemetry(input, env = process.env) {
133
+ try {
134
+ if (input.workspaceRoot && input.sessionId) {
135
+ rememberHookSession(input.workspaceRoot, input.sessionId, env);
136
+ }
137
+ const turnEnd = TURN_END_EVENTS.has(input.event.toLowerCase().replace(/[^a-z]/g, ""));
138
+ await flushTelemetry({ force: turnEnd }, env);
139
+ }
140
+ catch {
141
+ // Telemetry is best effort and must never disturb the hook.
142
+ }
143
+ }
93
144
  // implements REQ-claude-hook-usage-telemetry-v2
94
145
  /**
95
146
  * Version of the adapter package whose `package.json` sits at
package/dist/index.d.ts CHANGED
@@ -5,3 +5,4 @@ export * from "./knowledge-index.js";
5
5
  export * from "./path-policy.js";
6
6
  export * from "./snippets.js";
7
7
  export * from "./requirement-candidates.js";
8
+ export * from "./usage-telemetry.js";
package/dist/index.js CHANGED
@@ -5,3 +5,4 @@ export * from "./knowledge-index.js";
5
5
  export * from "./path-policy.js";
6
6
  export * from "./snippets.js";
7
7
  export * from "./requirement-candidates.js";
8
+ export * from "./usage-telemetry.js";
@@ -0,0 +1,143 @@
1
+ /**
2
+ * Anonymous usage telemetry shared by the CLI, the MCP server and the host
3
+ * hooks.
4
+ *
5
+ * `.kb/usage.log` stays the detailed, opt-in diagnostic record and never
6
+ * leaves the machine. This module sends a much smaller summary to the Kibi
7
+ * PostHog project so maintainers can see which operations people run, how
8
+ * long they take and how they fail. Events carry only fixed vocabulary
9
+ * (operation and command names, statuses, error categories, path kinds),
10
+ * durations, versions and platform; never paths, queries, entity ids, KB
11
+ * content, repository names or error messages. The install id is random and
12
+ * the host session id is hashed.
13
+ *
14
+ * Events are appended to a per-user queue file and sent in batches, so
15
+ * short-lived processes (hooks, the CLI) do not wait on the network.
16
+ * `KIBI_TELEMETRY=0`, `DO_NOT_TRACK=1`, `kibi telemetry disable`, CI and test
17
+ * runs, and sandboxes whose home directory is a temp directory (eval and
18
+ * packaging harnesses) turn it off.
19
+ */
20
+ /** Public, write-only PostHog project key: it can send events, not read them. */
21
+ export declare const DEFAULT_TELEMETRY_KEY = "phc_A5z8jRhD528abGJiTtPfgu4d4hpbEbfiJr9iUGn9TMsY";
22
+ export declare const DEFAULT_TELEMETRY_HOST = "https://eu.i.posthog.com";
23
+ export declare const TELEMETRY_DOCS_URL = "https://looted.github.io/kibi/guide/telemetry.html";
24
+ type Env = NodeJS.ProcessEnv;
25
+ export type TelemetryPreference = "enabled" | "disabled";
26
+ export type TelemetryConfig = {
27
+ installId?: string;
28
+ preference?: TelemetryPreference;
29
+ noticeShownAt?: string;
30
+ };
31
+ export type TelemetryStatus = {
32
+ enabled: boolean;
33
+ /** Why telemetry is on or off, e.g. `KIBI_TELEMETRY=0` or `default`. */
34
+ reason: string;
35
+ directory: string;
36
+ };
37
+ /** Summary of one Kibi operation run through MCP or the CLI. */
38
+ export type OperationTelemetry = {
39
+ interface: "mcp" | "cli";
40
+ /** Registered MCP tool or CLI command name. */
41
+ operation: string;
42
+ status: "success" | "error";
43
+ durationMs: number;
44
+ /** Fixed diagnostic category such as `tool_timeout`, when known. */
45
+ errorCategory?: string | undefined;
46
+ exitCode?: number | undefined;
47
+ };
48
+ /** Summary of one host hook decision. */
49
+ export type HookTelemetry = {
50
+ hookEvent: string;
51
+ hookAction: string;
52
+ pathKind?: string | undefined;
53
+ kbOperation?: string | undefined;
54
+ kbUsedBefore?: boolean | undefined;
55
+ requirementCount?: number | undefined;
56
+ };
57
+ /** Who is sending: the package, its version and the host agent. */
58
+ export type TelemetrySource = {
59
+ /** npm package name, e.g. `kibi-cli`, `kibi-mcp`, `kibi-claude`. */
60
+ packageName: string;
61
+ packageVersion?: string | null | undefined;
62
+ /** Host agent, e.g. `claude-code`, `cursor`, `codex`, or `unknown`. */
63
+ host?: string | undefined;
64
+ /** Host session id; only its hash is sent. */
65
+ sessionId?: string | null | undefined;
66
+ /**
67
+ * Workspace the CLI or MCP server works in. Without a session id of its
68
+ * own, the event takes the session a host hook last reported there.
69
+ */
70
+ workspaceRoot?: string | undefined;
71
+ };
72
+ /** Variables CI providers set; any non-false value marks a CI run. */
73
+ export declare const CI_ENV_KEYS: readonly ["CI", "CONTINUOUS_INTEGRATION", "GITHUB_ACTIONS", "GITLAB_CI", "BUILDKITE", "CIRCLECI", "TRAVIS", "TF_BUILD", "JENKINS_URL", "TEAMCITY_VERSION", "BITBUCKET_BUILD_NUMBER", "CODEBUILD_BUILD_ID", "DRONE", "APPVEYOR", "SEMAPHORE", "BUILDKITE_BUILD_ID", "CF_BUILD_ID", "HEROKU_TEST_RUN_ID"];
74
+ /** Variables test runners set for the code under test (`NAME=value` must match). */
75
+ export declare const TEST_ENV_KEYS: readonly ["NODE_ENV=test", "JEST_WORKER_ID", "VITEST", "VITEST_WORKER_ID", "NODE_TEST_CONTEXT"];
76
+ /** Variables an agent host sets for the processes it starts, in priority order. */
77
+ export declare const HOST_ENV_KEYS: readonly [readonly ["CLAUDECODE=1", "claude-code"], readonly ["CURSOR_AGENT=1", "cursor"], readonly ["CODEX_SANDBOX", "codex"], readonly ["CODEX_THREAD_ID", "codex"], readonly ["GEMINI_CLI=1", "gemini-cli"], readonly ["OPENCODE=1", "opencode"]];
78
+ /** Variables that carry the host agent's session id; only its hash is sent. */
79
+ export declare const SESSION_ENV_KEYS: readonly ["KIBI_SESSION_ID", "CLAUDE_CODE_SESSION_ID", "CODEX_THREAD_ID"];
80
+ /**
81
+ * The agent host running Kibi, from an explicit `KIBI_HOST`/`KIBI_MCP_HOST`,
82
+ * the variables hosts set for their children, or the `AI_AGENT` convention
83
+ * (`claude-code_2-1-3_agent`). Undefined when nothing names one.
84
+ */
85
+ export declare function detectTelemetryHost(env?: Env): string | undefined;
86
+ /** The host agent's session id from the environment, when it exposes one. */
87
+ export declare function detectTelemetrySession(env?: Env): string | undefined;
88
+ /** Per-user directory holding the telemetry config and queue. */
89
+ export declare function telemetryDirectory(env?: Env): string;
90
+ export declare function readTelemetryConfig(env?: Env): TelemetryConfig;
91
+ /**
92
+ * Persist the user's choice. Disabling also deletes anything still queued,
93
+ * so nothing recorded before the choice is sent afterwards.
94
+ */
95
+ export declare function setTelemetryPreference(preference: TelemetryPreference, env?: Env): void;
96
+ /**
97
+ * Whether events are recorded and sent, and why. Explicit opt-outs win over
98
+ * everything. CI and test runs are off even after `kibi telemetry enable`;
99
+ * only an explicit `KIBI_TELEMETRY=1` sends from them.
100
+ */
101
+ export declare function telemetryStatus(env?: Env): TelemetryStatus;
102
+ export declare function telemetryEnabled(env?: Env): boolean;
103
+ /** Stable one-way hash, so a session can be grouped without revealing its id. */
104
+ export declare function hashTelemetryId(value: string): string;
105
+ /**
106
+ * The notice users see before the first event is sent, or null once it was
107
+ * shown. Callers that can reach the user (CLI and MCP stderr) print it.
108
+ */
109
+ export declare function takeTelemetryNotice(env?: Env): string | null;
110
+ /**
111
+ * Remember which host session last ran a hook in a workspace. Every host
112
+ * hands its hooks the session id, but only some expose it to the CLI and MCP
113
+ * server through the environment. Only hashes are stored: of the workspace
114
+ * path and of the session id.
115
+ */
116
+ export declare function rememberHookSession(workspaceRoot: string, sessionId: string, env?: Env): void;
117
+ /**
118
+ * Hashed session a host hook recently reported for this directory or the
119
+ * nearest ancestor that has one, or undefined.
120
+ */
121
+ export declare function workspaceSessionHash(startDirectory: string, env?: Env): string | undefined;
122
+ /**
123
+ * An error category as sent: fixed identifiers such as `tool_timeout` or
124
+ * `UPSERT_DRY_RUN_INVALID` pass, lower-cased; anything that looks like free
125
+ * text is replaced, so a message can never leak through this field.
126
+ */
127
+ export declare function telemetryCategory(value: string | undefined): string | null;
128
+ export declare function recordOperationTelemetry(source: TelemetrySource, operation: OperationTelemetry, env?: Env): void;
129
+ export declare function recordHookTelemetry(source: TelemetrySource, hook: HookTelemetry, env?: Env): void;
130
+ export declare function clearTelemetryQueue(env?: Env): void;
131
+ export type FlushOptions = {
132
+ /** Send even when the queue is small and recent (process exit, Stop hook). */
133
+ force?: boolean;
134
+ timeoutMs?: number;
135
+ fetchImpl?: typeof fetch;
136
+ };
137
+ /**
138
+ * Send queued events in one batch when a flush is due (or forced). Returns
139
+ * the number of events sent. A failed send puts the events back for the next
140
+ * flush; nothing here throws.
141
+ */
142
+ export declare function flushTelemetry(options?: FlushOptions, env?: Env): Promise<number>;
143
+ export {};
@@ -0,0 +1,660 @@
1
+ // implements REQ-kibi-anonymous-usage-telemetry
2
+ import { createHash, randomUUID } from "node:crypto";
3
+ import fs from "node:fs";
4
+ import os from "node:os";
5
+ import path from "node:path";
6
+ /**
7
+ * Anonymous usage telemetry shared by the CLI, the MCP server and the host
8
+ * hooks.
9
+ *
10
+ * `.kb/usage.log` stays the detailed, opt-in diagnostic record and never
11
+ * leaves the machine. This module sends a much smaller summary to the Kibi
12
+ * PostHog project so maintainers can see which operations people run, how
13
+ * long they take and how they fail. Events carry only fixed vocabulary
14
+ * (operation and command names, statuses, error categories, path kinds),
15
+ * durations, versions and platform; never paths, queries, entity ids, KB
16
+ * content, repository names or error messages. The install id is random and
17
+ * the host session id is hashed.
18
+ *
19
+ * Events are appended to a per-user queue file and sent in batches, so
20
+ * short-lived processes (hooks, the CLI) do not wait on the network.
21
+ * `KIBI_TELEMETRY=0`, `DO_NOT_TRACK=1`, `kibi telemetry disable`, CI and test
22
+ * runs, and sandboxes whose home directory is a temp directory (eval and
23
+ * packaging harnesses) turn it off.
24
+ */
25
+ // implements REQ-kibi-anonymous-usage-telemetry
26
+ /** Public, write-only PostHog project key: it can send events, not read them. */
27
+ export const DEFAULT_TELEMETRY_KEY = "phc_A5z8jRhD528abGJiTtPfgu4d4hpbEbfiJr9iUGn9TMsY";
28
+ // implements REQ-kibi-anonymous-usage-telemetry
29
+ export const DEFAULT_TELEMETRY_HOST = "https://eu.i.posthog.com";
30
+ // implements REQ-kibi-anonymous-usage-telemetry
31
+ export const TELEMETRY_DOCS_URL = "https://looted.github.io/kibi/guide/telemetry.html";
32
+ const QUEUE_FILE = "telemetry-queue.jsonl";
33
+ const SESSIONS_FILE = "telemetry-sessions.json";
34
+ /** A hook-recorded session older than this no longer names the workspace's session. */
35
+ const SESSION_MARKER_MAX_AGE_MS = 30 * 60 * 1000;
36
+ const MAX_SESSION_MARKERS = 200;
37
+ const CONFIG_FILE = "telemetry.json";
38
+ const SENDING_SUFFIX = ".sending";
39
+ /** Queue size that makes a flush due regardless of age. */
40
+ const FLUSH_BATCH_EVENTS = 20;
41
+ /** Age of the oldest queued event that makes a flush due. */
42
+ const FLUSH_MAX_AGE_MS = 5 * 60 * 1000;
43
+ /** A claimed batch older than this was left by a process that died. */
44
+ const STALE_CLAIM_MS = 10 * 60 * 1000;
45
+ /** Queued events older than this are dropped instead of sent. */
46
+ const MAX_EVENT_AGE_MS = 7 * 24 * 60 * 60 * 1000;
47
+ /** The queue stops growing past this size when sends keep failing. */
48
+ const MAX_QUEUE_BYTES = 1024 * 1024;
49
+ const DEFAULT_FLUSH_TIMEOUT_MS = 1500;
50
+ function flagValue(value) {
51
+ const normalized = value?.trim().toLowerCase();
52
+ if (normalized === undefined || normalized === "")
53
+ return undefined;
54
+ if (["1", "true", "yes", "on"].includes(normalized))
55
+ return true;
56
+ if (["0", "false", "no", "off"].includes(normalized))
57
+ return false;
58
+ return undefined;
59
+ }
60
+ // implements REQ-kibi-anonymous-usage-telemetry
61
+ /** Variables CI providers set; any non-false value marks a CI run. */
62
+ export const CI_ENV_KEYS = [
63
+ "CI",
64
+ "CONTINUOUS_INTEGRATION",
65
+ "GITHUB_ACTIONS",
66
+ "GITLAB_CI",
67
+ "BUILDKITE",
68
+ "CIRCLECI",
69
+ "TRAVIS",
70
+ "TF_BUILD",
71
+ "JENKINS_URL",
72
+ "TEAMCITY_VERSION",
73
+ "BITBUCKET_BUILD_NUMBER",
74
+ "CODEBUILD_BUILD_ID",
75
+ "DRONE",
76
+ "APPVEYOR",
77
+ "SEMAPHORE",
78
+ "BUILDKITE_BUILD_ID",
79
+ "CF_BUILD_ID",
80
+ "HEROKU_TEST_RUN_ID",
81
+ ];
82
+ // implements REQ-kibi-anonymous-usage-telemetry
83
+ /** Variables test runners set for the code under test (`NAME=value` must match). */
84
+ export const TEST_ENV_KEYS = [
85
+ "NODE_ENV=test",
86
+ "JEST_WORKER_ID",
87
+ "VITEST",
88
+ "VITEST_WORKER_ID",
89
+ "NODE_TEST_CONTEXT",
90
+ ];
91
+ function automationName(env, keys) {
92
+ for (const key of keys) {
93
+ const [name, expected] = key.split("=");
94
+ const value = env[name]?.trim();
95
+ if (!value)
96
+ continue;
97
+ if (expected !== undefined) {
98
+ if (value === expected)
99
+ return key;
100
+ continue;
101
+ }
102
+ if (flagValue(value) !== false)
103
+ return name;
104
+ }
105
+ return undefined;
106
+ }
107
+ // implements REQ-kibi-anonymous-usage-telemetry
108
+ /** Variables an agent host sets for the processes it starts, in priority order. */
109
+ export const HOST_ENV_KEYS = [
110
+ ["CLAUDECODE=1", "claude-code"],
111
+ ["CURSOR_AGENT=1", "cursor"],
112
+ ["CODEX_SANDBOX", "codex"],
113
+ ["CODEX_THREAD_ID", "codex"],
114
+ ["GEMINI_CLI=1", "gemini-cli"],
115
+ ["OPENCODE=1", "opencode"],
116
+ ];
117
+ // implements REQ-kibi-anonymous-usage-telemetry
118
+ /** Variables that carry the host agent's session id; only its hash is sent. */
119
+ export const SESSION_ENV_KEYS = [
120
+ "KIBI_SESSION_ID",
121
+ "CLAUDE_CODE_SESSION_ID",
122
+ "CODEX_THREAD_ID",
123
+ ];
124
+ /** `Claude Code`, `claude_code` and `claude-code` name the same host. */
125
+ function hostKey(name) {
126
+ return name
127
+ .trim()
128
+ .toLowerCase()
129
+ .replace(/[^a-z0-9]+/g, "-")
130
+ .replace(/^-|-$/g, "");
131
+ }
132
+ // implements REQ-kibi-anonymous-usage-telemetry
133
+ /**
134
+ * The agent host running Kibi, from an explicit `KIBI_HOST`/`KIBI_MCP_HOST`,
135
+ * the variables hosts set for their children, or the `AI_AGENT` convention
136
+ * (`claude-code_2-1-3_agent`). Undefined when nothing names one.
137
+ */
138
+ export function detectTelemetryHost(env = process.env) {
139
+ const explicit = env.KIBI_HOST?.trim() || env.KIBI_MCP_HOST?.trim();
140
+ if (explicit)
141
+ return hostKey(explicit) || undefined;
142
+ for (const [key, host] of HOST_ENV_KEYS) {
143
+ if (automationName(env, [key]))
144
+ return host;
145
+ }
146
+ const agent = env.AI_AGENT?.trim().split("_")[0];
147
+ return agent ? hostKey(agent) || undefined : undefined;
148
+ }
149
+ // implements REQ-kibi-anonymous-usage-telemetry
150
+ /** The host agent's session id from the environment, when it exposes one. */
151
+ export function detectTelemetrySession(env = process.env) {
152
+ for (const key of SESSION_ENV_KEYS) {
153
+ const value = env[key]?.trim();
154
+ if (value)
155
+ return value;
156
+ }
157
+ return undefined;
158
+ }
159
+ /** Whether the process runs in a hosted cloud workspace rather than on a laptop. */
160
+ function remoteEnvironment(env) {
161
+ return (flagValue(env.CLAUDE_CODE_REMOTE) === true ||
162
+ flagValue(env.CODESPACES) === true ||
163
+ Boolean(env.GITPOD_WORKSPACE_ID?.trim()));
164
+ }
165
+ function realDirectory(directory) {
166
+ try {
167
+ return fs.realpathSync(directory);
168
+ }
169
+ catch {
170
+ return path.resolve(directory);
171
+ }
172
+ }
173
+ /**
174
+ * Eval, packaging and e2e harnesses give each run a fresh home under the temp
175
+ * directory, so every run would count as a new install. A real user's home
176
+ * never lives there.
177
+ */
178
+ function sandboxedHome(env) {
179
+ const home = (env.HOME ?? env.USERPROFILE)?.trim();
180
+ if (!home)
181
+ return false;
182
+ const temp = realDirectory(os.tmpdir());
183
+ const resolved = realDirectory(home);
184
+ return resolved !== temp && resolved.startsWith(`${temp}${path.sep}`);
185
+ }
186
+ // implements REQ-kibi-anonymous-usage-telemetry
187
+ /** Per-user directory holding the telemetry config and queue. */
188
+ export function telemetryDirectory(env = process.env) {
189
+ const explicit = env.KIBI_TELEMETRY_DIR?.trim();
190
+ if (explicit)
191
+ return explicit;
192
+ if (process.platform === "win32" && env.LOCALAPPDATA) {
193
+ return path.join(env.LOCALAPPDATA, "kibi");
194
+ }
195
+ const stateHome = env.XDG_STATE_HOME?.trim();
196
+ return path.join(stateHome || path.join(env.HOME || os.homedir(), ".local", "state"), "kibi");
197
+ }
198
+ // implements REQ-kibi-anonymous-usage-telemetry
199
+ export function readTelemetryConfig(env = process.env) {
200
+ try {
201
+ const parsed = JSON.parse(fs.readFileSync(path.join(telemetryDirectory(env), CONFIG_FILE), "utf8"));
202
+ return typeof parsed === "object" && parsed !== null
203
+ ? parsed
204
+ : {};
205
+ }
206
+ catch {
207
+ return {};
208
+ }
209
+ }
210
+ function writeTelemetryConfig(config, env) {
211
+ const directory = telemetryDirectory(env);
212
+ fs.mkdirSync(directory, { recursive: true });
213
+ fs.writeFileSync(path.join(directory, CONFIG_FILE), `${JSON.stringify(config, null, 2)}\n`, "utf8");
214
+ }
215
+ // implements REQ-kibi-anonymous-usage-telemetry
216
+ /**
217
+ * Persist the user's choice. Disabling also deletes anything still queued,
218
+ * so nothing recorded before the choice is sent afterwards.
219
+ */
220
+ export function setTelemetryPreference(preference, env = process.env) {
221
+ writeTelemetryConfig({ ...readTelemetryConfig(env), preference }, env);
222
+ if (preference === "disabled")
223
+ clearTelemetryQueue(env);
224
+ }
225
+ // implements REQ-kibi-anonymous-usage-telemetry
226
+ /**
227
+ * Whether events are recorded and sent, and why. Explicit opt-outs win over
228
+ * everything. CI and test runs are off even after `kibi telemetry enable`;
229
+ * only an explicit `KIBI_TELEMETRY=1` sends from them.
230
+ */
231
+ export function telemetryStatus(env = process.env) {
232
+ const directory = telemetryDirectory(env);
233
+ const status = (enabled, reason) => ({
234
+ enabled,
235
+ reason,
236
+ directory,
237
+ });
238
+ const explicit = flagValue(env.KIBI_TELEMETRY);
239
+ if (explicit === false)
240
+ return status(false, "KIBI_TELEMETRY=0");
241
+ if (flagValue(env.DO_NOT_TRACK) === true) {
242
+ return status(false, "DO_NOT_TRACK=1");
243
+ }
244
+ const preference = readTelemetryConfig(env).preference;
245
+ if (preference === "disabled") {
246
+ return status(false, "disabled with `kibi telemetry disable`");
247
+ }
248
+ if (telemetryKey(env) === "")
249
+ return status(false, "no telemetry key");
250
+ if (explicit === true)
251
+ return status(true, "KIBI_TELEMETRY=1");
252
+ // Read through a variable: bundlers inline `process.env.NODE_ENV`.
253
+ const processEnv = process.env;
254
+ // CI and test runs are checked in both the given env and the process env,
255
+ // so a suite that passes its own env object cannot leak events either.
256
+ const ciName = automationName(env, CI_ENV_KEYS) ?? automationName(processEnv, CI_ENV_KEYS);
257
+ if (ciName)
258
+ return status(false, `CI environment (${ciName})`);
259
+ const testName = automationName(env, TEST_ENV_KEYS) ??
260
+ automationName(processEnv, TEST_ENV_KEYS);
261
+ if (testName)
262
+ return status(false, `test environment (${testName})`);
263
+ if (sandboxedHome(env)) {
264
+ return status(false, "sandboxed home in the temp directory (harness run)");
265
+ }
266
+ if (preference === "enabled") {
267
+ return status(true, "enabled with `kibi telemetry enable`");
268
+ }
269
+ return status(true, "on by default; anonymous, opt-out");
270
+ }
271
+ // implements REQ-kibi-anonymous-usage-telemetry
272
+ export function telemetryEnabled(env = process.env) {
273
+ return telemetryStatus(env).enabled;
274
+ }
275
+ function telemetryKey(env) {
276
+ const override = env.KIBI_TELEMETRY_KEY;
277
+ return (override === undefined ? DEFAULT_TELEMETRY_KEY : override).trim();
278
+ }
279
+ function telemetryHost(env) {
280
+ return (env.KIBI_TELEMETRY_HOST?.trim() || DEFAULT_TELEMETRY_HOST).replace(/\/+$/, "");
281
+ }
282
+ function installId(env) {
283
+ const config = readTelemetryConfig(env);
284
+ if (typeof config.installId === "string" && config.installId !== "") {
285
+ return config.installId;
286
+ }
287
+ const created = randomUUID();
288
+ try {
289
+ writeTelemetryConfig({ ...config, installId: created }, env);
290
+ }
291
+ catch {
292
+ // An unwritable directory still lets this process send with a fresh id.
293
+ }
294
+ return created;
295
+ }
296
+ // implements REQ-kibi-anonymous-usage-telemetry
297
+ /** Stable one-way hash, so a session can be grouped without revealing its id. */
298
+ export function hashTelemetryId(value) {
299
+ return createHash("sha256")
300
+ .update("kibi-telemetry\0")
301
+ .update(value)
302
+ .digest("hex")
303
+ .slice(0, 16);
304
+ }
305
+ // implements REQ-kibi-anonymous-usage-telemetry
306
+ /**
307
+ * The notice users see before the first event is sent, or null once it was
308
+ * shown. Callers that can reach the user (CLI and MCP stderr) print it.
309
+ */
310
+ export function takeTelemetryNotice(env = process.env) {
311
+ if (!telemetryEnabled(env))
312
+ return null;
313
+ const config = readTelemetryConfig(env);
314
+ if (config.noticeShownAt)
315
+ return null;
316
+ try {
317
+ writeTelemetryConfig({ ...config, noticeShownAt: new Date().toISOString() }, env);
318
+ }
319
+ catch {
320
+ // Without a writable config the notice would repeat on every run.
321
+ return null;
322
+ }
323
+ return [
324
+ "Kibi collects anonymous usage statistics (operation names, durations, error categories and versions) to improve Kibi.",
325
+ "It never sends code, file paths, queries, KB content or repository names.",
326
+ `Turn it off with \`kibi telemetry disable\` or KIBI_TELEMETRY=0. Details: ${TELEMETRY_DOCS_URL}`,
327
+ ].join("\n");
328
+ }
329
+ function runtimeName() {
330
+ return typeof globalThis.Bun === "undefined"
331
+ ? "node"
332
+ : "bun";
333
+ }
334
+ function sessionMarkersPath(env) {
335
+ return path.join(telemetryDirectory(env), SESSIONS_FILE);
336
+ }
337
+ function readSessionMarkers(env) {
338
+ try {
339
+ const parsed = JSON.parse(fs.readFileSync(sessionMarkersPath(env), "utf8"));
340
+ return parsed !== null &&
341
+ typeof parsed === "object" &&
342
+ !Array.isArray(parsed)
343
+ ? parsed
344
+ : {};
345
+ }
346
+ catch {
347
+ return {};
348
+ }
349
+ }
350
+ function workspaceKey(workspaceRoot) {
351
+ return hashTelemetryId(`workspace\0${path.resolve(workspaceRoot)}`);
352
+ }
353
+ // implements REQ-kibi-anonymous-usage-telemetry
354
+ /**
355
+ * Remember which host session last ran a hook in a workspace. Every host
356
+ * hands its hooks the session id, but only some expose it to the CLI and MCP
357
+ * server through the environment. Only hashes are stored: of the workspace
358
+ * path and of the session id.
359
+ */
360
+ export function rememberHookSession(workspaceRoot, sessionId, env = process.env) {
361
+ if (!sessionId.trim() || !telemetryEnabled(env))
362
+ return;
363
+ const now = Date.now();
364
+ const markers = readSessionMarkers(env);
365
+ markers[workspaceKey(workspaceRoot)] = {
366
+ session: hashTelemetryId(sessionId.trim()),
367
+ at: now,
368
+ };
369
+ const kept = Object.entries(markers)
370
+ .filter(([, marker]) => typeof marker?.at === "number" &&
371
+ now - marker.at <= SESSION_MARKER_MAX_AGE_MS)
372
+ .sort(([, left], [, right]) => right.at - left.at)
373
+ .slice(0, MAX_SESSION_MARKERS);
374
+ try {
375
+ const file = sessionMarkersPath(env);
376
+ fs.mkdirSync(path.dirname(file), { recursive: true });
377
+ const temporary = `${file}.${process.pid}.${randomUUID()}.tmp`;
378
+ fs.writeFileSync(temporary, JSON.stringify(Object.fromEntries(kept)));
379
+ fs.renameSync(temporary, file);
380
+ }
381
+ catch {
382
+ // Telemetry is best effort and must never disturb the hook.
383
+ }
384
+ }
385
+ // implements REQ-kibi-anonymous-usage-telemetry
386
+ /**
387
+ * Hashed session a host hook recently reported for this directory or the
388
+ * nearest ancestor that has one, or undefined.
389
+ */
390
+ export function workspaceSessionHash(startDirectory, env = process.env) {
391
+ const markers = readSessionMarkers(env);
392
+ const now = Date.now();
393
+ let current = path.resolve(startDirectory);
394
+ for (;;) {
395
+ const marker = markers[workspaceKey(current)];
396
+ if (marker &&
397
+ typeof marker.session === "string" &&
398
+ typeof marker.at === "number" &&
399
+ now - marker.at <= SESSION_MARKER_MAX_AGE_MS) {
400
+ return marker.session;
401
+ }
402
+ const parent = path.dirname(current);
403
+ if (parent === current)
404
+ return undefined;
405
+ current = parent;
406
+ }
407
+ }
408
+ function sessionProperty(source, env) {
409
+ const sessionId = source.sessionId?.trim() || detectTelemetrySession(env);
410
+ if (sessionId)
411
+ return hashTelemetryId(sessionId);
412
+ return source.workspaceRoot
413
+ ? (workspaceSessionHash(source.workspaceRoot, env) ?? null)
414
+ : null;
415
+ }
416
+ function baseProperties(source, env) {
417
+ return {
418
+ distinct_id: installId(env),
419
+ $process_person_profile: false,
420
+ $geoip_disable: true,
421
+ $lib: "kibi",
422
+ package: source.packageName,
423
+ package_version: source.packageVersion ?? null,
424
+ host: (source.host?.trim() && hostKey(source.host)) ||
425
+ detectTelemetryHost(env) ||
426
+ "unknown",
427
+ remote: remoteEnvironment(env),
428
+ session: sessionProperty(source, env),
429
+ os: process.platform,
430
+ arch: process.arch,
431
+ runtime: runtimeName(),
432
+ runtime_version: process.versions.node.split(".")[0] ?? null,
433
+ };
434
+ }
435
+ function queuePath(env) {
436
+ return path.join(telemetryDirectory(env), QUEUE_FILE);
437
+ }
438
+ function appendEvent(event, env) {
439
+ try {
440
+ const file = queuePath(env);
441
+ fs.mkdirSync(path.dirname(file), { recursive: true });
442
+ try {
443
+ if (fs.statSync(file).size > MAX_QUEUE_BYTES)
444
+ return;
445
+ }
446
+ catch {
447
+ // No queue yet.
448
+ }
449
+ fs.appendFileSync(file, `${JSON.stringify(event)}\n`, "utf8");
450
+ }
451
+ catch {
452
+ // Telemetry is best effort and must never disturb the caller.
453
+ }
454
+ }
455
+ // implements REQ-kibi-anonymous-usage-telemetry
456
+ /**
457
+ * An error category as sent: fixed identifiers such as `tool_timeout` or
458
+ * `UPSERT_DRY_RUN_INVALID` pass, lower-cased; anything that looks like free
459
+ * text is replaced, so a message can never leak through this field.
460
+ */
461
+ export function telemetryCategory(value) {
462
+ const trimmed = value?.trim();
463
+ if (!trimmed)
464
+ return null;
465
+ return /^[A-Za-z0-9_.:+-]{1,160}$/.test(trimmed)
466
+ ? trimmed.toLowerCase()
467
+ : "unclassified";
468
+ }
469
+ // implements REQ-kibi-anonymous-usage-telemetry
470
+ export function recordOperationTelemetry(source, operation, env = process.env) {
471
+ if (!telemetryEnabled(env))
472
+ return;
473
+ appendEvent({
474
+ event: "kibi_operation",
475
+ timestamp: new Date().toISOString(),
476
+ properties: {
477
+ ...baseProperties(source, env),
478
+ interface: operation.interface,
479
+ operation: operation.operation,
480
+ status: operation.status,
481
+ duration_ms: Math.max(0, Math.round(operation.durationMs)),
482
+ error_category: telemetryCategory(operation.errorCategory),
483
+ exit_code: operation.exitCode ?? null,
484
+ },
485
+ }, env);
486
+ }
487
+ // implements REQ-kibi-anonymous-usage-telemetry
488
+ export function recordHookTelemetry(source, hook, env = process.env) {
489
+ if (!telemetryEnabled(env))
490
+ return;
491
+ appendEvent({
492
+ event: "kibi_hook",
493
+ timestamp: new Date().toISOString(),
494
+ properties: {
495
+ ...baseProperties(source, env),
496
+ hook_event: hook.hookEvent,
497
+ hook_action: hook.hookAction,
498
+ path_kind: hook.pathKind ?? null,
499
+ kb_operation: hook.kbOperation ?? null,
500
+ kb_used_before: hook.kbUsedBefore ?? null,
501
+ requirement_count: hook.requirementCount ?? null,
502
+ },
503
+ }, env);
504
+ }
505
+ // implements REQ-kibi-anonymous-usage-telemetry
506
+ export function clearTelemetryQueue(env = process.env) {
507
+ const directory = telemetryDirectory(env);
508
+ let names;
509
+ try {
510
+ names = fs.readdirSync(directory);
511
+ }
512
+ catch {
513
+ return;
514
+ }
515
+ for (const name of names) {
516
+ if (name === QUEUE_FILE ||
517
+ name === SESSIONS_FILE ||
518
+ name.endsWith(SENDING_SUFFIX)) {
519
+ fs.rmSync(path.join(directory, name), { force: true });
520
+ }
521
+ }
522
+ }
523
+ function parseQueued(text, now) {
524
+ const events = [];
525
+ for (const line of text.split("\n")) {
526
+ if (line.trim() === "")
527
+ continue;
528
+ try {
529
+ const event = JSON.parse(line);
530
+ const age = now - Date.parse(event.timestamp);
531
+ if (Number.isFinite(age) && age <= MAX_EVENT_AGE_MS)
532
+ events.push(event);
533
+ }
534
+ catch {
535
+ // A torn line from a crashed writer is dropped.
536
+ }
537
+ }
538
+ return events;
539
+ }
540
+ function flushDue(file, now) {
541
+ let text;
542
+ try {
543
+ text = fs.readFileSync(file, "utf8");
544
+ }
545
+ catch {
546
+ return false;
547
+ }
548
+ const lines = text.split("\n").filter((line) => line.trim() !== "");
549
+ if (lines.length === 0)
550
+ return false;
551
+ if (lines.length >= FLUSH_BATCH_EVENTS)
552
+ return true;
553
+ try {
554
+ const first = JSON.parse(lines[0] ?? "");
555
+ return now - Date.parse(first.timestamp) >= FLUSH_MAX_AGE_MS;
556
+ }
557
+ catch {
558
+ return true;
559
+ }
560
+ }
561
+ /** Atomically take the queue and any batch a dead process left behind. */
562
+ function claimBatches(directory, now) {
563
+ const claimed = [];
564
+ let names;
565
+ try {
566
+ names = fs.readdirSync(directory);
567
+ }
568
+ catch {
569
+ return claimed;
570
+ }
571
+ for (const name of names) {
572
+ if (!name.endsWith(SENDING_SUFFIX))
573
+ continue;
574
+ const file = path.join(directory, name);
575
+ try {
576
+ if (now - fs.statSync(file).mtimeMs < STALE_CLAIM_MS)
577
+ continue;
578
+ const reclaimed = `${file}.${randomUUID()}${SENDING_SUFFIX}`;
579
+ fs.renameSync(file, reclaimed);
580
+ claimed.push(reclaimed);
581
+ }
582
+ catch {
583
+ // Another process reclaimed it first.
584
+ }
585
+ }
586
+ const queue = path.join(directory, QUEUE_FILE);
587
+ const target = path.join(directory, `${QUEUE_FILE}.${process.pid}.${randomUUID()}${SENDING_SUFFIX}`);
588
+ try {
589
+ fs.renameSync(queue, target);
590
+ claimed.push(target);
591
+ }
592
+ catch {
593
+ // Nothing queued, or another process is sending it.
594
+ }
595
+ return claimed;
596
+ }
597
+ // implements REQ-kibi-anonymous-usage-telemetry
598
+ /**
599
+ * Send queued events in one batch when a flush is due (or forced). Returns
600
+ * the number of events sent. A failed send puts the events back for the next
601
+ * flush; nothing here throws.
602
+ */
603
+ export async function flushTelemetry(options = {}, env = process.env) {
604
+ if (!telemetryEnabled(env))
605
+ return 0;
606
+ const directory = telemetryDirectory(env);
607
+ const now = Date.now();
608
+ if (!options.force && !flushDue(queuePath(env), now))
609
+ return 0;
610
+ const claimed = claimBatches(directory, now);
611
+ if (claimed.length === 0)
612
+ return 0;
613
+ const events = [];
614
+ for (const file of claimed) {
615
+ try {
616
+ events.push(...parseQueued(fs.readFileSync(file, "utf8"), now));
617
+ }
618
+ catch {
619
+ // Unreadable batch: drop it.
620
+ }
621
+ }
622
+ const release = () => {
623
+ for (const file of claimed)
624
+ fs.rmSync(file, { force: true });
625
+ };
626
+ if (events.length === 0) {
627
+ release();
628
+ return 0;
629
+ }
630
+ const fetchImpl = options.fetchImpl ?? globalThis.fetch;
631
+ const controller = new AbortController();
632
+ const timer = setTimeout(() => controller.abort(), options.timeoutMs ?? DEFAULT_FLUSH_TIMEOUT_MS);
633
+ timer.unref?.();
634
+ try {
635
+ const response = await fetchImpl(`${telemetryHost(env)}/batch/`, {
636
+ method: "POST",
637
+ headers: { "content-type": "application/json" },
638
+ body: JSON.stringify({
639
+ api_key: telemetryKey(env),
640
+ historical_migration: false,
641
+ batch: events,
642
+ }),
643
+ signal: controller.signal,
644
+ });
645
+ // A 4xx means PostHog will never accept this batch; drop it.
646
+ if (!response.ok && response.status >= 500)
647
+ throw new Error("retry");
648
+ release();
649
+ return response.ok ? events.length : 0;
650
+ }
651
+ catch {
652
+ release();
653
+ for (const event of events)
654
+ appendEvent(event, env);
655
+ return 0;
656
+ }
657
+ finally {
658
+ clearTimeout(timer);
659
+ }
660
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "kibi-agent-core",
3
- "version": "0.9.1",
3
+ "version": "0.11.0",
4
4
  "description": "Shared low-latency hook helpers for Kibi agent adapters",
5
5
  "type": "module",
6
6
  "main": "./dist/index.js",
@@ -34,6 +34,10 @@
34
34
  "types": "./dist/requirement-candidates.d.ts",
35
35
  "default": "./dist/requirement-candidates.js"
36
36
  },
37
+ "./usage-telemetry": {
38
+ "types": "./dist/usage-telemetry.d.ts",
39
+ "default": "./dist/usage-telemetry.js"
40
+ },
37
41
  "./snippets": {
38
42
  "types": "./dist/snippets.d.ts",
39
43
  "default": "./dist/snippets.js"