@rackrot/pi-core 0.0.1 → 0.1.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/README.md CHANGED
@@ -1 +1,47 @@
1
- Placeholder. See https://github.com/rackrot/pi-tools
1
+ # @rackrot/pi-core
2
+
3
+ The core rackrot extension, plus shared code for the other `@rackrot/pi-*` packages.
4
+
5
+ ```bash
6
+ pi install npm:@rackrot/pi-core
7
+ ```
8
+
9
+ Install this one everywhere. It is where always-on behavior goes.
10
+
11
+ ## Features
12
+
13
+ ### Anthropic thinking-block binding
14
+
15
+ Anthropic ties each thinking-block signature to the `system` prompt, `tools` and earlier messages that
16
+ produced it. When that prefix changes (an extension edits a tool description, or pi restarts into an old
17
+ session) every earlier block is dropped server-side on every later turn, and pi reports
18
+ `Anthropic dropped N thinking blocks: prefix_binding_mismatch` for the rest of the session.
19
+
20
+ The extension fingerprints `system` + `tools` on each Anthropic request. When the fingerprint changes it
21
+ strips thinking from the replayed history once, records a cutoff in the session, and keeps stripping
22
+ anything at or before it. Cases the fingerprint can't see (already-broken sessions, rewritten history) are
23
+ caught from Anthropic's own `prefix_binding_mismatch` diagnostic, costing one warning instead of one per
24
+ turn. Only `anthropic-messages` models are touched; session files keep the original blocks; there is no
25
+ configuration. A message that is only thinking is left as is.
26
+
27
+ Adapted from [luan/agents `pi-thinking-binding`](https://github.com/luan/agents/tree/main/harnesses/pi/agent/packages/pi-thinking-binding) (MIT).
28
+ Uninstall that package if you have it, or both will act.
29
+
30
+ ## Shared utilities
31
+
32
+ Other packages in this repo depend on it (`"@rackrot/pi-core": "workspace:*"` in `dependencies`):
33
+
34
+ ```ts
35
+ import { readJson, writeJsonAtomic, readSettingsLayers } from "@rackrot/pi-core";
36
+ // or: "@rackrot/pi-core/json", "@rackrot/pi-core/settings", "@rackrot/pi-core/thinking-binding"
37
+ ```
38
+
39
+ | Export | Purpose |
40
+ | ------------------------------ | ----------------------------------------------------------------- |
41
+ | `readJson(path)` | Read a JSON object; `{}` if missing or invalid |
42
+ | `readJsonStrict(path)` | Same, but throws on bad content and returns the file's indent |
43
+ | `writeJsonAtomic(path, data)` | Write via temp file + rename, creating parent dirs |
44
+ | `settingsPaths(cwd)` | Global and project `settings.json` paths, lowest precedence first |
45
+ | `readSettingsLayers(key, cwd)` | One settings key from each layer |
46
+
47
+ Put code here only when two or more packages need it.
package/package.json CHANGED
@@ -1 +1,41 @@
1
- {"name":"@rackrot/pi-core","version":"0.0.1","description":"Placeholder - real releases are published from github.com/rackrot/pi-tools","license":"MIT","repository":{"type":"git","url":"git+https://github.com/rackrot/pi-tools.git","directory":"packages/core"}}
1
+ {
2
+ "name": "@rackrot/pi-core",
3
+ "version": "0.1.0",
4
+ "description": "Core rackrot pi extension and shared utilities for the other @rackrot packages",
5
+ "type": "module",
6
+ "keywords": [
7
+ "pi-package",
8
+ "pi-extension"
9
+ ],
10
+ "license": "MIT",
11
+ "files": [
12
+ "src",
13
+ "README.md"
14
+ ],
15
+ "exports": {
16
+ ".": "./src/lib.ts",
17
+ "./json": "./src/json.ts",
18
+ "./settings": "./src/settings.ts",
19
+ "./thinking-binding": "./src/thinking-binding/binding.ts"
20
+ },
21
+ "scripts": {
22
+ "test": "node --test test/*.test.ts"
23
+ },
24
+ "pi": {
25
+ "extensions": [
26
+ "./src/index.ts"
27
+ ]
28
+ },
29
+ "peerDependencies": {
30
+ "@earendil-works/pi-agent-core": "*",
31
+ "@earendil-works/pi-coding-agent": "*"
32
+ },
33
+ "publishConfig": {
34
+ "access": "public"
35
+ },
36
+ "repository": {
37
+ "type": "git",
38
+ "url": "git+https://github.com/rackrot/pi-tools.git",
39
+ "directory": "packages/core"
40
+ }
41
+ }
package/src/index.ts ADDED
@@ -0,0 +1,11 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import thinkingBinding from "./thinking-binding/index.ts";
3
+
4
+ /**
5
+ * Core rackrot extension: things we always want installed and enabled.
6
+ * Each feature lives in its own directory and is registered here. Shared code for the other
7
+ * packages lives in `lib.ts` and its submodules, not here.
8
+ */
9
+ export default function (pi: ExtensionAPI) {
10
+ thinkingBinding(pi);
11
+ }
package/src/json.ts ADDED
@@ -0,0 +1,39 @@
1
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from "node:fs";
2
+ import { dirname } from "node:path";
3
+
4
+ export type Json = Record<string, unknown>;
5
+
6
+ export const isObject = (v: unknown): v is Json =>
7
+ !!v && typeof v === "object" && !Array.isArray(v);
8
+
9
+ /** Reads a JSON object; a missing, unreadable or non-object file yields `{}`. */
10
+ export function readJson(path: string): Json {
11
+ if (!existsSync(path)) return {};
12
+ try {
13
+ const data = JSON.parse(readFileSync(path, "utf8")) as unknown;
14
+ return isObject(data) ? data : {};
15
+ } catch {
16
+ return {};
17
+ }
18
+ }
19
+
20
+ /**
21
+ * Reads a JSON object and the indent it uses, so edits keep the file's style.
22
+ * Unlike `readJson`, throws on malformed or non-object content so callers don't overwrite it.
23
+ */
24
+ export function readJsonStrict(path: string): { data: Json; indent: string } {
25
+ if (!existsSync(path)) return { data: {}, indent: "\t" };
26
+ const text = readFileSync(path, "utf8");
27
+ if (!text.trim()) return { data: {}, indent: "\t" };
28
+ const data = JSON.parse(text) as unknown;
29
+ if (!isObject(data)) throw new Error(`${path} is not a JSON object`);
30
+ return { data, indent: /^\{\r?\n(\t| +)/.exec(text)?.[1] ?? "\t" };
31
+ }
32
+
33
+ /** Writes via a temp file and rename so concurrent readers never see a partial file. */
34
+ export function writeJsonAtomic(path: string, data: unknown, indent: string | number = "\t"): void {
35
+ mkdirSync(dirname(path), { recursive: true });
36
+ const tmp = `${path}.${process.pid}.tmp`;
37
+ writeFileSync(tmp, `${JSON.stringify(data, null, indent)}\n`);
38
+ renameSync(tmp, path);
39
+ }
package/src/lib.ts ADDED
@@ -0,0 +1,3 @@
1
+ export * from "./json.ts";
2
+ export * from "./settings.ts";
3
+ export * from "./thinking-binding/binding.ts";
@@ -0,0 +1,17 @@
1
+ import { join } from "node:path";
2
+ import { getAgentDir } from "@earendil-works/pi-coding-agent";
3
+ import { type Json, readJson } from "./json.ts";
4
+
5
+ /** Settings files in precedence order, lowest first: global, then project. */
6
+ export function settingsPaths(cwd: string, agentDir: string = getAgentDir()): string[] {
7
+ return [join(agentDir, "settings.json"), join(cwd, ".pi", "settings.json")];
8
+ }
9
+
10
+ /** The raw value of one settings key from each layer (global, project); `undefined` when unset. */
11
+ export function readSettingsLayers(
12
+ key: string,
13
+ cwd: string,
14
+ agentDir: string = getAgentDir(),
15
+ ): unknown[] {
16
+ return settingsPaths(cwd, agentDir).map((p) => (readJson(p) as Json)[key]);
17
+ }
@@ -0,0 +1,144 @@
1
+ import { createHash } from "node:crypto";
2
+ import type { AgentMessage } from "@earendil-works/pi-agent-core";
3
+
4
+ export const BINDING_ENTRY_TYPE = "@rackrot/pi-core:thinking-binding";
5
+
6
+ /** Persisted per branch: the last signed prefix and the cutoff through which thinking is dead. */
7
+ export interface BindingState {
8
+ version: 1;
9
+ fingerprint: string;
10
+ /** Assistant messages with this timestamp or older carry thinking bound to an older prefix. */
11
+ staleThrough?: number;
12
+ }
13
+
14
+ interface AnthropicBlock {
15
+ type: string;
16
+ [field: string]: unknown;
17
+ }
18
+
19
+ interface AnthropicMessage {
20
+ role: string;
21
+ content: string | AnthropicBlock[];
22
+ }
23
+
24
+ export interface AnthropicPayload {
25
+ system?: unknown;
26
+ tools?: unknown;
27
+ messages: AnthropicMessage[];
28
+ }
29
+
30
+ // Pi's before_provider_request hands over the raw Anthropic Messages body; this narrows it.
31
+ type RawProviderPayload = unknown;
32
+
33
+ function isRecord(value: unknown): value is Record<string, unknown> {
34
+ return typeof value === "object" && value !== null && !Array.isArray(value);
35
+ }
36
+
37
+ function isAnthropicMessage(value: unknown): value is AnthropicMessage {
38
+ if (!isRecord(value) || typeof value.role !== "string") return false;
39
+ if (typeof value.content === "string") return true;
40
+ return (
41
+ Array.isArray(value.content) &&
42
+ value.content.every((block) => isRecord(block) && typeof block.type === "string")
43
+ );
44
+ }
45
+
46
+ export function parseAnthropicPayload(payload: RawProviderPayload): AnthropicPayload | undefined {
47
+ if (!isRecord(payload) || !Array.isArray(payload.messages)) return undefined;
48
+ if (!payload.messages.every(isAnthropicMessage)) return undefined;
49
+ return payload as unknown as AnthropicPayload;
50
+ }
51
+
52
+ interface SessionEntryLike {
53
+ type: string;
54
+ customType?: string;
55
+ data?: unknown;
56
+ }
57
+
58
+ function isBindingState(value: unknown): value is BindingState {
59
+ return (
60
+ isRecord(value) &&
61
+ value.version === 1 &&
62
+ typeof value.fingerprint === "string" &&
63
+ (value.staleThrough === undefined || typeof value.staleThrough === "number")
64
+ );
65
+ }
66
+
67
+ /** The newest binding state recorded on the active branch. */
68
+ export function readBindingState(branch: readonly SessionEntryLike[]): BindingState | undefined {
69
+ for (let index = branch.length - 1; index >= 0; index--) {
70
+ const entry = branch[index];
71
+ if (!entry) continue;
72
+ if (entry.type !== "custom" || entry.customType !== BINDING_ENTRY_TYPE) continue;
73
+ return isBindingState(entry.data) ? entry.data : undefined;
74
+ }
75
+ return undefined;
76
+ }
77
+
78
+ /** Anthropic binds each thinking signature to the system prompt and tool set that produced it. */
79
+ export function fingerprintPrefix(payload: AnthropicPayload): string {
80
+ return createHash("sha256")
81
+ .update(JSON.stringify(payload.system ?? null))
82
+ .update(JSON.stringify(payload.tools ?? null))
83
+ .digest("hex");
84
+ }
85
+
86
+ function isThinkingBlock(block: AnthropicBlock): boolean {
87
+ return block.type === "thinking" || block.type === "redacted_thinking";
88
+ }
89
+
90
+ /** Remove every thinking block from the outgoing body. Used on the request where the prefix changed. */
91
+ export function stripPayloadThinking(payload: AnthropicPayload): AnthropicPayload {
92
+ const messages = payload.messages.map((message) => {
93
+ if (message.role !== "assistant" || typeof message.content === "string") return message;
94
+ const content = message.content.filter((block) => !isThinkingBlock(block));
95
+ return content.length === 0 || content.length === message.content.length
96
+ ? message
97
+ : { ...message, content };
98
+ });
99
+ return { ...payload, messages };
100
+ }
101
+
102
+ /** Timestamp of the newest assistant message already in history; the in-flight reply is never among them. */
103
+ export function newestAssistantTimestamp(messages: readonly AgentMessage[]): number | undefined {
104
+ let newest: number | undefined;
105
+ for (const message of messages) {
106
+ if (message.role === "assistant" && (newest === undefined || message.timestamp > newest))
107
+ newest = message.timestamp;
108
+ }
109
+ return newest;
110
+ }
111
+
112
+ /** True when Anthropic reported that it dropped replayed thinking because the prefix changed. */
113
+ export function reportsPrefixMismatch(message: AgentMessage): boolean {
114
+ if (message.role !== "assistant") return false;
115
+ return (message.diagnostics ?? []).some((diagnostic) => {
116
+ if (diagnostic.type !== "anthropic_input_transformations") return false;
117
+ const transformations = diagnostic.details?.transformations;
118
+ return (
119
+ Array.isArray(transformations) &&
120
+ transformations.some(
121
+ (item) =>
122
+ isRecord(item) &&
123
+ item.type === "thinking_dropped" &&
124
+ item.reason === "prefix_binding_mismatch",
125
+ )
126
+ );
127
+ });
128
+ }
129
+
130
+ /** Remove thinking from assistant messages at or before the cutoff. Returns undefined when nothing changed. */
131
+ export function stripStaleThinking(
132
+ messages: readonly AgentMessage[],
133
+ staleThrough: number,
134
+ ): AgentMessage[] | undefined {
135
+ let changed = false;
136
+ const next = messages.map((message) => {
137
+ if (message.role !== "assistant" || message.timestamp > staleThrough) return message;
138
+ const content = message.content.filter((block) => block.type !== "thinking");
139
+ if (content.length === 0 || content.length === message.content.length) return message;
140
+ changed = true;
141
+ return { ...message, content };
142
+ });
143
+ return changed ? next : undefined;
144
+ }
@@ -0,0 +1,67 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+ import {
3
+ BINDING_ENTRY_TYPE,
4
+ type BindingState,
5
+ fingerprintPrefix,
6
+ newestAssistantTimestamp,
7
+ parseAnthropicPayload,
8
+ readBindingState,
9
+ reportsPrefixMismatch,
10
+ stripPayloadThinking,
11
+ stripStaleThinking,
12
+ } from "./binding.ts";
13
+
14
+ /**
15
+ * Drops Anthropic thinking blocks that a system prompt or tool change has already invalidated,
16
+ * so `prefix_binding_mismatch` is reported once instead of on every turn.
17
+ *
18
+ * Anthropic binds each thinking signature to the `system`, `tools` and earlier messages that
19
+ * produced it. When the prefix changes (an extension edits a tool description, pi restarts into
20
+ * an old session), every earlier block is dropped server-side on each later turn. We do the drop
21
+ * ourselves, once, and remember the cutoff in the session. The session file keeps the originals.
22
+ *
23
+ * Adapted from luan/agents `pi-thinking-binding` (MIT).
24
+ */
25
+ export default function thinkingBinding(pi: ExtensionAPI): void {
26
+ // The assistant message timestamp predates before_provider_request, so the cutoff comes from history.
27
+ let newestAssistant: number | undefined;
28
+ let fingerprint: string | undefined;
29
+ const record = (state: BindingState): void => pi.appendEntry(BINDING_ENTRY_TYPE, state);
30
+
31
+ pi.on("context", (event, ctx) => {
32
+ if (ctx.model?.api !== "anthropic-messages") return;
33
+ newestAssistant = newestAssistantTimestamp(event.messages);
34
+ const state = readBindingState(ctx.sessionManager.getBranch());
35
+ if (state?.staleThrough === undefined) return;
36
+ const messages = stripStaleThinking(event.messages, state.staleThrough);
37
+ return messages ? { messages } : undefined;
38
+ });
39
+
40
+ pi.on("before_provider_request", (event, ctx) => {
41
+ if (ctx.model?.api !== "anthropic-messages") return;
42
+ const payload = parseAnthropicPayload(event.payload);
43
+ if (!payload) return;
44
+ fingerprint = fingerprintPrefix(payload);
45
+ const previous = readBindingState(ctx.sessionManager.getBranch());
46
+ if (previous?.fingerprint === fingerprint) return;
47
+ // A changed prefix invalidates every thinking block sent so far; a first sighting invalidates nothing.
48
+ const staleThrough = previous ? (newestAssistant ?? previous.staleThrough) : undefined;
49
+ record({ version: 1, fingerprint, staleThrough });
50
+ return previous && newestAssistant !== undefined ? stripPayloadThinking(payload) : undefined;
51
+ });
52
+
53
+ // Prefix changes the fingerprint cannot see (pre-existing breakage, rewritten message content):
54
+ // trust Anthropic's own drop report once.
55
+ pi.on("message_end", (event, ctx) => {
56
+ if (
57
+ ctx.model?.api !== "anthropic-messages" ||
58
+ fingerprint === undefined ||
59
+ newestAssistant === undefined
60
+ )
61
+ return;
62
+ if (!reportsPrefixMismatch(event.message)) return;
63
+ const previous = readBindingState(ctx.sessionManager.getBranch());
64
+ if (previous?.staleThrough !== undefined && previous.staleThrough >= newestAssistant) return;
65
+ record({ version: 1, fingerprint, staleThrough: newestAssistant });
66
+ });
67
+ }