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,246 @@
1
+ /**
2
+ * Local user helpers — `import()`-loaded transform modules.
3
+ *
4
+ * User-authored TypeScript helpers live alongside their guide in a per-domain
5
+ * subdirectory: `~/.pi/agent/pi-lean-host/api-guides/<domain>/helper.ts`.
6
+ * They are loaded on demand via dynamic `import()` when an API guide's
7
+ * operation sets `helper: true`. A load failure (syntax error, missing
8
+ * dep, top-level throw) or execution throw disables the helper for the
9
+ * rest of the session.
10
+ *
11
+ * One helper per domain is the v1 contract.
12
+ *
13
+ * Helper contract:
14
+ * ```ts
15
+ * export default function(
16
+ * params: Record<string, unknown>,
17
+ * ctx: { operation: string; domain: string },
18
+ * ): Record<string, unknown> | Promise<Record<string, unknown>>;
19
+ * ```
20
+ *
21
+ * The helper is a **pre-call transform**: it receives the agent-supplied
22
+ * params and returns the params the executor should use for URL
23
+ * templating / query assembly. It must be synchronous-pure or
24
+ * fully-awaited — no background work (setTimeout/setInterval/process.on
25
+ * callbacks escape as uncaughtException and cannot be caught here).
26
+ */
27
+
28
+ import { join } from "node:path";
29
+ import { pathToFileURL } from "node:url";
30
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
31
+ import { getUserGuidesDir, assertSafeDomain } from "./guide-store.js";
32
+
33
+ // ═══════════════════════════════════════════════════════════════════
34
+ // Session-level state
35
+ // ═══════════════════════════════════════════════════════════════════
36
+
37
+ const disabledHelpers = new Map<string, true>();
38
+
39
+ // ═══════════════════════════════════════════════════════════════════
40
+ // Test hooks
41
+ // ═══════════════════════════════════════════════════════════════════
42
+
43
+ export function resetDisabledHelpers(): void {
44
+ disabledHelpers.clear();
45
+ }
46
+
47
+ // ═══════════════════════════════════════════════════════════════════
48
+ // Internal — resolve a helper file path under the guides dir
49
+ // ═══════════════════════════════════════════════════════════════════
50
+
51
+ /** Find an existing helper file for the domain, or null. */
52
+ function findHelperFile(domain: string): string | null {
53
+ assertSafeDomain(domain);
54
+ const guidesDir = getUserGuidesDir();
55
+ for (const ext of [".ts", ".mjs", ".js"] as const) {
56
+ const candidate = join(guidesDir, domain, `helper${ext}`);
57
+ if (existsSync(candidate)) {
58
+ return candidate;
59
+ }
60
+ }
61
+ return null;
62
+ }
63
+
64
+ // ═══════════════════════════════════════════════════════════════════
65
+ // Public API
66
+ // ═══════════════════════════════════════════════════════════════════
67
+
68
+ /** Helper transform function type. */
69
+ export type HelperFn = (
70
+ params: Record<string, unknown>,
71
+ ctx: { operation: string; domain: string },
72
+ ) => Record<string, unknown> | Promise<Record<string, unknown>>;
73
+
74
+ /**
75
+ * Post-response transform function type — the named `transform` export of a
76
+ * guide's helper.ts. Receives the parsed response body and returns the shaped
77
+ * data. Must be synchronous-pure or fully awaited (same constraint as the
78
+ * pre-call helper).
79
+ *
80
+ * `ctx.domain` is the matched guide's `dirName`, not the routing `domain` —
81
+ * the same value api-fetch threads into the pre-call `callHelper`.
82
+ */
83
+ export type TransformFn = (
84
+ data: unknown,
85
+ ctx: { operation: string; domain: string },
86
+ ) => unknown;
87
+
88
+ /** Result of calling a helper — either transformed params or an error. */
89
+ export type CallHelperResult =
90
+ | { ok: true; params: Record<string, unknown> }
91
+ | { ok: false; error: string; disabled: boolean };
92
+
93
+ /**
94
+ * List all persisted helper domains (domain subdirs with a helper.ts).
95
+ */
96
+ export function getAllHelpers(): string[] {
97
+ const guidesDir = getUserGuidesDir();
98
+ if (!existsSync(guidesDir)) return [];
99
+ const result: string[] = [];
100
+ for (const entry of readdirSync(guidesDir)) {
101
+ const entryPath = join(guidesDir, entry);
102
+ try {
103
+ if (!statSync(entryPath).isDirectory()) continue;
104
+ } catch {
105
+ continue;
106
+ }
107
+ // Check for helper.ts (or .mjs / .js fallback for tests)
108
+ for (const ext of [".ts", ".mjs", ".js"] as const) {
109
+ if (existsSync(join(entryPath, `helper${ext}`))) {
110
+ result.push(entry);
111
+ break;
112
+ }
113
+ }
114
+ }
115
+ return result;
116
+ }
117
+
118
+ /**
119
+ * Read a helper's source for display.
120
+ */
121
+ export function readHelperSource(domain: string): string | null {
122
+ const filePath = findHelperFile(domain);
123
+ if (!filePath) return null;
124
+ try {
125
+ return readFileSync(filePath, "utf-8");
126
+ } catch {
127
+ return null;
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Return the list of disabled helper domains.
133
+ */
134
+ export function getDisabledHelperDomains(): string[] {
135
+ return Array.from(disabledHelpers.keys());
136
+ }
137
+
138
+ /**
139
+ * Load a helper module, returning the default export if present.
140
+ * Returns null when the helper file doesn't exist, is already disabled,
141
+ * or failed to load (in which case it marks it disabled).
142
+ */
143
+ async function loadHelper(domain: string): Promise<HelperFn | null> {
144
+ if (disabledHelpers.has(domain)) return null;
145
+
146
+ let filePath: string | null;
147
+ try {
148
+ filePath = findHelperFile(domain);
149
+ } catch {
150
+ // assertSafeDomain rejected a traversal domain — treat as unloadable.
151
+ disabledHelpers.set(domain, true);
152
+ return null;
153
+ }
154
+ if (!filePath) return null;
155
+
156
+ try {
157
+ const fileUrl = pathToFileURL(filePath).href;
158
+ const mod = await import(fileUrl);
159
+
160
+ if (typeof mod.default !== "function") {
161
+ disabledHelpers.set(domain, true);
162
+ return null;
163
+ }
164
+
165
+ return mod.default as HelperFn;
166
+ } catch {
167
+ disabledHelpers.set(domain, true);
168
+ return null;
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Load a guide's named `transform` export (post-response), or null.
174
+ *
175
+ * Load-only — does not invoke the transform (the executor hookpoint owns the
176
+ * invocation and its try/catch). Reuses the pre-call helper's file resolution
177
+ * (`findHelperFile`, `.ts` → `.mjs` → `.js`). Returns null when the file is
178
+ * missing, the named export is absent, or the module fails to load. No
179
+ * disable map: each call re-`import()`s (a successful load is a Node module
180
+ * cache hit) and re-attempts, per the design's graceful no-disable contract.
181
+ */
182
+ export async function loadTransform(
183
+ dirName: string,
184
+ ): Promise<TransformFn | null> {
185
+ let filePath: string | null;
186
+ try {
187
+ filePath = findHelperFile(dirName);
188
+ } catch {
189
+ // assertSafeDomain rejected a traversal domain — treat as unloadable.
190
+ return null;
191
+ }
192
+ if (!filePath) return null;
193
+
194
+ try {
195
+ const fileUrl = pathToFileURL(filePath).href;
196
+ const mod = await import(fileUrl);
197
+ if (typeof mod.transform !== "function") return null;
198
+ return mod.transform as TransformFn;
199
+ } catch {
200
+ return null;
201
+ }
202
+ }
203
+
204
+ /**
205
+ * Call a helper for the given domain and operation.
206
+ *
207
+ * Returns transformed params on success, raw params when no helper file
208
+ * exists (passthrough), or an error result when the helper is disabled
209
+ * or throws.
210
+ */
211
+ export async function callHelper(
212
+ domain: string,
213
+ operationName: string,
214
+ params: Record<string, unknown>,
215
+ ): Promise<CallHelperResult> {
216
+ const helper = await loadHelper(domain);
217
+
218
+ if (helper === null) {
219
+ if (disabledHelpers.has(domain)) {
220
+ return {
221
+ ok: false,
222
+ disabled: true,
223
+ error:
224
+ `Helper '${domain}' is disabled for this session after a load or execution failure. ` +
225
+ `Fix the helper file and restart the session.`,
226
+ };
227
+ }
228
+ // No helper file exists — passthrough unchanged.
229
+ return { ok: true, params };
230
+ }
231
+
232
+ try {
233
+ const ctx = { operation: operationName, domain };
234
+ const result = await helper(params, ctx);
235
+ return { ok: true, params: result };
236
+ } catch {
237
+ disabledHelpers.set(domain, true);
238
+ return {
239
+ ok: false,
240
+ disabled: true,
241
+ error:
242
+ `Helper '${domain}' threw during execution and has been disabled for this session. ` +
243
+ `Fix the helper file and restart the session.`,
244
+ };
245
+ }
246
+ }