@openreachtech/hora-skills-ort-renchan 0.3.0 → 0.4.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 (50) hide show
  1. package/dist/skills/hor-backend-testing/SKILL.md +4 -3
  2. package/dist/skills/hor-backend-testing/references/running-tests.md +9 -1
  3. package/dist/skills/hor-build-e2e-test-environment/SKILL.md +17 -8
  4. package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +11 -7
  5. package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +1 -1
  6. package/dist/skills/hor-cookie-authentication/SKILL.md +4 -2
  7. package/dist/skills/hor-cookie-authentication/references/environment.md +4 -2
  8. package/dist/skills/hor-database-design/references/column-types.md +25 -9
  9. package/dist/skills/hor-database-design/references/datetimes.md +7 -3
  10. package/dist/skills/hor-graphql-schema/SKILL.md +10 -8
  11. package/dist/skills/hor-graphql-server-engine/SKILL.md +376 -44
  12. package/dist/skills/hor-light-rag/SKILL.md +6 -1
  13. package/dist/skills/hor-light-rag/references/retrieval-internals.md +3 -1
  14. package/dist/skills/hor-multi-llm-provider/SKILL.md +158 -20
  15. package/dist/skills/hor-multi-llm-provider/references/access-routes.md +230 -0
  16. package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +9 -3
  17. package/dist/skills/hor-mutation-resolver/SKILL.md +6 -2
  18. package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +10 -6
  19. package/dist/skills/hor-oidc-sign-in/SKILL.md +61 -0
  20. package/dist/skills/hor-oidc-sign-in/references/environment.md +94 -0
  21. package/dist/skills/hor-oidc-sign-in/references/id-token-verification.md +98 -0
  22. package/dist/skills/hor-oidc-sign-in/references/resolvers.md +134 -0
  23. package/dist/skills/hor-oidc-sign-in/references/storage.md +118 -0
  24. package/dist/skills/hor-query-resolver/SKILL.md +2 -0
  25. package/dist/skills/hor-query-resolver/references/anatomy.md +7 -7
  26. package/dist/skills/hor-query-resolver/references/data-access.md +17 -0
  27. package/dist/skills/hor-renchan-job-bullmq/SKILL.md +15 -6
  28. package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +4 -2
  29. package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +39 -5
  30. package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +57 -0
  31. package/dist/skills/hor-resolver-validator/SKILL.md +5 -6
  32. package/dist/skills/hor-resolver-validator/references/validator-pattern.md +5 -5
  33. package/dist/skills/hor-restfulapi-architecture/SKILL.md +33 -7
  34. package/dist/skills/hor-restfulapi-architecture/references/behind-iap.md +116 -0
  35. package/dist/skills/hor-restfulapi-architecture/references/credential-routes.md +173 -0
  36. package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +11 -5
  37. package/dist/skills/hor-restfulapi-architecture/references/renderers.md +4 -0
  38. package/dist/skills/hor-sequelize-migration/SKILL.md +30 -15
  39. package/dist/skills/hor-sequelize-migration/references/alter-table.md +26 -13
  40. package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +5 -2
  41. package/dist/skills/hor-sequelize-migration/references/indexes.md +41 -2
  42. package/dist/skills/hor-sequelize-migration/references/notation.md +1 -1
  43. package/dist/skills/hor-sequelize-model/references/associations.md +2 -1
  44. package/dist/skills/hor-sequelize-model/references/notation.md +1 -1
  45. package/dist/skills/hor-sequelize-seeder/SKILL.md +9 -4
  46. package/dist/skills/hor-sequelize-seeder/references/notation.md +59 -0
  47. package/dist/skills/hor-type-interface/SKILL.md +48 -32
  48. package/docs/skills.ja.md +5 -4
  49. package/docs/skills.md +5 -4
  50. package/package.json +1 -1
@@ -1,12 +1,11 @@
1
1
  ---
2
2
  name: hor-multi-llm-provider
3
3
  description: >
4
- Support multiple LLM providers (Anthropic Claude / OpenAI / Google Gemini) behind one
5
- abstraction in a renchan backend: an abstract model processor, one provider base per vendor, one
6
- concrete processor per model, and a loader that picks one by model name at runtime, with model
7
- and provider metadata in the DB and env, not in code. Use whenever the user asks to add an LLM
8
- model or provider, change how a model is selected, normalize provider responses, or wire
9
- function calls and file upload.
4
+ Support multiple LLM providers (Anthropic Claude / OpenAI / Google Gemini) behind one abstraction in
5
+ a renchan backend: a provider base per vendor, a processor per model, a loader that picks one by
6
+ model name, and an access route per way of reaching it (vendor API key, Vertex AI service account,
7
+ Amazon Bedrock), with model and route metadata in the DB and env. Use whenever the user asks to add
8
+ an LLM model, provider or access route, or to wire function calls and file upload.
10
9
  ---
11
10
 
12
11
  # Multi-LLM Provider (Claude / OpenAI / Gemini behind one abstraction)
@@ -16,6 +15,10 @@ resolvers, jobs) never branch on the provider. A caller resolves a **model name*
16
15
  `processor.sendRequestToAi(...)`; everything provider-specific (SDK calls, function-call shape, file
17
16
  upload, response parsing) is hidden behind the processor and its capsule.
18
17
 
18
+ Which **model** answers and which **access route** carries the request are two separate choices. The
19
+ model is a vendor's model (Claude Sonnet, Gemini Flash). The route is how the request reaches it and how
20
+ it authenticates: the vendor's own API with an API key, or a cloud platform that hosts the model.
21
+
19
22
  ## Grand principle: one base + one subclass per model; provider differences live in a provider base, the model is chosen from the DB
20
23
 
21
24
  The abstraction is a three-level strategy: `BaseAiModelProcessor` (the contract) → one **provider base**
@@ -38,6 +41,11 @@ string at runtime.
38
41
  - **Why choose the model from the DB**: which model an agent uses is per-agent config
39
42
  (`AiAgentDefaultModel → AiModel.name`), overridable per call — never hard-coded. Swapping a model is a
40
43
  data change.
44
+ - **Why the access route is separate from the model**: one model is often reachable several ways, and each
45
+ way differs in the client, the credentials, and the vendor model id (the same Claude model has a
46
+ different id on the vendor's API than on a cloud platform). Putting the route in the provider base or
47
+ the concrete processor would need one class per model per route. A route class owns the client and the
48
+ authentication instead, and the model's DB rows say which routes reach it.
41
49
 
42
50
  ## Layers and files
43
51
 
@@ -60,6 +68,15 @@ app/tools/
60
68
  OpenAiMessagePayloadGenerator.js
61
69
  GeminiMessagePayloadGenerator.js
62
70
  AiModelResponse.js normalized response wrapper
71
+ BaseAiAccessRoute.js abstract contract (provider, route name, client, auth)
72
+ AiAccessRoute/
73
+ ClaudeDirectAiAccessRoute.js concrete: Claude through the vendor API key
74
+ GeminiDirectAiAccessRoute.js concrete: Gemini through the vendor API key
75
+ OpenAiDirectAiAccessRoute.js concrete: OpenAI through the vendor API key
76
+ ClaudeVertexAiAccessRoute.js concrete: Claude on Vertex AI, service account
77
+ GeminiVertexAiAccessRoute.js concrete: Gemini on Vertex AI, service account
78
+ ClaudeBedrockAiAccessRoute.js concrete: Claude on Amazon Bedrock, AWS credentials
79
+ BulkAiAccessRoutesLoader.js auto-discovery + getRoute({ aiProviderId, accessRouteName })
63
80
  app/claudeClient/ | app/geminiClient/ | app/openAiClient/ low-level Launcher/Payload/Capsule/Client
64
81
  ```
65
82
 
@@ -73,8 +90,11 @@ Abstract members a concrete processor must satisfy:
73
90
  - `#prepareAttachedFiles({ fileUrls })` (concrete default: returns `fileUrls` unchanged) — overridden per
74
91
  provider to upload files and attach provider file ids/uris.
75
92
  - `#findAiModelByName({ aiModelName })` (concrete) —
76
- `AiModel.findOne({ where: { name }, include: [AiModelCapability] })`; this is how a processor gets its
77
- DB-backed `targetModelName` and `maxOutputToken`.
93
+ `AiModel.findOne({ where: { name }, include: [AiModelCapability, AiModelAccessRoute] })`; this is how a
94
+ processor gets its DB-backed `maxOutputToken` and its routes.
95
+ - `#findAccessRoute({ aiModel })` (concrete), picks the model's default active `AiModelAccessRoute` row and
96
+ returns `{ accessRoute, targetModelName }`: the route instance from the loader and the vendor model id
97
+ on that route (see section 4).
78
98
 
79
99
  The request param bag is uniform across providers:
80
100
 
@@ -135,6 +155,13 @@ export default class ClaudeSonnet4_5AiModelProcessor extends BaseClaudeAIProcess
135
155
  aiModelName: this.aiModel,
136
156
  })
137
157
 
158
+ const {
159
+ accessRoute,
160
+ targetModelName,
161
+ } = await this.findAccessRoute({
162
+ aiModel,
163
+ })
164
+
138
165
  const documentInstructionComposer = await this.createDocumentInstructionComposer({
139
166
  // ...splits documents, wires the agent's default instruction (see `hor-ai-prompt-document-store` skill)
140
167
  })
@@ -146,6 +173,7 @@ export default class ClaudeSonnet4_5AiModelProcessor extends BaseClaudeAIProcess
146
173
  const payloadGenerator = this.createClaudeMessagePayloadGenerator({
147
174
  aiAgent,
148
175
  aiModel,
176
+ targetModelName,
149
177
  message: documentInstructionComposer.generateComposedInstruction(),
150
178
  fileUrls: preparedFileUrls,
151
179
  historyMessages,
@@ -154,7 +182,9 @@ export default class ClaudeSonnet4_5AiModelProcessor extends BaseClaudeAIProcess
154
182
  })
155
183
 
156
184
  const payload = payloadGenerator.generateClaudeMessagePayload()
157
- const fetcher = this.createSendMessageToClaudeFetcher()
185
+ const fetcher = this.createSendMessageToClaudeFetcher({
186
+ client: accessRoute.createClient(),
187
+ })
158
188
  const capsule = await fetcher.launchRequest(payload)
159
189
 
160
190
  if (capsule.hasError()) {
@@ -191,8 +221,8 @@ export default class ClaudeSonnet4_5AiModelProcessor extends BaseClaudeAIProcess
191
221
  ```
192
222
 
193
223
  - **`targetModelName` and `maxOutputToken` come from the DB row**, not the class. `#get:aiModel` returns
194
- the app-facing name (`AI_MODEL.*.NAME`); the DB row's `targetModelName` is the vendor API model id
195
- (e.g. `'claude-sonnet-4-5-20250929'`).
224
+ the app-facing name (`AI_MODEL.*.NAME`); `targetModelName` is the vendor model id on the chosen access
225
+ route (e.g. `'claude-sonnet-4-5-20250929'` on the vendor API, see section 4).
196
226
  - **`isAutoHandleFunctionCall: false`** short-circuits after the first response and returns the raw
197
227
  function call — this is exactly what the forced-single-tool actions in the **`hor-ai-agent-structure` skill**
198
228
  rely on.
@@ -240,7 +270,96 @@ or directly via the agent's default-model chain
240
270
  > Do not confuse this with `BulkAiToolProcessorsLoader`: the provider bases use a *tool*-processor loader
241
271
  > (`getProcessor(toolName)`) to run function calls — a different loader over `app/aiTools/`.
242
272
 
243
- ## 4. Adding a model or a provider
273
+ ## 4. Access routes
274
+
275
+ An access route is a class under `app/tools/AiAccessRoute/`, one per provider and route pair. It holds
276
+ the two things that change with the route and nothing else: the low-level client and the credentials
277
+ that client authenticates with. Prompting, payload shaping, function-call handling and response
278
+ parsing stay in the provider base, so they are written once per vendor and never per route.
279
+
280
+ `BaseAiAccessRoute` contract:
281
+
282
+ - `#get:aiProviderId` (abstract), the `AI_PROVIDER.*.ID` this route serves. A route never changes the
283
+ provider: Claude reached through a cloud platform is still the Anthropic provider.
284
+ - `#get:accessRouteName` (abstract), the `AI_ACCESS_ROUTE.*.NAME` the loader matches on.
285
+ - `#get:supportsFileUpload` (abstract), whether `#prepareAttachedFiles()` may upload through this route.
286
+ - `#createClient()` (abstract), returns the client the Fetcher already calls
287
+ (`this.client.sendMessageToClaude({ ...p })`), built from env, never from a literal. For the vendor API
288
+ this is the construction `Base<Provider>ApiRequestLauncher` did when it read the key itself; that read
289
+ moves here.
290
+ - `#createHttpRequestClient()` (concrete), the HTTP client the vendor-API clients wrap.
291
+
292
+ ```js
293
+ import environment from '../../globals/env.js'
294
+ import ClaudeApiClient from '../../claudeClient/ClaudeApiClient.js'
295
+ import BaseAiAccessRoute from '../BaseAiAccessRoute.js'
296
+
297
+ import CONSTANT_HASH from '../../../constants/aiConstants.cjs'
298
+
299
+ const {
300
+ AI_PROVIDER,
301
+ AI_ACCESS_ROUTE,
302
+ } = CONSTANT_HASH
303
+
304
+ export default class ClaudeDirectAiAccessRoute extends BaseAiAccessRoute {
305
+ static create () {
306
+ return new this()
307
+ }
308
+
309
+ get aiProviderId () {
310
+ return AI_PROVIDER.ANTHROPIC.ID
311
+ }
312
+
313
+ get accessRouteName () {
314
+ return AI_ACCESS_ROUTE.DIRECT.NAME
315
+ }
316
+
317
+ get supportsFileUpload () {
318
+ return true
319
+ }
320
+
321
+ createClient () {
322
+ return ClaudeApiClient.create({
323
+ token: environment.CLAUDE_API_TOKEN,
324
+ httpRequestClient: this.createHttpRequestClient(),
325
+ })
326
+ }
327
+ }
328
+ ```
329
+
330
+ **Choosing the route is a data lookup, like choosing the model.** A model's reachable routes are
331
+ `AiModelAccessRoute` rows (see section 6). The processor resolves the route after it resolves the model:
332
+
333
+ ```js
334
+ const aiModel = await this.findAiModelByName({
335
+ aiModelName: this.aiModel,
336
+ })
337
+
338
+ const {
339
+ accessRoute,
340
+ targetModelName,
341
+ } = await this.findAccessRoute({
342
+ aiModel,
343
+ })
344
+
345
+ const fetcher = this.createSendMessageToClaudeFetcher({
346
+ client: accessRoute.createClient(),
347
+ })
348
+ ```
349
+
350
+ - **The vendor model id comes from the route row**, not from `AiModel.targetModelName`: the payload
351
+ generator receives `targetModelName` from `#findAccessRoute()`. A model with no route row falls back to the
352
+ `direct` route and `AiModel.targetModelName`, so models that exist before routes keep working.
353
+ - **A route that cannot upload files** (`supportsFileUpload` is `false`) makes `#prepareAttachedFiles()`
354
+ return the files unchanged, so the provider id/uri stays unset and the payload generator takes its
355
+ non-upload source (see `provider-internals.md`).
356
+ - **Callers still never see the route.** `#sendRequestToAi()` and `AiModelResponse` are identical for
357
+ every route, because each route's client returns the same response shape the provider capsule parses.
358
+
359
+ See [access-routes.md](./references/access-routes.md) for the loader, the route rows, and what each
360
+ route needs.
361
+
362
+ ## 5. Adding a model, a provider, or a route
244
363
 
245
364
  - **New model of an existing provider**: add one file under `app/tools/AiModelProcessor/` extending that
246
365
  provider base, with `#get:aiModel` returning the new `AI_MODEL.*.NAME`; add the `AiModel` +
@@ -249,31 +368,48 @@ or directly via the agent's default-model chain
249
368
  - **New provider**: add a provider base under `app/tools/BaseAiModelProviderProcessor/` implementing the
250
369
  function-call handling + `#prepareAttachedFiles()` for that vendor, a payload generator under
251
370
  `AiPayloadGenerator/`, a capsule that exposes the standard method surface, the low-level
252
- Launcher/Payload/Capsule/Client under `app/<provider>Client/`, and an `AI_PROVIDER` entry. Then per-model
253
- processors as above.
371
+ Launcher/Payload/Capsule/Client under `app/<provider>Client/`, and an `AI_PROVIDER` entry. Then a
372
+ `direct` access route for it and per-model processors as above.
373
+ - **New route for an existing provider**: add one file under `app/tools/AiAccessRoute/` extending
374
+ `BaseAiAccessRoute`, an `AI_ACCESS_ROUTE` entry, the env vars it reads, and one `AiModelAccessRoute` row
375
+ per model that route reaches. No processor or caller changes.
254
376
 
255
377
  See [provider-internals.md](./references/provider-internals.md) for the per-vendor function-call and
256
378
  file-upload differences, the payload generators, `AiModelResponse`, and the low-level client pattern.
257
379
 
258
- ## 5. Config and secrets
380
+ ## 6. Config and secrets
259
381
 
260
382
  - **`AiProvider`** (`ai_providers`): `name`. `AI_PROVIDER = { ANTHROPIC {ID:1}, GOOGLE {ID:2}, OPENAI {ID:3} }`.
261
- - **`AiModel`** (`ai_models`): `AiProviderId`, `name` (app key), `targetModelName` (vendor id), `isDefault`,
262
- `isActive`, `displayOrder`.
383
+ - **`AiModel`** (`ai_models`): `AiProviderId`, `name` (app key), `targetModelName` (vendor id on the `direct`
384
+ route), `isDefault`, `isActive`, `displayOrder`.
263
385
  - **`AiModelCapability`** (`ai_model_capabilities`): `contextWindowToken`, `maxOutputToken` (→ payload
264
386
  `maxTokens`).
387
+ - **`AiModelAccessRoute`** (`ai_model_access_routes`): `AiModelId`, `accessRouteName` (an
388
+ `AI_ACCESS_ROUTE.*.NAME`), `targetModelName` (the vendor id on that route), `isDefault`, `isActive`.
265
389
  - **`AiModelToolAssignment`** (`ai_model_tool_assignments`): which tools a model may use (see the
266
390
  `hor-ai-prompt-document-store` skill for `AiTool`).
267
391
  - **API keys / base URLs** come from `@openreachtech/renchan-env` via `app/globals/env.js` (e.g.
268
392
  `CLAUDE_API_TOKEN`, `CLAUDE_API_BASE_URL`, and the analogous OpenAI/Gemini vars) — never hard-code a key.
269
-
270
- Model/provider constants live in `constants/aiConstants.cjs` (see the **`hor-constant-definition` skill** for the
393
+ Only the route that uses a credential reads it, so each route's env vars are listed in
394
+ [access-routes.md](./references/access-routes.md).
395
+ - **Vertex AI uses a service account, not a key**: Application Default Credentials supply it, and only the
396
+ project id and location come from env. Keep a service-account key file out of the repository and the DB.
397
+ - **Bedrock uses AWS credentials**: the AWS default credential chain supplies them (prefer a role attached to
398
+ the runtime), and only the region comes from env. Never set `AWS_BEARER_TOKEN_BEDROCK` where IAM
399
+ credentials should sign.
400
+
401
+ `AI_ACCESS_ROUTE` names the routes: `DIRECT { NAME: 'direct' }`, `VERTEX_AI { NAME: 'vertex-ai' }` and
402
+ `BEDROCK { NAME: 'bedrock' }`.
403
+
404
+ Model/provider/route constants live in `constants/aiConstants.cjs` (see the **`hor-constant-definition` skill** for the
271
405
  two-file `.cjs` master + ESM bridge rule).
272
406
 
273
407
  ## Cross-cutting rules
274
408
 
275
409
  - **Callers never branch on the provider** — resolve a processor by name and use the uniform
276
410
  `#sendRequestToAi()` / `AiModelResponse` surface.
411
+ - **A route owns the client and the credentials, and a processor never reads a key.** Reading a
412
+ credential outside the route that uses it spreads one secret across several classes.
277
413
  - **A concrete model processor adds no logic beyond `#get:aiModel`** — put shared behavior on the provider
278
414
  base, per-vendor behavior on the provider base too, and model specifics in the DB.
279
415
  - **Return `null` / a normalized error response, not `undefined`**, on failure; check `#hasError()` before
@@ -282,7 +418,9 @@ two-file `.cjs` master + ESM bridge rule).
282
418
 
283
419
  ## Detail files
284
420
 
421
+ - [access-routes.md](./references/access-routes.md), the route contract in full, `BulkAiAccessRoutesLoader`,
422
+ the `AiModelAccessRoute` rows, and the env vars and authentication each route needs.
285
423
  - [provider-internals.md](./references/provider-internals.md) — the three provider bases' function-call
286
424
  feedback shapes and file-upload models (Claude/OpenAI/Gemini), the payload generators
287
425
  (tools/toolChoice/history trimming/file source), the `AiModelResponse` + capsule method surface, and the
288
- low-level Launcher/Payload/Capsule/Client pattern with where API keys are read.
426
+ low-level Launcher/Payload/Capsule/Client pattern and the SDK clients the routes wrap.
@@ -0,0 +1,230 @@
1
+ # Access routes (loader, route rows, authentication per route)
2
+
3
+ Referenced from `SKILL.md`. A route is how a request reaches a model and how it authenticates. The model
4
+ stays the same across routes; only the client, the credentials and the vendor model id change.
5
+
6
+ ## Loader
7
+
8
+ `BulkAiAccessRoutesLoader` mirrors `BulkAiModelProcessorsLoader`: it auto-discovers every class under
9
+ `app/tools/AiAccessRoute/` with `DeepBulkClassLoader`, instantiates each via `.create()`, and matches on
10
+ the pair `(aiProviderId, accessRouteName)`:
11
+
12
+ ```js
13
+ getRoute ({ aiProviderId, accessRouteName }) {
14
+ return this.routes.find(route =>
15
+ route.aiProviderId === aiProviderId
16
+ && route.accessRouteName === accessRouteName
17
+ )
18
+ }
19
+ ```
20
+
21
+ `BaseAiAccessRoute` sits in `app/tools/`, outside the pool path, as `BaseAiModelProcessor` does, so
22
+ discovery never instantiates the abstract base.
23
+
24
+ ## Route rows
25
+
26
+ `AiModelAccessRoute` holds one row per model and route the model is reachable through. The same model has
27
+ a different `targetModelName` on each route:
28
+
29
+ | `AiModel.name` | `accessRouteName` | `targetModelName` shape | `isDefault` |
30
+ | --- | --- | --- | --- |
31
+ | `sonnet-4-5` | `direct` | `claude-sonnet-4-5-20250929` | true |
32
+ | `sonnet-4-5` | `vertex-ai` | `claude-sonnet-4-5@20250929` | false |
33
+ | `sonnet-4-5` | `bedrock` | `anthropic.claude-sonnet-4-5-20250929-v1:0` | false |
34
+
35
+ Swapping the route for a model is a data change: flip `isDefault` between its rows. Disabling a route is
36
+ `isActive: false`. A model with no rows uses `direct` and `AiModel.targetModelName`.
37
+
38
+ ## The direct route
39
+
40
+ The vendor's own API, authenticated by one API key per provider.
41
+
42
+ | Provider | Route class | Credentials (env) |
43
+ | --- | --- | --- |
44
+ | Anthropic | `ClaudeDirectAiAccessRoute` | `CLAUDE_API_TOKEN`, `CLAUDE_API_BASE_URL` |
45
+ | Google | `GeminiDirectAiAccessRoute` | the Gemini key and base URL vars |
46
+ | OpenAI | `OpenAiDirectAiAccessRoute` | the OpenAI key and base URL vars |
47
+
48
+ - `supportsFileUpload` is `true`: this is the route the Files API upload in `#prepareAttachedFiles()`
49
+ was written for.
50
+ - `#createClient()` returns the existing `ClaudeApiClient` / Gemini / OpenAI client, so a deployment that
51
+ only uses this route behaves exactly as before the routes existed.
52
+
53
+ ## The Vertex AI route (service account)
54
+
55
+ Models hosted on Google Cloud, reached with a **service account**, never an API key. There is no key
56
+ variable to read: the client resolves Application Default Credentials (ADC) itself.
57
+
58
+ | Provider | Route class | Client |
59
+ | --- | --- | --- |
60
+ | Anthropic | `ClaudeVertexAiAccessRoute` | `AnthropicVertex` from `@anthropic-ai/vertex-sdk` |
61
+ | Google | `GeminiVertexAiAccessRoute` | `GoogleGenAI` from `@google/genai`, constructed with `vertexai: true` |
62
+
63
+ ```js
64
+ import {
65
+ AnthropicVertex,
66
+ } from '@anthropic-ai/vertex-sdk'
67
+
68
+ import environment from '../../globals/env.js'
69
+ import ClaudeSdkApiClient from '../../claudeClient/ClaudeSdkApiClient.js'
70
+ import BaseAiAccessRoute from '../BaseAiAccessRoute.js'
71
+
72
+ import CONSTANT_HASH from '../../../constants/aiConstants.cjs'
73
+
74
+ const {
75
+ AI_PROVIDER,
76
+ AI_ACCESS_ROUTE,
77
+ } = CONSTANT_HASH
78
+
79
+ export default class ClaudeVertexAiAccessRoute extends BaseAiAccessRoute {
80
+ static create () {
81
+ return new this()
82
+ }
83
+
84
+ get aiProviderId () {
85
+ return AI_PROVIDER.ANTHROPIC.ID
86
+ }
87
+
88
+ get accessRouteName () {
89
+ return AI_ACCESS_ROUTE.VERTEX_AI.NAME
90
+ }
91
+
92
+ get supportsFileUpload () {
93
+ return false
94
+ }
95
+
96
+ createClient () {
97
+ return ClaudeSdkApiClient.create({
98
+ sdkClient: new AnthropicVertex({
99
+ projectId: environment.VERTEX_AI_PROJECT_ID,
100
+ region: environment.VERTEX_AI_LOCATION,
101
+ }),
102
+ })
103
+ }
104
+ }
105
+ ```
106
+
107
+ `GeminiVertexAiAccessRoute#createClient()` builds its SDK client the same way, with the option names the
108
+ Google Gen AI SDK defines for Vertex AI (its documentation now recommends the `enterprise` flag over
109
+ `vertexai` for the same switch):
110
+
111
+ ```js
112
+ import {
113
+ GoogleGenAI,
114
+ } from '@google/genai'
115
+
116
+ new GoogleGenAI({
117
+ vertexai: true,
118
+ project: environment.VERTEX_AI_PROJECT_ID,
119
+ location: environment.VERTEX_AI_LOCATION,
120
+ })
121
+ ```
122
+
123
+ - **Authentication is ADC**, which the Google auth library resolves in this order: the key file named by
124
+ `GOOGLE_APPLICATION_CREDENTIALS`, the credentials `gcloud auth application-default login` stores, and the
125
+ service account attached to the runtime (Cloud Run, GKE, Compute Engine). On a server, attach the service account to the
126
+ runtime so no key file exists. Use a key file only where nothing can be attached, and keep it outside the
127
+ repository and outside the DB.
128
+ - **Grant the service account only a Vertex AI prediction role** on the project (for example Vertex AI
129
+ User), never an owner or editor role.
130
+ - **Pass the project and location explicitly from env** (`VERTEX_AI_PROJECT_ID`, `VERTEX_AI_LOCATION`,
131
+ app-level names) so the route is the one place that reads them. `AnthropicVertex` would otherwise read
132
+ `CLOUD_ML_REGION` and `ANTHROPIC_VERTEX_PROJECT_ID` from the process by itself. For Claude, `region` also
133
+ accepts `'global'`; check which models the chosen location serves before seeding a row.
134
+ - **The Claude payload is unchanged.** `AnthropicVertex` takes the same Messages params as the direct
135
+ client, moves `model` into the request path, and sets `anthropic_version` when the body lacks it. So
136
+ `ClaudeSdkApiClient#sendMessageToClaude(params)` is `sdkClient.messages.create(params)`, streaming is
137
+ `sdkClient.beta.messages.stream(params)` as in the direct client, and `SendMessageToClaudeCapsule` parses the result as it
138
+ does for the direct route. Do not send the `anthropic-beta: files-api-...` header on this route.
139
+ - **An SDK client throws on a failed request.** `ClaudeSdkApiClient` must convert the thrown error into
140
+ whatever the capsule's `#hasError()` reads, so callers still get a normalized error response and never
141
+ a route-specific exception.
142
+ - **`targetModelName` takes the Vertex spelling**, which puts the version after an `@` (for example
143
+ `claude-sonnet-4-5@20250929`), where the direct id uses a dash. Seed it as its own
144
+ `AiModelAccessRoute` row.
145
+ - **`supportsFileUpload` is `false`** for both classes. The SDK rewrites only the message paths, so the
146
+ Files API upload in `#prepareAttachedFiles()` does not go through it.
147
+ - **Gemini on Vertex** needs a client with the same surface as the direct Gemini client
148
+ (`GeminiSdkApiClient`) that maps the existing `contents` payload onto the SDK's request. The function-call
149
+ shape (`functionCall` / `functionResponse`) does not change.
150
+ - Add the two env vars, `AI_ACCESS_ROUTE.VERTEX_AI`, and one `AiModelAccessRoute` row per reachable model.
151
+
152
+ ## The Bedrock route (AWS credentials)
153
+
154
+ Claude hosted on Amazon Bedrock, reached with **AWS credentials** (SigV4 signing), not the vendor key.
155
+
156
+ | Provider | Route class | Client |
157
+ | --- | --- | --- |
158
+ | Anthropic | `ClaudeBedrockAiAccessRoute` | `AnthropicBedrock` from `@anthropic-ai/bedrock-sdk` |
159
+
160
+ ```js
161
+ import {
162
+ AnthropicBedrock,
163
+ } from '@anthropic-ai/bedrock-sdk'
164
+
165
+ import environment from '../../globals/env.js'
166
+ import ClaudeSdkApiClient from '../../claudeClient/ClaudeSdkApiClient.js'
167
+ import BaseAiAccessRoute from '../BaseAiAccessRoute.js'
168
+
169
+ import CONSTANT_HASH from '../../../constants/aiConstants.cjs'
170
+
171
+ const {
172
+ AI_PROVIDER,
173
+ AI_ACCESS_ROUTE,
174
+ } = CONSTANT_HASH
175
+
176
+ export default class ClaudeBedrockAiAccessRoute extends BaseAiAccessRoute {
177
+ static create () {
178
+ return new this()
179
+ }
180
+
181
+ get aiProviderId () {
182
+ return AI_PROVIDER.ANTHROPIC.ID
183
+ }
184
+
185
+ get accessRouteName () {
186
+ return AI_ACCESS_ROUTE.BEDROCK.NAME
187
+ }
188
+
189
+ get supportsFileUpload () {
190
+ return false
191
+ }
192
+
193
+ createClient () {
194
+ return ClaudeSdkApiClient.create({
195
+ sdkClient: new AnthropicBedrock({
196
+ awsRegion: environment.BEDROCK_AWS_REGION,
197
+ }),
198
+ })
199
+ }
200
+ }
201
+ ```
202
+
203
+ - **Authentication is the AWS default credential chain.** Pass no key options and the client signs with
204
+ whatever the chain finds: `AWS_ACCESS_KEY_ID` / `AWS_SECRET_ACCESS_KEY` (and `AWS_SESSION_TOKEN`) in the
205
+ process, a shared profile or SSO login, or the role attached to the runtime (ECS task, EC2 instance
206
+ profile). On a server, prefer the attached role so no secret exists. Where the keys must come through
207
+ `env.js` under app-level names, pass all three as `awsAccessKey`, `awsSecretKey` and `awsSessionToken`;
208
+ pass both or neither of the first two.
209
+ - **Never set `AWS_BEARER_TOKEN_BEDROCK` in a process that should sign with IAM credentials.** The client
210
+ reads it by default and sends it as a bearer token instead of signing, so the IAM role is silently
211
+ ignored.
212
+ - **Pass the region explicitly** (`BEDROCK_AWS_REGION`, an app-level name). When neither `awsRegion` nor
213
+ `AWS_REGION` is set, the client falls back to `us-east-1`, which may not be where the model is enabled.
214
+ - **Grant only the invoke actions**: `bedrock:InvokeModel` and `bedrock:InvokeModelWithResponseStream`,
215
+ scoped to the model or inference-profile ARNs the app uses.
216
+ - **The Claude payload is unchanged.** Like `AnthropicVertex`, `AnthropicBedrock` takes the same Messages
217
+ params, moves `model` into the request path (`/model/{model}/invoke`, or
218
+ `invoke-with-response-stream` when streaming), and sets `anthropic_version` when the body lacks it. It
219
+ also copies the `anthropic-beta` header into the body, so the `files-api` beta has no use here. The same
220
+ `ClaudeSdkApiClient` and `SendMessageToClaudeCapsule` serve this route and the Vertex AI route.
221
+ - **`targetModelName` takes the Bedrock spelling**, in the shape `anthropic.claude-sonnet-4-5-20250929-v1:0`.
222
+ A model that Bedrock serves only through a cross-region inference profile takes the profile id, which
223
+ prefixes a geography (for example `us.anthropic.claude-...`). Seed the id the Bedrock console lists for
224
+ the region, and confirm the AWS account may invoke that model there.
225
+ - **`supportsFileUpload` is `false`**, for the same reason as on Vertex AI: the SDK rewrites only the
226
+ message paths.
227
+ - **This route serves Claude only**, because `@anthropic-ai/bedrock-sdk` serves Claude models. Another
228
+ vendor's model on Bedrock is a new provider base with its own client, not a route of an existing one.
229
+ - Add `BEDROCK_AWS_REGION`, `AI_ACCESS_ROUTE.BEDROCK`, and one `AiModelAccessRoute` row per Claude model
230
+ the account can invoke.
@@ -138,7 +138,8 @@ UploadFile) a **Payload** (request builder; `#create({ params })`, `#toActualPar
138
138
  (extends `Base<Provider>ApiRequestLauncher` → `BaseRequestLauncher` from
139
139
  `@openreachtech/renchan-tools-external-api`; `#launchRequest()` / `#launchStreamRequest()`, defines
140
140
  `#get:CapsuleClass` and `#requestToClient()`), and a **Capsule** (normalizes the response). Plus one shared
141
- **ApiClient** and one shared **Base...RequestLauncher** that reads the vendor key/base URL from env.
141
+ **ApiClient** and one shared **Base...RequestLauncher**. The launcher receives its client from the
142
+ access route (see `access-routes.md`) and reads no credential itself.
142
143
 
143
144
  - `SendMessageToClaudeFetcher#get:CapsuleClass` → `SendMessageToClaudeCapsule`;
144
145
  `#requestToClient(p)` → `this.client.sendMessageToClaude({ ...p })`.
@@ -146,8 +147,13 @@ UploadFile) a **Payload** (request builder; `#create({ params })`, `#toActualPar
146
147
  with `x-api-key`, `anthropic-version`, `anthropic-beta: files-api-2025-04-14`; `#uploadFileToClaude()`
147
148
  POSTs `/files` as FormData; streaming uses the official SDK
148
149
  (`import Anthropic from '@anthropic-ai/sdk'` → `client.beta.messages.stream(...)`).
149
- - `Base<Provider>ApiRequestLauncher` reads `environment.CLAUDE_API_TOKEN` / `environment.CLAUDE_API_BASE_URL`
150
- (and the OpenAI/Gemini analogues) from the renchan-env facade.
150
+ - `Base<Provider>ApiRequestLauncher` takes the `client` the processor passes in
151
+ (`accessRoute.createClient()`). The `direct` route builds `ClaudeApiClient` from
152
+ `environment.CLAUDE_API_TOKEN` / `environment.CLAUDE_API_BASE_URL` (and the OpenAI/Gemini analogues) of
153
+ the renchan-env facade.
154
+ - `ClaudeSdkApiClient` (and `GeminiSdkApiClient`) wrap a platform SDK client for the Vertex AI and Bedrock
155
+ routes. They expose the method the Fetcher calls (`#sendMessageToClaude()`), so the Fetcher, the Payload
156
+ and the Capsule stay the same on every route.
151
157
 
152
158
  This Launcher/Payload/Capsule/Client shape is the same external-API-client pattern the **external-api-client
153
159
  skill** describes; here it is specialized per LLM vendor.
@@ -93,10 +93,10 @@ one transaction → format**. It receives `{ variables: { input }, context }`; `
93
93
  ```js
94
94
  /**
95
95
  * @param {{
96
- * variables: { input: server.graphql.user.UpdateArticleInput }
96
+ * variables: { input: graphql.user.UpdateArticleInput }
97
97
  * context: UserGraphqlContext
98
98
  * }} params
99
- * @returns {Promise<server.graphql.user.UpdateArticleResult>}
99
+ * @returns {Promise<graphql.user.UpdateArticleResult>}
100
100
  */
101
101
  async resolve ({
102
102
  variables: {
@@ -248,6 +248,10 @@ formatResponse ({
248
248
  }
249
249
  ```
250
250
 
251
+ - **On PostgreSQL, convert a `BIGINT` id with `Number()`** (`articleId: Number(article.id)`):
252
+ node-postgres returns `BIGINT` as a string, and the SDL type is `Int`. `Number()` changes nothing
253
+ on MariaDB, MySQL and SQLite. Branch a nullable id first, because `Number(null)` is `0`. `Number()` loses precision above
254
+ `Number.MAX_SAFE_INTEGER` (2^53 - 1), so an id that can exceed it stays a string (GraphQL `ID`).
251
255
  - **Why minimal:** a Mutation's job is to report *that* the write happened. The frontend re-fetches
252
256
  the updated data with a **Query**. Returning a fully rendered object here duplicates the Query and
253
257
  couples the two. Keep Mutation and Query concerns separate. See
@@ -45,11 +45,11 @@ export default class UpdateArticleMutationResolver extends BaseMutationResolver
45
45
  *
46
46
  * @param {{
47
47
  * variables: {
48
- * input: server.graphql.user.UpdateArticleInput
48
+ * input: graphql.user.UpdateArticleInput
49
49
  * }
50
50
  * context: UserGraphqlContext
51
51
  * }} params
52
- * @returns {Promise<server.graphql.user.UpdateArticleResult>}
52
+ * @returns {Promise<graphql.user.UpdateArticleResult>}
53
53
  */
54
54
  async resolve ({
55
55
  variables: {
@@ -80,7 +80,7 @@ export default class UpdateArticleMutationResolver extends BaseMutationResolver
80
80
  /**
81
81
  * Create an input validator instance
82
82
  *
83
- * @param {{ input: server.graphql.user.UpdateArticleInput }} params
83
+ * @param {{ input: graphql.user.UpdateArticleInput }} params
84
84
  * @returns {UpdateArticleInputValidator}
85
85
  */
86
86
  createInputValidator ({
@@ -95,7 +95,7 @@ export default class UpdateArticleMutationResolver extends BaseMutationResolver
95
95
  /**
96
96
  * Validate the input
97
97
  *
98
- * @param {{ input: server.graphql.user.UpdateArticleInput }} params
98
+ * @param {{ input: graphql.user.UpdateArticleInput }} params
99
99
  * @returns {import('@openreachtech/renchan').RenchanGraphqlError | null}
100
100
  */
101
101
  validateInput ({
@@ -111,7 +111,7 @@ export default class UpdateArticleMutationResolver extends BaseMutationResolver
111
111
  * Generate the transaction callback
112
112
  *
113
113
  * @param {{
114
- * input: server.graphql.user.UpdateArticleInput
114
+ * input: graphql.user.UpdateArticleInput
115
115
  * context: UserGraphqlContext
116
116
  * }} params
117
117
  * @returns {(transaction?: import('sequelize').Transaction) => Promise<model.ArticleEntity>}
@@ -186,7 +186,7 @@ export default class UpdateArticleMutationResolver extends BaseMutationResolver
186
186
  * Format the response
187
187
  *
188
188
  * @param {{ article: model.ArticleEntity }} params
189
- * @returns {server.graphql.user.UpdateArticleResult}
189
+ * @returns {graphql.user.UpdateArticleResult}
190
190
  */
191
191
  formatResponse ({
192
192
  article,
@@ -261,6 +261,10 @@ formatResponse ({
261
261
  }
262
262
  ```
263
263
 
264
+ On PostgreSQL, wrap each `BIGINT` id in `Number()` (`articleId: Number(article.id)`): node-postgres
265
+ returns it as a string, while the result type declares `Int`. It is a no-op on MariaDB, MySQL and
266
+ SQLite, and a nullable id is branched first because `Number(null)` is `0`.
267
+
264
268
  Do not assemble a display object here. The mutation reports the write; the frontend re-queries for
265
269
  the rendered data. A `formatResponse` that maps/sorts/joins rows is a sign business logic leaked
266
270
  out of the transaction callback, or that a Query's job crept into the Mutation — pull it back. (A