pi-lean-host 0.3.1 → 0.5.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,171 @@
1
+ /**
2
+ * Generic picker with a muted description column (SelectList from
3
+ * @earendil-works/pi-tui, already a peer dep) — the two-column layout used by
4
+ * the guide picker and the oauth init wizard's grant / auth-method pickers.
5
+ *
6
+ * TUI-only for the custom component: `ctx.mode === "tui"` (custom components
7
+ * don't exist in RPC/print). Everywhere else this falls back to plain
8
+ * `ctx.ui.select` over the labels, returning the matching item's `value` —
9
+ * descriptions are dropped, the flow is not.
10
+ */
11
+
12
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
13
+ import {
14
+ Container,
15
+ type SelectItem,
16
+ SelectList,
17
+ Text,
18
+ } from "@earendil-works/pi-tui";
19
+
20
+ /** Shared SelectList theme callbacks — keep both pickers visually identical. */
21
+ function pickerTheme(theme: { fg(color: string, text: string): string }) {
22
+ return {
23
+ selectedPrefix: (text: string) => theme.fg("accent", text),
24
+ selectedText: (text: string) => theme.fg("accent", text),
25
+ description: (text: string) => theme.fg("muted", text),
26
+ scrollInfo: (text: string) => theme.fg("dim", text),
27
+ noMatch: (text: string) => theme.fg("warning", text),
28
+ };
29
+ }
30
+
31
+ export async function pickWithDescription(
32
+ ctx: ExtensionContext,
33
+ title: string,
34
+ items: SelectItem[],
35
+ ): Promise<string | undefined> {
36
+ if (ctx.mode !== "tui") {
37
+ const picked = await ctx.ui.select(
38
+ title,
39
+ items.map((i) => i.label),
40
+ );
41
+ return picked === undefined
42
+ ? undefined
43
+ : items.find((i) => i.label === picked)?.value;
44
+ }
45
+
46
+ // Defensive copy so SelectList can't retain caller-owned item objects.
47
+ const selectItems: SelectItem[] = items.map((i) => ({ ...i }));
48
+ return ctx.ui.custom<string | undefined>((tui, theme, _kb, done) => {
49
+ const container = new Container();
50
+ container.addChild(new Text(theme.fg("accent", theme.bold(title))));
51
+ const list = new SelectList(
52
+ selectItems,
53
+ Math.min(selectItems.length, 10),
54
+ pickerTheme(theme),
55
+ );
56
+ list.onSelect = (item) => done(item.value);
57
+ list.onCancel = () => done(undefined);
58
+ container.addChild(list);
59
+ container.addChild(
60
+ new Text(theme.fg("dim", "↑↓ navigate • enter select • esc cancel")),
61
+ );
62
+ return {
63
+ render(width: number) {
64
+ return container.render(width);
65
+ },
66
+ invalidate() {
67
+ container.invalidate();
68
+ },
69
+ handleInput(data: string) {
70
+ list.handleInput(data);
71
+ tui.requestRender();
72
+ },
73
+ };
74
+ });
75
+ }
76
+
77
+ // Checklist multi-select (✓/○ toggle + Done row) — the one new UI
78
+ // component of the agent-driven OAuth2 bootstrap. Same ctx.ui.custom +
79
+ // SelectList scaffolding as above; Enter on a row toggles ✓/○, Enter on the
80
+ // Done row proceeds, Esc cancels.
81
+
82
+ const DONE_VALUE = "__done__";
83
+
84
+ /**
85
+ * Multi-select checklist: Enter toggles ✓/○, Enter on the Done row resolves
86
+ * the checked values, Esc returns undefined (whole tool call cancels).
87
+ * All rows start unchecked — granting is the human's affirmative act.
88
+ * Non-TUI fallback: comma-separated `ctx.ui.input` over the names.
89
+ */
90
+ export async function pickChecklist(
91
+ ctx: ExtensionContext,
92
+ title: string,
93
+ rows: SelectItem[],
94
+ ): Promise<string[] | undefined> {
95
+ if (ctx.mode !== "tui") {
96
+ const raw = await ctx.ui.input(
97
+ `${title} — comma-separated names to grant`,
98
+ rows.map((r) => r.value).join(","),
99
+ );
100
+ if (raw === undefined) return undefined;
101
+ return raw
102
+ .split(",")
103
+ .map((s) => s.trim())
104
+ .filter((v) => rows.some((r) => r.value === v));
105
+ }
106
+
107
+ const checked = new Set<string>();
108
+ return ctx.ui.custom<string[] | undefined>((tui, theme, _kb, done) => {
109
+ const container = new Container();
110
+ let selectedIndex = 0;
111
+ let list = buildList();
112
+
113
+ function buildList(): SelectList {
114
+ const selectItems: SelectItem[] = rows.map((r) => ({
115
+ ...r,
116
+ label: `${checked.has(r.value) ? "✓" : "○"} ${r.label}`,
117
+ }));
118
+ selectItems.push({
119
+ value: DONE_VALUE,
120
+ label: "✔ Done — grant the checked scopes",
121
+ });
122
+ const fresh = new SelectList(
123
+ selectItems,
124
+ Math.min(selectItems.length, 12),
125
+ pickerTheme(theme),
126
+ );
127
+ fresh.setSelectedIndex(Math.min(selectedIndex, selectItems.length - 1));
128
+ fresh.onSelectionChange = (item) => {
129
+ const at = selectItems.findIndex((s) => s.value === item.value);
130
+ if (at >= 0) selectedIndex = at;
131
+ };
132
+ fresh.onSelect = (item) => {
133
+ if (item.value === DONE_VALUE) {
134
+ done([...checked]);
135
+ return;
136
+ }
137
+ if (checked.has(item.value)) checked.delete(item.value);
138
+ else checked.add(item.value);
139
+ // Rebuild so the ✓/○ prefixes re-render; the highlight follows
140
+ // the tracked index across the swap.
141
+ container.removeChild(list);
142
+ list = buildList();
143
+ container.addChild(list);
144
+ // addChild appends — keep the footer below the rebuilt list.
145
+ container.removeChild(footer);
146
+ container.addChild(footer);
147
+ };
148
+ fresh.onCancel = () => done(undefined);
149
+ return fresh;
150
+ }
151
+
152
+ container.addChild(new Text(theme.fg("accent", theme.bold(title))));
153
+ container.addChild(list);
154
+ const footer = new Text(
155
+ theme.fg("dim", "↑↓ navigate • enter toggle • esc cancel all"),
156
+ );
157
+ container.addChild(footer);
158
+ return {
159
+ render(width: number) {
160
+ return container.render(width);
161
+ },
162
+ invalidate() {
163
+ container.invalidate();
164
+ },
165
+ handleInput(data: string) {
166
+ list.handleInput(data);
167
+ tui.requestRender();
168
+ },
169
+ };
170
+ });
171
+ }
@@ -0,0 +1,29 @@
1
+ /**
2
+ * Shared /tmp staging root for api-learn + api-scaffold staged drafts.
3
+ * Both tools must agree on this root at runtime — scaffold stages drafts
4
+ * that learn's save reads.
5
+ */
6
+
7
+ import { tmpdir } from "node:os";
8
+ import { join, sep } from "node:path";
9
+
10
+ let _stagingRoot = join(tmpdir(), "pi-lean-host");
11
+
12
+ /** Test override — mirrors `setUserGuidesDir` so tests keep drafts out of
13
+ * the real /tmp root. */
14
+ export function setStagingRoot(dir: string): void {
15
+ _stagingRoot = dir;
16
+ }
17
+
18
+ /** Deterministic staged dir: `<root>/<key>/`. The key is the requested
19
+ * `domain` for templates (placeholder shortName) and `slug(shortName)` for
20
+ * fetched recipes (which is the on-disk dirName). */
21
+ export function stagingDirFor(key: string): string {
22
+ return join(_stagingRoot, key);
23
+ }
24
+
25
+ /** True when `p` is a staged dir under the staging root (the root itself
26
+ * excluded — save must never try to rename the whole root). */
27
+ export function isUnderStagingRoot(p: string): boolean {
28
+ return p !== _stagingRoot && p.startsWith(`${_stagingRoot}${sep}`);
29
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Shared HTTP-error classification for the probe and fetch paths.
3
+ *
4
+ * Both api-probe and api-fetch (/api verify) hit the same real-world 403
5
+ * reality: an authenticated-but-forbidden response whose body carries the
6
+ * server's own reason. One classifier keeps the two paths from drifting —
7
+ * probe used to surface the server message while fetch threw a bare status,
8
+ * which made plan-gated 403s read as recipe bugs.
9
+ */
10
+
11
+ /** Structured "plan not authorized" signal — a 403 whose extracted reason
12
+ * mentions any of these is a key/subscription limitation, not a recipe bug.
13
+ * ponytail: keyword match, not a per-API catalog — error-code 1006 is the
14
+ * motivating case; add provider error-code regexes here if one uses a code
15
+ * without a matching word. */
16
+ const PLAN_GATING = /plan|subscription|tier|not authorized|insufficient|1006/i;
17
+
18
+ function isObj(data: unknown): data is object {
19
+ return typeof data === "object" && data !== null && !Array.isArray(data);
20
+ }
21
+
22
+ /** Extracts the server's own human-readable reason from an error body — the
23
+ * note says what the API actually means instead of a synthesized
24
+ * classification. Returns undefined when the body isn't JSON or carries no
25
+ * message field; the caller falls back to the bare status.
26
+ * ponytail: secret-scrub invariant — callers MUST pass the scrubbed body,
27
+ * never the raw one, or a key echoed in the body would leak into agent
28
+ * context. */
29
+ export function serverMessage(raw: string): string | undefined {
30
+ let data: unknown;
31
+ try {
32
+ data = JSON.parse(raw);
33
+ } catch {
34
+ return undefined;
35
+ }
36
+ if (!isObj(data)) return undefined;
37
+ const d = data as Record<string, unknown>;
38
+ const status = isObj(d["status"])
39
+ ? (d["status"] as Record<string, unknown>)
40
+ : undefined;
41
+ const candidates: unknown[] = [
42
+ d["message"],
43
+ d["error"],
44
+ d["error_message"],
45
+ d["detail"],
46
+ status?.["error_message"],
47
+ ];
48
+ const msg = candidates.find(
49
+ (c) => typeof c === "string" && c.trim().length > 0,
50
+ );
51
+ return typeof msg === "string" ? msg.trim().slice(0, 200) : undefined;
52
+ }
53
+
54
+ /** True when the body signals a plan/subscription limitation rather than a
55
+ * recipe or credential problem. Tests the whole body (not just the
56
+ * extracted message) so bare error codes like 1006 are caught even when no
57
+ * message field exists. Callers pass the scrubbed body, per the invariant
58
+ * on `serverMessage`. */
59
+ export function isPlanGated(raw: string): boolean {
60
+ return PLAN_GATING.test(raw);
61
+ }