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,244 @@
1
+ /**
2
+ * API guide recipe schema types — the richer `ApiGuide extends Guide` shape.
3
+ *
4
+ * The projection slice (Guide) lives in guide-loader.ts; this file owns the
5
+ * recipe slice (apiHost, operations, auth, pagination, responseShape) that
6
+ * host consumes internally and never crosses to portal.
7
+ */
8
+
9
+ import type { Guide } from "./guide-loader.js";
10
+
11
+ // ═══════════════════════════════════════════════════════════════════
12
+ // Constants
13
+ // ═══════════════════════════════════════════════════════════════════
14
+
15
+ /**
16
+ * Global fallback ceiling for `gatherAll` when a guide declares no
17
+ * `gatherAllMax`. Prevents self-DoS against a 100k-item paginator.
18
+ * ponytail: tune per-domain when a real guide hits the ceiling.
19
+ */
20
+ export const GATHER_ALL_MAX_FALLBACK = 1000;
21
+
22
+ /** Auth strategies recognized by the schema (the seam). v1 realizes only `none`. */
23
+ export const KNOWN_AUTH_KINDS: ReadonlySet<string> = new Set([
24
+ "none",
25
+ "static-key",
26
+ "oauth2",
27
+ ]);
28
+
29
+ // ═══════════════════════════════════════════════════════════════════
30
+ // Auth
31
+ // ═══════════════════════════════════════════════════════════════════
32
+
33
+ export type AuthKind = "none" | "static-key" | "oauth2";
34
+
35
+ export interface AuthConfig {
36
+ kind: AuthKind;
37
+ /** Extra headers merged into every request (e.g. `X-Api-Key: DEMO_KEY`). */
38
+ headers?: Record<string, string>;
39
+ }
40
+
41
+ // ═══════════════════════════════════════════════════════════════════
42
+ // Pagination
43
+ // ═══════════════════════════════════════════════════════════════════
44
+
45
+ export type PaginationStyle =
46
+ | "offset-limit"
47
+ | "nextLink"
48
+ | "cursor"
49
+ | "page"
50
+ | "resumptionToken"
51
+ | "tokenBag";
52
+
53
+ export interface PaginationConfig {
54
+ style: PaginationStyle;
55
+ /** JSON path to the items array in each page body. Required for all styles. */
56
+ itemsPath: string;
57
+ /** offset-limit: the row-offset param name; page: the page-number param name. */
58
+ pageParam?: string;
59
+ /** offset-limit / page: the page-size param name. */
60
+ pageSizeParam?: string;
61
+ /** offset-limit / page: requested page size. */
62
+ pageSize?: number;
63
+ /** nextLink: JSON path to the next-page URL. */
64
+ nextLinkPath?: string;
65
+ /** cursor: the cursor query param name. */
66
+ cursorParam?: string;
67
+ /** cursor: JSON path to the next cursor in the body. */
68
+ cursorPath?: string;
69
+ /** resumptionToken: the query param name to echo the opaque token into. */
70
+ tokenParam?: string;
71
+ /** resumptionToken: JSON path to the next token string in the body. */
72
+ tokenPath?: string;
73
+ /**
74
+ * Style-agnostic JSON path to the server's reported total count, surfaced
75
+ * as `serverTotal` in PaginateResult / the api-fetch footer. Guides whose
76
+ * APIs expose a total opt in; guides that don't simply omit it. The count
77
+ * is read from the first page only. Supersedes the old resumptionToken-only
78
+ * `completeListSizePath` (removed pre-release, not aliased).
79
+ */
80
+ totalCountPath?: string;
81
+ /** tokenBag: response keys read from each page and merged into the next request's query params. */
82
+ continuationParams?: string[];
83
+ }
84
+
85
+ // ═══════════════════════════════════════════════════════════════════
86
+ // Response shape
87
+ // ═══════════════════════════════════════════════════════════════════
88
+
89
+ export type ResponseFormat = "json" | "xml" | "text";
90
+ /** Response charset: "utf-8" (default) or any IANA charset name (e.g. "iso-8859-1"). Used by the transport as a fallback when the response's Content-Type header omits a charset; an explicit header charset always wins. */
91
+ export type ResponseCharset = string;
92
+
93
+ export interface ResponseShape {
94
+ format: ResponseFormat;
95
+ charset: ResponseCharset;
96
+ }
97
+
98
+ // ═══════════════════════════════════════════════════════════════════
99
+ // Operations
100
+ // ═══════════════════════════════════════════════════════════════════
101
+
102
+ export type ExecutorVia = "restGet" | "paginate";
103
+ export type AcceptType = string;
104
+
105
+ export interface QueryParamSpec {
106
+ required?: boolean;
107
+ default?: unknown;
108
+ /** Human-readable hint surfaced to the model via api-guide (format, semantics). */
109
+ description?: string;
110
+ }
111
+
112
+ export type DateParamFormat = "iso8601" | "yyyymmdd" | "yyyy-mm-dd";
113
+
114
+ export interface Operation {
115
+ name: string;
116
+ via: ExecutorVia;
117
+ /** Relative path; `{token}` = inferred path param. */
118
+ path: string;
119
+ /** Request-side Accept header (json|xml|any media-type string). */
120
+ accept: AcceptType;
121
+ /** Query params; path params are inferred from `{token}` in `path`. */
122
+ params: Record<string, QueryParamSpec>;
123
+ /** Path-param names inferred from `{token}` tokens in `path`. */
124
+ pathParams: string[];
125
+ /**
126
+ * Docs-only descriptions for path-param tokens, declared as
127
+ * `params.<token>.description` in the recipe. Never sent as query params —
128
+ * the token is filled from `{token}` in `path` at call time. Surfaced to
129
+ * the model via api-guide only.
130
+ */
131
+ pathParamDocs?: Record<string, string>;
132
+ /**
133
+ * Whether this operation uses the domain's local helper (coarse, pre-call).
134
+ * A `true` value means call `<guidesDir>/<domain>/helper.ts` for this op.
135
+ */
136
+ helper?: boolean;
137
+ /**
138
+ * Whether this operation post-processes the parsed response with the
139
+ * domain's local helper `transform` export (post-response). A `true`
140
+ * value means call `<guidesDir>/<domain>/helper.ts`'s named `transform`.
141
+ */
142
+ transform?: boolean;
143
+ /** Op-level responseShape override. */
144
+ parse?: ResponseShape;
145
+ /** Op-level pagination override (for `via: paginate`). */
146
+ pagination?: PaginationConfig;
147
+ /** Param names → target date format. Applied in buildQueryParams before serialization. */
148
+ dateParams?: Record<string, DateParamFormat>;
149
+ /** Op-level gatherAll ceiling override. */
150
+ gatherAllMax?: number;
151
+ /**
152
+ * Forward caller-supplied params not declared in `params` onto the query
153
+ * string as-is. For APIs with an open param surface (Infogami
154
+ * `/query.json`, CKAN, OAI-PMH) where the caller supplies type-specific
155
+ * keys at query time. Default false: closed contract — extras are
156
+ * dropped so the agent gets a predictable request, not a silent miss.
157
+ */
158
+ passthrough?: boolean;
159
+ }
160
+
161
+ // ═══════════════════════════════════════════════════════════════════
162
+ // ApiGuide
163
+ // ═══════════════════════════════════════════════════════════════════
164
+
165
+ /**
166
+ * Full API guide — recipe slice + projection slice. Host owns this type;
167
+ * portal never imports it. The projection (`projectToGuide`) strips the
168
+ * recipe fields and hands portal a plain `Guide`.
169
+ */
170
+ export interface ApiGuide extends Guide {
171
+ kind: "api";
172
+ /** Execution root: scheme + host + base path; version prefix lives here. */
173
+ apiHost: string;
174
+ /** Drift signal; defaulted not enforced. */
175
+ verified: string;
176
+ /** Optional canonical API documentation URL; surfaced to the model in api-guide. */
177
+ docs?: string;
178
+ /**
179
+ * Optional org identity across guides (catalog grouping + disambiguation).
180
+ * Routing-independent — never enters api-guide/api-fetch resolution (both
181
+ * route on `domains:`). Convention: the org's primary registrable domain.
182
+ * Not projected to portal (Guide has no such field).
183
+ */
184
+ organization?: string;
185
+ /**
186
+ * Optional one-line summary of what the API is for. Primary signal in the
187
+ * multi-guide disambiguation menu. Parser rejects newlines (structural);
188
+ * the ≤200-char cap is enforced on the api-learn write path only.
189
+ * Not projected to portal (Guide has no such field).
190
+ */
191
+ description?: string;
192
+ /** Per-guide gatherAll ceiling; falls back to GATHER_ALL_MAX_FALLBACK. */
193
+ gatherAllMax: number;
194
+ auth: AuthConfig;
195
+ /** Top-level pagination default; operations may override. */
196
+ pagination?: PaginationConfig;
197
+ /** Top-level responseShape default; operations may override. */
198
+ responseShape: ResponseShape;
199
+ operations: Operation[];
200
+ }
201
+
202
+ // ═══════════════════════════════════════════════════════════════════
203
+ // Parse error + result
204
+ // ═══════════════════════════════════════════════════════════════════
205
+
206
+ export interface ParseError {
207
+ /** On-disk path (load-time) or omitted (write-time). */
208
+ file?: string;
209
+ /** Dotted path to the failing field, e.g. "operations[1].path". */
210
+ field: string;
211
+ /** One-line shape description. */
212
+ expected: string;
213
+ /** What was actually there. */
214
+ found: string;
215
+ /** The failing block verbatim, for context. */
216
+ snippet?: string;
217
+ /** The minimal correction, when the validator can suggest one. */
218
+ fix?: string;
219
+ }
220
+
221
+ export type ParseApiGuideResult =
222
+ | { ok: true; guide: ApiGuide }
223
+ | { ok: false; error: ParseError };
224
+
225
+ export interface ParseApiGuideOptions {
226
+ /** On-disk path (load-time) — included in ParseError.file. */
227
+ file?: string;
228
+ /** Filename without extension — used for the shortName default. */
229
+ filename?: string;
230
+ }
231
+
232
+ export interface MalformedGuide {
233
+ file: string;
234
+ filename: string;
235
+ error: ParseError;
236
+ }
237
+
238
+ export interface LoadedApiGuides {
239
+ guides: Record<string, ApiGuide>;
240
+ malformed: MalformedGuide[];
241
+ }
242
+
243
+ // `Guide` (the projection-slice base type) is imported above and extended by
244
+ // `ApiGuide`; consumers import it directly from ./guide-loader.js when needed.
@@ -0,0 +1,313 @@
1
+ /**
2
+ * API Toggle — independent peer toggle for pi-lean-host.
3
+ *
4
+ * Provides /api on, /api off, /api learn, /api status, and /api helpers
5
+ * commands to enable/disable API tools in the system prompt.
6
+ *
7
+ * Three states: on (api-guide + api-fetch), learn (on + api-learn + api-probe),
8
+ * off (all three disabled).
9
+ *
10
+ * Starts enabled (api-guide + api-fetch on, api-learn + api-probe off), mirroring
11
+ * portal's browser toggle. Both defaults are overridable via the
12
+ * `toolsetDefaults` settings tier read by pi-tool-masking. The /api toggle
13
+ * is an independent peer: it composes freely with /web (portal's toggle)
14
+ * by using additive-on / filter-off semantics.
15
+ *
16
+ * Persistence: handled by the pi-tool-masking library via ToolsetSpec.persistKey.
17
+ */
18
+
19
+ import type {
20
+ ExtensionAPI,
21
+ ExtensionCommandContext,
22
+ ExtensionContext,
23
+ ThemeColor,
24
+ } from "@earendil-works/pi-coding-agent";
25
+ import {
26
+ defineToolset,
27
+ TOOLSET_EVENTS,
28
+ getDefaultResolutionMode,
29
+ } from "pi-tool-masking";
30
+ import type { ToolsetSpec } from "pi-tool-masking";
31
+ import { handleHelpersSubcommand } from "./helpers-command.js";
32
+ import { loadAllGuides } from "./guide-store.js";
33
+ import { getAllHelpers, getDisabledHelperDomains } from "./local-helpers.js";
34
+
35
+ // Focus-mode guard: refuse actuating subcommands while the library holds the
36
+ // line — inclusion mode or allowlist focus (an upstream pi-tool-masking
37
+ // consumer). Either way a sibling toggle must not write a focus-
38
+ // indistinguishable {enabled} entry.
39
+ function isFocusHolding(): boolean {
40
+ const mode = getDefaultResolutionMode();
41
+ return mode === "inclusion" || mode === "allowlist";
42
+ }
43
+
44
+ // ---- Toolset specs -----------------------------------------------
45
+
46
+ const HOST_API_SPEC: ToolsetSpec = {
47
+ id: "pi-lean-dimension.api",
48
+ names: new Set(["api-guide", "api-fetch"]),
49
+ persistKey: "toolset-state:pi-lean-dimension.api",
50
+ };
51
+
52
+ const HOST_API_LEARN_SPEC: ToolsetSpec = {
53
+ id: "pi-lean-dimension.api-learn",
54
+ names: new Set(["api-learn", "api-probe"]),
55
+ persistKey: "toolset-state:pi-lean-dimension.api-learn",
56
+ defaultEnabled: false,
57
+ requires: ["pi-lean-dimension.api"],
58
+ };
59
+
60
+ // ---- Status bar cached state (derived from library events) ------
61
+
62
+ /** @internal Last known api-tools toggle state for status bar rendering. */
63
+ let _lastToggleState = false;
64
+
65
+ /** @internal Last known learn state for status bar coloring. */
66
+ let _lastLearnState = false;
67
+
68
+ /** @internal Last captured ExtensionContext for event-driven glyph rendering. */
69
+ let _lastCtx: ExtensionContext | null = null;
70
+
71
+ export function getApiToggleState(): boolean {
72
+ return _lastToggleState;
73
+ }
74
+
75
+ /** @internal Test-only read access to live learn state. */
76
+ export function _getApiLearnStateForTest(): boolean {
77
+ return _lastLearnState;
78
+ }
79
+
80
+ // ---- Test helpers -------------------------------------------------
81
+
82
+ /** @internal Reset cached state to defaults (test helper). */
83
+ export function _resetToggleStateForTest(): void {
84
+ _lastToggleState = false;
85
+ _lastLearnState = false;
86
+ _lastCtx = null;
87
+ }
88
+
89
+ /** @internal Set cached state for test purposes only. */
90
+ export function _setToggleStateForTest(apiOn: boolean, learnOn: boolean): void {
91
+ _lastToggleState = apiOn;
92
+ _lastLearnState = learnOn;
93
+ }
94
+
95
+ /** @internal Reset cached state (called from index.ts on re-entry). */
96
+ function resetToggleModuleState(): void {
97
+ _lastToggleState = false;
98
+ _lastLearnState = false;
99
+ _lastCtx = null;
100
+ }
101
+
102
+ export { resetToggleModuleState };
103
+
104
+ // ---- Glyph helpers -----------------------------------------------
105
+
106
+ function renderApiGlyph(
107
+ ctx: {
108
+ ui: {
109
+ setStatus: (key: string, label: string) => void;
110
+ theme: { fg: (c: ThemeColor, t: string) => string };
111
+ };
112
+ },
113
+ apiEnabled: boolean,
114
+ learnEnabled: boolean,
115
+ ): void {
116
+ if (!apiEnabled) {
117
+ ctx.ui.setStatus("api", "○ api");
118
+ return;
119
+ }
120
+ const color: ThemeColor = learnEnabled ? "success" : "accent";
121
+ const dot = ctx.ui.theme?.fg(color, "●") ?? "●";
122
+ ctx.ui.setStatus("api", `${dot} api`);
123
+ }
124
+
125
+ // ---- /api status command ------------------------------------------
126
+
127
+ function handleStatusSubcommand(
128
+ apiOn: boolean,
129
+ learnOn: boolean,
130
+ ctx: ExtensionCommandContext,
131
+ ): void {
132
+ let state: string;
133
+ if (apiOn) {
134
+ state = learnOn ? "learn" : "on";
135
+ } else {
136
+ state = "off";
137
+ }
138
+ const learnFlag = learnOn
139
+ ? "✅ on (api-learn + api-probe available)"
140
+ : "❌ off";
141
+
142
+ const allGuides = loadAllGuides();
143
+ const guideCount = Object.keys(allGuides.guides).length;
144
+ const domainList = Object.values(allGuides.guides)
145
+ .flatMap((g) => g.domains ?? [])
146
+ .filter(Boolean);
147
+ const uniqueDomains = [...new Set(domainList)];
148
+
149
+ const helpers = getAllHelpers();
150
+ const disabled = getDisabledHelperDomains();
151
+
152
+ const lines: string[] = [
153
+ `📡 API status`,
154
+ ` State: ${state}`,
155
+ ` Learn: ${learnFlag}`,
156
+ ``,
157
+ ` Guides: ${guideCount} active`,
158
+ ];
159
+
160
+ if (uniqueDomains.length > 0) {
161
+ lines.push(` Domains: ${uniqueDomains.join(", ")}`);
162
+ } else {
163
+ lines.push(` Domains: (none — write a guide via api-learn)`);
164
+ }
165
+
166
+ lines.push(` Helpers: ${helpers.length} present`);
167
+ if (disabled.length > 0) {
168
+ lines.push(` ⚠ Disabled: ${disabled.join(", ")}`);
169
+ }
170
+ if (helpers.length > 0) {
171
+ lines.push(` Run /api helpers to list them.`);
172
+ }
173
+
174
+ lines.push(
175
+ ``,
176
+ ` /api on enable api-guide + api-fetch`,
177
+ ` /api learn enable all four tools (adds api-learn + api-probe)`,
178
+ ` /api off disable all API tools`,
179
+ );
180
+
181
+ ctx.ui.notify(lines.join("\n"), "info");
182
+ }
183
+
184
+ // ---- Extension factory -------------------------------------------
185
+
186
+ export default function initApiToggle(pi: ExtensionAPI): void {
187
+ // Settings-based toolset defaults (`toolsetDefaults` tier) are read by
188
+ // pi-tool-masking itself inside defineToolset/restore — pass the packaged
189
+ // spec straight through.
190
+ const apiToolset = defineToolset(pi, HOST_API_SPEC);
191
+ const learnToolset = defineToolset(pi, HOST_API_LEARN_SPEC);
192
+
193
+ // ── Keep cached state in sync with library events ─────────
194
+ const syncCachedState = () => {
195
+ _lastToggleState = apiToolset.isEnabled(pi);
196
+ _lastLearnState = learnToolset.isEnabled(pi);
197
+ if (_lastCtx) {
198
+ renderApiGlyph(_lastCtx, _lastToggleState, _lastLearnState);
199
+ }
200
+ };
201
+
202
+ pi.events.on(TOOLSET_EVENTS.changed, syncCachedState);
203
+ pi.events.on(TOOLSET_EVENTS.restored, syncCachedState);
204
+
205
+ // ── /api command ──────────────────────────────────────────
206
+ pi.registerCommand("api", {
207
+ description:
208
+ "Enable/disable API tools. " +
209
+ "Usage: /api on | off | learn | status | helpers [domain]",
210
+ handler: async (args: string, ctx: ExtensionCommandContext) => {
211
+ const trimmed = args.trim();
212
+ const parts = trimmed.split(/\s+/);
213
+ const sub = parts[0]?.toLowerCase() ?? "";
214
+ const rest = parts.slice(1).join(" ");
215
+
216
+ // Focus-mode guard: refuse actuating subcommands while the library
217
+ // holds the line — either inclusion mode or allowlist focus (an
218
+ // upstream pi-tool-masking consumer). Either way a sibling toggle
219
+ // must not write a focus-indistinguishable {enabled} entry.
220
+ // Read-only subcommands (status/helpers/bare /api) stay unguarded.
221
+ if (["on", "off", "learn"].includes(sub) && isFocusHolding()) {
222
+ const inInclusion = getDefaultResolutionMode() === "inclusion";
223
+ ctx.ui.notify(
224
+ inInclusion
225
+ ? "Another plugin has active inclusion mode — this toolset can't be toggled while inclusion is holding the line. Deactivate it there first."
226
+ : "Focus mode (allowlist) is active — this toolset can't be toggled while focus is holding the line. Exit focus there first.",
227
+ "warning",
228
+ );
229
+ return;
230
+ }
231
+
232
+ switch (sub) {
233
+ case "on": {
234
+ apiToolset.enable(pi);
235
+ learnToolset.disable(pi);
236
+ ctx.ui.notify(
237
+ "📡 API tools enabled. /api learn to make api-learn + api-probe available.",
238
+ "info",
239
+ );
240
+ return;
241
+ }
242
+
243
+ case "off": {
244
+ apiToolset.disable(pi); // cascades learn off via requires
245
+ ctx.ui.notify("📡 API tools disabled. /api on to re-enable.", "info");
246
+ return;
247
+ }
248
+
249
+ case "learn": {
250
+ learnToolset.enable(pi); // cascades api on via requires
251
+ ctx.ui.notify(
252
+ "📖 api-learn + api-probe tools are now available. " +
253
+ "Agent will discover shapes and save/update guides when asked.",
254
+ "info",
255
+ );
256
+ return;
257
+ }
258
+
259
+ case "status": {
260
+ handleStatusSubcommand(
261
+ apiToolset.isEnabled(pi),
262
+ learnToolset.isEnabled(pi),
263
+ ctx,
264
+ );
265
+ return;
266
+ }
267
+
268
+ case "helpers": {
269
+ await handleHelpersSubcommand(rest, ctx);
270
+ return;
271
+ }
272
+
273
+ default: {
274
+ const apiStatus = apiToolset.isEnabled(pi) ? "✅ on" : "❌ off";
275
+ const learnStatus = learnToolset.isEnabled(pi) ? "✅ on" : "❌ off";
276
+
277
+ const lines: string[] = [
278
+ `📡 API tools: ${apiStatus}`,
279
+ `📖 Learn mode: ${learnStatus}`,
280
+ ``,
281
+ ` /api on enable api-guide + api-fetch`,
282
+ ` /api learn enable all four tools (adds api-learn + api-probe)`,
283
+ ` /api off disable all API tools`,
284
+ ` /api status detailed status (guides, helpers)`,
285
+ ` /api helpers list local helpers`,
286
+ ` /api show this status`,
287
+ ];
288
+
289
+ if (sub) {
290
+ lines.unshift(`Unknown /api subcommand: "${sub}".`, "");
291
+ }
292
+
293
+ ctx.ui.notify(lines.join("\n"), "info");
294
+ }
295
+ }
296
+ },
297
+ });
298
+
299
+ // ── Session handlers: restore profile + render glyph ─────
300
+ pi.on("session_start", async (_event, ctx) => {
301
+ _lastCtx = ctx;
302
+ syncCachedState();
303
+ });
304
+
305
+ pi.on("session_tree", async (_event, ctx) => {
306
+ _lastCtx = ctx;
307
+ syncCachedState();
308
+ });
309
+
310
+ pi.on("session_shutdown", async () => {
311
+ _lastCtx = null;
312
+ });
313
+ }
@@ -0,0 +1,80 @@
1
+ /**
2
+ * Minimal guide-loader vendored from pi-lean-portal's guides.ts.
3
+ *
4
+ * Provides the shared projection slice: Guide type and domain-map
5
+ * building. Host's richer ApiGuide type and its YAML-nested parser live
6
+ * in core/parse-api-guide.ts.
7
+ *
8
+ * No portal dependency — this file is a verbatim-ish copy of the shared
9
+ * slice from portal's guides.ts, stripped of portal-specific imports
10
+ * and the builtin-guide catalog.
11
+ */
12
+
13
+ // ═══════════════════════════════════════════════════════════════════
14
+ // Types
15
+ // ═══════════════════════════════════════════════════════════════════
16
+
17
+ export type GuideCategory = "site" | "pattern";
18
+ export type GuideSource = "builtin" | "user";
19
+ /** Presentation-ordering hint on the projection slice. Defaults to "web". */
20
+ export type GuideKind = "web" | "api";
21
+
22
+ /**
23
+ * Minimal Guide type — the shared projection slice.
24
+ *
25
+ * Host's full ApiGuide extends this with recipe fields
26
+ * (apiHost, operations, auth, pagination, responseShape, etc.).
27
+ */
28
+ export interface Guide {
29
+ /** Markdown guidance text. */
30
+ content: string;
31
+ /** ISO date of last update. */
32
+ updated: string;
33
+ category: GuideCategory;
34
+ source: GuideSource;
35
+ /** Emoji shown in badge + footer bullet. */
36
+ icon: string;
37
+ /** Compact label shown in badge. */
38
+ shortName: string;
39
+ /** Domain name(s) this site guide applies to. */
40
+ domains?: string[];
41
+ /** Pattern guides only: signal that triggers this guide. */
42
+ triggerSignal?: "botDetected" | "dialogDetected";
43
+ /** Presentation-ordering hint ("web" | "api"); omitted = "web". */
44
+ kind?: GuideKind;
45
+ }
46
+
47
+ // ═══════════════════════════════════════════════════════════════════
48
+ // Domain map
49
+ // ═══════════════════════════════════════════════════════════════════
50
+
51
+ /**
52
+ * Build a domain map (hostname → guide names) from a guides record.
53
+ *
54
+ * Multi-valued: a hostname may be claimed by more than one guide (one
55
+ * domain, multiple APIs). Mirrors portal's `buildDomainMap` shape so the
56
+ * disambiguation surface can list every matching guide instead of
57
+ * last-write-wins. The array preserves load (insertion) order.
58
+ */
59
+ export function buildDomainMap(
60
+ guides: Record<string, Guide>,
61
+ ): Record<string, string[]> {
62
+ const map: Record<string, string[]> = {};
63
+ for (const [name, guide] of Object.entries(guides)) {
64
+ if (
65
+ guide.category === "site" &&
66
+ guide.domains &&
67
+ guide.domains.length > 0
68
+ ) {
69
+ for (const domain of guide.domains) {
70
+ const existing = map[domain];
71
+ if (existing) {
72
+ existing.push(name);
73
+ } else {
74
+ map[domain] = [name];
75
+ }
76
+ }
77
+ }
78
+ }
79
+ return map;
80
+ }