pi-reasoning-zip 0.2.0 → 0.2.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/CHANGELOG.md CHANGED
@@ -7,6 +7,12 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
7
7
 
8
8
  ## [Unreleased]
9
9
 
10
+ ## [0.2.1] - 2026-07-02
11
+
12
+ ### Changed
13
+
14
+ - Pi package metadata now loads readable source from `./extensions` and ships `src` for transparency.
15
+
10
16
  ## [0.2.0] - 2026-07-02
11
17
 
12
18
  ### Added
@@ -39,6 +45,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
39
45
  - Added package motto to README.
40
46
  - Added npm release metadata: description, keywords, repository links, exports, and Node engine.
41
47
 
42
- [Unreleased]: https://github.com/Ryu-CZ/pi-reasoning-zip/compare/v0.2.0...HEAD
48
+ [Unreleased]: https://github.com/Ryu-CZ/pi-reasoning-zip/compare/v0.2.1...HEAD
49
+ [0.2.1]: https://github.com/Ryu-CZ/pi-reasoning-zip/compare/v0.2.0...v0.2.1
43
50
  [0.2.0]: https://github.com/Ryu-CZ/pi-reasoning-zip/compare/v0.1.0...v0.2.0
44
51
  [0.1.0]: https://github.com/Ryu-CZ/pi-reasoning-zip/releases/tag/v0.1.0
package/README.md CHANGED
@@ -44,13 +44,14 @@ npm run check
44
44
  npm run smoke
45
45
  ```
46
46
 
47
- For local development you can also load the built extension directly:
47
+ For local development you can also load the readable source extension directly:
48
48
 
49
49
  ```bash
50
- npm run build
51
- pi -e ./dist/index.js
50
+ pi -e ./extensions
52
51
  ```
53
52
 
53
+ The npm library entrypoint still builds to `dist/index.js`, but Pi package metadata points at `./extensions` so Pi can inspect the source it loads.
54
+
54
55
  ## Features
55
56
 
56
57
  - **Forward-only compaction** — modifies only the new assistant message being finalized.
@@ -188,6 +189,7 @@ npm test
188
189
  npm run build
189
190
  npm run check
190
191
  npm run smoke
192
+ pi -e ./extensions --no-extensions --offline --list-models
191
193
  npm pack --dry-run
192
194
  ```
193
195
 
@@ -220,11 +222,12 @@ npm pack --dry-run
220
222
  [0.1.0]: https://github.com/Ryu-CZ/pi-reasoning-zip/releases/tag/v0.1.0
221
223
  ```
222
224
 
223
- 4. Verify build, smoke test, package contents, and npm publish metadata.
225
+ 4. Verify build, source-extension load, smoke test, package contents, and npm publish metadata.
224
226
 
225
227
  ```bash
226
228
  npm run check
227
229
  npm run smoke
230
+ pi -e ./extensions --no-extensions --offline --list-models
228
231
  npm pack --dry-run
229
232
  npm publish --dry-run
230
233
  ```
@@ -0,0 +1,3 @@
1
+ // Source entrypoint for Pi package loading.
2
+ // The npm library entrypoint remains dist/index.js, but Pi loads this readable source path.
3
+ export { default } from "../src/index.ts";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "pi-reasoning-zip",
3
- "version": "0.2.0",
3
+ "version": "0.2.1",
4
4
  "private": false,
5
5
  "description": "Compact reasoning blocks to keep the context short.",
6
6
  "license": "MIT",
@@ -10,6 +10,8 @@
10
10
  "types": "dist/index.d.ts",
11
11
  "files": [
12
12
  "dist",
13
+ "src",
14
+ "extensions",
13
15
  "scripts/smoke-extension.mjs",
14
16
  "README.md",
15
17
  "CHANGELOG.md",
@@ -57,7 +59,7 @@
57
59
  },
58
60
  "pi": {
59
61
  "extensions": [
60
- "dist/index.js"
62
+ "./extensions"
61
63
  ],
62
64
  "image": "https://raw.githubusercontent.com/Ryu-CZ/pi-reasoning-zip/main/media/banner.webp"
63
65
  },
@@ -0,0 +1,12 @@
1
+ export function buildCompactionPrompt(thinking: string): string {
2
+ return `Compress this model reasoning into a compact decision trace for future coding-agent context.
3
+
4
+ Keep exact paths, commands, symbols, errors, decisions, constraints, failed attempts, and next actions.
5
+ Drop self-talk, repeated planning, obvious reasoning, filler, and prose.
6
+ Use terse bullets under: facts, decisions, constraints, failed, next.
7
+ Target 10-20% of original length.
8
+ If no useful content remains, output exactly: none
9
+
10
+ Reasoning:
11
+ ${thinking}`;
12
+ }
@@ -0,0 +1,34 @@
1
+ import { buildCompactionPrompt } from "./compactPrompt.js";
2
+ import type { ReasoningZipSettings } from "./types.js";
3
+
4
+ export async function compactWithOpenAI(thinking: string, settings: ReasoningZipSettings): Promise<string> {
5
+ const controller = new AbortController();
6
+ const timeout = setTimeout(() => controller.abort(), settings.compactor.timeoutMs);
7
+ try {
8
+ const response = await fetch(`${settings.compactor.baseUrl}/chat/completions`, {
9
+ method: "POST",
10
+ headers: {
11
+ "content-type": "application/json",
12
+ authorization: `Bearer ${settings.compactor.apiKey}`,
13
+ },
14
+ body: JSON.stringify({
15
+ model: settings.compactor.model,
16
+ messages: [
17
+ { role: "system", content: "You compress reasoning traces. Output only compact trace." },
18
+ { role: "user", content: buildCompactionPrompt(thinking) },
19
+ ],
20
+ max_tokens: settings.compactor.maxTokens,
21
+ temperature: settings.compactor.temperature,
22
+ }),
23
+ signal: controller.signal,
24
+ });
25
+
26
+ if (!response.ok) throw new Error(`Compactor HTTP ${response.status}`);
27
+ const json = (await response.json()) as { choices?: Array<{ message?: { content?: unknown } }> };
28
+ const content = json.choices?.[0]?.message?.content;
29
+ if (typeof content !== "string") throw new Error("Compactor response missing message content");
30
+ return content.trim();
31
+ } finally {
32
+ clearTimeout(timeout);
33
+ }
34
+ }
package/src/index.ts ADDED
@@ -0,0 +1,54 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import { readFileSync } from "node:fs";
3
+ import { homedir } from "node:os";
4
+ import { join } from "node:path";
5
+ import { compactWithOpenAI } from "./compactorClient.js";
6
+ import { compactAssistantMessage } from "./messageTransform.js";
7
+ import { injectReasoningZipPrompt } from "./promptInjection.js";
8
+ import { resolveReasoningZipSettings } from "./settings.js";
9
+
10
+ function globalSettingsPath(): string {
11
+ return join(process.env.PI_CODING_AGENT_DIR ?? join(homedir(), ".pi", "agent"), "settings.json");
12
+ }
13
+
14
+ function projectSettingsPath(cwd: string | undefined): string | undefined {
15
+ return cwd ? join(cwd, ".pi", "settings.json") : undefined;
16
+ }
17
+
18
+ function readSettingsSection(path: string | undefined): unknown {
19
+ if (!path) return undefined;
20
+ try {
21
+ const parsed = JSON.parse(readFileSync(path, "utf8")) as { reasoningZip?: unknown };
22
+ return parsed.reasoningZip;
23
+ } catch {
24
+ return undefined;
25
+ }
26
+ }
27
+
28
+ function readRawSettings(cwd: string | undefined): unknown {
29
+ return readSettingsSection(projectSettingsPath(cwd)) ?? readSettingsSection(globalSettingsPath());
30
+ }
31
+
32
+ function eventProvider(event: Record<string, unknown>): string | undefined {
33
+ const message = event.message as { provider?: unknown } | undefined;
34
+ if (typeof message?.provider === "string") return message.provider;
35
+ if (typeof event.provider === "string") return event.provider;
36
+ return undefined;
37
+ }
38
+
39
+ export default function reasoningZipExtension(pi: ExtensionAPI) {
40
+ const extension = pi as any;
41
+
42
+ extension.on("message_end", async (event: any, ctx: any) => {
43
+ const settings = resolveReasoningZipSettings(readRawSettings(ctx?.cwd));
44
+ const result = await compactAssistantMessage(event.message, settings, (thinking) => compactWithOpenAI(thinking, settings));
45
+ if (result.changed) return { message: result.message };
46
+ return undefined;
47
+ });
48
+
49
+ extension.on("before_provider_request", (event: any, ctx: any) => {
50
+ const settings = resolveReasoningZipSettings(readRawSettings(ctx?.cwd));
51
+ const nextPayload = injectReasoningZipPrompt(event.payload, eventProvider(event), settings);
52
+ return nextPayload === event.payload ? undefined : nextPayload;
53
+ });
54
+ }
@@ -0,0 +1,59 @@
1
+ import type { PiMessage, PiMessageBlock, ReasoningZipSettings } from "./types.js";
2
+ import { shouldHandleMessage } from "./target.js";
3
+
4
+ export type CompactText = (thinking: string) => Promise<string>;
5
+
6
+ function isThinkingBlock(block: PiMessageBlock): block is PiMessageBlock & { thinking: string } {
7
+ return block.type === "thinking" && typeof block.thinking === "string";
8
+ }
9
+
10
+ function hasOpaqueReasoningMetadata(block: PiMessageBlock): boolean {
11
+ return (
12
+ typeof block.signature === "string" ||
13
+ typeof block.reasoning_signature === "string" ||
14
+ typeof block.encrypted_content === "string" ||
15
+ Array.isArray(block.reasoning_details)
16
+ );
17
+ }
18
+
19
+ function acceptableCompaction(original: string, compacted: string, settings: ReasoningZipSettings): string | undefined {
20
+ const text = compacted.trim();
21
+ if (!text || text === "none") return undefined;
22
+ if (text.length >= original.length) return undefined;
23
+ if (text.length > settings.thresholds.maxTraceChars) return undefined;
24
+ return text;
25
+ }
26
+
27
+ export async function compactAssistantMessage(
28
+ message: PiMessage,
29
+ settings: ReasoningZipSettings,
30
+ compactText: CompactText,
31
+ ): Promise<{ message: PiMessage; changed: boolean }> {
32
+ if (!shouldHandleMessage(message, settings)) return { message, changed: false };
33
+ if (!Array.isArray(message.content)) return { message, changed: false };
34
+
35
+ let changed = false;
36
+ const nextContent: PiMessageBlock[] = [];
37
+
38
+ for (const block of message.content) {
39
+ if (!isThinkingBlock(block) || hasOpaqueReasoningMetadata(block) || block.thinking.length < settings.thresholds.minChars) {
40
+ nextContent.push(block);
41
+ continue;
42
+ }
43
+
44
+ try {
45
+ const compacted = acceptableCompaction(block.thinking, await compactText(block.thinking), settings);
46
+ if (!compacted) {
47
+ nextContent.push(block);
48
+ continue;
49
+ }
50
+ nextContent.push({ ...block, thinking: compacted });
51
+ changed = true;
52
+ } catch {
53
+ nextContent.push(block);
54
+ }
55
+ }
56
+
57
+ if (!changed) return { message, changed: false };
58
+ return { message: { ...message, content: nextContent }, changed: true };
59
+ }
@@ -0,0 +1,43 @@
1
+ import { shouldTargetProvider } from "./target.js";
2
+ import type { ReasoningZipSettings } from "./types.js";
3
+
4
+ export const PROMPT_MARKER = "<!-- pi-reasoning-zip -->";
5
+ export const PROMPT_INJECTION = `${PROMPT_MARKER}\nYou are Grug. Save token, save world.\nVisible reasoning: terse, keyword-heavy trace only. Keep facts, decisions, constraints, failed paths, next action. No prose reasoning, no self-talk.\nFinal answer: no conversational fluff, no repeated question, minimal markdown. If code is enough, give only code. Think hard, output few tokens.`;
6
+
7
+ type ChatMessage = { role?: unknown; content?: unknown; [key: string]: unknown };
8
+
9
+ type Payload = { messages?: unknown; [key: string]: unknown };
10
+
11
+ function appendToContent(content: unknown): unknown {
12
+ if (typeof content === "string") {
13
+ if (content.includes(PROMPT_MARKER)) return content;
14
+ return `${content}\n\n${PROMPT_INJECTION}`;
15
+ }
16
+ if (Array.isArray(content)) {
17
+ if (content.some((part) => typeof part === "object" && part && "text" in part && typeof part.text === "string" && part.text.includes(PROMPT_MARKER))) {
18
+ return content;
19
+ }
20
+ return [...content, { type: "text", text: PROMPT_INJECTION }];
21
+ }
22
+ return content;
23
+ }
24
+
25
+ export function injectReasoningZipPrompt(payload: unknown, provider: string | undefined, settings: ReasoningZipSettings): unknown {
26
+ if (!settings.injectPrompt || !shouldTargetProvider(provider, settings)) return payload;
27
+ if (!payload || typeof payload !== "object") return payload;
28
+ const typed = payload as Payload;
29
+ if (!Array.isArray(typed.messages)) return payload;
30
+
31
+ const messages = typed.messages as ChatMessage[];
32
+ const existing = JSON.stringify(messages).includes(PROMPT_MARKER);
33
+ if (existing) return payload;
34
+
35
+ const index = messages.findIndex((message) => message.role === "system" || message.role === "developer");
36
+ if (index >= 0) {
37
+ const nextMessages = messages.slice();
38
+ nextMessages[index] = { ...messages[index], content: appendToContent(messages[index].content) };
39
+ return { ...typed, messages: nextMessages };
40
+ }
41
+
42
+ return { ...typed, messages: [{ role: "system", content: PROMPT_INJECTION }, ...messages] };
43
+ }
@@ -0,0 +1,71 @@
1
+ import type { ReasoningZipMode, ReasoningZipSettings, ReasoningZipStorageMode } from "./types.js";
2
+
3
+ export const DEFAULT_SETTINGS: ReasoningZipSettings = {
4
+ enabled: true,
5
+ mode: "llama-only",
6
+ storageMode: "compact-new",
7
+ injectPrompt: true,
8
+ compactor: {
9
+ baseUrl: "http://127.0.0.1:7484/v1",
10
+ model: "unsloth",
11
+ apiKey: "sk-placeholder",
12
+ maxTokens: 512,
13
+ temperature: 0.1,
14
+ timeoutMs: 30000,
15
+ },
16
+ thresholds: {
17
+ minChars: 1000,
18
+ targetRatio: 0.15,
19
+ maxTraceChars: 2000,
20
+ },
21
+ };
22
+
23
+ const modes = new Set<ReasoningZipMode>(["llama-only", "local-only", "all", "disabled"]);
24
+ const storageModes = new Set<ReasoningZipStorageMode>(["compact-new", "off"]);
25
+
26
+ function asObject(value: unknown): Record<string, unknown> {
27
+ return value && typeof value === "object" && !Array.isArray(value) ? (value as Record<string, unknown>) : {};
28
+ }
29
+
30
+ function stringValue(value: unknown, fallback: string): string {
31
+ return typeof value === "string" && value.length > 0 ? value : fallback;
32
+ }
33
+
34
+ function booleanValue(value: unknown, fallback: boolean): boolean {
35
+ return typeof value === "boolean" ? value : fallback;
36
+ }
37
+
38
+ function numberValue(value: unknown, fallback: number, min = 0): number {
39
+ return typeof value === "number" && Number.isFinite(value) && value >= min ? value : fallback;
40
+ }
41
+
42
+ export function resolveReasoningZipSettings(input: unknown): ReasoningZipSettings {
43
+ const root = asObject(input);
44
+ const compactor = asObject(root.compactor);
45
+ const thresholds = asObject(root.thresholds);
46
+
47
+ const mode = modes.has(root.mode as ReasoningZipMode) ? (root.mode as ReasoningZipMode) : DEFAULT_SETTINGS.mode;
48
+ const storageMode = storageModes.has(root.storageMode as ReasoningZipStorageMode)
49
+ ? (root.storageMode as ReasoningZipStorageMode)
50
+ : DEFAULT_SETTINGS.storageMode;
51
+
52
+ return {
53
+ enabled: booleanValue(root.enabled, DEFAULT_SETTINGS.enabled),
54
+ mode,
55
+ storageMode,
56
+ injectPrompt: booleanValue(root.injectPrompt, DEFAULT_SETTINGS.injectPrompt),
57
+ compactor: {
58
+ baseUrl: stringValue(compactor.baseUrl, DEFAULT_SETTINGS.compactor.baseUrl).replace(/\/$/, ""),
59
+ model: stringValue(compactor.model, DEFAULT_SETTINGS.compactor.model),
60
+ apiKey: stringValue(compactor.apiKey, DEFAULT_SETTINGS.compactor.apiKey),
61
+ maxTokens: numberValue(compactor.maxTokens, DEFAULT_SETTINGS.compactor.maxTokens, 1),
62
+ temperature: numberValue(compactor.temperature, DEFAULT_SETTINGS.compactor.temperature, 0),
63
+ timeoutMs: numberValue(compactor.timeoutMs, DEFAULT_SETTINGS.compactor.timeoutMs, 1),
64
+ },
65
+ thresholds: {
66
+ minChars: numberValue(thresholds.minChars, DEFAULT_SETTINGS.thresholds.minChars, 0),
67
+ targetRatio: numberValue(thresholds.targetRatio, DEFAULT_SETTINGS.thresholds.targetRatio, 0),
68
+ maxTraceChars: numberValue(thresholds.maxTraceChars, DEFAULT_SETTINGS.thresholds.maxTraceChars, 1),
69
+ },
70
+ };
71
+ }
package/src/target.ts ADDED
@@ -0,0 +1,36 @@
1
+ import type { PiMessage, ReasoningZipSettings } from "./types.js";
2
+
3
+ export function isLlamaProvider(providerId: string | undefined): boolean {
4
+ if (!providerId) return false;
5
+ const id = providerId.toLowerCase();
6
+ return id.startsWith("llama-server=") || id.includes("llama.cpp") || id.includes("llamacpp");
7
+ }
8
+
9
+ export function isLocalUrl(value: string | undefined): boolean {
10
+ if (!value) return false;
11
+ try {
12
+ const url = new URL(value.includes("://") ? value : `http://${value}`);
13
+ return ["127.0.0.1", "localhost", "::1", "0.0.0.0"].includes(url.hostname);
14
+ } catch {
15
+ return false;
16
+ }
17
+ }
18
+
19
+ export function shouldHandleMessage(message: PiMessage, settings: ReasoningZipSettings): boolean {
20
+ if (!settings.enabled || settings.mode === "disabled" || settings.storageMode !== "compact-new") return false;
21
+ if (message.role !== "assistant") return false;
22
+
23
+ const provider = typeof message.provider === "string" ? message.provider : undefined;
24
+ if (settings.mode === "all") return true;
25
+ if (settings.mode === "llama-only") return isLlamaProvider(provider);
26
+ if (settings.mode === "local-only") return isLocalUrl(provider) || isLlamaProvider(provider);
27
+ return false;
28
+ }
29
+
30
+ export function shouldTargetProvider(provider: string | undefined, settings: ReasoningZipSettings): boolean {
31
+ if (!settings.enabled || settings.mode === "disabled") return false;
32
+ if (settings.mode === "all") return true;
33
+ if (settings.mode === "llama-only") return isLlamaProvider(provider);
34
+ if (settings.mode === "local-only") return isLocalUrl(provider) || isLlamaProvider(provider);
35
+ return false;
36
+ }
package/src/types.ts ADDED
@@ -0,0 +1,38 @@
1
+ export type ReasoningZipMode = "llama-only" | "local-only" | "all" | "disabled";
2
+ export type ReasoningZipStorageMode = "compact-new" | "off";
3
+
4
+ export interface ReasoningZipSettings {
5
+ enabled: boolean;
6
+ mode: ReasoningZipMode;
7
+ storageMode: ReasoningZipStorageMode;
8
+ injectPrompt: boolean;
9
+ compactor: {
10
+ baseUrl: string;
11
+ model: string;
12
+ apiKey: string;
13
+ maxTokens: number;
14
+ temperature: number;
15
+ timeoutMs: number;
16
+ };
17
+ thresholds: {
18
+ minChars: number;
19
+ targetRatio: number;
20
+ maxTraceChars: number;
21
+ };
22
+ }
23
+
24
+ export interface PiMessageBlock {
25
+ type?: string;
26
+ text?: string;
27
+ thinking?: string;
28
+ [key: string]: unknown;
29
+ }
30
+
31
+ export interface PiMessage {
32
+ role?: string;
33
+ content?: string | PiMessageBlock[];
34
+ provider?: string;
35
+ model?: string;
36
+ api?: string;
37
+ [key: string]: unknown;
38
+ }