@casualjim/pi-headroom 0.1.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/LICENSE ADDED
@@ -0,0 +1,24 @@
1
+ MIT License
2
+
3
+ This package is derived from @raquezha/noheadroom, itself derived from @ryan_nookpi/pi-extension-headroom by Ryan/Jonghakseo, MIT licensed.
4
+
5
+ Copyright for original portions belongs to the original authors.
6
+ Modifications are copyright raquezha; further modifications copyright casualjim.
7
+
8
+ Permission is hereby granted, free of charge, to any person obtaining a copy
9
+ of this software and associated documentation files (the "Software"), to deal
10
+ in the Software without restriction, including without limitation the rights
11
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12
+ copies of the Software, and to permit persons to whom the Software is
13
+ furnished to do so, subject to the following conditions:
14
+
15
+ The above copyright notice and this permission notice shall be included in all
16
+ copies or substantial portions of the Software.
17
+
18
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
24
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,82 @@
1
+ # @casualjim/pi-headroom
2
+
3
+ Headroom context compression for **pi and omp** (side by side). Compresses
4
+ oversized tool results through a local
5
+ [Headroom](https://github.com/headroomlabs-ai/headroom) proxy and exposes a
6
+ `headroom_retrieve` tool so compressed originals stay recoverable.
7
+
8
+ Fork lineage: `@raquezha/noheadroom` → `@ryan_nookpi/pi-extension-headroom`
9
+ (Jonghakseo), MIT.
10
+
11
+ ## Install
12
+
13
+ ```bash
14
+ pi install /path/to/pi-mimir/packages/pi-headroom # pi
15
+ omp plugin install /path/to/pi-mimir/packages/pi-headroom # omp
16
+ ```
17
+
18
+ Both hosts read the same source: the manifest declares `pi.extensions` and
19
+ `omp.extensions`, and omp's legacy-pi compat layer remaps `@earendil-works/*`
20
+ imports (plus `typebox`) onto its own packages.
21
+
22
+ Run a Headroom proxy yourself (never spawned by this package):
23
+
24
+ ```bash
25
+ headroom proxy # default port 8787
26
+ headroom proxy --port 8788 # custom port: also set baseUrl in this host's settings
27
+ ```
28
+
29
+ The default `baseUrl` is `http://127.0.0.1:8787` — Headroom's own default. Running a
30
+ custom port (this setup uses 8788) means the settings file must set `baseUrl`, e.g.
31
+ `~/.pi/agent/headroom/settings.json` for pi and `~/.omp/agent/headroom/settings.json`
32
+ for omp: `{ "baseUrl": "http://127.0.0.1:8788" }` (or export `PI_HEADROOM_URL`).
33
+
34
+ ## Settings
35
+
36
+ Resolved per host, first match wins:
37
+
38
+ | Order | Source |
39
+ |---|---|
40
+ | 1 | `PI_HEADROOM_SETTINGS` — exact settings file path |
41
+ | 2 | `PI_CODING_AGENT_DIR` → `<dir>/headroom/settings.json` |
42
+ | 3 | host default: `~/.omp/agent/headroom/settings.json` (omp) / `~/.pi/agent/headroom/settings.json` (pi) |
43
+
44
+ Keys: `baseUrl`, `enabled`, `mode`, `minContextTokens`, `minMessageChars`,
45
+ `timeoutMs`, `allowRemote`, `renameToolCalls`. `/headroom mode <m>` writes back
46
+ to the file the host resolved.
47
+
48
+ Host detection is a capability probe: omp's `ExtensionAPI` exposes `zod`, pi's
49
+ does not.
50
+
51
+ ## Retrieve
52
+
53
+ Compressed results carry a hash marker, e.g.
54
+ `[400 items compressed to 10. Retrieve more: hash=abc…]` or `<<ccr:abc…>>`.
55
+ Call `headroom_retrieve(hash="abc…")` to get the full original from the
56
+ proxy's CCR store (TTL 1800 s).
57
+
58
+ `/headroom status|on|off|health|stats|mode <normal|quiet|silent>`
59
+
60
+ ## Behavior
61
+
62
+ - Only `toolResult` content is mutated; user/assistant text, tool-call ids and
63
+ names stay unchanged in the session.
64
+ - Tool calls are renamed to `pi_tool_result` in the compression payload so
65
+ Headroom's `DEFAULT_EXCLUDE_TOOLS` does not skip large `read`/`grep` results.
66
+ Set `renameToolCalls: false` to keep Headroom's intended read protection.
67
+ - Unset or unreachable proxy degrades to a no-op with a one-time warning.
68
+ - Loop guards: reentrancy flag, 3 s throttle, input/output/candidate
69
+ fingerprints, bounded seen-content FIFO.
70
+
71
+ ## Host compatibility
72
+
73
+ - `headroom_retrieve` declares `loadMode: "essential"` and `approval: "read"`.
74
+ omp defaults extension tools to `discoverable` and `exec`, which would keep a
75
+ marker-redeeming tool out of the top-level set and route it through the
76
+ approval gate; pi ignores both fields.
77
+ - Default `timeoutMs` is 20 s. The compress call runs inside the `context`
78
+ handler, and omp kills a handler at its 30 s per-event cap
79
+ (`EXTENSION_HANDLER_TIMEOUT_MS`), which would drop the whole context
80
+ transform. pi has no such cap.
81
+ - omp's handler context exposes no `AbortSignal`; a `ctx.signal` absence simply
82
+ leaves the internal timeout as the only bound.
@@ -0,0 +1,334 @@
1
+ import type { ImageContent, TextContent, ToolCall } from "@earendil-works/pi-ai";
2
+ import type {
3
+ AgentMessage,
4
+ ApplyCompressionOptions,
5
+ ApplyCompressionResult,
6
+ CompressionMapping,
7
+ CompressionPayload,
8
+ OpenAIAssistantMessage,
9
+ OpenAIMessage,
10
+ OpenAIToolCall,
11
+ } from "./types.js";
12
+
13
+ type AnyMessage = AgentMessage & { role?: string; content?: unknown; timestamp?: number };
14
+
15
+ interface MessageWithContent {
16
+ content: unknown;
17
+ }
18
+
19
+ const STANDARD_COMPRESSIBLE_ROLES = new Set(["user", "assistant", "toolResult"]);
20
+
21
+ export function buildCompressionPayload(
22
+ messages: AgentMessage[],
23
+ minMessageChars: number,
24
+ options: { renameToolCalls?: boolean } = {},
25
+ ): CompressionPayload {
26
+ const mappings: CompressionMapping[] = [];
27
+ let candidateCount = 0;
28
+
29
+ for (let sourceIndex = 0; sourceIndex < messages.length; sourceIndex++) {
30
+ const source = messages[sourceIndex] as AnyMessage;
31
+ const converted = convertMessage(source, options);
32
+ if (!converted) continue;
33
+
34
+ const originalText = extractOpenAIText(converted);
35
+ // Mark candidates for compression.
36
+ // ONLY toolResults are candidates, preserving original Pi conversation fidelity.
37
+ let applyTo: "toolResult" | null = source.role === "toolResult" ? "toolResult" : null;
38
+
39
+ // Headroom Bypass Rules (Android Hat)
40
+ // We never want to compress `android layout` JSON dumps or critical adb dumps.
41
+ if (source.role === "toolResult" && originalText.trim().startsWith("[") && originalText.includes('"resource-id"')) {
42
+ applyTo = null;
43
+ }
44
+
45
+ if (applyTo && originalText.length >= minMessageChars) candidateCount++;
46
+ mappings.push({ sourceIndex, message: converted, applyTo, originalText });
47
+ }
48
+
49
+ return {
50
+ messages: mappings.map((mapping) => mapping.message),
51
+ mappings,
52
+ candidateCount,
53
+ };
54
+ }
55
+
56
+ export function applyCompressionResult(
57
+ originalMessages: AgentMessage[],
58
+ mappings: CompressionMapping[],
59
+ compressedMessages: OpenAIMessage[],
60
+ _options: ApplyCompressionOptions,
61
+ ): ApplyCompressionResult {
62
+ if (compressedMessages.length !== mappings.length) {
63
+ return { ok: false, reason: "message-count-changed" };
64
+ }
65
+
66
+ const nextMessages = structuredClone(originalMessages) as AgentMessage[];
67
+ let appliedMessages = 0;
68
+ let appliedTokensBefore = 0;
69
+ let appliedTokensAfter = 0;
70
+
71
+ for (let index = 0; index < mappings.length; index++) {
72
+ const mapping = mappings[index];
73
+ const compressed = compressedMessages[index];
74
+
75
+ // We only validate and apply changes to explicit candidates.
76
+ // Headroom is allowed to mangle non-candidates (like assistant history) in its output,
77
+ // but we simply ignore those changes and keep the original Pi message intact.
78
+ if (!mapping.applyTo) continue;
79
+
80
+ const validation = validateAlignedMessage(mapping.message, compressed);
81
+ if (!validation.ok) return validation;
82
+
83
+ let nextText = extractOpenAIText(compressed);
84
+ if (nextText === mapping.originalText) continue;
85
+
86
+ // Naturalize Headroom's native CCR markers to provide Pi-native tooling hints (Upstream #846)
87
+ nextText = naturalizeHeadroomMarkers(nextText);
88
+
89
+ const target = nextMessages[mapping.sourceIndex] as AnyMessage;
90
+ if (!hasContent(target) || !replaceTextContent(target, nextText)) {
91
+ return { ok: false, reason: "target-content-unreplaceable" };
92
+ }
93
+ appliedTokensBefore += estimateTokens(mapping.originalText);
94
+ appliedTokensAfter += estimateTokens(nextText);
95
+ appliedMessages++;
96
+ }
97
+
98
+ if (appliedMessages === 0) {
99
+ return { ok: false, reason: "no-applicable-message-changed" };
100
+ }
101
+ const appliedTokensSaved = Math.max(0, appliedTokensBefore - appliedTokensAfter);
102
+ if (appliedTokensSaved === 0) {
103
+ return { ok: false, reason: "no-estimated-token-savings" };
104
+ }
105
+
106
+ return {
107
+ ok: true,
108
+ messages: nextMessages,
109
+ appliedMessages,
110
+ appliedTokensBefore,
111
+ appliedTokensAfter,
112
+ appliedTokensSaved,
113
+ appliedCompressionRatio: appliedTokensAfter / appliedTokensBefore,
114
+ };
115
+ }
116
+
117
+ export function convertMessage(message: AnyMessage, options: { renameToolCalls?: boolean } = {}): OpenAIMessage | undefined {
118
+ if (!message.role || !STANDARD_COMPRESSIBLE_ROLES.has(message.role)) return undefined;
119
+ switch (message.role) {
120
+ case "user":
121
+ return convertUserMessage(message);
122
+ case "assistant":
123
+ return convertAssistantMessage(message, options);
124
+ case "toolResult":
125
+ return convertToolResultMessage(message);
126
+ default:
127
+ return undefined;
128
+ }
129
+ }
130
+
131
+ function convertUserMessage(message: AnyMessage): OpenAIMessage | undefined {
132
+ if (!hasContent(message)) return undefined;
133
+ if (typeof message.content === "string") {
134
+ return { role: "user", content: message.content };
135
+ }
136
+ if (!Array.isArray(message.content)) return undefined;
137
+
138
+ const text = message.content
139
+ .filter((part): part is TextContent => isTextContent(part))
140
+ .map((part) => part.text)
141
+ .join("\n");
142
+ if (text) return { role: "user", content: text };
143
+ const hasImages = message.content.some((part) => isImageContent(part));
144
+ return hasImages ? { role: "user", content: "[image omitted from Headroom compression payload]" } : undefined;
145
+ }
146
+
147
+ function convertAssistantMessage(
148
+ message: AnyMessage,
149
+ options: { renameToolCalls?: boolean } = {},
150
+ ): OpenAIAssistantMessage | undefined {
151
+ if (!hasContent(message) || !Array.isArray(message.content)) return undefined;
152
+ const text = message.content
153
+ .filter((part): part is TextContent => isTextContent(part))
154
+ .map((part) => part.text)
155
+ .join("");
156
+ const toolCalls = message.content.filter((part): part is ToolCall => isToolCall(part));
157
+ if (!text && toolCalls.length === 0) return undefined;
158
+
159
+ const converted: OpenAIAssistantMessage = {
160
+ role: "assistant",
161
+ content: text || null,
162
+ };
163
+ if (toolCalls.length > 0) {
164
+ converted.tool_calls = toolCalls.map((toolCall) => convertToolCall(toolCall, options.renameToolCalls !== false));
165
+ }
166
+ return converted;
167
+ }
168
+
169
+ function convertToolResultMessage(message: AnyMessage): OpenAIMessage | undefined {
170
+ if (!hasContent(message)) return undefined;
171
+ const toolCallId = readStringProperty(message, "toolCallId");
172
+ if (!toolCallId) return undefined;
173
+ return {
174
+ role: "tool",
175
+ content: extractTextFromContent(message.content),
176
+ tool_call_id: toolCallId,
177
+ };
178
+ }
179
+
180
+ function convertToolCall(toolCall: ToolCall, renameToolCalls: boolean): OpenAIToolCall {
181
+ return {
182
+ id: toolCall.id,
183
+ type: "function",
184
+ function: {
185
+ // Headroom protects exact tool names (read, glob, grep, ...) in its DEFAULT_EXCLUDE_TOOLS;
186
+ // a neutral name keeps large reads compressible.
187
+ name: renameToolCalls ? "pi_tool_result" : toolCall.name,
188
+ arguments: renameToolCalls
189
+ ? JSON.stringify({ originalToolName: toolCall.name })
190
+ : JSON.stringify(toolCall.arguments ?? {}),
191
+ },
192
+ };
193
+ }
194
+
195
+ function validateAlignedMessage(
196
+ original: OpenAIMessage,
197
+ compressed: OpenAIMessage,
198
+ ): { ok: true } | { ok: false; reason: string } {
199
+ if (original.role !== compressed.role) {
200
+ return { ok: false, reason: `role-changed:${original.role}->${compressed.role}` };
201
+ }
202
+ if (original.role === "tool" && compressed.role === "tool") {
203
+ if (original.tool_call_id !== compressed.tool_call_id) return { ok: false, reason: "tool-call-id-changed" };
204
+ }
205
+ if (original.role === "assistant" && compressed.role === "assistant") {
206
+ const originalIds = (original.tool_calls ?? []).map((call) => call.id).join("\n");
207
+ const compressedIds = (compressed.tool_calls ?? []).map((call) => call.id).join("\n");
208
+ if (originalIds !== compressedIds) return { ok: false, reason: "assistant-tool-calls-changed" };
209
+ }
210
+ return { ok: true };
211
+ }
212
+
213
+ export function extractOpenAIText(message: OpenAIMessage): string {
214
+ if (message.role === "assistant") return typeof message.content === "string" ? message.content : "";
215
+ if (message.role === "tool" || message.role === "system") return message.content;
216
+ if (typeof message.content === "string") return message.content;
217
+ return message.content
218
+ .filter((part): part is { type: "text"; text: string } => part.type === "text")
219
+ .map((part) => part.text)
220
+ .join("\n");
221
+ }
222
+
223
+ function extractTextFromContent(content: unknown): string {
224
+ if (typeof content === "string") return content;
225
+ if (!Array.isArray(content)) return "";
226
+ return content
227
+ .filter((part): part is TextContent => isTextContent(part))
228
+ .map((part) => part.text)
229
+ .join("\n");
230
+ }
231
+
232
+ function replaceTextContent(message: MessageWithContent, text: string): boolean {
233
+ if (typeof message.content === "string") {
234
+ message.content = text;
235
+ return true;
236
+ }
237
+ if (!Array.isArray(message.content)) return false;
238
+
239
+ const nextContent: unknown[] = [];
240
+ let replacedText = false;
241
+
242
+ for (const part of message.content) {
243
+ if (isTextContent(part)) {
244
+ if (!replacedText) {
245
+ nextContent.push({ type: "text", text });
246
+ replacedText = true;
247
+ }
248
+ continue;
249
+ }
250
+ nextContent.push(part);
251
+ }
252
+
253
+ if (!replacedText && text.length > 0) {
254
+ nextContent.unshift({ type: "text", text });
255
+ }
256
+
257
+ message.content = nextContent as typeof message.content;
258
+ return true;
259
+ }
260
+
261
+ function hasContent(message: AnyMessage): message is AnyMessage & MessageWithContent {
262
+ return "content" in message;
263
+ }
264
+
265
+ function isTextContent(value: unknown): value is TextContent {
266
+ return isRecord(value) && value.type === "text" && typeof value.text === "string";
267
+ }
268
+
269
+ function isImageContent(value: unknown): value is ImageContent {
270
+ return (
271
+ isRecord(value) && value.type === "image" && typeof value.data === "string" && typeof value.mimeType === "string"
272
+ );
273
+ }
274
+
275
+ function isToolCall(value: unknown): value is ToolCall {
276
+ return (
277
+ isRecord(value) &&
278
+ value.type === "toolCall" &&
279
+ typeof value.id === "string" &&
280
+ typeof value.name === "string" &&
281
+ isRecord(value.arguments)
282
+ );
283
+ }
284
+
285
+ function readStringProperty(value: unknown, key: string): string | undefined {
286
+ if (!isRecord(value)) return undefined;
287
+ const property = value[key];
288
+ return typeof property === "string" ? property : undefined;
289
+ }
290
+
291
+ function isRecord(value: unknown): value is Record<string, unknown> {
292
+ return typeof value === "object" && value !== null;
293
+ }
294
+
295
+ function estimateTokens(text: string): number {
296
+ // ponytail: cheap local estimate; exact tokenizer would add a heavy dependency for a footer number.
297
+ return text.length === 0 ? 0 : Math.max(1, Math.ceil(text.length / 4));
298
+ }
299
+
300
+ export function naturalizeHeadroomMarkers(text: string): string {
301
+ // Headroom's bracket markers carry the CCR hash. Keep the hash and name the
302
+ // Pi tool that redeems it; `<<ccr:...>>` machine markers stay byte-intact
303
+ // (they sit inside JSON payloads and must not be rewritten).
304
+ return text
305
+ .replace(
306
+ /\[(.*?(?:compressed|omitted).*?)\.?\s*Retrieve (?:more|original): hash=([a-f0-9]{12,24})\]/gi,
307
+ "[$1. Retrieve the full original with the `headroom_retrieve` tool using hash=$2.]",
308
+ )
309
+ .replace(
310
+ /Retrieve original: hash=([a-f0-9]{12,24})/gi,
311
+ "Retrieve the full original with the `headroom_retrieve` tool using hash=$1",
312
+ );
313
+ }
314
+
315
+ export function injectCompressionAwareness(messages: AgentMessage[]): AgentMessage[] {
316
+ // If a system message already exists at the top, we append the hint to it.
317
+ // Otherwise, we inject a new system message at index 0.
318
+ const result = [...messages];
319
+ const hintText = "Environment Hint: Some tool results in this context have been automatically compressed by Headroom to optimize tokens. When a compressed result shows a marker with a hash — e.g. `[N items compressed to M. Retrieve more: hash=abc123]`, `Retrieve original: hash=abc123`, or a `<<ccr:abc123 ...>>` machine marker — call the `headroom_retrieve` tool with that exact hash to get the full original content back. Do NOT re-read whole files or guess at compressed content.";
320
+
321
+ // SAFETY: narrowing the structural AgentMessage union to inspect optional system role/content fields; both checked before use.
322
+ const first = result[0] as unknown as Record<string, unknown>;
323
+ if (first && first.role === "system" && typeof first.content === "string") {
324
+ if (!first.content.includes("automatically compressed by Headroom")) {
325
+ // SAFETY: re-widening a spread copy of a verified system message back to AgentMessage.
326
+ result[0] = { ...first, content: `${first.content}\n\n${hintText}` } as unknown as AgentMessage;
327
+ }
328
+ } else {
329
+ // SAFETY: constructing a minimal system message AgentMessage; pi accepts role/content here.
330
+ result.unshift({ role: "system", content: hintText } as unknown as AgentMessage);
331
+ }
332
+
333
+ return result;
334
+ }
@@ -0,0 +1,162 @@
1
+ import type { CompressResult, OpenAIMessage } from "./types.js";
2
+
3
+ interface ProxyCompressResponse {
4
+ messages: OpenAIMessage[];
5
+ tokens_before: number;
6
+ tokens_after: number;
7
+ tokens_saved: number;
8
+ compression_ratio: number;
9
+ transforms_applied: string[];
10
+ ccr_hashes?: string[];
11
+ }
12
+
13
+ interface HeadroomClientOptions {
14
+ baseUrl: string;
15
+ timeoutMs: number;
16
+ }
17
+
18
+ export type RetrieveResult = { ok: true; content: string } | { ok: false; status?: number; error: string };
19
+
20
+ export class HeadroomHttpClient {
21
+ private readonly baseUrl: string;
22
+ private readonly timeoutMs: number;
23
+
24
+ constructor(options: HeadroomClientOptions) {
25
+ this.baseUrl = options.baseUrl.replace(/\/+$/, "");
26
+ this.timeoutMs = options.timeoutMs;
27
+ }
28
+
29
+ async health(signal?: AbortSignal): Promise<boolean> {
30
+ try {
31
+ const response = await fetch(`${this.baseUrl}/health`, {
32
+ signal: buildSignal(this.timeoutMs, signal),
33
+ });
34
+ if (!response.ok) return false;
35
+ const body = await readJsonObject(response);
36
+ if (!body) return true;
37
+ return body.status === "healthy" || body.status === "ok" || "optimize" in body || "stats" in body;
38
+ } catch {
39
+ return false;
40
+ }
41
+ }
42
+
43
+ async probe(signal?: AbortSignal): Promise<boolean> {
44
+ try {
45
+ const response = await fetch(`${this.baseUrl}/v1/compress`, {
46
+ method: "POST",
47
+ headers: { "Content-Type": "application/json" },
48
+ body: JSON.stringify({ messages: [{ role: "user", content: "ping" }], model: "gpt-4o" }),
49
+ signal: buildSignal(5_000, signal),
50
+ });
51
+ return response.ok;
52
+ } catch {
53
+ return false;
54
+ }
55
+ }
56
+
57
+ async stats(signal?: AbortSignal): Promise<unknown> {
58
+ const response = await fetch(`${this.baseUrl}/stats`, {
59
+ signal: buildSignal(this.timeoutMs, signal),
60
+ });
61
+ if (!response.ok) {
62
+ throw new Error(`Headroom /stats failed with HTTP ${response.status}`);
63
+ }
64
+ return response.json();
65
+ }
66
+
67
+ async compress(messages: OpenAIMessage[], model: string | undefined, signal?: AbortSignal): Promise<CompressResult> {
68
+ const response = await fetch(`${this.baseUrl}/v1/compress`, {
69
+ method: "POST",
70
+ headers: {
71
+ "Content-Type": "application/json",
72
+ "X-Headroom-Stack": "pi-extension",
73
+ },
74
+ body: JSON.stringify({ messages, model: model || "gpt-4o" }),
75
+ signal: buildSignal(this.timeoutMs, signal),
76
+ });
77
+
78
+ if (!response.ok) {
79
+ const message = await readErrorMessage(response);
80
+ throw new Error(message || `Headroom /v1/compress failed with HTTP ${response.status}`);
81
+ }
82
+
83
+ const payload = (await response.json()) as ProxyCompressResponse;
84
+ return {
85
+ messages: payload.messages,
86
+ tokensBefore: payload.tokens_before,
87
+ tokensAfter: payload.tokens_after,
88
+ tokensSaved: payload.tokens_saved,
89
+ compressionRatio: payload.compression_ratio,
90
+ transformsApplied: payload.transforms_applied ?? [],
91
+ ccrHashes: payload.ccr_hashes ?? [],
92
+ compressed: true,
93
+ };
94
+ }
95
+
96
+ async retrieve(hash: string, signal?: AbortSignal): Promise<RetrieveResult> {
97
+ try {
98
+ const response = await fetch(`${this.baseUrl}/v1/retrieve/${hash}`, {
99
+ signal: buildSignal(this.timeoutMs, signal),
100
+ });
101
+ if (!response.ok) {
102
+ const detail = await response.text().catch(() => "");
103
+ return {
104
+ ok: false,
105
+ status: response.status,
106
+ error:
107
+ response.status === 404
108
+ ? "Entry not found in Headroom's CCR store (TTL 1800s) — the compressed content expired."
109
+ : `Headroom /v1/retrieve failed with HTTP ${response.status}${detail ? `: ${detail.slice(0, 200)}` : ""}`,
110
+ };
111
+ }
112
+ const body = (await response.json()) as unknown;
113
+ if (typeof body === "string") return { ok: true, content: body };
114
+ if (
115
+ body !== null &&
116
+ typeof body === "object" &&
117
+ typeof (body as { original_content?: unknown }).original_content === "string"
118
+ ) {
119
+ return { ok: true, content: (body as { original_content: string }).original_content };
120
+ }
121
+ return { ok: true, content: JSON.stringify(body, null, 2) };
122
+ } catch (error) {
123
+ return {
124
+ ok: false,
125
+ error: `Headroom /v1/retrieve failed: ${error instanceof Error ? error.message : String(error)}`,
126
+ };
127
+ }
128
+ }
129
+ }
130
+
131
+ async function readJsonObject(response: Response): Promise<Record<string, unknown> | undefined> {
132
+ try {
133
+ const body = (await response.json()) as unknown;
134
+ return isRecord(body) ? body : undefined;
135
+ } catch {
136
+ return undefined;
137
+ }
138
+ }
139
+
140
+ async function readErrorMessage(response: Response): Promise<string | undefined> {
141
+ try {
142
+ const body = (await response.json()) as unknown;
143
+ if (!isRecord(body)) return undefined;
144
+ const error = body.error;
145
+ if (isRecord(error) && typeof error.message === "string") return error.message;
146
+ if (typeof body.message === "string") return body.message;
147
+ } catch {
148
+ // Ignore malformed error bodies.
149
+ }
150
+ return undefined;
151
+ }
152
+
153
+ function buildSignal(timeoutMs: number, signal?: AbortSignal): AbortSignal {
154
+ const timeoutSignal = AbortSignal.timeout(timeoutMs);
155
+ if (!signal) return timeoutSignal;
156
+ if (signal.aborted) return signal;
157
+ return AbortSignal.any([signal, timeoutSignal]);
158
+ }
159
+
160
+ function isRecord(value: unknown): value is Record<string, unknown> {
161
+ return typeof value === "object" && value !== null;
162
+ }