fito-tui 0.10.0 → 0.11.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.
@@ -6,8 +6,9 @@ import { fitoApiUrl } from "../fito-url/fito-url.ts";
6
6
  /**
7
7
  * The TUI's backend HTTP **transport boundary** (ADR-003): a thin client that mirrors backend
8
8
  * REST endpoints one method per endpoint, attaches auth, validates every response with Zod, and
9
- * normalises errors into `FitoApiError`. It is the only place raw `fetch` lives — no ad-hoc
10
- * `fetch`, no axios. That, and only that, is what "single seam" means.
9
+ * normalises errors into `FitoApiError`. It and the guide transport beside it (`guide.ts`, Task
10
+ * 17.35) are the only places raw `fetch` lives — no ad-hoc `fetch`, no axios. That, and only that,
11
+ * is what "single seam" means.
11
12
  *
12
13
  * It carries no domain logic: parsing identifiers, composing calls, or shaping responses for a
13
14
  * use case belong in a `shared/<subject>/` module that imports this client (e.g.
@@ -19,9 +20,9 @@ import { fitoApiUrl } from "../fito-url/fito-url.ts";
19
20
  /**
20
21
  * Sent on every request, so the backend can refuse a TUI older than the minimum version it serves,
21
22
  * with a message that says how to update (Task 15d.7a). Without it, Node's `fetch` sends `node`,
22
- * which the backend always lets through.
23
+ * which the backend always lets through. The guide transport (`guide.ts`, Task 17.35) sends it too.
23
24
  */
24
- const USER_AGENT = `fito-tui/${packageJson.version}`;
25
+ export const USER_AGENT = `fito-tui/${packageJson.version}`;
25
26
 
26
27
  export const tokenResponseSchema = z.object({
27
28
  accessToken: z.string().min(1),
@@ -0,0 +1,50 @@
1
+ import { fitoGuideUrl } from "../fito-url/fito-url.js";
2
+ import { USER_AGENT } from "./client.js";
3
+ /**
4
+ * The user guide's HTTP transport (Task 17.35): one read of a path under the guide's address. It
5
+ * lives in `fito-api/` beside the backend client because this folder is the TUI's whole HTTP
6
+ * transport boundary — the backend's and the guide's — so "issues an HTTP request → `fito-api/`"
7
+ * stays true as written (ADR-003, the 2026-11-16 scope note). It sends the backend client's
8
+ * `User-Agent`, so the guide's access logs show `/fito-docs` use.
9
+ *
10
+ * It holds no domain logic: which paths exist, what an index line says and what a page's address
11
+ * is belong to `shared/fito-guide/`, which imports this function.
12
+ */
13
+ /**
14
+ * The guide answered with anything but `200`. [status] is the HTTP status and [path] the path read,
15
+ * so a caller can say which page was missing.
16
+ */
17
+ export class FitoGuideError extends Error {
18
+ status;
19
+ path;
20
+ constructor(message, status, path) {
21
+ super(message);
22
+ this.name = "FitoGuideError";
23
+ this.status = status;
24
+ this.path = path;
25
+ }
26
+ }
27
+ /**
28
+ * How long one read may take, in milliseconds. Node's own limits let a stalled server hold a
29
+ * request for minutes, and the worker that reads the guide waits on it for the whole of that.
30
+ */
31
+ export const GUIDE_TIMEOUT_MS = 15_000;
32
+ /**
33
+ * `GET <guide address><path>` — the body as text. `path` starts with `/`. Any status but `200` is a
34
+ * `FitoGuideError`; a network failure rejects as `fetch` rejects, and so does a read that outlasts
35
+ * the time limit, with a `TimeoutError`.
36
+ */
37
+ export async function readGuideText(path, options = {}) {
38
+ const baseUrl = options.baseUrl ?? fitoGuideUrl();
39
+ const doFetch = options.fetch ?? fetch;
40
+ const response = await doFetch(`${baseUrl}${path}`, {
41
+ method: "GET",
42
+ headers: { "User-Agent": USER_AGENT },
43
+ // The same signal bounds the body's read below, not only the answer's arrival.
44
+ signal: AbortSignal.timeout(options.timeoutMs ?? GUIDE_TIMEOUT_MS),
45
+ });
46
+ if (response.status !== 200) {
47
+ throw new FitoGuideError(`The guide answered ${response.status} for ${path}`, response.status, path);
48
+ }
49
+ return response.text();
50
+ }
@@ -0,0 +1,63 @@
1
+ import { fitoGuideUrl } from "../fito-url/fito-url.ts";
2
+ import { USER_AGENT } from "./client.ts";
3
+
4
+ /**
5
+ * The user guide's HTTP transport (Task 17.35): one read of a path under the guide's address. It
6
+ * lives in `fito-api/` beside the backend client because this folder is the TUI's whole HTTP
7
+ * transport boundary — the backend's and the guide's — so "issues an HTTP request → `fito-api/`"
8
+ * stays true as written (ADR-003, the 2026-11-16 scope note). It sends the backend client's
9
+ * `User-Agent`, so the guide's access logs show `/fito-docs` use.
10
+ *
11
+ * It holds no domain logic: which paths exist, what an index line says and what a page's address
12
+ * is belong to `shared/fito-guide/`, which imports this function.
13
+ */
14
+
15
+ /**
16
+ * The guide answered with anything but `200`. [status] is the HTTP status and [path] the path read,
17
+ * so a caller can say which page was missing.
18
+ */
19
+ export class FitoGuideError extends Error {
20
+ readonly status: number;
21
+ readonly path: string;
22
+
23
+ constructor(message: string, status: number, path: string) {
24
+ super(message);
25
+ this.name = "FitoGuideError";
26
+ this.status = status;
27
+ this.path = path;
28
+ }
29
+ }
30
+
31
+ /**
32
+ * How long one read may take, in milliseconds. Node's own limits let a stalled server hold a
33
+ * request for minutes, and the worker that reads the guide waits on it for the whole of that.
34
+ */
35
+ export const GUIDE_TIMEOUT_MS = 15_000;
36
+
37
+ export interface GuideReadOptions {
38
+ /** The guide's address; defaults to the one `shared/fito-url/` gives (`FITO_GUIDE_URL`). */
39
+ baseUrl?: string;
40
+ fetch?: typeof fetch;
41
+ /** The time limit; defaults to `GUIDE_TIMEOUT_MS`. Tests pass a short one. */
42
+ timeoutMs?: number;
43
+ }
44
+
45
+ /**
46
+ * `GET <guide address><path>` — the body as text. `path` starts with `/`. Any status but `200` is a
47
+ * `FitoGuideError`; a network failure rejects as `fetch` rejects, and so does a read that outlasts
48
+ * the time limit, with a `TimeoutError`.
49
+ */
50
+ export async function readGuideText(path: string, options: GuideReadOptions = {}): Promise<string> {
51
+ const baseUrl = options.baseUrl ?? fitoGuideUrl();
52
+ const doFetch = options.fetch ?? fetch;
53
+ const response = await doFetch(`${baseUrl}${path}`, {
54
+ method: "GET",
55
+ headers: { "User-Agent": USER_AGENT },
56
+ // The same signal bounds the body's read below, not only the answer's arrival.
57
+ signal: AbortSignal.timeout(options.timeoutMs ?? GUIDE_TIMEOUT_MS),
58
+ });
59
+ if (response.status !== 200) {
60
+ throw new FitoGuideError(`The guide answered ${response.status} for ${path}`, response.status, path);
61
+ }
62
+ return response.text();
63
+ }
@@ -0,0 +1,84 @@
1
+ import { FitoGuideError, readGuideText } from "../fito-api/guide.js";
2
+ import { fitoGuideUrl } from "../fito-url/fito-url.js";
3
+ /** Where each locale's index lives. */
4
+ const INDEX_PATHS = { en: "/llms.txt", "pt-br": "/pt-br/llms.txt" };
5
+ /** One index line: `- [title](link): description`. */
6
+ const INDEX_LINE = /^- \[([^\]]+)\]\(([^)\s]+)\):\s*(.*)$/;
7
+ /** A guide path's segment: letters, digits, hyphens and underscores — never `.`, `..` or a backslash. */
8
+ const SEGMENT = /^[A-Za-z0-9_-]+$/;
9
+ /** A reference that opens with a scheme (`https:`) is a full address; only its path is kept. */
10
+ const HAS_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//;
11
+ /**
12
+ * The page path a reference names. Every form a page's link takes names the same path: the index's
13
+ * link to the copy (`/x/index.md`, root-relative or absolute), the page's own address, with or
14
+ * without its slashes, with a `#anchor`, and with the `pt-br/` prefix, which names the Portuguese
15
+ * page. Anything else — a `..`, a `.`, a backslash — is not a guide page and is refused here,
16
+ * before any request.
17
+ */
18
+ export function pagePathOf(reference) {
19
+ let path = reference.trim();
20
+ if (HAS_SCHEME.test(path)) {
21
+ path = new URL(path).pathname;
22
+ }
23
+ path = path.replace(/[#?].*$/, "").replace(/(^|\/)index\.md$/, "$1");
24
+ const segments = path.split("/").filter((segment) => segment !== "");
25
+ if (!segments.every((segment) => SEGMENT.test(segment))) {
26
+ throw new Error(`"${reference}" is not a guide page: name a page by the path its index line links`);
27
+ }
28
+ return segments.length === 0 ? "/" : `/${segments.join("/")}/`;
29
+ }
30
+ /** The locale a page path belongs to: the `pt-br/` prefix names the Portuguese side. */
31
+ function localeOf(path) {
32
+ return path === "/pt-br/" || path.startsWith("/pt-br/") ? "pt-br" : "en";
33
+ }
34
+ /**
35
+ * Read an index's text into its pages. Lines other than page lines — the H1, the summary, the
36
+ * topic H2s — are skipped; an index with no page line at all is refused, since the format has
37
+ * then changed under this TUI.
38
+ */
39
+ export function parseGuideIndex(text, locale, guideUrl) {
40
+ const pages = [];
41
+ for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
42
+ const match = INDEX_LINE.exec(line.trim());
43
+ if (!match)
44
+ continue;
45
+ const path = pagePathOf(match[2]);
46
+ pages.push({ path, title: match[1], description: match[3], locale, address: `${guideUrl}${path}` });
47
+ }
48
+ if (pages.length === 0) {
49
+ throw new Error(`The guide's ${locale} index at ${guideUrl}${INDEX_PATHS[locale]} lists no page`);
50
+ }
51
+ return pages;
52
+ }
53
+ /** One read through the transport, its failure said in one line that names the guide's address. */
54
+ async function readText(path, guideUrl, options) {
55
+ try {
56
+ return await readGuideText(path, { baseUrl: guideUrl, fetch: options.fetch });
57
+ }
58
+ catch (error) {
59
+ const reason = error instanceof FitoGuideError
60
+ ? `it answered ${error.status} for ${error.path}`
61
+ : (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim();
62
+ throw new Error(`The guide at ${guideUrl} could not be read: ${reason}`);
63
+ }
64
+ }
65
+ /** Read one locale's index. */
66
+ export async function readGuideIndex(locale, options = {}) {
67
+ const guideUrl = options.guideUrl ?? fitoGuideUrl();
68
+ const text = await readText(INDEX_PATHS[locale], guideUrl, options);
69
+ return { locale, address: `${guideUrl}${INDEX_PATHS[locale]}`, pages: parseGuideIndex(text, locale, guideUrl) };
70
+ }
71
+ /**
72
+ * Read one page by any of its links (`pagePathOf`). The page's locale's index is read first, and a
73
+ * page it does not list is refused before the page itself is requested.
74
+ */
75
+ export async function readGuidePage(reference, options = {}) {
76
+ const path = pagePathOf(reference);
77
+ const index = await readGuideIndex(localeOf(path), options);
78
+ const entry = index.pages.find((page) => page.path === path);
79
+ if (!entry) {
80
+ throw new Error(`${path} is not a page the guide's ${index.locale} index lists — read the index for the pages it lists`);
81
+ }
82
+ const guideUrl = options.guideUrl ?? fitoGuideUrl();
83
+ return { ...entry, markdown: await readText(`${path}index.md`, guideUrl, options) };
84
+ }
@@ -0,0 +1,143 @@
1
+ import { FitoGuideError, readGuideText } from "../fito-api/guide.ts";
2
+ import { fitoGuideUrl } from "../fito-url/fito-url.ts";
3
+
4
+ /**
5
+ * The user guide as `/fito-docs` reads it (Task 17.35): each locale's index of its pages, and one
6
+ * page's markdown copy. The guide serves both (Task 17.34): `/llms.txt` and `/pt-br/llms.txt` in
7
+ * the llmstxt.org format, one `- [title](link): description` line per page, where the link is the
8
+ * page's copy, `<page>/index.md`.
9
+ *
10
+ * This is the domain half: the request itself is `fito-api/guide.ts`. Here the index becomes pages,
11
+ * a reference becomes a page path, and a page is read only when its locale's index lists it — so no
12
+ * request ever reaches a path under the guide that the index does not name.
13
+ *
14
+ * **Addresses come from the TUI's guide address, never from the index's links.** Staging runs the
15
+ * image built with production's address, so its index links `https://docs.fito.codes/…`; only each
16
+ * link's path is kept. A page's address is the page itself — the copy's path without `index.md` —
17
+ * so a user is never shown a raw-markdown address.
18
+ */
19
+
20
+ export type GuideLocale = "en" | "pt-br";
21
+
22
+ /** One page an index lists. */
23
+ export interface GuidePageEntry {
24
+ /** The page's path under the guide's address: `/` for the English home page, `/pt-br/learn-with-fito/how-to/tutor/`. */
25
+ path: string;
26
+ title: string;
27
+ description: string;
28
+ locale: GuideLocale;
29
+ /** The page's full address under the TUI's guide address — what a user opens. */
30
+ address: string;
31
+ }
32
+
33
+ /** One locale's index, read. */
34
+ export interface GuideIndex {
35
+ locale: GuideLocale;
36
+ /** The index's own address. */
37
+ address: string;
38
+ pages: GuidePageEntry[];
39
+ }
40
+
41
+ /** One page, read: its index entry and its markdown copy. */
42
+ export interface GuidePage extends GuidePageEntry {
43
+ markdown: string;
44
+ }
45
+
46
+ export interface GuideOptions {
47
+ /** The guide's address; defaults to `fitoGuideUrl()`. */
48
+ guideUrl?: string;
49
+ fetch?: typeof fetch;
50
+ }
51
+
52
+ /** Where each locale's index lives. */
53
+ const INDEX_PATHS: Record<GuideLocale, string> = { en: "/llms.txt", "pt-br": "/pt-br/llms.txt" };
54
+
55
+ /** One index line: `- [title](link): description`. */
56
+ const INDEX_LINE = /^- \[([^\]]+)\]\(([^)\s]+)\):\s*(.*)$/;
57
+
58
+ /** A guide path's segment: letters, digits, hyphens and underscores — never `.`, `..` or a backslash. */
59
+ const SEGMENT = /^[A-Za-z0-9_-]+$/;
60
+
61
+ /** A reference that opens with a scheme (`https:`) is a full address; only its path is kept. */
62
+ const HAS_SCHEME = /^[A-Za-z][A-Za-z0-9+.-]*:\/\//;
63
+
64
+ /**
65
+ * The page path a reference names. Every form a page's link takes names the same path: the index's
66
+ * link to the copy (`/x/index.md`, root-relative or absolute), the page's own address, with or
67
+ * without its slashes, with a `#anchor`, and with the `pt-br/` prefix, which names the Portuguese
68
+ * page. Anything else — a `..`, a `.`, a backslash — is not a guide page and is refused here,
69
+ * before any request.
70
+ */
71
+ export function pagePathOf(reference: string): string {
72
+ let path = reference.trim();
73
+ if (HAS_SCHEME.test(path)) {
74
+ path = new URL(path).pathname;
75
+ }
76
+ path = path.replace(/[#?].*$/, "").replace(/(^|\/)index\.md$/, "$1");
77
+ const segments = path.split("/").filter((segment) => segment !== "");
78
+ if (!segments.every((segment) => SEGMENT.test(segment))) {
79
+ throw new Error(`"${reference}" is not a guide page: name a page by the path its index line links`);
80
+ }
81
+ return segments.length === 0 ? "/" : `/${segments.join("/")}/`;
82
+ }
83
+
84
+ /** The locale a page path belongs to: the `pt-br/` prefix names the Portuguese side. */
85
+ function localeOf(path: string): GuideLocale {
86
+ return path === "/pt-br/" || path.startsWith("/pt-br/") ? "pt-br" : "en";
87
+ }
88
+
89
+ /**
90
+ * Read an index's text into its pages. Lines other than page lines — the H1, the summary, the
91
+ * topic H2s — are skipped; an index with no page line at all is refused, since the format has
92
+ * then changed under this TUI.
93
+ */
94
+ export function parseGuideIndex(text: string, locale: GuideLocale, guideUrl: string): GuidePageEntry[] {
95
+ const pages: GuidePageEntry[] = [];
96
+ for (const line of text.replace(/\r\n/g, "\n").split("\n")) {
97
+ const match = INDEX_LINE.exec(line.trim());
98
+ if (!match) continue;
99
+ const path = pagePathOf(match[2]);
100
+ pages.push({ path, title: match[1], description: match[3], locale, address: `${guideUrl}${path}` });
101
+ }
102
+ if (pages.length === 0) {
103
+ throw new Error(`The guide's ${locale} index at ${guideUrl}${INDEX_PATHS[locale]} lists no page`);
104
+ }
105
+ return pages;
106
+ }
107
+
108
+ /** One read through the transport, its failure said in one line that names the guide's address. */
109
+ async function readText(path: string, guideUrl: string, options: GuideOptions): Promise<string> {
110
+ try {
111
+ return await readGuideText(path, { baseUrl: guideUrl, fetch: options.fetch });
112
+ } catch (error) {
113
+ const reason =
114
+ error instanceof FitoGuideError
115
+ ? `it answered ${error.status} for ${error.path}`
116
+ : (error instanceof Error ? error.message : String(error)).replace(/\s+/g, " ").trim();
117
+ throw new Error(`The guide at ${guideUrl} could not be read: ${reason}`);
118
+ }
119
+ }
120
+
121
+ /** Read one locale's index. */
122
+ export async function readGuideIndex(locale: GuideLocale, options: GuideOptions = {}): Promise<GuideIndex> {
123
+ const guideUrl = options.guideUrl ?? fitoGuideUrl();
124
+ const text = await readText(INDEX_PATHS[locale], guideUrl, options);
125
+ return { locale, address: `${guideUrl}${INDEX_PATHS[locale]}`, pages: parseGuideIndex(text, locale, guideUrl) };
126
+ }
127
+
128
+ /**
129
+ * Read one page by any of its links (`pagePathOf`). The page's locale's index is read first, and a
130
+ * page it does not list is refused before the page itself is requested.
131
+ */
132
+ export async function readGuidePage(reference: string, options: GuideOptions = {}): Promise<GuidePage> {
133
+ const path = pagePathOf(reference);
134
+ const index = await readGuideIndex(localeOf(path), options);
135
+ const entry = index.pages.find((page) => page.path === path);
136
+ if (!entry) {
137
+ throw new Error(
138
+ `${path} is not a page the guide's ${index.locale} index lists — read the index for the pages it lists`,
139
+ );
140
+ }
141
+ const guideUrl = options.guideUrl ?? fitoGuideUrl();
142
+ return { ...entry, markdown: await readText(`${path}index.md`, guideUrl, options) };
143
+ }
@@ -8,6 +8,9 @@
8
8
  *
9
9
  * A subject folder, not part of `fito-api/`: that folder maps API calls only, and the address also
10
10
  * serves the login page and the links a script prints.
11
+ *
12
+ * It also holds the user guide's address (`fitoGuideUrl`, Task 17.35), which no rule derives from
13
+ * Fito's.
11
14
  */
12
15
  /**
13
16
  * The hosted Fito. Every installed TUI holds this value, so a change of domain reaches a user only
@@ -27,3 +30,21 @@ export function fitoUrl(env = process.env) {
27
30
  export function fitoApiUrl(env = process.env) {
28
31
  return `${fitoUrl(env)}/api`;
29
32
  }
33
+ /**
34
+ * The hosted user guide. Like `HOSTED_FITO_URL`, every installed TUI holds this value, and
35
+ * `fito-url.test.ts` pins it (Task 17.35).
36
+ */
37
+ const HOSTED_GUIDE_URL = "https://docs.fito.codes";
38
+ /**
39
+ * The user guide's address, which `/fito-docs` reads (Task 17.35): `FITO_GUIDE_URL`, or the hosted
40
+ * guide when it is unset or empty — the same name and meaning as the guide image's build argument.
41
+ * Trailing slashes are dropped, so a page path joins it with one slash.
42
+ *
43
+ * It is not derived from `FITO_URL`: staging's guide is `staging-docs.fito.codes` and the
44
+ * development stack's `docs.localhost:8000`, so no rule maps one to the other. With `FITO_URL` set
45
+ * and `FITO_GUIDE_URL` unset, the TUI reads production's guide.
46
+ */
47
+ export function fitoGuideUrl(env = process.env) {
48
+ const chosen = (env.FITO_GUIDE_URL ?? "").replace(/\/+$/, "");
49
+ return chosen === "" ? HOSTED_GUIDE_URL : chosen;
50
+ }
@@ -8,6 +8,9 @@
8
8
  *
9
9
  * A subject folder, not part of `fito-api/`: that folder maps API calls only, and the address also
10
10
  * serves the login page and the links a script prints.
11
+ *
12
+ * It also holds the user guide's address (`fitoGuideUrl`, Task 17.35), which no rule derives from
13
+ * Fito's.
11
14
  */
12
15
 
13
16
  /**
@@ -30,3 +33,23 @@ export function fitoUrl(env: Record<string, string | undefined> = process.env):
30
33
  export function fitoApiUrl(env: Record<string, string | undefined> = process.env): string {
31
34
  return `${fitoUrl(env)}/api`;
32
35
  }
36
+
37
+ /**
38
+ * The hosted user guide. Like `HOSTED_FITO_URL`, every installed TUI holds this value, and
39
+ * `fito-url.test.ts` pins it (Task 17.35).
40
+ */
41
+ const HOSTED_GUIDE_URL = "https://docs.fito.codes";
42
+
43
+ /**
44
+ * The user guide's address, which `/fito-docs` reads (Task 17.35): `FITO_GUIDE_URL`, or the hosted
45
+ * guide when it is unset or empty — the same name and meaning as the guide image's build argument.
46
+ * Trailing slashes are dropped, so a page path joins it with one slash.
47
+ *
48
+ * It is not derived from `FITO_URL`: staging's guide is `staging-docs.fito.codes` and the
49
+ * development stack's `docs.localhost:8000`, so no rule maps one to the other. With `FITO_URL` set
50
+ * and `FITO_GUIDE_URL` unset, the TUI reads production's guide.
51
+ */
52
+ export function fitoGuideUrl(env: Record<string, string | undefined> = process.env): string {
53
+ const chosen = (env.FITO_GUIDE_URL ?? "").replace(/\/+$/, "");
54
+ return chosen === "" ? HOSTED_GUIDE_URL : chosen;
55
+ }
@@ -0,0 +1,104 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+ import { parse as parseYaml } from "yaml";
5
+ import { z } from "zod";
6
+ /**
7
+ * The installed Fito package's own agent-facing files, as `/fito-docs` reads them when the guide
8
+ * does not cover a TUI question (Task 17.35, decision b): its prompts (`prompts/*.md`), its skills
9
+ * (`skills/*\/SKILL.md`) and its workers (`agents/*.md`). Nothing else.
10
+ *
11
+ * **A closed set, named by kind and name, never by path.** A caller names a kind — `prompt`,
12
+ * `skill`, `worker` — and a name; the file comes from a listing this module builds itself, so what
13
+ * a worker can reach is a property of this code, as `shared/case-briefing/` makes it for the tutor.
14
+ * A name is a single kebab-case word, so `../`, a slash, a dot or a file extension is refused before
15
+ * the disk is touched. Tests, `__fixtures__` folders and every non-`.md` file are never listed, and
16
+ * so never served; nor is `~/.fito/`, nor any file outside the package.
17
+ *
18
+ * **The package root comes from this module's own location** (`import.meta.url`, two folders up).
19
+ * That holds wherever the package runs: from a developer's clone, from the built `.js` under Node,
20
+ * and from `node_modules`, where pi loads the extension through its own loader (jiti), which gives
21
+ * each module its real file location.
22
+ */
23
+ export const PACKAGE_KINDS = ["prompt", "skill", "worker"];
24
+ /** A name: one kebab-case word, as Fito names every prompt, skill and worker (`fito-tutor`). */
25
+ const NAME = /^[a-z0-9][a-z0-9-]*$/;
26
+ /** The front matter fields the listing shows. A field that is absent or not text reads as empty. */
27
+ const frontMatterSchema = z.object({
28
+ description: z.string().catch(""),
29
+ "argument-hint": z.string().nullable().catch(null),
30
+ });
31
+ /** The installed package's root: this module lives at `<root>/shared/tui-package/`. */
32
+ export function packageRoot() {
33
+ return resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
34
+ }
35
+ /** The folder each kind lives in. */
36
+ const KIND_FOLDERS = { prompt: "prompts", skill: "skills", worker: "agents" };
37
+ /**
38
+ * Each name of one kind, with its file — the closed set every read goes through. A name that is not
39
+ * a kebab-case word (a test, a fixture folder) is skipped, so it is neither listed nor served.
40
+ */
41
+ function filesOf(kind, root) {
42
+ const folder = join(root, KIND_FOLDERS[kind]);
43
+ const files = new Map();
44
+ if (!existsSync(folder))
45
+ return files;
46
+ for (const entry of readdirSync(folder, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
47
+ if (kind === "skill") {
48
+ const skillFile = join(folder, entry.name, "SKILL.md");
49
+ if (entry.isDirectory() && NAME.test(entry.name) && existsSync(skillFile))
50
+ files.set(entry.name, skillFile);
51
+ }
52
+ else if (entry.isFile() && entry.name.endsWith(".md")) {
53
+ const name = entry.name.slice(0, -".md".length);
54
+ if (NAME.test(name))
55
+ files.set(name, join(folder, entry.name));
56
+ }
57
+ }
58
+ return files;
59
+ }
60
+ /** A file's front matter, or nothing when it has none or it does not parse. */
61
+ function frontMatterOf(file) {
62
+ const text = readFileSync(file, "utf8").replace(/\r\n/g, "\n");
63
+ const block = text.match(/^---\n([\s\S]*?)\n---\n/);
64
+ let parsed = {};
65
+ try {
66
+ parsed = block ? (parseYaml(block[1]) ?? {}) : {};
67
+ }
68
+ catch {
69
+ parsed = {};
70
+ }
71
+ return frontMatterSchema.parse(typeof parsed === "object" ? parsed : {});
72
+ }
73
+ /** Every prompt, skill and worker the package holds, each with its description. */
74
+ export function listPackage(options = {}) {
75
+ const root = options.root ?? packageRoot();
76
+ const named = (kind) => [...filesOf(kind, root)].map(([name, file]) => ({ name, description: frontMatterOf(file).description }));
77
+ return {
78
+ prompts: [...filesOf("prompt", root)].map(([name, file]) => {
79
+ const front = frontMatterOf(file);
80
+ return { command: `/${name}`, description: front.description, argumentHint: front["argument-hint"] };
81
+ }),
82
+ skills: named("skill"),
83
+ workers: named("worker"),
84
+ };
85
+ }
86
+ /**
87
+ * Read one file by kind and name: a prompt by its command (`fito-tutor` or `/fito-tutor`), a skill
88
+ * by its folder, a worker by its file. A name that is not a kebab-case word, or that the listing
89
+ * does not hold, is refused.
90
+ */
91
+ export function readPackageFile(kind, name, options = {}) {
92
+ if (!PACKAGE_KINDS.includes(kind)) {
93
+ throw new Error(`"${kind}" is not a kind of Fito file — use one of: ${PACKAGE_KINDS.join(", ")}`);
94
+ }
95
+ const bare = kind === "prompt" ? name.trim().replace(/^\//, "") : name.trim();
96
+ if (!NAME.test(bare)) {
97
+ throw new Error(`"${name}" is not a name — name a ${kind} as the listing shows it, never a path or a file`);
98
+ }
99
+ const file = filesOf(kind, options.root ?? packageRoot()).get(bare);
100
+ if (file === undefined) {
101
+ throw new Error(`Fito has no ${kind} named "${bare}" — list the package for the names it holds`);
102
+ }
103
+ return { kind, name: bare, text: readFileSync(file, "utf8") };
104
+ }