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.
- package/README.md +761 -30
- package/core/api-guide-types.ts +244 -0
- package/core/api-toggle.ts +313 -0
- package/core/guide-loader.ts +80 -0
- package/core/guide-store.ts +125 -0
- package/core/helpers-command.ts +110 -0
- package/core/helpers.ts +792 -0
- package/core/local-helpers.ts +246 -0
- package/core/parse-api-guide.ts +1218 -0
- package/core/path-template.ts +50 -0
- package/core/portal-projection.ts +69 -0
- package/core/response-spill.ts +185 -0
- package/core/ssrf-guard.ts +99 -0
- package/core/transport.ts +440 -0
- package/core/verify-ship-manifest.ts +118 -0
- package/index.ts +46 -0
- package/package.json +42 -13
- package/tools/api-fetch.ts +578 -0
- package/tools/api-guide.ts +320 -0
- package/tools/api-learn.ts +348 -0
- package/tools/api-probe.ts +500 -0
- package/tools/index.ts +7 -0
- package/tools/utils.ts +34 -0
- package/AGENTS.md +0 -22
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Shared path-templating utilities.
|
|
3
|
+
*
|
|
4
|
+
* Owned as a single module (not duplicated across helpers.ts, api-probe.ts,
|
|
5
|
+
* and parse-api-guide.ts) so the executor (`restGet`/`paginate`), the
|
|
6
|
+
* authoring tool (`api-probe`), and the parser share one implementation.
|
|
7
|
+
*
|
|
8
|
+
* - `extractPathTokens` — pull `{token}` names out of a templated path.
|
|
9
|
+
* - `fillPathTemplate` — substitute `{token}` placeholders from params.
|
|
10
|
+
* - `joinUrl` — join a base host + path + query string into a full URL.
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** Extract `{token}` names from a templated path, in order, deduplicated. */
|
|
14
|
+
export function extractPathTokens(path: string): string[] {
|
|
15
|
+
const out: string[] = [];
|
|
16
|
+
for (const m of path.matchAll(/\{(\w+)\}/g)) {
|
|
17
|
+
const token = m[1];
|
|
18
|
+
if (token && !out.includes(token)) out.push(token);
|
|
19
|
+
}
|
|
20
|
+
return out;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Replace `{token}` placeholders in `path` with `encodeURIComponent`'d
|
|
25
|
+
* values from `params`. Tokens absent from `params` fall through to
|
|
26
|
+
* `onMissing` (default: keep the `{token}` literal — useful for probing a
|
|
27
|
+
* not-yet-filled path). Execution callers pass an `onMissing` that throws.
|
|
28
|
+
*/
|
|
29
|
+
export function fillPathTemplate(
|
|
30
|
+
path: string,
|
|
31
|
+
params: Record<string, unknown>,
|
|
32
|
+
onMissing: (token: string) => string = (token) => `{${token}}`,
|
|
33
|
+
): string {
|
|
34
|
+
return path.replace(/\{(\w+)\}/g, (_, token) => {
|
|
35
|
+
const val = params[token];
|
|
36
|
+
if (val === undefined) return onMissing(token);
|
|
37
|
+
return encodeURIComponent(String(val));
|
|
38
|
+
});
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
/**
|
|
42
|
+
* Join a base host, a (possibly leading-`/`) path, and an already-built
|
|
43
|
+
* query string into a full absolute URL.
|
|
44
|
+
*/
|
|
45
|
+
export function joinUrl(baseHost: string, path: string, query: string): string {
|
|
46
|
+
const base = baseHost.endsWith("/") ? baseHost : `${baseHost}/`;
|
|
47
|
+
const rel = path.startsWith("/") ? path.slice(1) : path;
|
|
48
|
+
const url = new URL(rel, base).toString();
|
|
49
|
+
return query ? `${url}${url.includes("?") ? "&" : "?"}${query}` : url;
|
|
50
|
+
}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Portal co-install integration — host-only boundary-safe runtime feature-detect.
|
|
3
|
+
*
|
|
4
|
+
* Registers host's guide projection with portal's guide-provider registry
|
|
5
|
+
* when portal is co-installed. Detection uses a global probe
|
|
6
|
+
* (globalThis.__piLeanPortalRegisterGuideProvider) — no static portal
|
|
7
|
+
* import, so the host-only boundary test stays green.
|
|
8
|
+
*
|
|
9
|
+
* The registered provider returns a projectToGuide() projection of every
|
|
10
|
+
* loaded ApiGuide, with recipe fields stripped and kind: "api" set. It
|
|
11
|
+
* self-gates — returns {} when /api toggle is off, so no host guide
|
|
12
|
+
* surfaces in portal's footer unless the user has turned the API tools on.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import type { Guide } from "./guide-loader.js";
|
|
16
|
+
import { loadAllGuides } from "./guide-store.js";
|
|
17
|
+
import { projectToGuide } from "./parse-api-guide.js";
|
|
18
|
+
import { getApiToggleState } from "./api-toggle.js";
|
|
19
|
+
|
|
20
|
+
// The global key portal's index.ts sets at load time.
|
|
21
|
+
const PORTAL_REGISTRY_KEY = "__piLeanPortalRegisterGuideProvider";
|
|
22
|
+
|
|
23
|
+
let _registered = false;
|
|
24
|
+
|
|
25
|
+
/**
|
|
26
|
+
* Build a snapshot of host's guide projections.
|
|
27
|
+
* Recipe fields (apiHost, operations, auth, pagination, responseShape) are
|
|
28
|
+
* stripped by projectToGuide(); only the presentation slice + kind remain.
|
|
29
|
+
* Self-gates on the /api toggle state.
|
|
30
|
+
*/
|
|
31
|
+
function buildProjection(): Record<string, Guide> {
|
|
32
|
+
if (!getApiToggleState()) return {};
|
|
33
|
+
|
|
34
|
+
const { guides } = loadAllGuides();
|
|
35
|
+
const out: Record<string, Guide> = {};
|
|
36
|
+
for (const [name, guide] of Object.entries(guides)) {
|
|
37
|
+
out[name] = projectToGuide(guide);
|
|
38
|
+
}
|
|
39
|
+
return out;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* Register host's guide projection with portal, if portal is co-installed.
|
|
44
|
+
*
|
|
45
|
+
* Uses runtime feature-detection (global property) instead of a static
|
|
46
|
+
* import — safe for host-only installs. Idempotent: subsequent calls are
|
|
47
|
+
* no-ops after the first successful registration.
|
|
48
|
+
*/
|
|
49
|
+
export function registerPortalProjection(): void {
|
|
50
|
+
if (_registered) return;
|
|
51
|
+
|
|
52
|
+
const fn = (globalThis as Record<string, unknown>)[PORTAL_REGISTRY_KEY];
|
|
53
|
+
if (typeof fn !== "function") {
|
|
54
|
+
// Portal not installed or not yet loaded — no-op.
|
|
55
|
+
return;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
try {
|
|
59
|
+
(fn as (provider: () => Record<string, Guide>) => void)(buildProjection);
|
|
60
|
+
_registered = true;
|
|
61
|
+
} catch {
|
|
62
|
+
// Portal present but registration failed — degrade to host-only.
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/** @internal Reset registration state (test helper). */
|
|
67
|
+
export function _resetPortalProjectionForTest(): void {
|
|
68
|
+
_registered = false;
|
|
69
|
+
}
|
|
@@ -0,0 +1,185 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Response Disk Spill — full JSON spilled to disk when api-fetch truncates.
|
|
3
|
+
*
|
|
4
|
+
* Mirrors portal's snapshot-cache.ts and fetch-backend.ts patterns:
|
|
5
|
+
* - Pure utility functions, no class
|
|
6
|
+
* - Writes only when truncation occurred (json > INLINE_LIMIT)
|
|
7
|
+
* - Graceful I/O degradation (try-catch, returns null on error)
|
|
8
|
+
* - Max 8 files per conversation session (oldest evicted)
|
|
9
|
+
*
|
|
10
|
+
* @module response-spill
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
import { writeFileSync, rmSync, mkdirSync } from "node:fs";
|
|
14
|
+
import { tmpdir } from "node:os";
|
|
15
|
+
import { createHash } from "node:crypto";
|
|
16
|
+
import { join } from "node:path";
|
|
17
|
+
|
|
18
|
+
// ─── Constants ──────────────────────────────────────────────────────────
|
|
19
|
+
|
|
20
|
+
/** Max cached spill files per session (conversation). */
|
|
21
|
+
// ponytail: cap; raise if agent reads >8 distinct ops concurrently
|
|
22
|
+
const MAX_FILES_PER_SESSION = 8;
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Spill-file char count above which a size warning is shown.
|
|
26
|
+
* 100k chars ≈ a few hundred KB of pretty-printed JSON.
|
|
27
|
+
*/
|
|
28
|
+
// ponytail: threshold; tune if agents routinely pull large legit responses
|
|
29
|
+
const LARGE_SPILL_THRESHOLD = 100_000;
|
|
30
|
+
|
|
31
|
+
// ─── Types ──────────────────────────────────────────────────────────────
|
|
32
|
+
|
|
33
|
+
/** Result of a spill attempt (null = not spilled for any reason). */
|
|
34
|
+
export interface SpillResult {
|
|
35
|
+
/** Absolute path to the spilled JSON file. */
|
|
36
|
+
path: string;
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/** Internal tracking entry. */
|
|
40
|
+
interface SpillEntry {
|
|
41
|
+
path: string;
|
|
42
|
+
timestamp: number;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
// ─── Internal state ────────────────────────────────────────────────────
|
|
46
|
+
|
|
47
|
+
const activeFiles = new Map<string, SpillEntry[]>();
|
|
48
|
+
let _indexCounter = 0;
|
|
49
|
+
|
|
50
|
+
// ─── Helpers ────────────────────────────────────────────────────────────
|
|
51
|
+
|
|
52
|
+
function getHostTempDir(): string {
|
|
53
|
+
return process.env.PI_HOST_TEMP_DIR ?? `${tmpdir()}/pi-lean-host`;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function ensureHostTempDir(): void {
|
|
57
|
+
try {
|
|
58
|
+
mkdirSync(getHostTempDir(), { recursive: true });
|
|
59
|
+
} catch {
|
|
60
|
+
/* best-effort */
|
|
61
|
+
}
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function sha256Prefix(content: string): string {
|
|
65
|
+
return createHash("sha256").update(content).digest("hex").slice(0, 8);
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Sanitize a session key for use in filenames. */
|
|
69
|
+
function safeSessionKey(s: string): string {
|
|
70
|
+
return s.replace(/[^a-zA-Z0-9-]/g, "_");
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
// ─── Public API ─────────────────────────────────────────────────────────
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* Spill a full JSON response to a temp file.
|
|
77
|
+
*
|
|
78
|
+
* Writes only when `json` is longer than 4000 chars (truncation will
|
|
79
|
+
* occur). Gracefully degrades to a no-op on any filesystem error.
|
|
80
|
+
* Evicts the oldest file per session when the count exceeds
|
|
81
|
+
* MAX_FILES_PER_SESSION.
|
|
82
|
+
*
|
|
83
|
+
* @param json - The full JSON string to spill
|
|
84
|
+
* @param sessionKey - Conversation-scoped key (e.g. pi session ID)
|
|
85
|
+
* @returns A SpillResult with path, or null if not spilled
|
|
86
|
+
*/
|
|
87
|
+
export function spillResponse(
|
|
88
|
+
json: string,
|
|
89
|
+
sessionKey: string,
|
|
90
|
+
): SpillResult | null {
|
|
91
|
+
if (json.length <= 4000) {
|
|
92
|
+
return null;
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
ensureHostTempDir();
|
|
97
|
+
|
|
98
|
+
const digest = sha256Prefix(json);
|
|
99
|
+
const entries = activeFiles.get(sessionKey) ?? [];
|
|
100
|
+
const index = _indexCounter++;
|
|
101
|
+
const safe = safeSessionKey(sessionKey);
|
|
102
|
+
const filePath = join(
|
|
103
|
+
getHostTempDir(),
|
|
104
|
+
`response-${safe}-${digest}-${index}.json`,
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
writeFileSync(filePath, json, "utf-8");
|
|
108
|
+
|
|
109
|
+
const newEntry: SpillEntry = { path: filePath, timestamp: Date.now() };
|
|
110
|
+
entries.push(newEntry);
|
|
111
|
+
activeFiles.set(sessionKey, entries);
|
|
112
|
+
|
|
113
|
+
// Evict oldest if over limit
|
|
114
|
+
if (entries.length > MAX_FILES_PER_SESSION) {
|
|
115
|
+
entries.sort((a, b) => a.timestamp - b.timestamp);
|
|
116
|
+
const toRemove = entries.splice(
|
|
117
|
+
0,
|
|
118
|
+
entries.length - MAX_FILES_PER_SESSION,
|
|
119
|
+
);
|
|
120
|
+
for (const entry of toRemove) {
|
|
121
|
+
try {
|
|
122
|
+
rmSync(entry.path, { force: true });
|
|
123
|
+
} catch {
|
|
124
|
+
/* best-effort */
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
return { path: filePath };
|
|
130
|
+
} catch {
|
|
131
|
+
// Graceful degradation: any I/O error → no spill
|
|
132
|
+
return null;
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* Remove ALL spilled files tracked by this process across all sessions.
|
|
138
|
+
* Called during session_shutdown.
|
|
139
|
+
*
|
|
140
|
+
* Only files this process created (tracked in `activeFiles`) are removed —
|
|
141
|
+
* the shared temp dir is left in place so a concurrent pi session's spill
|
|
142
|
+
* files aren't deleted out from under it.
|
|
143
|
+
*/
|
|
144
|
+
export function cleanupAllSpill(): void {
|
|
145
|
+
for (const [, entries] of activeFiles) {
|
|
146
|
+
for (const entry of entries) {
|
|
147
|
+
try {
|
|
148
|
+
rmSync(entry.path, { force: true });
|
|
149
|
+
} catch {
|
|
150
|
+
/* best-effort */
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
activeFiles.clear();
|
|
155
|
+
}
|
|
156
|
+
|
|
157
|
+
/**
|
|
158
|
+
* Build a hint string for the truncated-response spill notice.
|
|
159
|
+
*
|
|
160
|
+
* Returns a line pointing at the spill file when a result exists,
|
|
161
|
+
* or a graceful-degradation fallback when it doesn't.
|
|
162
|
+
*/
|
|
163
|
+
export function formatSpillNotice(
|
|
164
|
+
spill: SpillResult | null,
|
|
165
|
+
jsonLength: number,
|
|
166
|
+
): string {
|
|
167
|
+
if (!spill) {
|
|
168
|
+
return (
|
|
169
|
+
`\n_Response truncated at 4000 chars. Full response has ${jsonLength} chars ` +
|
|
170
|
+
`(disk spill unavailable — re-call api-fetch to regenerate)._`
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
const lines: string[] = [];
|
|
174
|
+
if (jsonLength > LARGE_SPILL_THRESHOLD) {
|
|
175
|
+
lines.push(
|
|
176
|
+
`⚠ Very large response — narrow your query params to reduce the result size.`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
lines.push(
|
|
180
|
+
`📄 Full response (${jsonLength} chars) written to ${spill.path}. ` +
|
|
181
|
+
`Search it with grep for the field you need (e.g. \`grep -o '"<field>":[^,]*' ${spill.path}\`), ` +
|
|
182
|
+
`or page through it with read + offset/limit — before calling api-fetch again, the data may already be here.`,
|
|
183
|
+
);
|
|
184
|
+
return lines.join("\n");
|
|
185
|
+
}
|
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* SSRF guard — blocks loopback, private RFC1918 ranges, and cloud metadata
|
|
3
|
+
* endpoints on server-supplied URLs only (paginate nextLink).
|
|
4
|
+
*
|
|
5
|
+
* Agent-supplied URLs (restGet / buildUrl) are NOT guarded — the agent has
|
|
6
|
+
* bash, so guarding them is theater. Scheme-blocking is redundant (undici
|
|
7
|
+
* only fetches http:/https:). The secret-in-URL regex is omitted (host
|
|
8
|
+
* doesn't handle secrets in v1).
|
|
9
|
+
*
|
|
10
|
+
* The guard becomes load-bearing when auth.kind:static-key / oauth2 ships:
|
|
11
|
+
* at that point a server-supplied nextUrl to an internal host would leak
|
|
12
|
+
* the Authorization header — textbook SSRF.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
// ─── Blocked hostnames ───────────────────────────────────────────────
|
|
16
|
+
|
|
17
|
+
const BLOCKED_HOSTNAMES = [
|
|
18
|
+
"localhost",
|
|
19
|
+
"127.0.0.1",
|
|
20
|
+
"0.0.0.0",
|
|
21
|
+
"169.254.169.254", // AWS/GCP metadata endpoint
|
|
22
|
+
"metadata.google.internal",
|
|
23
|
+
"100.100.100.200", // Alibaba Cloud metadata
|
|
24
|
+
];
|
|
25
|
+
|
|
26
|
+
/** Regex for internal IPv4: loopback (127.0.0.0/8), link-local (169.254.0.0/16), RFC1918 private (10.x, 172.16-31.x, 192.168.x) */
|
|
27
|
+
const INTERNAL_IP_REGEX =
|
|
28
|
+
/^(10\.|127\.|169\.254\.|172\.(1[6-9]|2\d|3[01])\.|192\.168\.)/;
|
|
29
|
+
|
|
30
|
+
// ─── Guard ───────────────────────────────────────────────────────────
|
|
31
|
+
|
|
32
|
+
export function ssrfGuard(
|
|
33
|
+
rawUrl: string,
|
|
34
|
+
): { ok: true } | { ok: false; reason: string } {
|
|
35
|
+
let parsed: URL;
|
|
36
|
+
try {
|
|
37
|
+
parsed = new URL(rawUrl);
|
|
38
|
+
} catch {
|
|
39
|
+
return { ok: false, reason: "Malformed URL" };
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const hostname = parsed.hostname.toLowerCase();
|
|
43
|
+
|
|
44
|
+
// Check against blocked hostname list (exact or subdomain match).
|
|
45
|
+
for (const blocked of BLOCKED_HOSTNAMES) {
|
|
46
|
+
if (hostname === blocked || hostname.endsWith("." + blocked)) {
|
|
47
|
+
return {
|
|
48
|
+
ok: false,
|
|
49
|
+
reason: `Blocked hostname: ${hostname} (private/internal network)`,
|
|
50
|
+
};
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
// Check for internal IP ranges (loopback, link-local, private).
|
|
55
|
+
if (INTERNAL_IP_REGEX.test(hostname)) {
|
|
56
|
+
return {
|
|
57
|
+
ok: false,
|
|
58
|
+
reason: `Blocked IP range: ${hostname} (internal network)`,
|
|
59
|
+
};
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
// Check IPv6. Node's URL.hostname INCLUDES brackets for IPv6 (e.g.
|
|
63
|
+
// "[::1]", "[fe80::1]"), so strip them and match structurally — a
|
|
64
|
+
// substring match on "::1" would also hit public addresses like
|
|
65
|
+
// "2001:db8::1:2:3".
|
|
66
|
+
const ipv6Inner = hostname.replace(/^\[|\]$/g, "");
|
|
67
|
+
|
|
68
|
+
// Loopback is exactly ::1.
|
|
69
|
+
if (ipv6Inner === "::1") {
|
|
70
|
+
return {
|
|
71
|
+
ok: false,
|
|
72
|
+
reason: `Blocked IPv6 address: ${hostname} (loopback)`,
|
|
73
|
+
};
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
// Link-local (fe80::/10 → first hextet fe80-febf) and unique-local
|
|
77
|
+
// (fc00::/7 → first hextet fc00-fdff).
|
|
78
|
+
if (/^(fe[89ab][0-9a-f]|f[cd][0-9a-f]{2}):/i.test(ipv6Inner)) {
|
|
79
|
+
return {
|
|
80
|
+
ok: false,
|
|
81
|
+
reason: `Blocked IPv6 address: ${hostname} (link-local / unique-local)`,
|
|
82
|
+
};
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
// IPv4-mapped IPv6 — the ::ffff: prefix marks the family. Node renders
|
|
86
|
+
// these in HEX (e.g. "[::ffff:7f00:1]"), so a decimal string check is
|
|
87
|
+
// silently dead. No legitimate public API serves nextLinks over
|
|
88
|
+
// IPv4-mapped IPv6, so reject the whole family rather than decoding the
|
|
89
|
+
// embedded IPv4. Match the prefix, not a substring — "::ffff:" can
|
|
90
|
+
// also appear mid-address in a legit public IPv6 like "2001:db8::ffff:1".
|
|
91
|
+
if (ipv6Inner.startsWith("::ffff:")) {
|
|
92
|
+
return {
|
|
93
|
+
ok: false,
|
|
94
|
+
reason: `Blocked IPv4-mapped IPv6 address: ${hostname} (private/internal network)`,
|
|
95
|
+
};
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
return { ok: true };
|
|
99
|
+
}
|