fito-tui 0.2.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.
Files changed (179) hide show
  1. package/README.md +88 -0
  2. package/agents/fito-case-source-planner.md +265 -0
  3. package/agents/fito-performance-reviewer.md +231 -0
  4. package/agents/fito-practice-concept-content-generator.md +318 -0
  5. package/agents/fito-practice-concept-identifier.md +482 -0
  6. package/agents/fito-practice-execution-fact-content-generator.md +299 -0
  7. package/agents/fito-practice-execution-fact-identifier.md +367 -0
  8. package/agents/fito-practice-usage-scenario-content-generator.md +331 -0
  9. package/agents/fito-practice-usage-scenario-identifier.md +397 -0
  10. package/agents/fito-subagent-selftest.md +27 -0
  11. package/agents/fito-technology-generator.md +207 -0
  12. package/agents/fito-tool-concept-content-generator.md +282 -0
  13. package/agents/fito-tool-concept-identifier.md +384 -0
  14. package/agents/fito-tool-execution-fact-content-generator.md +382 -0
  15. package/agents/fito-tool-execution-fact-identifier.md +360 -0
  16. package/agents/fito-tool-usage-scenario-content-generator.md +381 -0
  17. package/agents/fito-tool-usage-scenario-identifier.md +432 -0
  18. package/agents/fito-tutor.md +185 -0
  19. package/extensions/fito-delegate.js +539 -0
  20. package/extensions/fito-delegate.ts +691 -0
  21. package/extensions/fito-fetch-tools.js +380 -0
  22. package/extensions/fito-fetch-tools.ts +419 -0
  23. package/extensions/fito-startup.js +166 -0
  24. package/extensions/fito-startup.ts +188 -0
  25. package/package.json +56 -0
  26. package/prompts/fito-auth-refresh.md +15 -0
  27. package/prompts/fito-case-design.md +506 -0
  28. package/prompts/fito-case-edit.md +91 -0
  29. package/prompts/fito-case-generate.md +222 -0
  30. package/prompts/fito-case-open.md +124 -0
  31. package/prompts/fito-case-plan-source.md +114 -0
  32. package/prompts/fito-create-or-update-competence.md +261 -0
  33. package/prompts/fito-create-or-update-technology.md +199 -0
  34. package/prompts/fito-delete-competence.md +147 -0
  35. package/prompts/fito-evaluate.md +148 -0
  36. package/prompts/fito-fetch-urls-content.md +35 -0
  37. package/prompts/fito-generate-domain-concepts.md +85 -0
  38. package/prompts/fito-generate-execution-facts.md +85 -0
  39. package/prompts/fito-generate-usage-scenarios.md +85 -0
  40. package/prompts/fito-identify-domain-concepts.md +49 -0
  41. package/prompts/fito-identify-execution-facts.md +49 -0
  42. package/prompts/fito-identify-usage-scenarios.md +49 -0
  43. package/prompts/fito-login.md +21 -0
  44. package/prompts/fito-logout.md +14 -0
  45. package/prompts/fito-publish-case.md +266 -0
  46. package/prompts/fito-push-knowledge.md +84 -0
  47. package/prompts/fito-submit.md +208 -0
  48. package/prompts/fito-tutor.md +120 -0
  49. package/shared/case-briefing/briefing.js +221 -0
  50. package/shared/case-briefing/briefing.ts +261 -0
  51. package/shared/case-quiz/scoring.js +16 -0
  52. package/shared/case-quiz/scoring.ts +61 -0
  53. package/shared/case-validation/case-loader.js +88 -0
  54. package/shared/case-validation/case-loader.ts +106 -0
  55. package/shared/case-validation/case-schema.js +716 -0
  56. package/shared/case-validation/case-schema.ts +895 -0
  57. package/shared/competences/competence-list.js +29 -0
  58. package/shared/competences/competence-list.ts +32 -0
  59. package/shared/fito-api/README.md +192 -0
  60. package/shared/fito-api/client.js +731 -0
  61. package/shared/fito-api/client.ts +1426 -0
  62. package/shared/fito-session/credentials.js +79 -0
  63. package/shared/fito-session/credentials.ts +88 -0
  64. package/shared/fito-session/session.js +16 -0
  65. package/shared/fito-session/session.ts +35 -0
  66. package/shared/github-url/parse.js +26 -0
  67. package/shared/github-url/parse.ts +35 -0
  68. package/shared/knowledge-components/component-names.js +35 -0
  69. package/shared/knowledge-components/component-names.ts +39 -0
  70. package/shared/knowledge-components/knowledge-fetch.js +46 -0
  71. package/shared/knowledge-components/knowledge-fetch.ts +57 -0
  72. package/shared/knowledge-components/knowledge-search.js +101 -0
  73. package/shared/knowledge-components/knowledge-search.ts +144 -0
  74. package/shared/knowledge-components/push-payload.js +104 -0
  75. package/shared/knowledge-components/push-payload.ts +129 -0
  76. package/shared/knowledge-components/reference.js +24 -0
  77. package/shared/knowledge-components/reference.ts +43 -0
  78. package/shared/knowledge-components/technology-fetch.js +30 -0
  79. package/shared/knowledge-components/technology-fetch.ts +38 -0
  80. package/shared/shell-exec/exec.js +22 -0
  81. package/shared/shell-exec/exec.ts +46 -0
  82. package/skills/fito-auth/SKILL.md +68 -0
  83. package/skills/fito-auth/auth-refresh.js +23 -0
  84. package/skills/fito-auth/auth-refresh.ts +25 -0
  85. package/skills/fito-auth/browser.js +35 -0
  86. package/skills/fito-auth/browser.ts +57 -0
  87. package/skills/fito-auth/callback-server.js +152 -0
  88. package/skills/fito-auth/callback-server.ts +189 -0
  89. package/skills/fito-auth/login.js +37 -0
  90. package/skills/fito-auth/login.ts +42 -0
  91. package/skills/fito-auth/logout.js +24 -0
  92. package/skills/fito-auth/logout.ts +25 -0
  93. package/skills/fito-case-author/SKILL.md +179 -0
  94. package/skills/fito-case-author/checkout.js +222 -0
  95. package/skills/fito-case-author/checkout.ts +281 -0
  96. package/skills/fito-case-author/github-publish.js +218 -0
  97. package/skills/fito-case-author/github-publish.ts +251 -0
  98. package/skills/fito-case-author/publish-payload.js +108 -0
  99. package/skills/fito-case-author/publish-payload.ts +186 -0
  100. package/skills/fito-case-author/publish-state.js +72 -0
  101. package/skills/fito-case-author/publish-state.ts +87 -0
  102. package/skills/fito-case-author/publish-version.js +364 -0
  103. package/skills/fito-case-author/publish-version.ts +495 -0
  104. package/skills/fito-case-author/publish.js +284 -0
  105. package/skills/fito-case-author/publish.ts +394 -0
  106. package/skills/fito-case-author/semver.js +55 -0
  107. package/skills/fito-case-author/semver.ts +63 -0
  108. package/skills/fito-case-author/status-gate.js +34 -0
  109. package/skills/fito-case-author/status-gate.ts +54 -0
  110. package/skills/fito-case-author/validate.js +62 -0
  111. package/skills/fito-case-author/validate.ts +64 -0
  112. package/skills/fito-case-runner/SKILL.md +119 -0
  113. package/skills/fito-case-runner/case-component-names.js +45 -0
  114. package/skills/fito-case-runner/case-component-names.ts +65 -0
  115. package/skills/fito-case-runner/case-detail.js +20 -0
  116. package/skills/fito-case-runner/case-detail.ts +20 -0
  117. package/skills/fito-case-runner/github.js +234 -0
  118. package/skills/fito-case-runner/github.ts +287 -0
  119. package/skills/fito-case-runner/manifest.js +56 -0
  120. package/skills/fito-case-runner/manifest.ts +73 -0
  121. package/skills/fito-case-runner/open.js +175 -0
  122. package/skills/fito-case-runner/open.ts +241 -0
  123. package/skills/fito-case-runner/report.js +22 -0
  124. package/skills/fito-case-runner/report.ts +24 -0
  125. package/skills/fito-case-runner/runner.js +158 -0
  126. package/skills/fito-case-runner/runner.ts +304 -0
  127. package/skills/fito-case-runner/score-quiz-mc.js +85 -0
  128. package/skills/fito-case-runner/score-quiz-mc.ts +99 -0
  129. package/skills/fito-case-runner/submit-evaluation.js +73 -0
  130. package/skills/fito-case-runner/submit-evaluation.ts +98 -0
  131. package/skills/fito-case-runner/submit-quiz-result.js +75 -0
  132. package/skills/fito-case-runner/submit-quiz-result.ts +100 -0
  133. package/skills/fito-case-runner/submit.js +85 -0
  134. package/skills/fito-case-runner/submit.ts +111 -0
  135. package/skills/fito-case-runner/workdir.js +10 -0
  136. package/skills/fito-case-runner/workdir.ts +11 -0
  137. package/skills/fito-competence-write/SKILL.md +155 -0
  138. package/skills/fito-competence-write/create.js +64 -0
  139. package/skills/fito-competence-write/create.ts +80 -0
  140. package/skills/fito-competence-write/delete.js +136 -0
  141. package/skills/fito-competence-write/delete.ts +166 -0
  142. package/skills/fito-competence-write/display.js +20 -0
  143. package/skills/fito-competence-write/display.ts +21 -0
  144. package/skills/fito-competence-write/payload.js +96 -0
  145. package/skills/fito-competence-write/payload.ts +115 -0
  146. package/skills/fito-competence-write/update.js +155 -0
  147. package/skills/fito-competence-write/update.ts +206 -0
  148. package/skills/fito-evaluator/SKILL.md +73 -0
  149. package/skills/fito-evaluator/criterion-exec.js +64 -0
  150. package/skills/fito-evaluator/criterion-exec.ts +73 -0
  151. package/skills/fito-evaluator/evaluate-automated.js +57 -0
  152. package/skills/fito-evaluator/evaluate-automated.ts +84 -0
  153. package/skills/fito-evaluator/evaluate.js +28 -0
  154. package/skills/fito-evaluator/evaluate.ts +86 -0
  155. package/skills/fito-evaluator/report.js +112 -0
  156. package/skills/fito-evaluator/report.ts +128 -0
  157. package/skills/fito-evaluator/rubric.js +90 -0
  158. package/skills/fito-evaluator/rubric.ts +170 -0
  159. package/skills/fito-knowledge-push/SKILL.md +114 -0
  160. package/skills/fito-knowledge-push/push.js +282 -0
  161. package/skills/fito-knowledge-push/push.ts +360 -0
  162. package/skills/fito-source-ingestion/SKILL.md +77 -0
  163. package/skills/fito-source-ingestion/authoring-check.js +128 -0
  164. package/skills/fito-source-ingestion/authoring-check.ts +155 -0
  165. package/skills/fito-source-ingestion/bundle.js +198 -0
  166. package/skills/fito-source-ingestion/bundle.ts +246 -0
  167. package/skills/fito-technology-write/SKILL.md +108 -0
  168. package/skills/fito-technology-write/create.js +134 -0
  169. package/skills/fito-technology-write/create.ts +161 -0
  170. package/skills/fito-technology-write/payload.js +64 -0
  171. package/skills/fito-technology-write/payload.ts +70 -0
  172. package/skills/fito-technology-write/update.js +122 -0
  173. package/skills/fito-technology-write/update.ts +171 -0
  174. package/skills/fito-url-content-fetcher/SKILL.md +213 -0
  175. package/templates/concept-practice-content-template.md +281 -0
  176. package/templates/concept-tool-content-template.md +207 -0
  177. package/templates/execution-fact-practice-content-template.md +372 -0
  178. package/templates/execution-fact-tool-content-template.md +307 -0
  179. package/templates/usage-scenario-content-template.md +248 -0
@@ -0,0 +1,731 @@
1
+ import { z } from "zod";
2
+ import packageJson from "../../package.json" with { type: "json" };
3
+ /**
4
+ * The TUI's backend HTTP **transport boundary** (ADR-003): a thin client that mirrors backend
5
+ * REST endpoints one method per endpoint, attaches auth, validates every response with Zod, and
6
+ * normalises errors into `FitoApiError`. It is the only place raw `fetch` lives — no ad-hoc
7
+ * `fetch`, no axios. That, and only that, is what "single seam" means.
8
+ *
9
+ * It carries no domain logic: parsing identifiers, composing calls, or shaping responses for a
10
+ * use case belong in a `shared/<subject>/` module that imports this client (e.g.
11
+ * `shared/knowledge-components/`). New endpoints are added here as typed, Zod-validated functions;
12
+ * it grows per phase. At Task 1.5 it mapped only `refresh`, `logout`, `me`, plus the
13
+ * `401 → /auth/refresh → retry` helper `meWithRefresh`.
14
+ */
15
+ /** Default backend origin; overridable via `FITO_API_BASE_URL`. */
16
+ export const DEFAULT_BASE_URL = process.env.FITO_API_BASE_URL ?? "http://localhost:8080";
17
+ /**
18
+ * Sent on every request, so the backend can refuse a TUI older than the minimum version it serves,
19
+ * with a message that says how to update (Task 15d.7a). Without it, Node's `fetch` sends `node`,
20
+ * which the backend always lets through.
21
+ */
22
+ const USER_AGENT = `fito-tui/${packageJson.version}`;
23
+ export const tokenResponseSchema = z.object({
24
+ accessToken: z.string().min(1),
25
+ refreshToken: z.string().min(1),
26
+ expiresIn: z.number(),
27
+ tokenType: z.string().default("Bearer"),
28
+ });
29
+ export const meResponseSchema = z.object({
30
+ userId: z.string(),
31
+ email: z.string(),
32
+ username: z.string(),
33
+ // The learner's linked GitHub identity (Task 5.4) — null/absent when none is linked. The TUI
34
+ // matches these against the locally `gh`-authenticated account before a case submission.
35
+ githubLogin: z.string().nullable().optional(),
36
+ githubUserId: z.number().nullable().optional(),
37
+ });
38
+ /** The backend's health answer (`GET /actuator/health`); `status` is `UP` or `DOWN`. */
39
+ export const healthSchema = z.object({ status: z.string() });
40
+ /** The component-type wire tokens, identical to the URL path segments. Mirrors `web/src/lib/api/knowledge.ts`. */
41
+ export const componentTypeSchema = z.enum(["concept", "execution-fact", "usage-scenario"]);
42
+ export const COMPONENT_TYPES = componentTypeSchema.options;
43
+ /** The technology a knowledge component belongs to, embedded in every component response. */
44
+ export const componentTechnologySchema = z.object({
45
+ id: z.string(),
46
+ kind: z.string(),
47
+ name: z.string(),
48
+ slug: z.string(),
49
+ });
50
+ /**
51
+ * One renderable content section. `value` is a string or a list of strings, mirroring the
52
+ * backend's structured-content field types (`KnowledgeDtos.ContentSectionResponse`).
53
+ */
54
+ export const contentSectionSchema = z.object({
55
+ key: z.string(),
56
+ label: z.string(),
57
+ value: z.union([z.string(), z.array(z.string())]),
58
+ });
59
+ /**
60
+ * One knowledge component on the wire (`KnowledgeDtos.KnowledgeComponentResponse`). `id` is the
61
+ * canonical reference (`concept:git.bisect`); `slug` is the full dotted value (`git.bisect`). The
62
+ * shapes match `web/src/lib/api/knowledge.ts` so the TUI and web share one contract.
63
+ *
64
+ * `supersededById` is the forward version link (Task 11.4a6-4): the **newest** member of this
65
+ * component's version chain when something has replaced it — what a caller should be reading
66
+ * instead — mirroring the backward `previousVersionId`, which names the immediate predecessor.
67
+ *
68
+ * It is `nullish` because the backend sends the key only when the answer is a component: anything
69
+ * still in force has nothing to name. That is now true on **every** endpoint returning this shape
70
+ * (Task 11.14) — an absent key means "nothing replaced it", full stop. Until then listings did not
71
+ * carry the field at all, on the grounds that resolving it walks the chain per row, so an absent
72
+ * key meant "nothing replaced it" on the point read and "nobody computed it" in a listing: the same
73
+ * bytes, opposite facts. Postgres resolves a whole listing's chains in one recursive query, which
74
+ * is what closed the gap.
75
+ */
76
+ export const knowledgeComponentSchema = z.object({
77
+ id: z.string(),
78
+ type: componentTypeSchema,
79
+ technology: componentTechnologySchema,
80
+ slug: z.string(),
81
+ name: z.string(),
82
+ sections: z.array(contentSectionSchema),
83
+ version: z.string(),
84
+ previousVersionId: z.string().nullable(),
85
+ alternativeDefinitionOfId: z.string().nullable(),
86
+ templateId: z.string(),
87
+ supersededById: z.string().nullish(),
88
+ });
89
+ /**
90
+ * A field's requirement on the template wire (`KnowledgeDtos.FieldRequirementResponse`). The
91
+ * trigger fields are non-null only for `OPTIONAL_WITH_TRIGGER`.
92
+ */
93
+ export const templateFieldRequirementSchema = z.object({
94
+ kind: z.string(),
95
+ controllingField: z.string().nullable().optional(),
96
+ triggerValue: z.string().nullable().optional(),
97
+ });
98
+ /** One field descriptor on the template wire (`KnowledgeDtos.TemplateFieldResponse`); `type` is `TEXT` or `LIST`. */
99
+ export const templateFieldSchema = z.object({
100
+ key: z.string(),
101
+ label: z.string(),
102
+ type: z.string(),
103
+ requirement: templateFieldRequirementSchema,
104
+ includedInEmbedding: z.boolean(),
105
+ metadata: z.boolean(),
106
+ });
107
+ /**
108
+ * The technology kind a registered template is written for (`KnowledgeDtos.TemplateAppliesToKind`'s
109
+ * wire tokens). `tool` and `practice` match `TechnologySummary.kind` — which is exactly what a
110
+ * caller matches them against — while `any` is the shared row a component type keeps when its
111
+ * fields do not differ by kind.
112
+ */
113
+ export const templateAppliesToKindSchema = z.enum(["tool", "practice", "any"]);
114
+ /**
115
+ * One registered template on the wire (`KnowledgeDtos.TemplateResponse` from
116
+ * `GET /knowledge/templates/{type}`): the `templateId` a knowledge write must name, plus the
117
+ * field-schema the write's `content` must conform to.
118
+ *
119
+ * `appliesToKind` is **required** — no `.nullable()`, no `.optional()`. A component type may carry
120
+ * several templates along two independent axes (the kind variant and the version lineage), and an
121
+ * optional marker would let an omitted value read as "matches nothing" while parsing cleanly; a
122
+ * required one turns a backend that forgot the field into a loud parse failure.
123
+ */
124
+ export const knowledgeTemplateSchema = z.object({
125
+ id: z.string(),
126
+ componentType: componentTypeSchema,
127
+ version: z.string(),
128
+ previousVersionId: z.string().nullable(),
129
+ appliesToKind: templateAppliesToKindSchema,
130
+ schema: z.object({ fields: z.array(templateFieldSchema) }),
131
+ });
132
+ const templateListSchema = z.object({ items: z.array(knowledgeTemplateSchema) });
133
+ /** A technology's major release line on the wire (ADR-011), as the backend's `TechnologyVersionResponse`. */
134
+ export const technologyVersionSchema = z.object({
135
+ id: z.string(),
136
+ label: z.string(),
137
+ slug: z.string(),
138
+ description: z.string().nullable(),
139
+ });
140
+ /**
141
+ * One technology with its major release lines on the wire (`GET /technologies/{slug}`, the
142
+ * backend's `TechnologySummaryResponse`). `description` is the version-agnostic overview; the
143
+ * per-version compatibility prose (ADR-011 F7 — "Javalin 7 requires Java 17+, runs on Jetty 12")
144
+ * lives on each `technologyVersions[].description`, the toolchain cross-check's source (9a.6a).
145
+ * `componentCounts` keys are the component-type wire tokens. Mirrors `web/src/lib/api/technologies.ts`.
146
+ */
147
+ export const technologySummarySchema = z.object({
148
+ id: z.string(),
149
+ kind: z.string(),
150
+ name: z.string(),
151
+ slug: z.string(),
152
+ description: z.string().nullable(),
153
+ technologyVersions: z.array(technologyVersionSchema),
154
+ componentCounts: z.record(z.string(), z.number()),
155
+ });
156
+ /**
157
+ * One item of the `GET /knowledge` listing (Task 9c.11). The endpoint returns the **same** records
158
+ * the point read does — `sections` and all — so this is [knowledgeComponentSchema] plus
159
+ * `technologyVersions`, the major lines the component is bound to.
160
+ *
161
+ * **Why the extra field is here and not on [knowledgeComponentSchema] itself.** The wire carries
162
+ * `technologyVersions` on every component response, and the point-read schema has always dropped it
163
+ * (Zod strips unknown keys). Adding it there would change what `fito_knowledge_fetch` hands every
164
+ * caller, which is a different decision from this one. Here it is load-bearing: it is what each
165
+ * listing entry's `versions` is projected from in
166
+ * `shared/knowledge-components/knowledge-search.ts`, so a reader can tell a component bound to one
167
+ * major line from one shared across several. **Scoping the listing to a line is no longer its job**
168
+ * — `GET /knowledge` filters on `technologyVersion` server-side (Task 11.4a6-1) — but the field is
169
+ * still what the reader is shown, so dropping it would empty every entry's `versions`.
170
+ *
171
+ * Declared here, after [technologyVersionSchema], rather than beside its base schema: it composes
172
+ * both, and the version schema is defined further down the file.
173
+ */
174
+ export const knowledgeSearchItemSchema = knowledgeComponentSchema.extend({
175
+ technologyVersions: z.array(technologyVersionSchema),
176
+ });
177
+ const knowledgeSearchListSchema = z.object({ items: z.array(knowledgeSearchItemSchema) });
178
+ /**
179
+ * The technology a write resolved to (`TechnologyWriteDtos.WrittenTechnology`, Task 9b.2b/9b.4):
180
+ * the same identity fields the read carries, without the versions and component counts. On a
181
+ * **reuse** the `description` is the *stored* overview, not the submitted one — the backend persists
182
+ * a submitted overview only when it creates the row — so the caller reads back what actually exists.
183
+ */
184
+ export const writtenTechnologySchema = z.object({
185
+ id: z.string(),
186
+ kind: z.string(),
187
+ name: z.string(),
188
+ slug: z.string(),
189
+ description: z.string().nullable(),
190
+ });
191
+ /**
192
+ * Which branch a create-or-resolve took: `created` (201 — a brand-new technology), `reused` (200 —
193
+ * exact-slug hit, the major line already existed), or `version-added` (200 — the technology existed
194
+ * and the major line was added). A **closed** set, so it is an enum rather than a forward-compat
195
+ * string: the three exhaust the endpoint's logical branches (technology absent / present-with-line /
196
+ * present-without-line), and a fourth would be new resolution semantics the 9b.7 command has to
197
+ * handle anyway. Unlike the case enums — which ADR-005 explicitly declares open, hence
198
+ * [caseDetailSchema]'s strings — nothing declares this one open, and the narrowed union is what lets
199
+ * that command's three-way branch be checked exhaustively at build time.
200
+ */
201
+ export const technologyWriteOutcomeSchema = z.enum(["created", "reused", "version-added"]);
202
+ /**
203
+ * The `POST /technologies` response (`TechnologyWriteDtos.TechnologyWriteResponse`, Task 9b.2b):
204
+ * what the create-or-resolve did, plus the resolved technology and the single major line it landed
205
+ * on. The major line reuses [technologyVersionSchema] because `WrittenTechnologyVersion` and the
206
+ * read's `TechnologyVersionResponse` are the same wire shape.
207
+ */
208
+ export const technologyWriteResponseSchema = z.object({
209
+ outcome: technologyWriteOutcomeSchema,
210
+ technology: writtenTechnologySchema,
211
+ version: technologyVersionSchema,
212
+ });
213
+ /**
214
+ * One near-duplicate the technology create guard flagged (Task 9b.2b/9b.3, ADR-012), carried on the
215
+ * `409`'s problem detail under `matches`. `reason` names the layer that flagged it — `dedup-key` for
216
+ * the Layer-1 deterministic normalized-slug collision, `trigram` for a Layer-2 fuzzy `pg_trgm`
217
+ * candidate; Layer-1 matches come first. Kept a string for forward-compat, like the enums above.
218
+ */
219
+ export const technologyNearDuplicateMatchSchema = z.object({
220
+ slug: z.string(),
221
+ name: z.string(),
222
+ reason: z.string(),
223
+ });
224
+ /** A technology that demands a competence (`CompetenceDtos.CompetenceTechnologyResponse`): identity only, no kind or versions. */
225
+ export const competenceTechnologySchema = z.object({
226
+ id: z.string(),
227
+ name: z.string(),
228
+ slug: z.string(),
229
+ });
230
+ /**
231
+ * One element of a competence (`CompetenceDtos.CompetenceElementResponse`): the knowledge-component
232
+ * reference (`concept:javalin.handler`) and its type token. It carries no component name or content —
233
+ * those are a `getKnowledgeComponent` read away.
234
+ */
235
+ export const competenceElementSchema = z.object({
236
+ knowledgeComponent: z.string(),
237
+ type: componentTypeSchema,
238
+ });
239
+ /**
240
+ * One competence on the wire (`CompetenceDtos.CompetenceResponse`, Task 4.2) — the shape the listing,
241
+ * the create and the edit all return. `technologies` are the technologies that demand it, `elements`
242
+ * its knowledge-component references in order, and `components` its sub-competences, each the same
243
+ * shape (the getter is Zod's recursive-object form). The wire carries **no owner**: whether a caller
244
+ * may edit or delete a competence is answered by the write itself, as a 403.
245
+ */
246
+ export const competenceSchema = z.object({
247
+ id: z.string(),
248
+ name: z.string(),
249
+ description: z.string().nullable(),
250
+ technologies: z.array(competenceTechnologySchema),
251
+ elements: z.array(competenceElementSchema),
252
+ get components() {
253
+ return z.array(competenceSchema);
254
+ },
255
+ });
256
+ const competenceListSchema = z.object({ items: z.array(competenceSchema) });
257
+ /**
258
+ * One advisory-probe hit (`POST /knowledge/{type}/near-duplicate-probe`, Task 8.7): an existing
259
+ * component's reference identity plus its cosine `similarity` against the probed candidate.
260
+ * Both dedup thresholds — the soft reporting floor and the hard 409 bar — live server-side
261
+ * (`PublishKnowledgeComponentUseCase`); the client only relays what the probe reports.
262
+ *
263
+ * `technologyVersions` are the major lines the match applies to (Task 9a.5e). The probe, unlike
264
+ * the hard gate, still reports a match whose version scope is disjoint from the candidate's — the
265
+ * gate would admit it — so the author needs the scope to judge it. Two distinct axes: `version` is
266
+ * the match's own content revision, `technologyVersions` is what it applies to.
267
+ *
268
+ * `sameVersionScope` is the server's own reading of that scope against the probed candidate: true
269
+ * when they share a line (the gate would 409), false when disjoint (the gate would admit). It
270
+ * decides which of link / supersede / skip / proceed even applies, so it is relayed rather than
271
+ * re-derived here.
272
+ */
273
+ export const nearDuplicateMatchSchema = z.object({
274
+ id: z.string(),
275
+ name: z.string(),
276
+ version: z.string(),
277
+ technologyVersions: z.array(technologyVersionSchema),
278
+ sameVersionScope: z.boolean(),
279
+ urlPath: z.string(),
280
+ similarity: z.number(),
281
+ });
282
+ const nearDuplicateProbeSchema = z.object({ nearMatches: z.array(nearDuplicateMatchSchema) });
283
+ /**
284
+ * One role-tagged case→component reference resolved to its knowledge-component name
285
+ * (`CaseDtos.ResolvedReferenceResponse`). `description` carries the author's note on what the
286
+ * reference means for this case — present on learning-objective and prerequisite references
287
+ * (Task 12a.3), null on rubric ones, whose source file has none. `weight` is learning-objective-only.
288
+ */
289
+ export const resolvedCaseReferenceSchema = z.object({
290
+ componentId: z.string(),
291
+ name: z.string(),
292
+ bloomLevel: z.string(),
293
+ description: z.string().nullable(),
294
+ weight: z.string().nullable(),
295
+ });
296
+ /**
297
+ * One structured reference view (`CaseDtos.ReferenceListResponse` from
298
+ * `GET /cases/{id}/learning-objectives`, `/prerequisite-components`, or `/rubric`): the case's
299
+ * references of that role, resolved to knowledge-component names.
300
+ */
301
+ const caseReferenceListSchema = z.object({ items: z.array(resolvedCaseReferenceSchema) });
302
+ /**
303
+ * One case on the wire (`CaseDtos.CaseDetailResponse` from `GET /cases/{id}`): the S1 presentation
304
+ * metadata, the external-repo pointer (`repositoryUrl` / `versionRef` / `gitPlatform` — what the
305
+ * case-runner needs to fork + check out), and the resolved learning-objective / prerequisite references.
306
+ * `version` is the current SemVer (`versionRef` minus the `v`); `changeDescription` is the current
307
+ * version's chain-row correction note (ADR-009) — null on an initial version; `/fito-case-edit`'s
308
+ * orientation brief shows both (Task 9.7). The `type` / `status` / `gitPlatform` / `visibility`
309
+ * enums are kept as strings so a new forward-compat enum value (ADR-005) does not break parsing;
310
+ * the consumer validates the platform.
311
+ */
312
+ export const caseDetailSchema = z.object({
313
+ id: z.string(),
314
+ type: z.string(),
315
+ status: z.string(),
316
+ title: z.string().nullable(),
317
+ descriptionOverview: z.string().nullable(),
318
+ tags: z.array(z.string()),
319
+ estimatedDurationMinutes: z.number().nullable(),
320
+ language: z.string().nullable(),
321
+ repositoryUrl: z.string(),
322
+ versionRef: z.string(),
323
+ version: z.string(),
324
+ changeDescription: z.string().nullable(),
325
+ gitPlatform: z.string(),
326
+ visibility: z.string(),
327
+ learningObjectives: z.array(resolvedCaseReferenceSchema),
328
+ prerequisites: z.array(resolvedCaseReferenceSchema),
329
+ });
330
+ /**
331
+ * One published case in the discovery listing (`CaseDtos.CaseSummaryResponse` from `GET /cases`):
332
+ * the S1 presentation metadata plus identity and type — no external-repo pointer (that's the
333
+ * detail view). `type` stays a string for forward-compat, mirroring [caseDetailSchema].
334
+ */
335
+ export const caseSummarySchema = z.object({
336
+ id: z.string(),
337
+ type: z.string(),
338
+ title: z.string().nullable(),
339
+ descriptionOverview: z.string().nullable(),
340
+ tags: z.array(z.string()),
341
+ estimatedDurationMinutes: z.number().nullable(),
342
+ language: z.string().nullable(),
343
+ });
344
+ /** One page of the discovery listing (`CaseDtos.CaseListResponse`); `total` counts every match, not the window. */
345
+ export const caseListSchema = z.object({
346
+ items: z.array(caseSummarySchema),
347
+ page: z.number(),
348
+ size: z.number(),
349
+ total: z.number(),
350
+ });
351
+ /**
352
+ * Returned by both Case Registry writes (`CaseDtos.RegisterCaseResponse` / `PublishCaseResponse`):
353
+ * the backend case id (a UUID) and its lifecycle status (`DRAFT` after register, `PUBLISHED` after
354
+ * publish). `status` stays a string for forward-compat, mirroring [caseDetailSchema].
355
+ */
356
+ export const caseWriteResponseSchema = z.object({
357
+ id: z.string(),
358
+ status: z.string(),
359
+ });
360
+ /**
361
+ * Returned by `POST /cases/{id}/versions` (`CaseDtos.PublishCaseVersionResponse`, Task 9.4): the
362
+ * case id, its lifecycle status (stays `PUBLISHED`), and the new current version identity — the
363
+ * caller's confirmation of what the backend now serves. `status` stays a string for
364
+ * forward-compat, mirroring [caseWriteResponseSchema].
365
+ */
366
+ export const caseVersionResponseSchema = z.object({
367
+ id: z.string(),
368
+ status: z.string(),
369
+ versionRef: z.string(),
370
+ version: z.string(),
371
+ });
372
+ /**
373
+ * A recorded case enrollment on the wire (`CaseDtos.CaseEnrollmentResponse` from
374
+ * `POST /cases/{id}/enrollments`, Task 9.5): the enrollment id, the case, the `versionRef` of the
375
+ * case version it pinned (the current one at the open), and the recorded open moment.
376
+ */
377
+ export const caseEnrollmentSchema = z.object({
378
+ id: z.string(),
379
+ caseId: z.string(),
380
+ versionRef: z.string(),
381
+ openedAt: z.string(),
382
+ });
383
+ /**
384
+ * The learner's participant status on the wire (`CaseDtos.ParticipantStatusResponse` from
385
+ * `GET /cases/{id}/enrollments/me`, Task 9.6): whether the authenticated learner participates in
386
+ * the case — an enrollment **or** a recorded submission exists. Learner-scoped; an unknown case
387
+ * reads as `false` (existence never leaks).
388
+ */
389
+ export const caseParticipationSchema = z.object({
390
+ participant: z.boolean(),
391
+ });
392
+ /**
393
+ * A recorded submission on the wire (`SubmissionDtos.SubmissionResponse` from `POST /submissions` and
394
+ * `GET /submissions/{id}`). All fields are strings; `status` is kept as a string (forward-compat with
395
+ * new lifecycle values) — the TUI only needs the round-trip confirmation, not to branch on it.
396
+ */
397
+ export const submissionResponseSchema = z.object({
398
+ id: z.string(),
399
+ caseId: z.string(),
400
+ learnerId: z.string(),
401
+ prUrl: z.string(),
402
+ submittedAt: z.string(),
403
+ status: z.string(),
404
+ });
405
+ /**
406
+ * One rubric criterion's evaluation outcome the TUI `fito-performance-reviewer` produces and the
407
+ * `/fito-submit` round-trip POSTs to `POST /submissions/{id}/results` (Task 6.3) — the wire shape of
408
+ * the backend's `CriterionResultDto`. `score` is the reviewer's 0–3 band, or `null` for a `human`
409
+ * criterion still awaiting a human reviewer. This schema is the contract used to validate the
410
+ * reviewer's JSON before it is sent (see `fito-case-runner/submit-evaluation.ts`).
411
+ */
412
+ export const criterionEvaluationResultSchema = z.object({
413
+ criterionId: z.string().min(1),
414
+ knowledgeComponent: z.string().min(1),
415
+ // One of the three declared levels, for the reason the quiz schema below checks its own: the
416
+ // reviewer's JSON template spells this field as all three at once, and since Task 17.6 the level
417
+ // decides the proficiency awarded, so a copied placeholder must fail here, not on the backend 400.
418
+ bloomLevel: z.enum(["KNOWLEDGE", "COMPREHENSION", "APPLICATION"]),
419
+ evaluationType: z.string().min(1),
420
+ // 0–3 rubric band, or null for a `human` criterion needing review. Bounded here so a reviewer
421
+ // (LLM) emitting an out-of-band score fails fast at the file-parse boundary rather than on the
422
+ // backend 400 round-trip (the schema also validates the reviewer's results file in submit-evaluation.ts).
423
+ score: z.number().int().min(0).max(3).nullable(),
424
+ label: z.string().min(1),
425
+ justification: z.string().min(1),
426
+ });
427
+ /**
428
+ * One quiz question's scored outcome the TUI `fito-performance-reviewer` produces and the
429
+ * `/fito-submit` round-trip POSTs to `POST /submissions/{id}/quiz-result` (Task 7.3) — the wire shape
430
+ * of the backend's `QuestionScoreDto`. `score` is the reviewer's 0–3 band (multiple-choice scored
431
+ * deterministically as met (2) or not (0), `short_answer` / `code_snippet` scored by the local LLM), or
432
+ * `null` for a question awaiting human review. `bloomLevel` is the question's declared level, which the
433
+ * backend awards at score 2 or 3 (Task 17.7) to each of the question's `knowledgeComponents`. This
434
+ * schema validates the reviewer's JSON before it is sent (see `fito-case-runner/submit-quiz-result.ts`).
435
+ */
436
+ export const questionScoreResultSchema = z.object({
437
+ questionId: z.string().min(1),
438
+ knowledgeComponents: z.array(z.string().min(1)).min(1),
439
+ // One of the three declared levels, checked here for the reason the score is bounded below: the
440
+ // reviewer's JSON template spells this field as a placeholder listing all three, so a model that
441
+ // copies it verbatim fails at the file-parse boundary rather than on the backend 400 round-trip.
442
+ bloomLevel: z.enum(["KNOWLEDGE", "COMPREHENSION", "APPLICATION"]),
443
+ // 0–3 band, or null for a question needing human review. Bounded here so a reviewer (LLM) emitting
444
+ // an out-of-band score fails fast at the file-parse boundary rather than on the backend 400 round-trip.
445
+ score: z.number().int().min(0).max(3).nullable(),
446
+ justification: z.string().nullable(),
447
+ });
448
+ /**
449
+ * Carries the backend's RFC 9457 problem-detail message and HTTP status, plus each write API's 409
450
+ * resolution properties when present: [duplicateId] (knowledge near-duplicate on create — the most
451
+ * similar component's canonical reference), [supersededBy] (new-version target already superseded —
452
+ * the existing successor's reference), and [matches] (the technology create guard's flagged rows,
453
+ * Task 9b.2b/9b.3). All are `undefined` on every other error; consumers branch on them to drive the
454
+ * flow's human resolution (PLAN Task 8.5 / 9b.7), never resolving a duplicate automatically.
455
+ *
456
+ * [type] is the problem's `type`, which names the kind of error where the backend sets one: the
457
+ * refusal of a TUI older than the backend's minimum is `/problems/tui-too-old` (Task 15d.7a), which
458
+ * the startup check recognises (Task 15d.7b). It is `undefined` when the body carries none.
459
+ */
460
+ export class FitoApiError extends Error {
461
+ status;
462
+ type;
463
+ duplicateId;
464
+ supersededBy;
465
+ matches;
466
+ constructor(message, status, properties = {}) {
467
+ super(message);
468
+ this.name = "FitoApiError";
469
+ this.status = status;
470
+ this.type = properties.type;
471
+ this.duplicateId = properties.duplicateId;
472
+ this.supersededBy = properties.supersededBy;
473
+ this.matches = properties.matches;
474
+ }
475
+ }
476
+ const problemDetailSchema = z.object({
477
+ type: z.string().optional(),
478
+ detail: z.string().optional(),
479
+ title: z.string().optional(),
480
+ duplicateId: z.string().optional(),
481
+ supersededBy: z.string().optional(),
482
+ // `matches` is a shared problem-detail namespace, so a body carrying one of an unexpected shape
483
+ // degrades to "no matches" rather than failing the whole parse — which would drop the `detail`
484
+ // the author is shown back to the bare status fallback.
485
+ matches: z.array(technologyNearDuplicateMatchSchema).optional().catch(undefined),
486
+ });
487
+ export function createFitoApiClient(options = {}) {
488
+ const baseUrl = options.baseUrl ?? DEFAULT_BASE_URL;
489
+ const doFetch = options.fetch ?? fetch;
490
+ async function request(path, schema, init) {
491
+ const response = await doFetch(`${baseUrl}${path}`, {
492
+ ...init,
493
+ headers: { "Content-Type": "application/json", ...init?.headers, "User-Agent": USER_AGENT },
494
+ });
495
+ if (!response.ok) {
496
+ throw await toApiError(response);
497
+ }
498
+ return schema.parse(await response.json());
499
+ }
500
+ const refresh = (refreshToken) => request("/auth/refresh", tokenResponseSchema, {
501
+ method: "POST",
502
+ body: JSON.stringify({ refreshToken }),
503
+ });
504
+ const me = (accessToken) => request("/me", meResponseSchema, {
505
+ method: "GET",
506
+ headers: { Authorization: `Bearer ${accessToken}` },
507
+ });
508
+ async function logout(refreshToken) {
509
+ const response = await doFetch(`${baseUrl}/auth/logout`, {
510
+ method: "POST",
511
+ headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT },
512
+ body: JSON.stringify({ refreshToken }),
513
+ });
514
+ if (!response.ok) {
515
+ throw await toApiError(response);
516
+ }
517
+ }
518
+ async function meWithRefresh(tokens) {
519
+ try {
520
+ return { user: await me(tokens.accessToken), tokens };
521
+ }
522
+ catch (error) {
523
+ if (!(error instanceof FitoApiError) || error.status !== 401)
524
+ throw error;
525
+ const fresh = await refresh(tokens.refreshToken);
526
+ return { user: await me(fresh.accessToken), tokens: fresh };
527
+ }
528
+ }
529
+ const getHealth = (options = {}) => request("/actuator/health", healthSchema, { method: "GET", signal: options.signal });
530
+ const getKnowledgeComponent = (type, slug, params = {}) => {
531
+ const query = new URLSearchParams();
532
+ if (params.technologyVersion !== undefined) {
533
+ query.set("technologyVersion", params.technologyVersion);
534
+ }
535
+ const suffix = query.size > 0 ? `?${query}` : "";
536
+ return request(`/knowledge/${type}/${encodeURIComponent(slug)}${suffix}`, knowledgeComponentSchema, {
537
+ method: "GET",
538
+ });
539
+ };
540
+ const searchKnowledgeComponents = async (params) => {
541
+ const query = new URLSearchParams();
542
+ if (params.type !== undefined)
543
+ query.set("type", params.type);
544
+ if (params.technology !== undefined)
545
+ query.set("technology", params.technology);
546
+ if (params.technologyVersion !== undefined) {
547
+ query.set("technologyVersion", params.technologyVersion);
548
+ }
549
+ if (params.q !== undefined)
550
+ query.set("q", params.q);
551
+ // Always written, `false` included: the backend still tolerates an absent parameter, but
552
+ // Task 11.4a6-1c makes it required, and an omission would then read as a 400 rather than as
553
+ // a `false`. So there is no filter-less `/knowledge` request left to build.
554
+ query.set("excludeSuperseded", String(params.excludeSuperseded));
555
+ return (await request(`/knowledge?${query}`, knowledgeSearchListSchema, { method: "GET" })).items;
556
+ };
557
+ const getTechnology = (slug) => request(`/technologies/${encodeURIComponent(slug)}`, technologySummarySchema, { method: "GET" });
558
+ const createOrResolveTechnology = (accessToken, input) => request("/technologies", technologyWriteResponseSchema, {
559
+ method: "POST",
560
+ headers: { Authorization: `Bearer ${accessToken}` },
561
+ body: JSON.stringify(input),
562
+ });
563
+ const updateTechnologyDescription = (accessToken, slug, description) => request(`/technologies/${encodeURIComponent(slug)}`, writtenTechnologySchema, {
564
+ method: "PATCH",
565
+ headers: { Authorization: `Bearer ${accessToken}` },
566
+ body: JSON.stringify({ description }),
567
+ });
568
+ const updateTechnologyVersionDescription = (accessToken, slug, versionSlug, description) => request(`/technologies/${encodeURIComponent(slug)}/versions/${encodeURIComponent(versionSlug)}`, technologyVersionSchema, {
569
+ method: "PATCH",
570
+ headers: { Authorization: `Bearer ${accessToken}` },
571
+ body: JSON.stringify({ description }),
572
+ });
573
+ const listTechnologyCompetences = async (slug) => (await request(`/technologies/${encodeURIComponent(slug)}/competences`, competenceListSchema, { method: "GET" }))
574
+ .items;
575
+ const getCompetence = (id) => request(`/competences/${encodeURIComponent(id)}`, competenceSchema, { method: "GET" });
576
+ const createCompetence = (accessToken, input) => request("/competences", competenceSchema, {
577
+ method: "POST",
578
+ headers: { Authorization: `Bearer ${accessToken}` },
579
+ body: JSON.stringify(input),
580
+ });
581
+ const updateCompetence = (accessToken, id, input) => request(`/competences/${encodeURIComponent(id)}`, competenceSchema, {
582
+ method: "PATCH",
583
+ headers: { Authorization: `Bearer ${accessToken}` },
584
+ body: JSON.stringify(input),
585
+ });
586
+ async function deleteCompetence(accessToken, id) {
587
+ const response = await doFetch(`${baseUrl}/competences/${encodeURIComponent(id)}`, {
588
+ method: "DELETE",
589
+ headers: { "Content-Type": "application/json", "User-Agent": USER_AGENT, Authorization: `Bearer ${accessToken}` },
590
+ });
591
+ if (!response.ok) {
592
+ throw await toApiError(response);
593
+ }
594
+ }
595
+ const getCase = (id, accessToken) => request(`/cases/${encodeURIComponent(id)}`, caseDetailSchema, {
596
+ method: "GET",
597
+ ...(accessToken === undefined ? {} : { headers: { Authorization: `Bearer ${accessToken}` } }),
598
+ });
599
+ const listCases = (params = {}) => {
600
+ const query = new URLSearchParams();
601
+ if (params.repositoryUrl)
602
+ query.set("repositoryUrl", params.repositoryUrl);
603
+ const suffix = query.size > 0 ? `?${query}` : "";
604
+ return request(`/cases${suffix}`, caseListSchema, { method: "GET" });
605
+ };
606
+ const registerCase = (accessToken, input) => request("/cases", caseWriteResponseSchema, {
607
+ method: "POST",
608
+ headers: { Authorization: `Bearer ${accessToken}` },
609
+ body: JSON.stringify(input),
610
+ });
611
+ const publishCase = (accessToken, caseId, input) => request(`/cases/${encodeURIComponent(caseId)}/publish`, caseWriteResponseSchema, {
612
+ method: "POST",
613
+ headers: { Authorization: `Bearer ${accessToken}` },
614
+ body: JSON.stringify(input),
615
+ });
616
+ const publishCaseVersion = (accessToken, caseId, input) => request(`/cases/${encodeURIComponent(caseId)}/versions`, caseVersionResponseSchema, {
617
+ method: "POST",
618
+ headers: { Authorization: `Bearer ${accessToken}` },
619
+ body: JSON.stringify(input),
620
+ });
621
+ /**
622
+ * The path segment serving each structured reference view. Only `rubric` doubles as its own path:
623
+ * `prerequisites` is served at `/prerequisite-components` (Task 12.5), and `learningObjectives` at
624
+ * the kebab-case `/learning-objectives` (Task 12a.6b), so neither view name can be used as the
625
+ * path segment directly.
626
+ */
627
+ const referenceViewPaths = {
628
+ learningObjectives: "learning-objectives",
629
+ prerequisites: "prerequisite-components",
630
+ rubric: "rubric",
631
+ };
632
+ const caseReferences = async (caseId, view) => (await request(`/cases/${encodeURIComponent(caseId)}/${referenceViewPaths[view]}`, caseReferenceListSchema, {
633
+ method: "GET",
634
+ })).items;
635
+ const getCaseLearningObjectives = (caseId) => caseReferences(caseId, "learningObjectives");
636
+ const getCasePrerequisites = (caseId) => caseReferences(caseId, "prerequisites");
637
+ const getCaseRubric = (caseId) => caseReferences(caseId, "rubric");
638
+ const createCaseEnrollment = (accessToken, caseId) => request(`/cases/${encodeURIComponent(caseId)}/enrollments`, caseEnrollmentSchema, {
639
+ method: "POST",
640
+ headers: { Authorization: `Bearer ${accessToken}` },
641
+ });
642
+ const getCaseParticipation = (accessToken, caseId) => request(`/cases/${encodeURIComponent(caseId)}/enrollments/me`, caseParticipationSchema, {
643
+ method: "GET",
644
+ headers: { Authorization: `Bearer ${accessToken}` },
645
+ });
646
+ const createSubmission = (accessToken, input) => request("/submissions", submissionResponseSchema, {
647
+ method: "POST",
648
+ headers: { Authorization: `Bearer ${accessToken}` },
649
+ body: JSON.stringify(input),
650
+ });
651
+ const submitEvaluationResults = (accessToken, submissionId, results) => request(`/submissions/${encodeURIComponent(submissionId)}/results`, submissionResponseSchema, {
652
+ method: "POST",
653
+ headers: { Authorization: `Bearer ${accessToken}` },
654
+ body: JSON.stringify({ results }),
655
+ });
656
+ const submitQuizResult = (accessToken, submissionId, perQuestionScores) => request(`/submissions/${encodeURIComponent(submissionId)}/quiz-result`, submissionResponseSchema, {
657
+ method: "POST",
658
+ headers: { Authorization: `Bearer ${accessToken}` },
659
+ body: JSON.stringify({ perQuestionScores }),
660
+ });
661
+ const getKnowledgeTemplates = async (type) => (await request(`/knowledge/templates/${type}`, templateListSchema, { method: "GET" })).items;
662
+ const createKnowledgeComponent = (accessToken, type, input) => request(`/knowledge/${type}`, knowledgeComponentSchema, {
663
+ method: "POST",
664
+ headers: { Authorization: `Bearer ${accessToken}` },
665
+ body: JSON.stringify(input),
666
+ });
667
+ const createAlternativeDefinition = (accessToken, type, slug, input) => request(`/knowledge/${type}/${encodeURIComponent(slug)}/alternative-definitions`, knowledgeComponentSchema, {
668
+ method: "POST",
669
+ headers: { Authorization: `Bearer ${accessToken}` },
670
+ body: JSON.stringify(input),
671
+ });
672
+ const createNewVersion = (accessToken, type, slug, input) => request(`/knowledge/${type}/${encodeURIComponent(slug)}/new-version`, knowledgeComponentSchema, {
673
+ method: "POST",
674
+ headers: { Authorization: `Bearer ${accessToken}` },
675
+ body: JSON.stringify(input),
676
+ });
677
+ const probeNearDuplicates = async (accessToken, type, input) => (await request(`/knowledge/${type}/near-duplicate-probe`, nearDuplicateProbeSchema, {
678
+ method: "POST",
679
+ headers: { Authorization: `Bearer ${accessToken}` },
680
+ body: JSON.stringify(input),
681
+ })).nearMatches;
682
+ return {
683
+ refresh,
684
+ logout,
685
+ me,
686
+ meWithRefresh,
687
+ getHealth,
688
+ getKnowledgeComponent,
689
+ searchKnowledgeComponents,
690
+ getTechnology,
691
+ createOrResolveTechnology,
692
+ updateTechnologyDescription,
693
+ updateTechnologyVersionDescription,
694
+ listTechnologyCompetences,
695
+ getCompetence,
696
+ createCompetence,
697
+ updateCompetence,
698
+ deleteCompetence,
699
+ getCase,
700
+ listCases,
701
+ registerCase,
702
+ publishCase,
703
+ publishCaseVersion,
704
+ getCaseLearningObjectives,
705
+ getCasePrerequisites,
706
+ getCaseRubric,
707
+ createCaseEnrollment,
708
+ getCaseParticipation,
709
+ createSubmission,
710
+ submitEvaluationResults,
711
+ submitQuizResult,
712
+ getKnowledgeTemplates,
713
+ createKnowledgeComponent,
714
+ createAlternativeDefinition,
715
+ createNewVersion,
716
+ probeNearDuplicates,
717
+ };
718
+ }
719
+ async function toApiError(response) {
720
+ let message = `Request failed (${response.status})`;
721
+ let properties = {};
722
+ try {
723
+ const body = problemDetailSchema.parse(await response.json());
724
+ message = body.detail ?? body.title ?? message;
725
+ properties = { type: body.type, duplicateId: body.duplicateId, supersededBy: body.supersededBy, matches: body.matches };
726
+ }
727
+ catch {
728
+ // Non-JSON or unexpected body — keep the status-based fallback message.
729
+ }
730
+ return new FitoApiError(message, response.status, properties);
731
+ }