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.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "fito-tui",
3
- "version": "0.9.3",
3
+ "version": "0.11.0",
4
4
  "description": "Fito for pi: case-based practice for software engineers, in your terminal.",
5
5
  "keywords": [
6
6
  "pi-package"
@@ -0,0 +1,70 @@
1
+ ---
2
+ description: Ask how Fito works — answered from the Fito user guide, one question or a whole conversation
3
+ argument-hint: '[question]'
4
+ ---
5
+ The user wants to know how Fito works. A worker, `fito-docs`, answers from Fito's
6
+ user guide and cites the pages it read. Drive the flow below. Throughout it you
7
+ are the **relay** — the worker answers, you carry its words across.
8
+
9
+ The user's question: $ARGUMENTS
10
+
11
+ ## 1. Get the question
12
+
13
+ If `$ARGUMENTS` is empty, ask the user what they would like to know about Fito,
14
+ and wait for their answer before running anything.
15
+
16
+ **Done when** you hold the user's question, in their own words.
17
+
18
+ ## 2. Put the question to the worker
19
+
20
+ **The first question in this session** opens the thread:
21
+
22
+ ```
23
+ fito_delegate({ agent: "fito-docs", thread: true, task: "The user asks:\n<question>" })
24
+ ```
25
+
26
+ The worker's reply comes back as that tool's own result, and its last line
27
+ carries the handle for this conversation:
28
+
29
+ ```
30
+ Fito thread id: <thread-id>
31
+ ```
32
+
33
+ **Every later question** goes back to the same worker, which still remembers
34
+ everything said so far:
35
+
36
+ ```
37
+ fito_delegate({ agent: "fito-docs", thread: "<most recent fito-docs thread id>", task: "<question>" })
38
+ ```
39
+
40
+ Every turn answers with a `Fito thread id:` line of its own, and a continued turn
41
+ can name a new id — so carry the most recent one a `fito-docs` reply gave into
42
+ the next question. `/fito-tutor` and other Fito commands print the same kind of
43
+ line for their own workers, and a docs question never continues one of those
44
+ threads. That line is yours to keep: the user reads the worker's words and
45
+ nothing of the machinery underneath them.
46
+
47
+ If a turn comes back as an error — the thread has aged out, or belongs to another
48
+ session — tell the user in one line that the conversation was lost, then open a
49
+ new thread with `thread: true` and the same question. A new thread does not
50
+ remember the conversation, and the user should hear that from you. If that new
51
+ thread fails too, tell the user what failed and stop: one fresh attempt per
52
+ question.
53
+
54
+ **Done when** the worker's reply to this question is in hand, or its fresh
55
+ attempt failed and the user has been told.
56
+
57
+ ## 3. Relay the reply
58
+
59
+ Pass the worker's reply through in full, with every page address it cited. Add
60
+ nothing of your own — no summary, no extra fact, no answer from files you can
61
+ read yourself. The worker answers from the guide, so anything you add skipped
62
+ the guide.
63
+
64
+ **Done when** the user has the worker's reply and, beyond it, only §4's closing.
65
+
66
+ ## 4. Carry on
67
+
68
+ Close with how to keep going — `/fito-docs <question>` — and with the one limit
69
+ worth stating: the thread lives as long as this pi session does, so a new
70
+ session starts a fresh one.
@@ -0,0 +1,24 @@
1
+ ---
2
+ description: Log in to Fito with a code you approve in a browser (no localhost needed)
3
+ ---
4
+ Log the user in to Fito with a device code.
5
+
6
+ Use the `fito-auth` skill (read its `SKILL.md`), then run:
7
+
8
+ ```bash
9
+ node "<fito-auth skill dir>/login-by-device.js"
10
+ ```
11
+
12
+ The script prints Fito's `/device` address, a short code such as `WDJB-MJHT` and a
13
+ direct link, and tries to open the link in a browser. The user approves the code on
14
+ that page, from this computer or any other, and the script then writes this Fito's
15
+ `~/.fito/credentials-<host>`. Nothing calls `localhost`, so this login works over
16
+ SSH, in WSL or a VM, and where the browser blocks `localhost`.
17
+
18
+ Run the command in the foreground, so pi shows its output live: the user reads the
19
+ address and the code there while the script waits. Leave the bash tool's `timeout`
20
+ unset: the script waits for the approval as long as the code lives, and ends on its
21
+ own when the code expires.
22
+
23
+ When it prints the success line, confirm the user is logged in. When it fails,
24
+ report its error and suggest running `/fito-login-by-device` again.
@@ -84,9 +84,11 @@ fito_delegate({ agent: "fito-tutor", thread: "<thread id for this case>", task:
84
84
  ```
85
85
 
86
86
  Every turn answers with a `Fito thread id:` line of its own, and a continued turn
87
- can name a new id — so carry the most recent one into the next question. That
88
- line is yours to keep: the learner reads the tutor's words and nothing of the
89
- machinery underneath them.
87
+ can name a new id — so carry the most recent one a `fito-tutor` reply gave for
88
+ this case into the next question. `/fito-docs` and other Fito commands print the
89
+ same kind of line for their own workers, and a tutor question never continues
90
+ one of those threads. That line is yours to keep: the learner reads the tutor's
91
+ words and nothing of the machinery underneath them.
90
92
 
91
93
  If a turn comes back as an error — the thread has aged out, or belongs to another
92
94
  session — say so in one line and open a fresh one with `thread: true`. A new
@@ -1,9 +1,11 @@
1
1
  # Fito API Client
2
2
 
3
- The TUI's backend HTTP **transport boundary**: a thin client that mirrors backend REST
4
- endpoints one method per endpoint, attaches auth, validates every response with Zod, and
5
- normalises errors into `FitoApiError`. It is **shared code**, not a skill: a pure library
6
- *imported* by relative path (by `fito-auth` today, and by `shared/knowledge-components/`,
3
+ The TUI's whole HTTP **transport boundary** — the backend's and the user guide's. For the
4
+ backend, a thin client that mirrors backend REST endpoints one method per endpoint, attaches
5
+ auth, validates every response with Zod, and normalises errors into `FitoApiError`. For the
6
+ guide, one read of a path under the guide's address
7
+ ([The guide transport](#the-guide-transport)). It is **shared code**, not a skill: a pure
8
+ library *imported* by relative path (by `fito-auth` today, and by `shared/knowledge-components/`,
7
9
  case-runner, and others going forward), never invoked by the agent. See
8
10
  `.ai/architecture_decisions/ADR-006-shared-code-vs-skills.md` for why it lives in
9
11
  `tui/shared/` rather than `tui/skills/`.
@@ -13,9 +15,11 @@ mapping one endpoint, or defining a response's wire schema lives *here*. Interpr
13
15
  composing, or presenting that data — parsing an identifier, turning a 404 into a user-facing
14
16
  message, chaining calls into a workflow — lives in a subject folder under `shared/<subject>/`
15
17
  that *imports* this client (e.g. `shared/knowledge-components/`). "Single seam" means **all raw
16
- HTTP** funnels through here, not that all backend-shaped code belongs here.
18
+ HTTP** funnels through here, the guide's included, not that all backend-shaped code belongs
19
+ here.
17
20
 
18
- > **Convention (ADR-003).** Every TUI → backend call goes through this one client.
21
+ > **Convention (ADR-003).** Every TUI → backend call goes through this one client, and every
22
+ > TUI → guide read through `guide.ts` beside it.
19
23
  > **Do not** make ad-hoc `fetch` calls from skills, prompts, or extensions, and
20
24
  > **do not** add `axios` — native `fetch` + Zod is the sanctioned transport. This
21
25
  > governance rule is documentation, not an agent capability (ADR-006); it is also
@@ -40,6 +44,11 @@ const user = await api.me(accessToken); // GET /me -> SessionUser (+ linked
40
44
  const { user, tokens } = await api.meWithRefresh(storedTokens);
41
45
  // user.githubLogin / user.githubUserId are null when no GitHub identity is linked.
42
46
 
47
+ // POST /auth/device + POST /device-login/poll -> the device login (no token; Task 17.32): start one,
48
+ // then poll until the answer is { status: "approved", ...tokens } instead of { status: "pending" }.
49
+ const { deviceCode, userCode, expiresIn, interval } = await api.startDeviceLogin();
50
+ const answer = await api.pollDeviceLogin(deviceCode);
51
+
43
52
  // GET /knowledge/{type}/{slug} -> one component by (type, slug) (public read, no token):
44
53
  const component = await api.getKnowledgeComponent("concept", "git.bisect");
45
54
 
@@ -188,5 +197,25 @@ itself — `error.duplicateId` / `error.supersededBy` (knowledge) and `error.mat
188
197
  the backend sets one: `/problems/tui-too-old` is the refusal of a TUI older than the
189
198
  backend's minimum (Task 15d.7a).
190
199
 
200
+ ## The guide transport
201
+
202
+ `guide.ts` reads the user guide for `/fito-docs` (Task 17.35). It lives here, not in
203
+ `shared/fito-guide/`, so this folder stays the one place the TUI issues an HTTP request
204
+ (ADR-003's 2026-11-16 scope note):
205
+
206
+ ```ts
207
+ import { FitoGuideError, readGuideText } from "../../shared/fito-api/guide.ts";
208
+
209
+ // GET <guide address><path> -> the body as text. The address is shared/fito-url/'s fitoGuideUrl():
210
+ // FITO_GUIDE_URL, or https://docs.fito.codes. Any status but 200 is a FitoGuideError (status, path).
211
+ const index = await readGuideText("/llms.txt");
212
+ ```
213
+
214
+ It sends the client's `User-Agent: fito-tui/<version>`, so the guide's access logs show
215
+ `/fito-docs` use, and gives up after 15 seconds (`GUIDE_TIMEOUT_MS`), so a stalled guide cannot
216
+ hold the worker's turn. It knows nothing of what the guide holds: which paths exist, what an index line
217
+ says and what a page's address is belong to `shared/fito-guide/`, which imports it. `fetch` is
218
+ injected the same way (`readGuideText(path, { fetch })`).
219
+
191
220
  At Task 1.5 the client maps only what the TUI calls. New phases add typed,
192
221
  Zod-validated functions here — they do not introduce a different HTTP client.
@@ -4,8 +4,9 @@ import { fitoApiUrl } from "../fito-url/fito-url.js";
4
4
  /**
5
5
  * The TUI's backend HTTP **transport boundary** (ADR-003): a thin client that mirrors backend
6
6
  * REST endpoints one method per endpoint, attaches auth, validates every response with Zod, and
7
- * normalises errors into `FitoApiError`. It is the only place raw `fetch` lives — no ad-hoc
8
- * `fetch`, no axios. That, and only that, is what "single seam" means.
7
+ * normalises errors into `FitoApiError`. It and the guide transport beside it (`guide.ts`, Task
8
+ * 17.35) are the only places raw `fetch` lives — no ad-hoc `fetch`, no axios. That, and only that,
9
+ * is what "single seam" means.
9
10
  *
10
11
  * It carries no domain logic: parsing identifiers, composing calls, or shaping responses for a
11
12
  * use case belong in a `shared/<subject>/` module that imports this client (e.g.
@@ -16,9 +17,9 @@ import { fitoApiUrl } from "../fito-url/fito-url.js";
16
17
  /**
17
18
  * Sent on every request, so the backend can refuse a TUI older than the minimum version it serves,
18
19
  * with a message that says how to update (Task 15d.7a). Without it, Node's `fetch` sends `node`,
19
- * which the backend always lets through.
20
+ * which the backend always lets through. The guide transport (`guide.ts`, Task 17.35) sends it too.
20
21
  */
21
- const USER_AGENT = `fito-tui/${packageJson.version}`;
22
+ export const USER_AGENT = `fito-tui/${packageJson.version}`;
22
23
  export const tokenResponseSchema = z.object({
23
24
  accessToken: z.string().min(1),
24
25
  refreshToken: z.string().min(1),
@@ -34,6 +35,25 @@ export const meResponseSchema = z.object({
34
35
  githubLogin: z.string().nullable().optional(),
35
36
  githubUserId: z.number().nullable().optional(),
36
37
  });
38
+ /**
39
+ * `POST /auth/device`'s answer, the start of a device login (Task 17.32): the long secret
40
+ * `deviceCode` the CLI polls with, the short `userCode` the user approves on the website
41
+ * (`WDJB-MJHT`), the code's lifetime and the wait between two polls, in seconds.
42
+ */
43
+ export const deviceLoginStartSchema = z.object({
44
+ deviceCode: z.string().min(1),
45
+ userCode: z.string().min(1),
46
+ expiresIn: z.number().int().positive(),
47
+ interval: z.number().int().positive(),
48
+ });
49
+ /**
50
+ * `POST /device-login/poll`'s answer: still waiting for the approval, or approved, with the token
51
+ * pair, which the backend sends once. A pending poll is a `200`, not RFC 8628's `400`.
52
+ */
53
+ export const deviceLoginPollSchema = z.discriminatedUnion("status", [
54
+ z.object({ status: z.literal("pending") }),
55
+ tokenResponseSchema.extend({ status: z.literal("approved") }),
56
+ ]);
37
57
  /** The backend's health answer (`GET /actuator/health`); `status` is `UP` or `DOWN`. */
38
58
  export const healthSchema = z.object({ status: z.string() });
39
59
  /** The component-type wire tokens, identical to the URL path segments. Mirrors `web/src/lib/api/knowledge.ts`. */
@@ -522,6 +542,11 @@ export function createFitoApiClient(options = {}) {
522
542
  return { user: await me(fresh.accessToken), tokens: fresh };
523
543
  }
524
544
  }
545
+ const startDeviceLogin = () => request("/auth/device", deviceLoginStartSchema, { method: "POST" });
546
+ const pollDeviceLogin = (deviceCode) => request("/device-login/poll", deviceLoginPollSchema, {
547
+ method: "POST",
548
+ body: JSON.stringify({ deviceCode }),
549
+ });
525
550
  const getHealth = (options = {}) => request("/actuator/health", healthSchema, { method: "GET", signal: options.signal });
526
551
  const getKnowledgeComponent = (type, slug, params = {}) => {
527
552
  const query = new URLSearchParams();
@@ -680,6 +705,8 @@ export function createFitoApiClient(options = {}) {
680
705
  logout,
681
706
  me,
682
707
  meWithRefresh,
708
+ startDeviceLogin,
709
+ pollDeviceLogin,
683
710
  getHealth,
684
711
  getKnowledgeComponent,
685
712
  searchKnowledgeComponents,
@@ -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),
@@ -42,6 +43,29 @@ export const meResponseSchema = z.object({
42
43
  });
43
44
  export type SessionUser = z.infer<typeof meResponseSchema>;
44
45
 
46
+ /**
47
+ * `POST /auth/device`'s answer, the start of a device login (Task 17.32): the long secret
48
+ * `deviceCode` the CLI polls with, the short `userCode` the user approves on the website
49
+ * (`WDJB-MJHT`), the code's lifetime and the wait between two polls, in seconds.
50
+ */
51
+ export const deviceLoginStartSchema = z.object({
52
+ deviceCode: z.string().min(1),
53
+ userCode: z.string().min(1),
54
+ expiresIn: z.number().int().positive(),
55
+ interval: z.number().int().positive(),
56
+ });
57
+ export type DeviceLoginStart = z.infer<typeof deviceLoginStartSchema>;
58
+
59
+ /**
60
+ * `POST /device-login/poll`'s answer: still waiting for the approval, or approved, with the token
61
+ * pair, which the backend sends once. A pending poll is a `200`, not RFC 8628's `400`.
62
+ */
63
+ export const deviceLoginPollSchema = z.discriminatedUnion("status", [
64
+ z.object({ status: z.literal("pending") }),
65
+ tokenResponseSchema.extend({ status: z.literal("approved") }),
66
+ ]);
67
+ export type DeviceLoginPoll = z.infer<typeof deviceLoginPollSchema>;
68
+
45
69
  /** The backend's health answer (`GET /actuator/health`); `status` is `UP` or `DOWN`. */
46
70
  export const healthSchema = z.object({ status: z.string() });
47
71
  export type Health = z.infer<typeof healthSchema>;
@@ -730,6 +754,15 @@ export interface FitoApiClient {
730
754
  * the user and the (possibly refreshed) token pair so the caller can persist it.
731
755
  */
732
756
  meWithRefresh(tokens: TokenResponse): Promise<{ user: SessionUser; tokens: TokenResponse }>;
757
+ /**
758
+ * `POST /auth/device` — start a device login (Task 17.32). No login: the CLI holds no token yet.
759
+ */
760
+ startDeviceLogin(): Promise<DeviceLoginStart>;
761
+ /**
762
+ * `POST /device-login/poll` — whether the user approved the device login yet. No login. An
763
+ * unknown, expired or used device code is a 400 `FitoApiError`.
764
+ */
765
+ pollDeviceLogin(deviceCode: string): Promise<DeviceLoginPoll>;
733
766
  /**
734
767
  * `GET /actuator/health` — whether the backend is up. No login. The startup check calls it for
735
768
  * the backend's answer to this TUI's version (Task 15d.7b), and bounds the wait with `signal`.
@@ -1094,6 +1127,15 @@ export function createFitoApiClient(options: FitoApiClientOptions = {}): FitoApi
1094
1127
  }
1095
1128
  }
1096
1129
 
1130
+ const startDeviceLogin = (): Promise<DeviceLoginStart> =>
1131
+ request("/auth/device", deviceLoginStartSchema, { method: "POST" });
1132
+
1133
+ const pollDeviceLogin = (deviceCode: string): Promise<DeviceLoginPoll> =>
1134
+ request("/device-login/poll", deviceLoginPollSchema, {
1135
+ method: "POST",
1136
+ body: JSON.stringify({ deviceCode }),
1137
+ });
1138
+
1097
1139
  const getHealth = (options: { signal?: AbortSignal } = {}): Promise<Health> =>
1098
1140
  request("/actuator/health", healthSchema, { method: "GET", signal: options.signal });
1099
1141
 
@@ -1375,6 +1417,8 @@ export function createFitoApiClient(options: FitoApiClientOptions = {}): FitoApi
1375
1417
  logout,
1376
1418
  me,
1377
1419
  meWithRefresh,
1420
+ startDeviceLogin,
1421
+ pollDeviceLogin,
1378
1422
  getHealth,
1379
1423
  getKnowledgeComponent,
1380
1424
  searchKnowledgeComponents,
@@ -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
+ }