@openreachtech/hora-skills-ort-renchan 0.0.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 (126) hide show
  1. package/LICENSE +201 -0
  2. package/README.ja.md +135 -0
  3. package/README.md +135 -0
  4. package/dist/skills/hor-agent-loop/SKILL.md +123 -0
  5. package/dist/skills/hor-agent-loop/references/core.md +485 -0
  6. package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
  7. package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
  8. package/dist/skills/hor-agent-loop/references/testing.md +492 -0
  9. package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
  10. package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
  11. package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
  12. package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
  13. package/dist/skills/hor-backend-testing/SKILL.md +118 -0
  14. package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
  15. package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
  16. package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
  17. package/dist/skills/hor-bank-id/SKILL.md +91 -0
  18. package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
  19. package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
  20. package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
  21. package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
  22. package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
  23. package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
  24. package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
  25. package/dist/skills/hor-constant-definition/SKILL.md +139 -0
  26. package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
  27. package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
  28. package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
  29. package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
  30. package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
  31. package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
  32. package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
  33. package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
  34. package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
  35. package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
  36. package/dist/skills/hor-database-design/SKILL.md +54 -0
  37. package/dist/skills/hor-database-design/references/column-types.md +92 -0
  38. package/dist/skills/hor-database-design/references/datetimes.md +88 -0
  39. package/dist/skills/hor-database-design/references/master-tables.md +117 -0
  40. package/dist/skills/hor-database-design/references/normalization.md +40 -0
  41. package/dist/skills/hor-database-design/references/update-history.md +35 -0
  42. package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
  43. package/dist/skills/hor-external-api-client/SKILL.md +99 -0
  44. package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
  45. package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
  46. package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
  47. package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
  48. package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
  49. package/dist/skills/hor-external-api-client/references/payload.md +176 -0
  50. package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
  51. package/dist/skills/hor-external-api-client/references/testing.md +130 -0
  52. package/dist/skills/hor-external-api-client/references/usage.md +152 -0
  53. package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
  54. package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
  55. package/dist/skills/hor-light-rag/SKILL.md +242 -0
  56. package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
  57. package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
  58. package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
  59. package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
  60. package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
  61. package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
  62. package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
  63. package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
  64. package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
  65. package/dist/skills/hor-post-worker/SKILL.md +320 -0
  66. package/dist/skills/hor-query-resolver/SKILL.md +246 -0
  67. package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
  68. package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
  69. package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
  70. package/dist/skills/hor-query-resolver/references/testing.md +241 -0
  71. package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
  72. package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
  73. package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
  74. package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
  75. package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
  76. package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
  77. package/dist/skills/hor-resolver-share/SKILL.md +262 -0
  78. package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
  79. package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
  80. package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
  81. package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
  82. package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
  83. package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
  84. package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
  85. package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
  86. package/dist/skills/hor-security-audit/SKILL.md +110 -0
  87. package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
  88. package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
  89. package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
  90. package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
  91. package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
  92. package/dist/skills/hor-security-audit/references/secrets.md +95 -0
  93. package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
  94. package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
  95. package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
  96. package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
  97. package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
  98. package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
  99. package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
  100. package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
  101. package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
  102. package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
  103. package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
  104. package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
  105. package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
  106. package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
  107. package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
  108. package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
  109. package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
  110. package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
  111. package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
  112. package/dist/skills/hor-stub-api/SKILL.md +330 -0
  113. package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
  114. package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
  115. package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
  116. package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
  117. package/dist/skills/hor-type-interface/SKILL.md +200 -0
  118. package/docs/skills.ja.md +40 -0
  119. package/docs/skills.md +40 -0
  120. package/lib/equip/CommandLineArguments.js +178 -0
  121. package/lib/equip/HoraSkillsCli.js +590 -0
  122. package/lib/equip/SkillsInstaller.js +443 -0
  123. package/lib/equip/SkillsManifestFile.js +260 -0
  124. package/lib/equip/constants/CLI_COMMAND.js +8 -0
  125. package/lib/equip/hora-skills-ort-renchan.js +8 -0
  126. package/package.json +51 -0
@@ -0,0 +1,143 @@
1
+ # Retrieval internals (embedder, selectors, processor, n-gram)
2
+
3
+ Referenced from `SKILL.md`. The exact internals behind the vector-first / LLM-fallback document RAG and the
4
+ n-gram fulltext builder.
5
+
6
+ ## `LocalTextEmbedder` (`app/tools/embedding/LocalTextEmbedder.js`)
7
+
8
+ Self-contained, no imports. Turns text into a fixed-dim L2-normalized vector so cosine == dot product.
9
+
10
+ - `DIMENSION = 256`, `MODEL_VERSION = 'local-hash-ngram-v1'`.
11
+ - `.generateHash(token)` — FNV-1a 32-bit: seed `0x811c9dc5`, per char `Math.imul(hash ^ charCode,
12
+ 0x01000193)`, returned `>>> 0`.
13
+ - `#generateTokens(text)` — NFKC + lowercase, then:
14
+ - **word tokens**: `text.split(/[^0-9a-zÀ-ɏ]+/u)`, keep length ≥ 2, prefix `w:`.
15
+ - **ideograph unigrams**: from whitespace-stripped `compactText`, chars with codepoint ≥ `0x3400`, prefix
16
+ `u:`.
17
+ - **character grams**: sliding windows of size `[2, 3]` over `compactText`, prefix `g:`.
18
+ - `#generateEmbedding(text)`:
19
+
20
+ ```js
21
+ const bucketCounts = this.generateTokens(text).reduce(
22
+ (counts, token) => {
23
+ const bucketIndex = Ctor.generateHash(token) % dimension
24
+
25
+ counts.set(bucketIndex, (counts.get(bucketIndex) ?? 0) + 1)
26
+
27
+ return counts
28
+ },
29
+ new Map()
30
+ )
31
+
32
+ const rawVector = Array.from({ length: dimension }, (each, index) => bucketCounts.get(index) ?? 0)
33
+ const sumOfSquares = rawVector.reduce((sum, value) => sum + value * value, 0)
34
+ const norm = Math.sqrt(sumOfSquares) || 1
35
+
36
+ return Float32Array.from(rawVector, value => value / norm)
37
+ ```
38
+
39
+ - `#calculateCosineSimilarity(vectorA, vectorB)` — `vectorA.reduce((sum, value, index) => sum + value *
40
+ vectorB[index], 0)` (dot product; both are pre-normalized).
41
+
42
+ The `Map` here is a local accumulator inside one method (a legitimate collection use), not per-instance
43
+ mutable state.
44
+
45
+ ## `DynamicDocumentVectorSelector` step methods
46
+
47
+ `#fetchPrefetchedDynamicDocumentsBackgroundSectionAsync(...)` runs the 8 steps in `SKILL.md`; the helpers:
48
+
49
+ - `#extractEligibleDocumentPrimaryKeys(...)` → delegates to
50
+ `DynamicDocumentCatalogSectionBuilder#extractEligibleDynamicDocumentPrimaryKeys` (DYNAMIC assignments with
51
+ a `Document` whose `DocumentSkillGenerationOutcome` is COMPLETE).
52
+ - `#loadDocumentEmbeddings(...)` → `DocumentEmbedding.findAll({ where: { DocumentId: { [Op.in]: ids } } })`.
53
+ - `#generateVectorScores(...)` → per row `{ documentId, score: embedder.calculateCosineSimilarity(query,
54
+ LocalTextEmbedder.deserializeVector(row.embedding)) }`.
55
+ - `#rankVectorScores(...)` → sort by descending `score`.
56
+ - `#loadDocumentTokenCounts(...)` → load `id, name, description, content`, return `Map<id,
57
+ estimatedTokenCount>`.
58
+ - `#estimateDocumentTokenCount(...)` → join name+description+content with `\n`, split on `/\s+/u`, count
59
+ non-empty (a dependency-free proxy — do not confuse with `tiktoken`).
60
+ - `#limitDocumentPrimaryKeysToTokenBudget(...)` → the greedy reduce in `SKILL.md` (always keep the top-ranked
61
+ doc).
62
+ - `#fetchPrefetchedDynamicDocumentsPayload(...)` → `RetrieveDynamicDocumentsProcessor.process({ contextHint:
63
+ null, documentIds, extraToolOptions: { employeeId, employeeRoleIds } })`.
64
+
65
+ `.MAX_TOTAL_TOKEN_COUNT` reads `process.env.DYNAMIC_DOCUMENT_VECTOR_SELECTION_MAX_TOKEN_COUNT`, falling back
66
+ to `DEFAULT_MAX_TOTAL_TOKEN_COUNT = 50000` when not finite or ≤ 0.
67
+
68
+ ## `DynamicDocumentsBackgroundKnowledgeFetcher` (LLM fallback)
69
+
70
+ - Provider→tool-id map: `.retrieveDynamicDocumentsAiToolIdsByProvider` → `{ claude, gemini, openai }` from
71
+ `CONTEXT_ASSEMBLER_DYNAMIC_DOCUMENT.AI_TOOL.RETRIEVE_DYNAMIC_DOCUMENTS_*.ID`; tool name
72
+ `'retrieve_dynamic_documents'`.
73
+ - `#buildDynamicDocumentSelectionArguments(...)` — resolve eligible keys, load the prefetch worker agent
74
+ (`AiAgent.findByPk(DEFAULT_AI_AGENT.AI_AGENT_FOR_DYNAMIC_DOCUMENT_BODY_PREFETCH.ID, { include: [...] })`),
75
+ pick the processor by its default model (see the `hor-multi-llm-provider` skill), resolve the provider-specific
76
+ `AiTool` id, `JSON.parse` its `payload`, build the metadata catalog + instruction.
77
+ - `#sendDynamicDocumentSelectionRequestAsync(...)` — one `processor.sendRequestToAi(...)` with
78
+ `toolChoices: [{ name: 'retrieve_dynamic_documents' }]`, `isAutoHandleFunctionCall: false`,
79
+ `shouldPrefetchDynamicDocumentsForBackground: false` (recursion guard).
80
+ - `#extractRetrieveDynamicDocumentsFunctionCall(...)` → `#normalizeRetrieveToolInvocationDocumentIds(...)`
81
+ (`arguments.documentIds` → `Number`s) → `#filterDocumentPrimaryKeysToCatalogSubset(...)` (intersect with
82
+ the eligible set, order preserved) → `''` if empty, else fetch the payload.
83
+ - The instruction (`#buildDynamicDocumentBodyPrefetchInstruction`) lists the allowed `document_id` values
84
+ and requires exactly one tool call returning a non-empty integer array.
85
+
86
+ ## `DynamicDocumentCatalogSectionBuilder`
87
+
88
+ Builds the `<dynamic_document_catalog>` metadata block (no bodies) and the shared eligibility rule
89
+ (`#extractEligibleDynamicDocumentPrimaryKeys`, used by **both** selectors): an assignment must be DYNAMIC
90
+ category, have a `Document`, and that document's skill-generation outcome must be COMPLETE
91
+ (`DocumentSkillGenerationStatusId === DOCUMENT_SKILL_GENERATION_STATUS.COMPLETE.ID`).
92
+
93
+ ## `RetrieveDynamicDocumentsProcessor` (retrieval leaf)
94
+
95
+ `#get:aiToolName` = `'retrieve_dynamic_documents'`. `#process(...)` validates → normalizes ids →
96
+ `Document.findAll({ where: { id: { [Op.in]: ids } } })` → maps by PK → emits, in request order (missing ids
97
+ omitted):
98
+
99
+ ```xml
100
+ <?xml version="1.0" encoding="UTF-8"?>
101
+ <retrieve_dynamic_documents_result>
102
+ <document_ids>
103
+ <document_id>{id}</document_id>
104
+ </document_ids>
105
+ <documents>
106
+ <document>
107
+ <document_id>{id}</document_id>
108
+ <document_title>{escaped name}</document_title>
109
+ <document_body>{escaped content}</document_body>
110
+ </document>
111
+ </documents>
112
+ </retrieve_dynamic_documents_result>
113
+ ```
114
+
115
+ (Phase-1 note in the code: per-document ACL is intentionally omitted here and restored later; documents are
116
+ returned by id in request order.) The assembler CDATA-wraps this XML into the background block.
117
+
118
+ ## N-gram tokenizer and fulltext builder
119
+
120
+ `NgramTextTokenizer` (`app/tools/TextTokenizer/`) — uses the `ngram` package.
121
+
122
+ - `.create()` defaults `minNgram = 2, maxNgram = 3`; `.createAsync()` defaults `minNgram = 2, maxNgram = 2`.
123
+ - `#isJapaneseText({ text })` — resets `REGEX.JAPANESE.lastIndex` then `.test(text)`; the regex covers
124
+ hiragana/katakana/kanji/fullwidth forms and select symbols.
125
+ - `#tokenizeSentence(sentence)` — `''` for empty; **returns non-Japanese text unchanged**; else
126
+ `[...new Set(this.tokenizer.ngram(sentence, minNgram, maxNgram))].join(' ')`.
127
+
128
+ `NgramSearchWordGenerator` (`app/tools/FullTextSearch/NgramSearchKeywordGenerator.js` — class name differs
129
+ from the filename):
130
+
131
+ - `.create()` defaults `nGramLength = 2, logicalOperator = 'and'`.
132
+ - `#splitToWords()` — replace BOOLEAN-mode operator chars `/[+\-*()<>~'"@[\]{}]/ug` with spaces, split on
133
+ `/\s+/u`.
134
+ - `#generateTokenGroups({ words })` — short words (`length < nGramLength`) become single-token groups; long
135
+ words are n-grammed, filtered to grams the word actually `includes` (drops padding), deduped per word.
136
+ - `#formatTokenGroups(...)` — the AND/OR formatting in `SKILL.md`.
137
+
138
+ `FullTextSearchConditionGenerator` — `#generateCondition()` returns
139
+ `MATCH (${matchColumnNames}) AGAINST ('${againstText}' IN BOOLEAN MODE)`, or `null` when the against text is
140
+ empty; `#formatAgainstText()` delegates to `NgramSearchWordGenerator`.
141
+
142
+ This n-gram/fulltext infra is generic MySQL/MariaDB fulltext and is **not** wired into the document-RAG
143
+ selectors.
@@ -0,0 +1,288 @@
1
+ ---
2
+ name: hor-multi-llm-provider
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.
10
+ ---
11
+
12
+ # Multi-LLM Provider (Claude / OpenAI / Gemini behind one abstraction)
13
+
14
+ This backend talks to three LLM vendors through **one processor abstraction** so callers (agents,
15
+ resolvers, jobs) never branch on the provider. A caller resolves a **model name** to a processor and calls
16
+ `processor.sendRequestToAi(...)`; everything provider-specific (SDK calls, function-call shape, file
17
+ upload, response parsing) is hidden behind the processor and its capsule.
18
+
19
+ ## Grand principle: one base + one subclass per model; provider differences live in a provider base, the model is chosen from the DB
20
+
21
+ The abstraction is a three-level strategy: `BaseAiModelProcessor` (the contract) → one **provider base**
22
+ per vendor (Claude/OpenAI/Gemini plumbing) → one **concrete processor per model** whose only distinct
23
+ member is `#get:aiModel`. A loader auto-discovers the concrete processors and picks one by model-name
24
+ string at runtime.
25
+
26
+ - **Why a per-model class whose only identity is `#get:aiModel`**: adding a model must be additive
27
+ (Open–Closed) — drop one file whose `#get:aiModel` returns the new name, and the loader finds it. The
28
+ concrete class holds *no* target model id or token limit; those come from the DB `AiModel` /
29
+ `AiModelCapability` rows, so a model's real endpoint and limits are data, not code.
30
+ - **Why a provider base between them**: the three vendors differ only in a few mechanics —
31
+ function-call event shape (`tool_use` vs `function_call` vs `functionCall`), how tool results are fed
32
+ back (`messages` vs `input` vs `contents`), and file upload (Claude file id / OpenAI file id / Gemini
33
+ file uri). Concentrating those in one provider base per vendor keeps every concrete model processor
34
+ identical except for its name.
35
+ - **Why normalize responses through `AiModelResponse`**: callers must read `#hasError()`,
36
+ `#extractFunctionCalls()`, `#extractContentText()` the same way regardless of vendor. Each provider's
37
+ capsule exposes the same method surface; `AiModelResponse` is the thin uniform wrapper over it.
38
+ - **Why choose the model from the DB**: which model an agent uses is per-agent config
39
+ (`AiAgentDefaultModel → AiModel.name`), overridable per call — never hard-coded. Swapping a model is a
40
+ data change.
41
+
42
+ ## Layers and files
43
+
44
+ ```
45
+ app/tools/
46
+ BaseAiModelProcessor.js abstract contract (get aiModel, sendRequestToAi, ...)
47
+ BaseAiModelProviderProcessor/
48
+ BaseClaudeAIProcessor.js Claude function-call loop + Files API upload
49
+ BaseOpenAIProcessor.js OpenAI function_call + file upload (with expiry)
50
+ BaseGeminiAIProcessor.js Gemini functionCall + file uri upload
51
+ AiModelProcessor/
52
+ ClaudeSonnet4_5AiModelProcessor.js concrete: get aiModel + sendRequestToAi
53
+ OpenAiGPT_5_AiModelProcessor.js (~21 concrete model files, one per model)
54
+ Gemini2_5FlashAiModelProcessor.js
55
+ ...
56
+ BulkAiModelProcessorsLoader.js auto-discovery + getProcessor(aiModel)
57
+ AiPayloadGenerator/
58
+ BaseAiMessagePayloadGenerator.js shared history trimming / token budget
59
+ ClaudeMessagePayloadGenerator.js provider payload shaping (tools, toolChoice, files)
60
+ OpenAiMessagePayloadGenerator.js
61
+ GeminiMessagePayloadGenerator.js
62
+ AiModelResponse.js normalized response wrapper
63
+ app/claudeClient/ | app/geminiClient/ | app/openAiClient/ low-level Launcher/Payload/Capsule/Client
64
+ ```
65
+
66
+ ## 1. The contract — `BaseAiModelProcessor`
67
+
68
+ Abstract members a concrete processor must satisfy:
69
+
70
+ - `#get:aiModel` (abstract) — the model-name string the loader matches on (e.g. `'sonnet-4-5'`).
71
+ - `#sendRequestToAi({ ... })` (abstract) — non-streaming request; returns an `AiModelResponse`.
72
+ - `#sendStreamRequestToAi({ ..., onText, onComplete })` (abstract) — streaming variant.
73
+ - `#prepareAttachedFiles({ fileUrls })` (concrete default: returns `fileUrls` unchanged) — overridden per
74
+ provider to upload files and attach provider file ids/uris.
75
+ - `#findAiModelByName({ aiModelName })` (concrete) —
76
+ `AiModel.findOne({ where: { name }, include: [AiModelCapability] })`; this is how a processor gets its
77
+ DB-backed `targetModelName` and `maxOutputToken`.
78
+
79
+ The request param bag is uniform across providers:
80
+
81
+ ```js
82
+ async sendRequestToAi ({
83
+ aiAgent,
84
+ instruction,
85
+ documents,
86
+ fileUrls,
87
+ historyMessages = [],
88
+ tools = [],
89
+ toolChoices = [],
90
+ isAutoHandleFunctionCall = true,
91
+ extraToolOptions = {},
92
+ shouldPrefetchDynamicDocumentsForBackground = false,
93
+ }) {
94
+ // ...
95
+ }
96
+ ```
97
+
98
+ ## 2. A concrete model processor — only `#get:aiModel` is unique
99
+
100
+ Everything else (build the instruction, prepare files, build the payload, send, handle one round of
101
+ function calls, wrap the response) is the same standard flow inherited/composed from the provider base.
102
+
103
+ ```js
104
+ import BaseClaudeAIProcessor from '../BaseAiModelProviderProcessor/BaseClaudeAIProcessor.js'
105
+ import AiModelResponse from '../AiModelResponse.js'
106
+
107
+ import CONSTANT_HASH from '../../../constants/aiConstants.cjs'
108
+
109
+ const {
110
+ AI_MODEL,
111
+ } = CONSTANT_HASH
112
+
113
+ export default class ClaudeSonnet4_5AiModelProcessor extends BaseClaudeAIProcessor {
114
+ static create () {
115
+ return new this()
116
+ }
117
+
118
+ get aiModel () {
119
+ return AI_MODEL.CLAUDE_SONNET_4_5.NAME
120
+ }
121
+
122
+ async sendRequestToAi ({
123
+ aiAgent,
124
+ instruction,
125
+ documents,
126
+ fileUrls,
127
+ historyMessages = [],
128
+ tools = [],
129
+ toolChoices = [],
130
+ isAutoHandleFunctionCall = true,
131
+ extraToolOptions = {},
132
+ shouldPrefetchDynamicDocumentsForBackground = false,
133
+ }) {
134
+ const aiModel = await this.findAiModelByName({
135
+ aiModelName: this.aiModel,
136
+ })
137
+
138
+ const documentInstructionComposer = await this.createDocumentInstructionComposer({
139
+ // ...splits documents, wires the agent's default instruction (see `hor-ai-prompt-document-store` skill)
140
+ })
141
+
142
+ const preparedFileUrls = await this.prepareAttachedFiles({
143
+ fileUrls,
144
+ })
145
+
146
+ const payloadGenerator = this.createClaudeMessagePayloadGenerator({
147
+ aiAgent,
148
+ aiModel,
149
+ message: documentInstructionComposer.generateComposedInstruction(),
150
+ fileUrls: preparedFileUrls,
151
+ historyMessages,
152
+ tools,
153
+ toolChoices,
154
+ })
155
+
156
+ const payload = payloadGenerator.generateClaudeMessagePayload()
157
+ const fetcher = this.createSendMessageToClaudeFetcher()
158
+ const capsule = await fetcher.launchRequest(payload)
159
+
160
+ if (capsule.hasError()) {
161
+ return AiModelResponse.create({
162
+ aiResponseCapsule: capsule,
163
+ })
164
+ }
165
+
166
+ if (!capsule.hasFunctionCallEvent()) {
167
+ return AiModelResponse.create({
168
+ aiResponseCapsule: capsule,
169
+ })
170
+ }
171
+
172
+ if (!isAutoHandleFunctionCall) {
173
+ return AiModelResponse.create({
174
+ aiResponseCapsule: capsule,
175
+ })
176
+ }
177
+
178
+ const followUpPayload = await this.handleFunctionCalls({
179
+ payloadParams: payload.params,
180
+ aiResponses: capsule.extractContent(),
181
+ extraToolOptions,
182
+ })
183
+
184
+ const followUpCapsule = await fetcher.launchRequest(followUpPayload)
185
+
186
+ return AiModelResponse.create({
187
+ aiResponseCapsule: followUpCapsule,
188
+ })
189
+ }
190
+ }
191
+ ```
192
+
193
+ - **`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'`).
196
+ - **`isAutoHandleFunctionCall: false`** short-circuits after the first response and returns the raw
197
+ function call — this is exactly what the forced-single-tool actions in the **`hor-ai-agent-structure` skill**
198
+ rely on.
199
+ - The flow handles **one** round of function calls (one follow-up request), not an open-ended tool loop.
200
+
201
+ ## 3. Runtime selection — `BulkAiModelProcessorsLoader`
202
+
203
+ The loader auto-discovers every class under `app/tools/AiModelProcessor/` with renchan's
204
+ `DeepBulkClassLoader`, instantiates each via `.create()`, and picks one by matching `#get:aiModel`:
205
+
206
+ ```js
207
+ import {
208
+ DeepBulkClassLoader,
209
+ } from '@openreachtech/renchan'
210
+
211
+ // ...
212
+ static async loadProcessorClasses (path) {
213
+ return DeepBulkClassLoader.create({
214
+ poolPath: path,
215
+ })
216
+ .loadClasses()
217
+ }
218
+
219
+ getProcessor (aiModel) {
220
+ return this.processors.find(processor => processor.aiModel === aiModel)
221
+ }
222
+ ```
223
+
224
+ The model **name** passed to `#getProcessor()` comes from the DB — the agent's default model, overridable
225
+ per call:
226
+
227
+ ```js
228
+ // explicit id wins, else the agent's default model
229
+ const targetAiModelId = aiModelId
230
+ ?? aiAgentDefaultModel?.AiModelId
231
+ ?? null
232
+
233
+ const aiModel = await AiModel.findByPk(targetAiModelId)
234
+ const processor = this.bulkAiModelProcessorsLoader.getProcessor(aiModel.name)
235
+ ```
236
+
237
+ or directly via the agent's default-model chain
238
+ `aiAgent.AiAgentDefaultModel.AiModel.name → getProcessor(...)`.
239
+
240
+ > Do not confuse this with `BulkAiToolProcessorsLoader`: the provider bases use a *tool*-processor loader
241
+ > (`getProcessor(toolName)`) to run function calls — a different loader over `app/aiTools/`.
242
+
243
+ ## 4. Adding a model or a provider
244
+
245
+ - **New model of an existing provider**: add one file under `app/tools/AiModelProcessor/` extending that
246
+ provider base, with `#get:aiModel` returning the new `AI_MODEL.*.NAME`; add the `AiModel` +
247
+ `AiModelCapability` rows (and `AiModelToolAssignment` rows) via a seeder; add the `AI_MODEL` entry in
248
+ `constants/aiConstants.cjs`. No caller changes — the loader finds it.
249
+ - **New provider**: add a provider base under `app/tools/BaseAiModelProviderProcessor/` implementing the
250
+ function-call handling + `#prepareAttachedFiles()` for that vendor, a payload generator under
251
+ `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.
254
+
255
+ See [provider-internals.md](./references/provider-internals.md) for the per-vendor function-call and
256
+ file-upload differences, the payload generators, `AiModelResponse`, and the low-level client pattern.
257
+
258
+ ## 5. Config and secrets
259
+
260
+ - **`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`.
263
+ - **`AiModelCapability`** (`ai_model_capabilities`): `contextWindowToken`, `maxOutputToken` (→ payload
264
+ `maxTokens`).
265
+ - **`AiModelToolAssignment`** (`ai_model_tool_assignments`): which tools a model may use (see the
266
+ `hor-ai-prompt-document-store` skill for `AiTool`).
267
+ - **API keys / base URLs** come from `@openreachtech/renchan-env` via `app/globals/env.js` (e.g.
268
+ `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
271
+ two-file `.cjs` master + ESM bridge rule).
272
+
273
+ ## Cross-cutting rules
274
+
275
+ - **Callers never branch on the provider** — resolve a processor by name and use the uniform
276
+ `#sendRequestToAi()` / `AiModelResponse` surface.
277
+ - **A concrete model processor adds no logic beyond `#get:aiModel`** — put shared behavior on the provider
278
+ base, per-vendor behavior on the provider base too, and model specifics in the DB.
279
+ - **Return `null` / a normalized error response, not `undefined`**, on failure; check `#hasError()` before
280
+ reading content.
281
+ - One class per file, one `export default`, `static create()` factory; getters return a constant.
282
+
283
+ ## Detail files
284
+
285
+ - [provider-internals.md](./references/provider-internals.md) — the three provider bases' function-call
286
+ feedback shapes and file-upload models (Claude/OpenAI/Gemini), the payload generators
287
+ (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.
@@ -0,0 +1,153 @@
1
+ # Provider internals (function calls, file upload, payloads, response, clients)
2
+
3
+ Referenced from `SKILL.md`. This is the per-vendor detail behind the uniform processor surface. The
4
+ concrete model processors are identical except for `#get:aiModel`; the differences below live in the
5
+ three provider bases under `app/tools/BaseAiModelProviderProcessor/` and the payload generators under
6
+ `app/tools/AiPayloadGenerator/`.
7
+
8
+ ## Function-call feedback — the one real per-vendor difference
9
+
10
+ Each provider base runs the same shape: filter the AI response for tool calls, run each tool via the
11
+ `BulkAiToolProcessorsLoader` (`getProcessor(toolName).process({ ...input, extraToolOptions })`), then push
12
+ the tool results back into the payload and re-request. Only the **event type**, the **result envelope**,
13
+ and the **payload channel** differ.
14
+
15
+ | Vendor | Function-call event | Tool result fed back as | Payload channel | Arguments |
16
+ | --- | --- | --- | --- | --- |
17
+ | Claude | `response.type === 'tool_use'` | `{ type: 'tool_result', tool_use_id, content }` (role `user`) | `payloadParams.messages` | `response.input` (object) |
18
+ | OpenAI | `response.type === 'function_call'` | original call + `{ type: 'function_call_output', call_id, output }` | `payloadParams.input` | `JSON.parse(response.arguments)` |
19
+ | Gemini | `functionCall` part | `{ role: 'model', parts: [{ functionCall }] }` + `{ role: 'user', parts: [{ functionResponse: { name, response: { result } } }] }` | `payloadParams.contents` | `response.arguments` (already an object) |
20
+
21
+ Claude's loop, verbatim (the other two mirror it with the shapes above):
22
+
23
+ ```js
24
+ const functionCalls = aiResponses.filter(response => response.type === 'tool_use')
25
+
26
+ const toolResults = await functionCalls.reduce(
27
+ async (resultsPromise, response) => {
28
+ const collectedResults = await resultsPromise
29
+
30
+ const aiToolProcessor = bulkAiToolProcessorsLoader.getProcessor(response.name)
31
+
32
+ const toolResult = await aiToolProcessor.process({
33
+ ...response.input,
34
+ extraToolOptions: {
35
+ ...extraToolOptions,
36
+ toolName: response.name,
37
+ },
38
+ })
39
+
40
+ collectedResults.push({
41
+ type: 'tool_result',
42
+ tool_use_id: response.id,
43
+ content: toolResult.toString(),
44
+ })
45
+
46
+ return collectedResults
47
+ },
48
+ Promise.resolve([])
49
+ )
50
+
51
+ payloadParams.messages.push({
52
+ role: 'user',
53
+ content: toolResults,
54
+ })
55
+ ```
56
+
57
+ `#handleStreamingFunctionCalls()` is the streaming counterpart: it builds the same follow-up payload, then
58
+ calls the streaming fetcher forwarding `{ onText, onComplete }` (Claude/Gemini) or `{ onText, onComplete,
59
+ onError }` (Claude adds `onError`).
60
+
61
+ ## File upload — `#prepareAttachedFiles({ fileUrls })`
62
+
63
+ Each provider base overrides `#prepareAttachedFiles()` to upload attachments once and reuse them, keyed by
64
+ the uploaded file's `idHash` (extracted from the file URL's last path segment; base URLs come from
65
+ `env.BASE_EMPLOYEE_FILE_URL` / `env.BASE_CLIENT_FILE_URL`). It maps app `UploadedFile` rows to a
66
+ per-provider upload record, reusing an existing one when valid, else uploading and saving.
67
+
68
+ | Vendor | Upload record model | Reuse rule | File identity attached |
69
+ | --- | --- | --- | --- |
70
+ | Claude | `ClaudeUploadedFile` | always reusable (Claude file ids do not expire) | `claudeFileId` |
71
+ | OpenAI | `OpenAiUploadedFile` | reusable if no `expiresAt`, else `expiresAt > now` (Unix seconds → Date) | `openAiFileId` |
72
+ | Gemini | `GeminiUploadedFile` | reusable if `expiresAt > now` (ordered by `expiresAt` DESC) | `geminiFileUri` |
73
+
74
+ Only files that end up with a provider id/uri are returned. The `AttachedFile` typedef on
75
+ `BaseAiModelProcessor` carries all three optional identities (`claudeFileId` / `openAiFileId` /
76
+ `geminiFileUri`) plus `fileUrl` / `fileType`.
77
+
78
+ ## Payload generators (`app/tools/AiPayloadGenerator/`)
79
+
80
+ `BaseAiMessagePayloadGenerator` holds the shared state (`aiAgent`, `aiModel`, `targetAiModel`, `message`,
81
+ `historyMessages`, `maxTokens`, `tools`, `emotionalLevel`, `fileUrls`, `toolChoices`) and the
82
+ history-trimming helpers (`#extractFilteredHistoryMessages(...)`, `#createMessageTokenLimiter(...)` →
83
+ `MessageTokenLimiter` for token-budget trimming). Each provider generator extends it.
84
+
85
+ `ClaudeMessagePayloadGenerator` (the others mirror it):
86
+
87
+ - `#generateClaudeMessagePayload()` — system prompt = `aiAgent.AiAgentRoleInstruction.role`; trims history;
88
+ `messages = [...formattedHistory, { role: 'user', content: generateMessagesContent() }]`; returns
89
+ `SendMessageToClaudePayload.create({ params })`.
90
+ - `#generatePayloadParams(...)` — omit `tools` / `toolChoice` entirely when there are no tools; else include
91
+ `tools` + `toolChoice: generateToolChoice()`.
92
+ - `#generateToolChoice()` — `{ type: 'auto' }` (none) / `{ type: 'tool', name }` (exactly one — the forced
93
+ single tool) / `{ type: 'any' }` (multiple).
94
+ - `#formatSingleMessage()` — role from `MESSAGE_SENDER_CATEGORY.HUMAN.ID` → `'user'` else `'assistant'`;
95
+ appends document linkages + one-time documents.
96
+ - `#generateMessagesContent()` / `#generateFileSource()` — text block + file blocks; a file block prefers
97
+ `{ type: 'file', file_id: claudeFileId }` when a Claude file id exists, else `{ type: 'url', url }`;
98
+ `#extractTypeFromFileType()` → `'document'` (PDF) or `'image'`.
99
+
100
+ Provider nuances: OpenAI's `#generateOpenAiMessagePayload()` is async (awaited) and passes
101
+ `emotionalLevel: null`; Gemini/OpenAI use their own message channels (`contents` / `input`).
102
+
103
+ ## `AiModelResponse` and the capsule surface
104
+
105
+ `AiModelResponse.create({ aiResponseCapsule })` is a thin uniform wrapper. Each method guards that the
106
+ capsule implements it, then delegates:
107
+
108
+ ```js
109
+ extractFunctionCalls () {
110
+ return this.aiResponseCapsule.extractFunctionCalls()
111
+ }
112
+
113
+ extractContentText () {
114
+ return this.aiResponseCapsule.extractContentText()
115
+ }
116
+
117
+ extractErrorMessage () {
118
+ return this.aiResponseCapsule.extractErrorMessage()
119
+ }
120
+
121
+ hasError () {
122
+ return this.aiResponseCapsule.hasError()
123
+ }
124
+ ```
125
+
126
+ The real logic is in the provider capsule (e.g. `SendMessageToClaudeCapsule extends BaseCapsule` from
127
+ `@openreachtech/renchan-tools-external-api`), which every vendor implements with the same surface:
128
+ `#hasError()`, `#extractContent()`, `#hasFunctionCallEvent()`, `#extractFunctionCalls()` (→
129
+ `{ name, arguments }`), `#extractContentText()`, plus model / role / stop-reason / token-usage extractors.
130
+ **This shared surface is what makes the whole abstraction provider-agnostic** — the forced-tool actions in
131
+ the `hor-ai-agent-structure` skill call `response.hasError()` / `response.extractFunctionCalls()` without knowing
132
+ the vendor.
133
+
134
+ ## Low-level clients (`app/claudeClient/`, `app/geminiClient/`, `app/openAiClient/`)
135
+
136
+ Each provider dir has the same ~11-file layout: for each operation (SendMessage, StreamingMessage,
137
+ UploadFile) a **Payload** (request builder; `#create({ params })`, `#toActualParams()`), a **Fetcher**
138
+ (extends `Base<Provider>ApiRequestLauncher` → `BaseRequestLauncher` from
139
+ `@openreachtech/renchan-tools-external-api`; `#launchRequest()` / `#launchStreamRequest()`, defines
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.
142
+
143
+ - `SendMessageToClaudeFetcher#get:CapsuleClass` → `SendMessageToClaudeCapsule`;
144
+ `#requestToClient(p)` → `this.client.sendMessageToClaude({ ...p })`.
145
+ - `ClaudeApiClient` — constructed `{ token, httpRequestClient }`; `#sendMessageToClaude()` POSTs `/messages`
146
+ with `x-api-key`, `anthropic-version`, `anthropic-beta: files-api-2025-04-14`; `#uploadFileToClaude()`
147
+ POSTs `/files` as FormData; streaming uses the official SDK
148
+ (`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.
151
+
152
+ This Launcher/Payload/Capsule/Client shape is the same external-API-client pattern the **external-api-client
153
+ skill** describes; here it is specialized per LLM vendor.