pi-lean-host 0.0.1 → 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.
@@ -0,0 +1,125 @@
1
+ /**
2
+ * Guide store — loads and caches user-authored API guides.
3
+ *
4
+ * Provides the lookup primitives that `api-guide`, `api-fetch`, and
5
+ * `api-learn` tools share. Caches per session; call `invalidateCache()`
6
+ * after a write operation so the next read picks up the new guide.
7
+ */
8
+
9
+ import { join } from "node:path";
10
+ import { homedir } from "node:os";
11
+ import {
12
+ loadApiGuidesFromDir,
13
+ formatApiGuideCatalog,
14
+ } from "./parse-api-guide.js";
15
+ import { buildDomainMap } from "./guide-loader.js";
16
+ import type { ApiGuide, LoadedApiGuides } from "./api-guide-types.js";
17
+
18
+ // ═══════════════════════════════════════════════════════════════════
19
+ // Directory resolution
20
+ // ═══════════════════════════════════════════════════════════════════
21
+
22
+ let _userGuidesDir = join(
23
+ homedir(),
24
+ ".pi",
25
+ "agent",
26
+ "pi-lean-host",
27
+ "api-guides",
28
+ );
29
+
30
+ /** Cache — null = dirty. */
31
+ let _cache: {
32
+ loaded: LoadedApiGuides;
33
+ domainMap: Record<string, string[]>;
34
+ } | null = null;
35
+
36
+ // ═══════════════════════════════════════════════════════════════════
37
+ // Public API — override hooks for testing
38
+ // ═══════════════════════════════════════════════════════════════════
39
+
40
+ export function getUserGuidesDir(): string {
41
+ return _userGuidesDir;
42
+ }
43
+
44
+ export function setUserGuidesDir(dir: string): void {
45
+ _userGuidesDir = dir;
46
+ _cache = null;
47
+ }
48
+
49
+ export function invalidateCache(): void {
50
+ _cache = null;
51
+ }
52
+
53
+ /**
54
+ * Reject a `domain` that could escape the guides dir via path traversal.
55
+ *
56
+ * Domains are used in `join(guidesDir, domain, ...)` for helper lookups
57
+ * and guide writes. A user-typed `/api helpers ../../foo` or an agent
58
+ * `api-learn({domain: "../x"})` must not read or write outside the
59
+ * guides dir. Returns the domain if safe, throws otherwise.
60
+ */
61
+ export function assertSafeDomain(domain: string): string {
62
+ // A safe domain is a single path segment: no separators, no NUL,
63
+ // and not "."/".." (self/parent). Anything else is a literal dir name.
64
+ if (
65
+ domain.length === 0 ||
66
+ domain.includes("/") ||
67
+ domain.includes("\\") ||
68
+ domain.includes("\0") ||
69
+ domain === "." ||
70
+ domain === ".."
71
+ ) {
72
+ throw new Error(
73
+ `Invalid domain '${domain}': must be a single path segment with no '/', '\\', or '..'.`,
74
+ );
75
+ }
76
+ return domain;
77
+ }
78
+
79
+ // ═══════════════════════════════════════════════════════════════════
80
+ // Internal load
81
+ // ═══════════════════════════════════════════════════════════════════
82
+
83
+ function load(): {
84
+ loaded: LoadedApiGuides;
85
+ domainMap: Record<string, string[]>;
86
+ } {
87
+ if (_cache) return _cache;
88
+
89
+ const user = loadApiGuidesFromDir(_userGuidesDir);
90
+
91
+ const loaded: LoadedApiGuides = {
92
+ guides: user.guides,
93
+ malformed: user.malformed,
94
+ };
95
+ const domainMap = buildDomainMap(user.guides);
96
+
97
+ _cache = { loaded, domainMap };
98
+ return _cache;
99
+ }
100
+
101
+ // ═══════════════════════════════════════════════════════════════════
102
+ // Public lookup API
103
+ // ═══════════════════════════════════════════════════════════════════
104
+
105
+ export function loadAllGuides(): LoadedApiGuides {
106
+ return load().loaded;
107
+ }
108
+
109
+ export function findGuidesByDomain(
110
+ domain: string,
111
+ ): { guide: ApiGuide; dirName: string }[] {
112
+ const { loaded, domainMap } = load();
113
+ const names = domainMap[domain];
114
+ if (!names) return [];
115
+ const out: { guide: ApiGuide; dirName: string }[] = [];
116
+ for (const name of names) {
117
+ const guide = loaded.guides[name];
118
+ if (guide) out.push({ guide, dirName: name });
119
+ }
120
+ return out;
121
+ }
122
+
123
+ export function getCatalogText(): string {
124
+ return formatApiGuideCatalog(load().loaded);
125
+ }
@@ -0,0 +1,110 @@
1
+ /**
2
+ * `/api helpers [domain]` — list and read local user helpers.
3
+ *
4
+ * Visibility-only read command. Authoring is via `api-learn` in learn mode
5
+ * (or hand-editing the helper file).
6
+ *
7
+ * Mirrors `/web cookies list` / `/web profile` in portal.
8
+ */
9
+
10
+ import type { ExtensionCommandContext } from "@earendil-works/pi-coding-agent";
11
+ import {
12
+ getAllHelpers,
13
+ readHelperSource,
14
+ getDisabledHelperDomains,
15
+ } from "./local-helpers.js";
16
+
17
+ /**
18
+ * Handle the `helpers` subcommand of `/api`.
19
+ *
20
+ * @param args The text after "helpers" (e.g. "" for list, "boe.es" for detail)
21
+ * @param ctx The extension command context
22
+ */
23
+ export async function handleHelpersSubcommand(
24
+ args: string,
25
+ ctx: ExtensionCommandContext,
26
+ ): Promise<void> {
27
+ const domain = args.trim();
28
+
29
+ if (!domain) {
30
+ // ── List all helpers ────────────────────────────────────
31
+ const all = getAllHelpers();
32
+ const disabled = getDisabledHelperDomains();
33
+ const disabledSet = new Set(disabled);
34
+
35
+ if (all.length === 0) {
36
+ ctx.ui.notify(
37
+ "No local helpers found. Helpers live alongside their guide: " +
38
+ `api-guides/<domain>/helper.ts.\n\n` +
39
+ "Author a helper via api-learn in learn mode, or hand-edit a <domain>/helper.ts file.",
40
+ "info",
41
+ );
42
+ return;
43
+ }
44
+
45
+ const lines: string[] = [`Found ${all.length} helper(s):`, ""];
46
+
47
+ for (const name of all) {
48
+ if (disabledSet.has(name)) {
49
+ lines.push(` ⚠ ${name} (disabled — errored this session)`);
50
+ } else {
51
+ lines.push(` · ${name}`);
52
+ }
53
+ }
54
+
55
+ lines.push(
56
+ "",
57
+ "Call /api helpers <domain> to view a helper's source.",
58
+ "Call api-learn({domain, recipe}) to author or update a guide (and its helper).",
59
+ );
60
+
61
+ ctx.ui.notify(lines.join("\n"), "info");
62
+ return;
63
+ }
64
+
65
+ // ── Show single helper source ───────────────────────────────
66
+ // readHelperSource → findHelperFile → assertSafeDomain throws on
67
+ // path-traversal domains (e.g. `/api helpers ../../foo`).
68
+ let source: string | null;
69
+ try {
70
+ source = readHelperSource(domain);
71
+ } catch (err) {
72
+ ctx.ui.notify(
73
+ err instanceof Error ? err.message : `Invalid domain '${domain}'.`,
74
+ "warning",
75
+ );
76
+ return;
77
+ }
78
+ if (source === null) {
79
+ const all = getAllHelpers();
80
+ const known =
81
+ all.length > 0
82
+ ? ` Known helpers: ${all.join(", ")}.`
83
+ : " No helpers found.";
84
+ ctx.ui.notify(
85
+ `No helper for '${domain}'.${known}\n\n` +
86
+ `Helpers live alongside guides at api-guides/${domain}/helper.ts.\n` +
87
+ "Author via api-learn in learn mode.",
88
+ "warning",
89
+ );
90
+ return;
91
+ }
92
+
93
+ const lines: string[] = [
94
+ `📋 Helper: ${domain}.ts`,
95
+ "",
96
+ "```typescript",
97
+ source,
98
+ "```",
99
+ "",
100
+ "Helper contract:",
101
+ " (params: Record<string, unknown>, ctx: { operation: string; domain: string })",
102
+ " => Record<string, unknown> | Promise<Record<string, unknown>>",
103
+ "",
104
+ "The helper is a synchronous-pure or fully-awaited pre-call transform.",
105
+ "No background work — setTimeout/setInterval/process.on callbacks",
106
+ "escape as uncaughtException and cannot be caught.",
107
+ ];
108
+
109
+ ctx.ui.notify(lines.join("\n"), "info");
110
+ }