pi-lean-host 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.
@@ -0,0 +1,440 @@
1
+ /**
2
+ * HTTP transport layer — undici Agent with caching and retry.
3
+ *
4
+ * Provides `fetchUrl()` with:
5
+ * - ETag-based conditional requests (304 → cached body)
6
+ * - Cache-Control `max-age` TTL
7
+ * - Retry-on-429 with exponential backoff + `Retry-After` support
8
+ * - Configurable timeout
9
+ * - Automatic charset decoding from Content-Type
10
+ *
11
+ * Caching is per-URL, module-level (in-memory map). The cache is
12
+ * transparent to callers; each URL is cached independently.
13
+ */
14
+
15
+ import { request, Agent, interceptors, type Dispatcher } from "undici";
16
+ import { ssrfGuard } from "./ssrf-guard.js";
17
+
18
+ // ponytail: module-level composed agents; closed only on process exit.
19
+ // Add a close() in session_shutdown if leak-detection ever flags it.
20
+
21
+ /** Auto-follows up to 5 redirects. Used when redirect targets are trusted
22
+ * (agent-supplied URLs — the agent has bash, so guarding them is theater). */
23
+ const redirectAgent = new Agent().compose(
24
+ interceptors.redirect({ maxRedirections: 5 }),
25
+ );
26
+
27
+ /** No auto-redirect. Used with `guardRedirects` so each redirect target is
28
+ * SSRF-checked before it is followed. See fetchUrl for the manual loop. */
29
+ const noRedirectAgent = new Agent();
30
+
31
+ const MAX_REDIRECTS = 5;
32
+
33
+ // ═══════════════════════════════════════════════════════════════════
34
+ // Types
35
+ // ═══════════════════════════════════════════════════════════════════
36
+
37
+ export interface FetchOptions {
38
+ /** Request timeout in ms (default: 30_000). */
39
+ timeout?: number;
40
+ /** Additional request headers. */
41
+ headers?: Record<string, string>;
42
+ /** Max retries on 429 (default: 2). */
43
+ maxRetries?: number;
44
+ /** Skip cache (force fresh fetch). */
45
+ fresh?: boolean;
46
+ /** SSRF-check each redirect target before following it. Use only for
47
+ * server-supplied URLs (paginate nextLink) — a malicious API can 302
48
+ * to an internal host, and when auth headers ship the Authorization
49
+ * header would attach to the redirect. Agent-supplied URLs don't need
50
+ * this (the agent already has bash). */
51
+ guardRedirects?: boolean;
52
+ /** Charset to decode the body with when the response's Content-Type
53
+ * header omits one. Honors a guide's `responseShape.charset` for APIs
54
+ * that serve e.g. ISO-8859-1 bytes without a charset parameter. An
55
+ * explicit header charset always takes precedence. */
56
+ fallbackCharset?: string;
57
+ }
58
+
59
+ export interface FetchResult {
60
+ status: number;
61
+ headers: Record<string, string>;
62
+ body: string;
63
+ /** True when the result came from cache (no network request). */
64
+ cached: boolean;
65
+ /** Final URL after redirects — present only when at least one hop occurred. */
66
+ finalUrl?: string;
67
+ }
68
+
69
+ // ═══════════════════════════════════════════════════════════════════
70
+ // Cache
71
+ // ═══════════════════════════════════════════════════════════════════
72
+
73
+ interface CacheEntry {
74
+ body: string;
75
+ /** ETag for conditional requests; absent when the upstream didn't send one. */
76
+ etag?: string;
77
+ expiresAt: number;
78
+ }
79
+
80
+ const DEFAULT_TIMEOUT = 30_000;
81
+ const DEFAULT_MAX_RETRIES = 2;
82
+ const DEFAULT_TTL_MS = 60_000; // 60s fallback when no Cache-Control
83
+ const MAX_CACHE_ENTRIES = 100; // ponytail: hard cap; evict soonest-expiring when exceeded
84
+ const MAX_BODY_BYTES = 10 * 1024 * 1024; // 10 MB ceiling on a single response body
85
+
86
+ /** Module-level cache: cache-key → CacheEntry. */
87
+ const cache = new Map<string, CacheEntry>();
88
+
89
+ /**
90
+ * Drop expired entries, then — if still over the cap — evict the
91
+ * soonest-expiring entries. Called before every `cache.set`.
92
+ */
93
+ function evictCacheIfNeeded(): void {
94
+ if (cache.size < MAX_CACHE_ENTRIES) return;
95
+ const now = Date.now();
96
+ for (const [k, e] of cache) {
97
+ if (e.expiresAt <= now) cache.delete(k);
98
+ }
99
+ if (cache.size >= MAX_CACHE_ENTRIES) {
100
+ const sorted = [...cache.entries()].sort(
101
+ (a, b) => a[1].expiresAt - b[1].expiresAt,
102
+ );
103
+ while (cache.size >= MAX_CACHE_ENTRIES && sorted.length > 0) {
104
+ const next = sorted.shift();
105
+ if (next) cache.delete(next[0]);
106
+ }
107
+ }
108
+ }
109
+
110
+ // ═══════════════════════════════════════════════════════════════════
111
+ // Internal helpers
112
+ // ═══════════════════════════════════════════════════════════════════
113
+
114
+ /**
115
+ * Produce a cache key from URL and optional Accept header.
116
+ *
117
+ * Two requests for the same URL with different Accept values are cached
118
+ * separately so that content-negotiated responses don't collide.
119
+ * When no Accept header is present the plain URL is used as the key.
120
+ */
121
+ function cacheKey(url: string, opts?: FetchOptions): string {
122
+ const accept = opts?.headers?.accept;
123
+ const cs = opts?.fallbackCharset ?? "";
124
+ const suffix =
125
+ (accept ? `\x00accept=${accept}` : "") + (cs ? `\x00cs=${cs}` : "");
126
+ return suffix ? `${url}${suffix}` : url;
127
+ }
128
+
129
+ function parseHeaders(
130
+ hdrs: Dispatcher.ResponseData["headers"],
131
+ ): Record<string, string> {
132
+ const out: Record<string, string> = {};
133
+ if (hdrs && typeof hdrs === "object") {
134
+ // undici returns headers as an object with lowercased keys.
135
+ for (const [key, val] of Object.entries(hdrs)) {
136
+ if (typeof val === "string") {
137
+ out[key.toLowerCase()] = val;
138
+ } else if (Array.isArray(val)) {
139
+ // Repeated headers arrive as string[] — join like raw form.
140
+ out[key.toLowerCase()] = val.join(", ");
141
+ }
142
+ }
143
+ }
144
+ return out;
145
+ }
146
+
147
+ async function collectBody(
148
+ body: Dispatcher.ResponseData["body"],
149
+ ): Promise<Buffer> {
150
+ const chunks: Buffer[] = [];
151
+ let total = 0;
152
+ for await (const chunk of body) {
153
+ total += chunk.length;
154
+ if (total > MAX_BODY_BYTES) {
155
+ const err = new Error(`Response body exceeded ${MAX_BODY_BYTES} bytes`);
156
+ err.name = "BodyTooLargeError"; // checked by fetchUrl retry logic
157
+ throw err;
158
+ }
159
+ chunks.push(Buffer.from(chunk));
160
+ }
161
+ return Buffer.concat(chunks);
162
+ }
163
+
164
+ function decodeBuffer(buf: Buffer, charset: string): string {
165
+ const cs = charset.toLowerCase().replace(/[^a-z0-9_-]/g, "");
166
+ if (cs === "utf-8" || cs === "utf8" || cs === "") {
167
+ return buf.toString("utf-8");
168
+ }
169
+ try {
170
+ const decoder = new TextDecoder(cs);
171
+ return decoder.decode(buf);
172
+ } catch {
173
+ // Fallback to utf-8 if TextDecoder doesn't recognise the charset.
174
+ return buf.toString("utf-8");
175
+ }
176
+ }
177
+
178
+ function parseMaxAge(headers: Record<string, string>): number | null {
179
+ const cc = headers["cache-control"];
180
+ if (!cc) return null;
181
+ const m = cc.match(/max-age=(\d+)/i);
182
+ return m ? parseInt(m[1]!, 10) * 1000 : null;
183
+ }
184
+
185
+ function waitForRetry(
186
+ headers: Record<string, string>,
187
+ attempt: number,
188
+ ): number {
189
+ const raw = headers["retry-after"];
190
+ if (raw) {
191
+ const secs = parseInt(raw, 10);
192
+ if (!isNaN(secs) && secs > 0) return secs * 1000;
193
+ }
194
+ // Exponential backoff: 1s, 2s, 4s, …
195
+ return Math.min(1000 * 2 ** attempt, 30_000);
196
+ }
197
+
198
+ /**
199
+ * One GET request with its own abort timer. Returns status, parsed headers,
200
+ * and the raw collected body. Redirects are NOT followed here — the caller
201
+ * decides whether to follow and guard them.
202
+ */
203
+ async function singleGet(
204
+ url: string,
205
+ reqHeaders: Record<string, string>,
206
+ timeoutMs: number,
207
+ dispatcher: Dispatcher,
208
+ ): Promise<{
209
+ status: number;
210
+ headers: Record<string, string>;
211
+ rawBody: Buffer;
212
+ finalUrl: string;
213
+ }> {
214
+ if (timeoutMs <= 0) throw new Error("Request timeout");
215
+ const ac = new AbortController();
216
+ const timer = setTimeout(
217
+ () => ac.abort(new Error("Request timeout")),
218
+ timeoutMs,
219
+ );
220
+ try {
221
+ const resp = await request(url, {
222
+ method: "GET",
223
+ headers: reqHeaders,
224
+ signal: ac.signal,
225
+ dispatcher,
226
+ });
227
+ // The redirect interceptor records the hop chain in context.history;
228
+ // its last entry is where the response actually came from. No history
229
+ // (no interceptor / no redirect) means the URL is unchanged.
230
+ const history = (resp.context as { history?: URL[] } | null)?.history;
231
+ return {
232
+ status: resp.statusCode,
233
+ headers: parseHeaders(resp.headers),
234
+ rawBody: await collectBody(resp.body),
235
+ finalUrl: history?.at(-1) ? String(history.at(-1)) : url,
236
+ };
237
+ } finally {
238
+ clearTimeout(timer);
239
+ }
240
+ }
241
+
242
+ /**
243
+ * Follow redirects manually, SSRF-checking each target. Used only for
244
+ * server-supplied URLs (paginate nextLink). GET-only, so method is
245
+ * preserved across 301/302/303/307/308 trivially. Returns the final
246
+ * response; a redirect to a blocked host throws before it is fetched.
247
+ */
248
+ async function getWithGuardedRedirects(
249
+ url: string,
250
+ reqHeaders: Record<string, string>,
251
+ startTime: number,
252
+ timeoutMs: number,
253
+ ): Promise<{
254
+ status: number;
255
+ headers: Record<string, string>;
256
+ rawBody: Buffer;
257
+ finalUrl: string;
258
+ }> {
259
+ let current = url;
260
+ for (let hops = 0; hops <= MAX_REDIRECTS; hops++) {
261
+ const remaining = timeoutMs - (Date.now() - startTime);
262
+ const res = await singleGet(
263
+ current,
264
+ reqHeaders,
265
+ remaining,
266
+ noRedirectAgent,
267
+ );
268
+ const isRedirect =
269
+ res.status >= 300 && res.status < 400 && res.status !== 304;
270
+ if (!isRedirect || hops === MAX_REDIRECTS) return res;
271
+ const loc = res.headers["location"];
272
+ if (!loc) return res; // redirect with no Location — return as-is
273
+ const next = new URL(loc, current).toString();
274
+ const guard = ssrfGuard(next);
275
+ if (!guard.ok) {
276
+ // Security-control failure is not transient — don't retry.
277
+ const err = new Error(`Redirect to blocked host: ${guard.reason}`);
278
+ err.name = "SsrfBlockedError";
279
+ throw err;
280
+ }
281
+ current = next;
282
+ }
283
+ // Unreachable: the loop returns on the MAX_REDIRECTS hop.
284
+ throw new Error("Too many redirects");
285
+ }
286
+
287
+ // ═══════════════════════════════════════════════════════════════════
288
+ // Public API
289
+ // ═══════════════════════════════════════════════════════════════════
290
+
291
+ /**
292
+ * Fetch a URL with caching and retry-on-429.
293
+ *
294
+ * Cache behaviour:
295
+ * - URLs are cached in a module-level `Map<string, CacheEntry>`.
296
+ * - TTL from `Cache-Control: max-age=N` or the `DEFAULT_TTL_MS` fallback.
297
+ * - When a cached entry has an `etag`, the conditional `If-None-Match`
298
+ * header is sent and a 304 refreshes the cached body's expiry.
299
+ * - `opts.fresh = true` skips the cache read and bypasses sending
300
+ * `If-None-Match` (server returns full response).
301
+ * - Requests carrying caller-specific headers (anything besides Accept,
302
+ * e.g. API keys) are never cached or served from cache — the response
303
+ * is private to that caller.
304
+ *
305
+ * Retry behaviour:
306
+ * - 429 responses are retried up to `opts.maxRetries` times.
307
+ * - Backoff: if `Retry-After` is present, wait that many seconds;
308
+ * otherwise exponential backoff (1s, 2s, 4s, capped at 30s).
309
+ * - Other 4xx/5xx status codes are returned as-is without retry.
310
+ *
311
+ * Network errors (DNS, connection refused, timeout) are thrown.
312
+ */
313
+ export async function fetchUrl(
314
+ url: string,
315
+ opts?: FetchOptions,
316
+ ): Promise<FetchResult> {
317
+ const timeout = opts?.timeout ?? DEFAULT_TIMEOUT;
318
+ const maxRetries = opts?.maxRetries ?? DEFAULT_MAX_RETRIES;
319
+
320
+ // Responses to requests carrying caller-specific headers (auth keys,
321
+ // tokens, …) are private to that caller — never cache or reuse them.
322
+ // Only the Accept header (content negotiation) is cache-shareable, and
323
+ // it's already part of the cache key. Without this gate, the same URL
324
+ // fetched with two different auth headers would collide on one cache
325
+ // entry and the second caller would get the first caller's response.
326
+ const hasAuthHeaders =
327
+ !!opts?.headers &&
328
+ Object.keys(opts.headers).some((h) => h.toLowerCase() !== "accept");
329
+
330
+ // ── cache hit ───────────────────────────────────────────────
331
+ const key = cacheKey(url, opts);
332
+ if (!opts?.fresh && !hasAuthHeaders) {
333
+ const entry = cache.get(key);
334
+ if (entry && Date.now() < entry.expiresAt) {
335
+ return { status: 200, headers: {}, body: entry.body, cached: true };
336
+ }
337
+ }
338
+
339
+ // ── request headers ─────────────────────────────────────────
340
+ const reqHeaders: Record<string, string> = { ...opts?.headers };
341
+ if (!reqHeaders["user-agent"]) {
342
+ reqHeaders["user-agent"] =
343
+ "pi-lean-host/0.1.0 (+https://github.com/coreyryanhanson/pi-lean-dimension)";
344
+ }
345
+
346
+ if (!opts?.fresh && !hasAuthHeaders) {
347
+ const entry = cache.get(key);
348
+ if (entry?.etag) {
349
+ reqHeaders["If-None-Match"] = entry.etag;
350
+ }
351
+ }
352
+
353
+ const startTime = Date.now();
354
+
355
+ for (let attempt = 0; attempt <= maxRetries; attempt++) {
356
+ const remaining = timeout - (Date.now() - startTime);
357
+ if (remaining <= 0) throw new Error("Request timeout");
358
+
359
+ try {
360
+ // When guardRedirects is set, follow redirects manually and SSRF-
361
+ // check each target (server-supplied URLs only). Otherwise let
362
+ // undici auto-follow up to 5 redirects.
363
+ const {
364
+ status,
365
+ headers: respHeaders,
366
+ rawBody,
367
+ finalUrl,
368
+ } = opts?.guardRedirects
369
+ ? await getWithGuardedRedirects(url, reqHeaders, startTime, timeout)
370
+ : await singleGet(url, reqHeaders, remaining, redirectAgent);
371
+
372
+ // ── 304 Not Modified ────────────────────────────────
373
+ if (status === 304) {
374
+ const entry = cache.get(key);
375
+ if (entry) {
376
+ const maxAge = parseMaxAge(respHeaders) ?? DEFAULT_TTL_MS;
377
+ entry.expiresAt = Date.now() + maxAge;
378
+ // 304 refreshes an existing key — no growth, but cap-check is cheap.
379
+ cache.set(key, entry);
380
+ return {
381
+ status: 200,
382
+ headers: respHeaders,
383
+ body: entry.body,
384
+ cached: true,
385
+ ...(finalUrl !== url ? { finalUrl } : {}),
386
+ };
387
+ }
388
+ // No cached entry → fall through to process body.
389
+ }
390
+
391
+ // ── 429 Too Many Requests ───────────────────────────
392
+ if (status === 429 && attempt < maxRetries) {
393
+ const delay = waitForRetry(respHeaders, attempt);
394
+ await new Promise((r) => setTimeout(r, delay));
395
+ continue; // retry
396
+ }
397
+
398
+ // ── decode & cache (2xx only) ───────────────────────
399
+ const contentType = respHeaders["content-type"] ?? "";
400
+ const charsetMatch = contentType.match(/charset\s*=\s*([^\s;]+)/i);
401
+ const charset = charsetMatch?.[1] ?? opts?.fallbackCharset ?? "utf-8";
402
+ const body = decodeBuffer(rawBody, charset);
403
+
404
+ if (status >= 200 && status < 300 && !hasAuthHeaders) {
405
+ const maxAge = parseMaxAge(respHeaders) ?? DEFAULT_TTL_MS;
406
+ const etag = respHeaders["etag"];
407
+
408
+ const entry: CacheEntry = { body, expiresAt: Date.now() + maxAge };
409
+ if (etag) entry.etag = etag;
410
+ evictCacheIfNeeded();
411
+ cache.set(key, entry);
412
+ }
413
+
414
+ return {
415
+ status,
416
+ headers: respHeaders,
417
+ body,
418
+ cached: false,
419
+ ...(finalUrl !== url ? { finalUrl } : {}),
420
+ };
421
+ } catch (err) {
422
+ const e = err instanceof Error ? err : new Error(String(err));
423
+ // Don't retry on timeout/abort, oversized bodies, or SSRF
424
+ // blocks — none are transient.
425
+ const transient =
426
+ e.name !== "AbortError" &&
427
+ e.name !== "BodyTooLargeError" &&
428
+ e.name !== "SsrfBlockedError" &&
429
+ (e as NodeJS.ErrnoException).code !== "UND_ERR_ABORTED";
430
+ if (attempt < maxRetries && transient) {
431
+ const delay = Math.min(1000 * 2 ** attempt, 30_000);
432
+ await new Promise((r) => setTimeout(r, delay));
433
+ continue;
434
+ }
435
+ throw e;
436
+ }
437
+ }
438
+
439
+ throw new Error(`Failed to fetch ${url} after ${maxRetries + 1} attempts`);
440
+ }
@@ -0,0 +1,118 @@
1
+ /**
2
+ * Ship-manifest verification helper (vendored from pi-lean-portal).
3
+ *
4
+ * Walks a package directory for production `.ts` files and compares them to
5
+ * the `files` array in `package.json`. Used by `ship-manifest.test.ts` to
6
+ * prove the published npm tarball contains every module the package imports
7
+ * at runtime — with a negative assertion that `api-guides/` and helper .ts
8
+ * files are absent (GitHub-only recipes).
9
+ *
10
+ * Vendored (not imported from portal) so the host-only boundary stays intact.
11
+ */
12
+
13
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
14
+ import { dirname, relative, resolve } from "node:path";
15
+ import { fileURLToPath } from "node:url";
16
+
17
+ const DEFAULT_SKIP_DIRS = ["node_modules", "docs", "__tests__"];
18
+ const SKIP_FILES = new Set<string>(["test-fixtures.ts"]);
19
+ /** Entries that won't exist on disk at rest but are valid (generated at pack time). */
20
+ const SKIP_STALE = new Set(["LICENSE"]);
21
+
22
+ export interface ShipManifestResult {
23
+ declared: readonly string[];
24
+ onDisk: readonly string[];
25
+ missing: readonly string[];
26
+ stale: readonly string[];
27
+ }
28
+
29
+ export function verifyShipManifest(
30
+ packageDirOrUrl: string,
31
+ opts?: { skipDirs?: readonly string[] },
32
+ ): ShipManifestResult {
33
+ const packageDir = packageDirOrUrl.startsWith("file:")
34
+ ? dirname(fileURLToPath(packageDirOrUrl))
35
+ : packageDirOrUrl;
36
+ const skipDirs = new Set([...DEFAULT_SKIP_DIRS, ...(opts?.skipDirs ?? [])]);
37
+ let pkgRaw: string;
38
+ try {
39
+ pkgRaw = readFileSync(resolve(packageDir, "package.json"), "utf8");
40
+ } catch (err) {
41
+ throw new Error(
42
+ `verifyShipManifest: could not read package.json under "${packageDir}": ${
43
+ err instanceof Error ? err.message : String(err)
44
+ }`,
45
+ );
46
+ }
47
+ let pkg: { files?: string[] };
48
+ try {
49
+ pkg = JSON.parse(pkgRaw) as { files?: string[] };
50
+ } catch (err) {
51
+ throw new Error(
52
+ `verifyShipManifest: invalid package.json under "${packageDir}": ${
53
+ err instanceof Error ? err.message : String(err)
54
+ }`,
55
+ );
56
+ }
57
+ const declared = pkg.files ?? [];
58
+ const exactFiles = new Set<string>();
59
+ const dirPrefixes: string[] = [];
60
+ for (const entry of declared) {
61
+ if (entry.startsWith("!")) continue;
62
+ if (entry.endsWith("/")) dirPrefixes.push(entry);
63
+ else if (isDirOnDisk(packageDir, entry)) dirPrefixes.push(`${entry}/`);
64
+ else exactFiles.add(entry);
65
+ }
66
+
67
+ const onDisk = walkProductionTs(packageDir, packageDir, skipDirs);
68
+ const missing = onDisk.filter((f) => !isCovered(f, exactFiles, dirPrefixes));
69
+ const stale = declared.filter(
70
+ (entry) =>
71
+ !entry.startsWith("!") &&
72
+ !SKIP_STALE.has(entry) &&
73
+ !existsSync(resolve(packageDir, entry)),
74
+ );
75
+
76
+ return { declared, onDisk, missing, stale };
77
+ }
78
+
79
+ function isDirOnDisk(packageDir: string, entry: string): boolean {
80
+ try {
81
+ return statSync(resolve(packageDir, entry)).isDirectory();
82
+ } catch {
83
+ return false;
84
+ }
85
+ }
86
+
87
+ function isCovered(
88
+ file: string,
89
+ exactFiles: Set<string>,
90
+ dirPrefixes: readonly string[],
91
+ ): boolean {
92
+ if (exactFiles.has(file)) return true;
93
+ for (const prefix of dirPrefixes) {
94
+ if (file.startsWith(prefix)) return true;
95
+ }
96
+ return false;
97
+ }
98
+
99
+ function walkProductionTs(
100
+ root: string,
101
+ dir: string,
102
+ skipDirs: Set<string>,
103
+ ): string[] {
104
+ const out: string[] = [];
105
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
106
+ if (entry.name.startsWith(".")) continue;
107
+ if (entry.isDirectory() && skipDirs.has(entry.name)) continue;
108
+ const abs = resolve(dir, entry.name);
109
+ if (entry.isDirectory()) {
110
+ out.push(...walkProductionTs(root, abs, skipDirs));
111
+ continue;
112
+ }
113
+ if (!entry.isFile() || !entry.name.endsWith(".ts")) continue;
114
+ if (entry.name.endsWith(".test.ts") || SKIP_FILES.has(entry.name)) continue;
115
+ out.push(relative(root, abs));
116
+ }
117
+ return out;
118
+ }
package/index.ts ADDED
@@ -0,0 +1,46 @@
1
+ import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
2
+
3
+ import {
4
+ apiGuideTool,
5
+ apiFetchTool,
6
+ apiLearnTool,
7
+ apiProbeTool,
8
+ } from "./tools/index.js";
9
+ import initApiToggle from "./core/api-toggle.js";
10
+ import { registerPortalProjection } from "./core/portal-projection.js";
11
+ import { cleanupAllSpill } from "./core/response-spill.js";
12
+ import { resetToggleModuleState } from "./core/api-toggle.js";
13
+ import { resetDisabledHelpers } from "./core/local-helpers.js";
14
+
15
+ export default function (pi: ExtensionAPI): void {
16
+ // --- Ensure idempotent re-invocation ----------------------------
17
+ // pi reuses the cached extension factory on /resume (same cwd),
18
+ // which re-invokes this function with the same module-level
19
+ // singletons. Reset them here so the second load is safe.
20
+ resetToggleModuleState();
21
+ resetDisabledHelpers();
22
+ // ── Register tools ───────────────────────────────────────────
23
+ pi.registerTool(apiGuideTool);
24
+ pi.registerTool(apiFetchTool);
25
+ pi.registerTool(apiLearnTool);
26
+ pi.registerTool(apiProbeTool);
27
+
28
+ // ── Register /api command and session hooks ─────────────────
29
+ initApiToggle(pi);
30
+
31
+ // ── Portal co-install integration ────────────────────────────
32
+ // Register host's guide projection with portal if co-installed.
33
+ // Runtime feature-detect — no static portal import.
34
+ registerPortalProjection();
35
+ // session_start ensures registration even if host loads before portal.
36
+ pi.on("session_start", async () => {
37
+ registerPortalProjection();
38
+ });
39
+
40
+ // ── Response spill cleanup ─────────────────────────────────
41
+ pi.on("session_shutdown", async () => {
42
+ cleanupAllSpill();
43
+ });
44
+ // cleanupAllSpill() on shutdown + eviction cap bounds disk use.
45
+ // Add per-session cleanup if cross-conversation leaks are observed.
46
+ }
package/package.json CHANGED
@@ -1,14 +1,15 @@
1
1
  {
2
2
  "name": "pi-lean-host",
3
- "version": "0.0.1",
4
- "description": "Placeholder for future pi-lean-portal browser benchmarking suite. Host is the evaluation harness for BrowserPlugin backends against BrowserGym task suites (MiniWoB, WebArena, etc.).",
3
+ "version": "0.1.0",
4
+ "description": "Pi extension. Declarative HTTP API client — fetch structured data from REST APIs with recipe-based guides, no browser needed. Host-only installs are valid, or co-install with pi-lean-portal for API guide surfacing alongside web navigation.",
5
5
  "keywords": [
6
6
  "pi-package",
7
7
  "pi-extension",
8
- "benchmark",
9
- "browsergym",
10
- "miniwob",
11
- "webarena"
8
+ "api",
9
+ "rest",
10
+ "http",
11
+ "data",
12
+ "scraping"
12
13
  ],
13
14
  "license": "AGPL-3.0-only",
14
15
  "repository": {
@@ -21,16 +22,44 @@
21
22
  "access": "public"
22
23
  },
23
24
  "files": [
24
- "README.md",
25
- "AGENTS.md",
26
- "LICENSE"
25
+ "index.ts",
26
+ "LICENSE",
27
+ "core/ssrf-guard.ts",
28
+ "core/guide-loader.ts",
29
+ "core/api-guide-types.ts",
30
+ "core/parse-api-guide.ts",
31
+ "core/guide-store.ts",
32
+ "core/transport.ts",
33
+ "core/helpers.ts",
34
+ "core/path-template.ts",
35
+ "core/local-helpers.ts",
36
+ "core/helpers-command.ts",
37
+ "core/api-toggle.ts",
38
+ "core/portal-projection.ts",
39
+ "core/response-spill.ts",
40
+ "core/verify-ship-manifest.ts",
41
+ "tools/index.ts",
42
+ "tools/api-guide.ts",
43
+ "tools/api-fetch.ts",
44
+ "tools/api-learn.ts",
45
+ "tools/api-probe.ts",
46
+ "tools/utils.ts",
47
+ "README.md"
27
48
  ],
49
+ "pi": {
50
+ "extensions": [
51
+ "./index.ts"
52
+ ]
53
+ },
28
54
  "scripts": {
29
55
  "prepack": "cp ../../LICENSE ./LICENSE",
30
- "test": "vitest run",
31
- "test:miniwob": "npm run test",
32
- "setup:miniwob": "echo 'Not yet implemented — see browsergym-migration-plan.md §1.7'",
33
- "setup:venv": "echo 'Not yet implemented — see browsergym-migration-plan.md §1.7'"
56
+ "test": "vitest run"
57
+ },
58
+ "dependencies": {
59
+ "fast-xml-parser": "^5.7.0",
60
+ "pi-tool-masking": "^1.2.3",
61
+ "undici": "^8.0.0",
62
+ "yaml": "^2.7.0"
34
63
  },
35
64
  "peerDependencies": {
36
65
  "@earendil-works/pi-ai": "*",