pi-context-kit 0.3.1 → 0.4.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.
@@ -0,0 +1,153 @@
1
+ import {
2
+ chmodSync,
3
+ existsSync,
4
+ linkSync,
5
+ mkdirSync,
6
+ readFileSync,
7
+ realpathSync,
8
+ renameSync,
9
+ rmSync,
10
+ statSync,
11
+ writeFileSync,
12
+ } from "node:fs";
13
+ import { dirname, join } from "node:path";
14
+ import { isRecord } from "./config.ts";
15
+
16
+ const FILE_NAME = "context-kit.json";
17
+
18
+ export interface SettingsPaths {
19
+ global: string;
20
+ /** Undefined in an untrusted project, as Pi does for its own project settings. */
21
+ project: string | undefined;
22
+ }
23
+
24
+ export function settingsPaths(
25
+ agentDir: string,
26
+ cwd: string,
27
+ trusted: boolean,
28
+ ): SettingsPaths {
29
+ return {
30
+ global: join(agentDir, FILE_NAME),
31
+ project: trusted ? join(cwd, ".pi", FILE_NAME) : undefined,
32
+ };
33
+ }
34
+
35
+ /** Merges the global and project files. A file that cannot be read is reported and ignored. */
36
+ export function loadSettings(paths: SettingsPaths): {
37
+ raw: Record<string, unknown>;
38
+ problems: string[];
39
+ } {
40
+ const problems: string[] = [];
41
+ let raw: Record<string, unknown> = {};
42
+ for (const path of [paths.global, paths.project]) {
43
+ if (!path) continue;
44
+ try {
45
+ raw = mergeSettings(raw, readSettingsFile(path));
46
+ } catch (error) {
47
+ problems.push(`${errorMessage(error)}, file ignored`);
48
+ }
49
+ }
50
+ return { raw, problems };
51
+ }
52
+
53
+ /** Sets one top-level key and keeps the rest of the file. The file is replaced atomically. */
54
+ export function updateSetting(path: string, key: string, value: unknown) {
55
+ const next = { ...readSettingsFile(path), [key]: value };
56
+ // The rename replaces the target, so a symbolic link, for example to dotfiles, stays.
57
+ const target = existsSync(path) ? realpathSync(path) : path;
58
+ mkdirSync(dirname(target), { recursive: true });
59
+ const temporary = `${target}.${process.pid}.tmp`;
60
+ try {
61
+ writeFileSync(temporary, `${JSON.stringify(next, null, 2)}\n`);
62
+ if (existsSync(target)) chmodSync(temporary, statSync(target).mode);
63
+ renameSync(temporary, target);
64
+ } finally {
65
+ rmSync(temporary, { force: true });
66
+ }
67
+ }
68
+
69
+ /** Creates the file with this content. Returns false when the file exists, which it keeps. */
70
+ export function createSettings(
71
+ path: string,
72
+ content: Record<string, unknown>,
73
+ ): boolean {
74
+ mkdirSync(dirname(path), { recursive: true });
75
+ const temporary = `${path}.${process.pid}.tmp`;
76
+ try {
77
+ writeFileSync(temporary, `${JSON.stringify(content, null, 2)}\n`);
78
+ // The link appears complete or not at all, and fails when the file exists, so two Pi
79
+ // processes cannot both create it.
80
+ linkSync(temporary, path);
81
+ return true;
82
+ } catch (error) {
83
+ if (isRecord(error) && error.code === "EEXIST") return false;
84
+ throw error;
85
+ } finally {
86
+ rmSync(temporary, { force: true });
87
+ }
88
+ }
89
+
90
+ /**
91
+ * Writes the key where it takes effect: the project file when that file sets it, otherwise the
92
+ * global file. Returns the path written.
93
+ */
94
+ export function saveSetting(
95
+ paths: SettingsPaths,
96
+ key: string,
97
+ value: unknown,
98
+ ): string {
99
+ const path =
100
+ paths.project && readSettingsFile(paths.project)[key] !== undefined
101
+ ? paths.project
102
+ : paths.global;
103
+ updateSetting(path, key, value);
104
+ return path;
105
+ }
106
+
107
+ /** The content of one settings file, `{}` when it does not exist. Throws when it is not a JSON object. */
108
+ export function readSettingsFile(path: string): Record<string, unknown> {
109
+ let text: string;
110
+ try {
111
+ text = readFileSync(path, "utf8");
112
+ } catch (error) {
113
+ if (isRecord(error) && error.code === "ENOENT") return {};
114
+ throw new Error(`${path} cannot be read (${errorMessage(error)})`);
115
+ }
116
+ let value: unknown;
117
+ try {
118
+ value = JSON.parse(text);
119
+ } catch (error) {
120
+ throw new Error(`${path} is not valid JSON (${errorMessage(error)})`);
121
+ }
122
+ if (!isRecord(value)) throw new Error(`${path} must contain a JSON object`);
123
+ return value;
124
+ }
125
+
126
+ /**
127
+ * Merges `over` into `base` like Pi merges project settings over global ones: objects merge key by
128
+ * key; any other value, including a list, replaces the base value.
129
+ */
130
+ export function mergeSettings(
131
+ base: Record<string, unknown>,
132
+ over: Record<string, unknown>,
133
+ ): Record<string, unknown> {
134
+ const result = { ...base };
135
+ for (const [key, value] of Object.entries(over)) {
136
+ const current = result[key];
137
+ // A plain assignment of "__proto__" would set the prototype instead of a key.
138
+ Object.defineProperty(result, key, {
139
+ value:
140
+ isRecord(current) && isRecord(value)
141
+ ? mergeSettings(current, value)
142
+ : value,
143
+ enumerable: true,
144
+ writable: true,
145
+ configurable: true,
146
+ });
147
+ }
148
+ return result;
149
+ }
150
+
151
+ function errorMessage(error: unknown): string {
152
+ return error instanceof Error ? error.message : String(error);
153
+ }
package/src/status.ts ADDED
@@ -0,0 +1,41 @@
1
+ const NOTE_LABEL = {
2
+ writing: "writing summary",
3
+ ready: "summary ready",
4
+ } as const;
5
+
6
+ export interface StatusInput {
7
+ tokens: number;
8
+ /** Where compaction starts, or +Infinity when nothing compacts. */
9
+ limit: number;
10
+ contextWindow: number;
11
+ note?: keyof typeof NOTE_LABEL;
12
+ }
13
+
14
+ /** The footer text: context use and threshold as shares of the window, then the background note. */
15
+ export function statusText(input: StatusInput): string {
16
+ const share = (tokens: number) => percent(tokens, input.contextWindow);
17
+ const limit = Number.isFinite(input.limit)
18
+ ? `cleanup at ${share(input.limit)}`
19
+ : "no automatic cleanup";
20
+ const note = input.note ? ` · ${NOTE_LABEL[input.note]}` : "";
21
+ return `Context ${share(input.tokens)} · ${limit}${note}`;
22
+ }
23
+
24
+ /** The notice after context edits, which Pi does not show by itself. */
25
+ export function freedNotice(
26
+ before: number,
27
+ after: number,
28
+ contextWindow: number,
29
+ ): string {
30
+ const freed = before - after;
31
+ return `pi-context-kit freed ${percent(freed, contextWindow)} of the context (${tokenCount(freed)} tokens). The agent can still look up what was removed.`;
32
+ }
33
+
34
+ /** Rounded down, so 100% means the window is full. */
35
+ function percent(tokens: number, contextWindow: number): string {
36
+ return `${Math.floor((tokens * 100) / contextWindow)}%`;
37
+ }
38
+
39
+ function tokenCount(tokens: number): string {
40
+ return tokens >= 1_000 ? `${Math.round(tokens / 1_000)}k` : String(tokens);
41
+ }