fito-tui 0.9.3 → 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.
@@ -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
+ }
@@ -70,6 +70,34 @@ export function readCredentials(home = os.homedir(), url = fitoUrl()) {
70
70
  const parsed = credentialsSchema.safeParse(safeJsonParse(raw));
71
71
  return parsed.success ? parsed.data : null;
72
72
  }
73
+ /**
74
+ * The saved login of the Fito at `url`, read with no call to the backend: `null` when none is saved,
75
+ * as {@link readCredentials} reads the file, and otherwise the `username` claim of its access token.
76
+ * The claim is read from the token's payload (base64url JSON) **without checking the signature**: the
77
+ * footer line only shows the name, and the backend checks every token it is sent. A token that is
78
+ * not a JWT, or names no account, gives a login with no name. It never throws.
79
+ */
80
+ export function readSavedLogin(home = os.homedir(), url = fitoUrl()) {
81
+ let credentials;
82
+ try {
83
+ credentials = readCredentials(home, url);
84
+ }
85
+ catch {
86
+ return null;
87
+ }
88
+ return credentials === null ? null : { username: usernameClaim(credentials.accessToken) };
89
+ }
90
+ /** The `username` claim of a JWT's payload, or `undefined` when the token is no JWT or has none. */
91
+ function usernameClaim(token) {
92
+ const parts = token.split(".");
93
+ if (parts.length !== 3)
94
+ return undefined;
95
+ const claims = safeJsonParse(Buffer.from(parts[1], "base64url").toString("utf8"));
96
+ if (typeof claims !== "object" || claims === null)
97
+ return undefined;
98
+ const username = claims.username;
99
+ return typeof username === "string" && username !== "" ? username : undefined;
100
+ }
73
101
  /** Delete the credentials file. Returns `true` if a file was removed, `false` if absent. */
74
102
  export function deleteCredentials(home = os.homedir(), url = fitoUrl()) {
75
103
  const file = credentialsPath(home, url);
@@ -86,6 +86,39 @@ export function readCredentials(home: string = os.homedir(), url: string = fitoU
86
86
  return parsed.success ? parsed.data : null;
87
87
  }
88
88
 
89
+ /** The saved login of one Fito, as pi's footer line names it (Task 17.33). */
90
+ export type SavedLogin = {
91
+ /** The access token's `username` claim; `undefined` when the token names no account. */
92
+ username: string | undefined;
93
+ };
94
+
95
+ /**
96
+ * The saved login of the Fito at `url`, read with no call to the backend: `null` when none is saved,
97
+ * as {@link readCredentials} reads the file, and otherwise the `username` claim of its access token.
98
+ * The claim is read from the token's payload (base64url JSON) **without checking the signature**: the
99
+ * footer line only shows the name, and the backend checks every token it is sent. A token that is
100
+ * not a JWT, or names no account, gives a login with no name. It never throws.
101
+ */
102
+ export function readSavedLogin(home: string = os.homedir(), url: string = fitoUrl()): SavedLogin | null {
103
+ let credentials: Credentials | null;
104
+ try {
105
+ credentials = readCredentials(home, url);
106
+ } catch {
107
+ return null;
108
+ }
109
+ return credentials === null ? null : { username: usernameClaim(credentials.accessToken) };
110
+ }
111
+
112
+ /** The `username` claim of a JWT's payload, or `undefined` when the token is no JWT or has none. */
113
+ function usernameClaim(token: string): string | undefined {
114
+ const parts = token.split(".");
115
+ if (parts.length !== 3) return undefined;
116
+ const claims = safeJsonParse(Buffer.from(parts[1], "base64url").toString("utf8"));
117
+ if (typeof claims !== "object" || claims === null) return undefined;
118
+ const username = (claims as Record<string, unknown>).username;
119
+ return typeof username === "string" && username !== "" ? username : undefined;
120
+ }
121
+
89
122
  /** Delete the credentials file. Returns `true` if a file was removed, `false` if absent. */
90
123
  export function deleteCredentials(home: string = os.homedir(), url: string = fitoUrl()): boolean {
91
124
  const file = credentialsPath(home, url);
@@ -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
+ }
@@ -0,0 +1,143 @@
1
+ import { existsSync, readdirSync, readFileSync } from "node:fs";
2
+ import { dirname, join, resolve } from "node:path";
3
+ import { fileURLToPath } from "node:url";
4
+
5
+ import { parse as parseYaml } from "yaml";
6
+ import { z } from "zod";
7
+
8
+ /**
9
+ * The installed Fito package's own agent-facing files, as `/fito-docs` reads them when the guide
10
+ * does not cover a TUI question (Task 17.35, decision b): its prompts (`prompts/*.md`), its skills
11
+ * (`skills/*\/SKILL.md`) and its workers (`agents/*.md`). Nothing else.
12
+ *
13
+ * **A closed set, named by kind and name, never by path.** A caller names a kind — `prompt`,
14
+ * `skill`, `worker` — and a name; the file comes from a listing this module builds itself, so what
15
+ * a worker can reach is a property of this code, as `shared/case-briefing/` makes it for the tutor.
16
+ * A name is a single kebab-case word, so `../`, a slash, a dot or a file extension is refused before
17
+ * the disk is touched. Tests, `__fixtures__` folders and every non-`.md` file are never listed, and
18
+ * so never served; nor is `~/.fito/`, nor any file outside the package.
19
+ *
20
+ * **The package root comes from this module's own location** (`import.meta.url`, two folders up).
21
+ * That holds wherever the package runs: from a developer's clone, from the built `.js` under Node,
22
+ * and from `node_modules`, where pi loads the extension through its own loader (jiti), which gives
23
+ * each module its real file location.
24
+ */
25
+
26
+ export const PACKAGE_KINDS = ["prompt", "skill", "worker"] as const;
27
+ export type PackageKind = (typeof PACKAGE_KINDS)[number];
28
+
29
+ /** A prompt as the listing shows it: the command a user types, and its front matter. */
30
+ export interface PackagePrompt {
31
+ command: string;
32
+ description: string;
33
+ argumentHint: string | null;
34
+ }
35
+
36
+ /** A skill or a worker as the listing shows it. */
37
+ export interface PackageNamedEntry {
38
+ name: string;
39
+ description: string;
40
+ }
41
+
42
+ export interface PackageListing {
43
+ prompts: PackagePrompt[];
44
+ skills: PackageNamedEntry[];
45
+ workers: PackageNamedEntry[];
46
+ }
47
+
48
+ /** One file, read: its kind, its name, and its text as written, front matter included. */
49
+ export interface PackageFile {
50
+ kind: PackageKind;
51
+ name: string;
52
+ text: string;
53
+ }
54
+
55
+ export interface PackageOptions {
56
+ /** The package root; defaults to `packageRoot()`. Tests pass a fixture. */
57
+ root?: string;
58
+ }
59
+
60
+ /** A name: one kebab-case word, as Fito names every prompt, skill and worker (`fito-tutor`). */
61
+ const NAME = /^[a-z0-9][a-z0-9-]*$/;
62
+
63
+ /** The front matter fields the listing shows. A field that is absent or not text reads as empty. */
64
+ const frontMatterSchema = z.object({
65
+ description: z.string().catch(""),
66
+ "argument-hint": z.string().nullable().catch(null),
67
+ });
68
+
69
+ /** The installed package's root: this module lives at `<root>/shared/tui-package/`. */
70
+ export function packageRoot(): string {
71
+ return resolve(dirname(fileURLToPath(import.meta.url)), "..", "..");
72
+ }
73
+
74
+ /** The folder each kind lives in. */
75
+ const KIND_FOLDERS: Record<PackageKind, string> = { prompt: "prompts", skill: "skills", worker: "agents" };
76
+
77
+ /**
78
+ * Each name of one kind, with its file — the closed set every read goes through. A name that is not
79
+ * a kebab-case word (a test, a fixture folder) is skipped, so it is neither listed nor served.
80
+ */
81
+ function filesOf(kind: PackageKind, root: string): Map<string, string> {
82
+ const folder = join(root, KIND_FOLDERS[kind]);
83
+ const files = new Map<string, string>();
84
+ if (!existsSync(folder)) return files;
85
+ for (const entry of readdirSync(folder, { withFileTypes: true }).sort((a, b) => a.name.localeCompare(b.name))) {
86
+ if (kind === "skill") {
87
+ const skillFile = join(folder, entry.name, "SKILL.md");
88
+ if (entry.isDirectory() && NAME.test(entry.name) && existsSync(skillFile)) files.set(entry.name, skillFile);
89
+ } else if (entry.isFile() && entry.name.endsWith(".md")) {
90
+ const name = entry.name.slice(0, -".md".length);
91
+ if (NAME.test(name)) files.set(name, join(folder, entry.name));
92
+ }
93
+ }
94
+ return files;
95
+ }
96
+
97
+ /** A file's front matter, or nothing when it has none or it does not parse. */
98
+ function frontMatterOf(file: string): z.infer<typeof frontMatterSchema> {
99
+ const text = readFileSync(file, "utf8").replace(/\r\n/g, "\n");
100
+ const block = text.match(/^---\n([\s\S]*?)\n---\n/);
101
+ let parsed: unknown = {};
102
+ try {
103
+ parsed = block ? (parseYaml(block[1]) ?? {}) : {};
104
+ } catch {
105
+ parsed = {};
106
+ }
107
+ return frontMatterSchema.parse(typeof parsed === "object" ? parsed : {});
108
+ }
109
+
110
+ /** Every prompt, skill and worker the package holds, each with its description. */
111
+ export function listPackage(options: PackageOptions = {}): PackageListing {
112
+ const root = options.root ?? packageRoot();
113
+ const named = (kind: PackageKind): PackageNamedEntry[] =>
114
+ [...filesOf(kind, root)].map(([name, file]) => ({ name, description: frontMatterOf(file).description }));
115
+ return {
116
+ prompts: [...filesOf("prompt", root)].map(([name, file]) => {
117
+ const front = frontMatterOf(file);
118
+ return { command: `/${name}`, description: front.description, argumentHint: front["argument-hint"] };
119
+ }),
120
+ skills: named("skill"),
121
+ workers: named("worker"),
122
+ };
123
+ }
124
+
125
+ /**
126
+ * Read one file by kind and name: a prompt by its command (`fito-tutor` or `/fito-tutor`), a skill
127
+ * by its folder, a worker by its file. A name that is not a kebab-case word, or that the listing
128
+ * does not hold, is refused.
129
+ */
130
+ export function readPackageFile(kind: PackageKind, name: string, options: PackageOptions = {}): PackageFile {
131
+ if (!PACKAGE_KINDS.includes(kind)) {
132
+ throw new Error(`"${kind}" is not a kind of Fito file — use one of: ${PACKAGE_KINDS.join(", ")}`);
133
+ }
134
+ const bare = kind === "prompt" ? name.trim().replace(/^\//, "") : name.trim();
135
+ if (!NAME.test(bare)) {
136
+ throw new Error(`"${name}" is not a name — name a ${kind} as the listing shows it, never a path or a file`);
137
+ }
138
+ const file = filesOf(kind, options.root ?? packageRoot()).get(bare);
139
+ if (file === undefined) {
140
+ throw new Error(`Fito has no ${kind} named "${bare}" — list the package for the names it holds`);
141
+ }
142
+ return { kind, name: bare, text: readFileSync(file, "utf8") };
143
+ }
@@ -3,18 +3,19 @@ name: fito-auth
3
3
  description: >
4
4
  Authenticate the Fito TUI against the backend and manage the local credential
5
5
  store. Use when the learner wants to log in, log out, or refresh their Fito
6
- session — the /fito-login, /fito-logout, and /fito-auth-refresh commands — or
7
- when a command confirms the login before it writes to Fito.
6
+ session — the /fito-login, /fito-login-by-device, /fito-logout, and
7
+ /fito-auth-refresh commands — or when a command confirms the login before it
8
+ writes to Fito.
8
9
  allowed-tools: bash
9
10
  ---
10
11
 
11
12
  # Fito Auth
12
13
 
13
- Handles the browser-based login handoff and the token store: one credentials file
14
- per Fito, `~/.fito/credentials-<host>` (off Windows, file mode `0600` and dir
15
- `0700`). Backend access goes through the `fito-api` client (ADR-003); this skill
16
- never sees a password — the browser performs the login and hands back only the
17
- token pair.
14
+ Handles the two logins — the browser handoff and the device login — and the token
15
+ store: one credentials file per Fito, `~/.fito/credentials-<host>` (off Windows,
16
+ file mode `0600` and dir `0700`). Backend access goes through the `fito-api` client
17
+ (ADR-003); this skill never sees a password — the user logs in in the browser, and
18
+ the skill receives only the token pair.
18
19
 
19
20
  Run the commands from wherever you are — each one below names this
20
21
  skill's directory itself.
@@ -31,6 +32,21 @@ freshly minted token pair back. On success it writes this Fito's credentials fil
31
32
  and prints a confirmation that names it. The learner can complete either
32
33
  auth flow (email/password or "Continue with GitHub") in the browser.
33
34
 
35
+ ## Log in by device
36
+
37
+ ```bash
38
+ node "<fito-auth skill dir>/login-by-device.js"
39
+ ```
40
+
41
+ The login for a browser that cannot reach `localhost`: over SSH, in WSL or a VM,
42
+ or where the browser blocks the call. Starts a device login, prints Fito's
43
+ `/device` address with a short code and a direct link, and tries to open the link.
44
+ The user approves the code on that page, from any computer; the script polls
45
+ until then, writes this Fito's credentials file, and prints the same confirmation
46
+ as the login above. When the code expires first, it prints
47
+ `✗ The code expired. Run /fito-login-by-device again.` and exits non-zero. Run it
48
+ with the bash tool's `timeout` unset: it ends on its own when the code expires.
49
+
34
50
  ## Log out
35
51
 
36
52
  ```bash
@@ -66,7 +82,7 @@ first, so a logged-out author stops before any work.
66
82
  |---|---|
67
83
  | `callback-server.ts` | Loopback receiver for the browser token handoff (CORS) |
68
84
  | `browser.ts` | Per-platform system-browser launcher |
69
- | `login.ts` / `logout.ts` / `auth-refresh.ts` / `status.ts` | CLI entrypoints (above) |
85
+ | `login.ts` / `login-by-device.ts` / `logout.ts` / `auth-refresh.ts` / `status.ts` | CLI entrypoints (above) |
70
86
 
71
87
  The credentials store (read/write/delete, Zod-validated) lives in the
72
88
  shared [`fito-session`](../../shared/fito-session/credentials.ts) module, reused by `fito-case-runner`.