@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.
- package/LICENSE +201 -0
- package/README.ja.md +135 -0
- package/README.md +135 -0
- package/dist/skills/hor-agent-loop/SKILL.md +123 -0
- package/dist/skills/hor-agent-loop/references/core.md +485 -0
- package/dist/skills/hor-agent-loop/references/graphql-integration.md +178 -0
- package/dist/skills/hor-agent-loop/references/renchan-job-integration.md +368 -0
- package/dist/skills/hor-agent-loop/references/testing.md +492 -0
- package/dist/skills/hor-ai-agent-structure/SKILL.md +403 -0
- package/dist/skills/hor-ai-agent-structure/references/loop-and-actions.md +100 -0
- package/dist/skills/hor-ai-prompt-document-store/SKILL.md +220 -0
- package/dist/skills/hor-ai-prompt-document-store/references/models-and-composition.md +156 -0
- package/dist/skills/hor-backend-testing/SKILL.md +118 -0
- package/dist/skills/hor-backend-testing/references/placement-and-ordering.md +89 -0
- package/dist/skills/hor-backend-testing/references/purity-and-mocks.md +82 -0
- package/dist/skills/hor-backend-testing/references/running-tests.md +186 -0
- package/dist/skills/hor-bank-id/SKILL.md +91 -0
- package/dist/skills/hor-build-e2e-test-environment/SKILL.md +609 -0
- package/dist/skills/hor-build-e2e-test-environment/references/compose-definition.md +368 -0
- package/dist/skills/hor-build-e2e-test-environment/references/edge-and-proxy.md +287 -0
- package/dist/skills/hor-build-e2e-test-environment/references/environment-and-ports.md +201 -0
- package/dist/skills/hor-build-e2e-test-environment/references/runner-and-lifecycle.md +330 -0
- package/dist/skills/hor-build-e2e-test-environment/references/seed-data.md +145 -0
- package/dist/skills/hor-build-e2e-test-environment/references/windows-runner.md +146 -0
- package/dist/skills/hor-constant-definition/SKILL.md +139 -0
- package/dist/skills/hor-cookie-authentication/SKILL.md +33 -0
- package/dist/skills/hor-cookie-authentication/references/auth-filter.md +55 -0
- package/dist/skills/hor-cookie-authentication/references/cookie-context.md +53 -0
- package/dist/skills/hor-cookie-authentication/references/dev-login-seeder.md +22 -0
- package/dist/skills/hor-cookie-authentication/references/environment.md +64 -0
- package/dist/skills/hor-cookie-authentication/references/error-codes.md +24 -0
- package/dist/skills/hor-cookie-authentication/references/migrations.md +18 -0
- package/dist/skills/hor-cookie-authentication/references/resolvers.md +97 -0
- package/dist/skills/hor-cookie-authentication/references/session-clerk.md +41 -0
- package/dist/skills/hor-cookie-authentication/references/token-models.md +125 -0
- package/dist/skills/hor-database-design/SKILL.md +54 -0
- package/dist/skills/hor-database-design/references/column-types.md +92 -0
- package/dist/skills/hor-database-design/references/datetimes.md +88 -0
- package/dist/skills/hor-database-design/references/master-tables.md +117 -0
- package/dist/skills/hor-database-design/references/normalization.md +40 -0
- package/dist/skills/hor-database-design/references/update-history.md +35 -0
- package/dist/skills/hor-execution-placement-pattern/SKILL.md +216 -0
- package/dist/skills/hor-external-api-client/SKILL.md +99 -0
- package/dist/skills/hor-external-api-client/references/architecture.md +127 -0
- package/dist/skills/hor-external-api-client/references/authorization.md +105 -0
- package/dist/skills/hor-external-api-client/references/capsule.md +130 -0
- package/dist/skills/hor-external-api-client/references/conventions.md +68 -0
- package/dist/skills/hor-external-api-client/references/launcher.md +138 -0
- package/dist/skills/hor-external-api-client/references/payload.md +176 -0
- package/dist/skills/hor-external-api-client/references/sdk-wrapper.md +291 -0
- package/dist/skills/hor-external-api-client/references/testing.md +130 -0
- package/dist/skills/hor-external-api-client/references/usage.md +152 -0
- package/dist/skills/hor-graphql-schema/SKILL.md +360 -0
- package/dist/skills/hor-graphql-server-engine/SKILL.md +356 -0
- package/dist/skills/hor-light-rag/SKILL.md +242 -0
- package/dist/skills/hor-light-rag/references/retrieval-internals.md +143 -0
- package/dist/skills/hor-multi-llm-provider/SKILL.md +288 -0
- package/dist/skills/hor-multi-llm-provider/references/provider-internals.md +153 -0
- package/dist/skills/hor-mutation-resolver/SKILL.md +360 -0
- package/dist/skills/hor-mutation-resolver/references/dependency-injection.md +148 -0
- package/dist/skills/hor-mutation-resolver/references/errors.md +120 -0
- package/dist/skills/hor-mutation-resolver/references/resolve-flow.md +275 -0
- package/dist/skills/hor-mutation-resolver/references/testing.md +125 -0
- package/dist/skills/hor-mutation-resolver/references/transaction.md +197 -0
- package/dist/skills/hor-post-worker/SKILL.md +320 -0
- package/dist/skills/hor-query-resolver/SKILL.md +246 -0
- package/dist/skills/hor-query-resolver/references/anatomy.md +384 -0
- package/dist/skills/hor-query-resolver/references/data-access.md +248 -0
- package/dist/skills/hor-query-resolver/references/errors-and-context.md +172 -0
- package/dist/skills/hor-query-resolver/references/testing.md +241 -0
- package/dist/skills/hor-renchan-job-bullmq/SKILL.md +178 -0
- package/dist/skills/hor-renchan-job-bullmq/references/daemon-and-scheduler.md +182 -0
- package/dist/skills/hor-renchan-job-bullmq/references/engine-and-infra.md +106 -0
- package/dist/skills/hor-renchan-job-bullmq/references/job-triple.md +189 -0
- package/dist/skills/hor-renchan-job-bullmq/references/queues.md +74 -0
- package/dist/skills/hor-renchan-job-bullmq/references/subscriptions.md +113 -0
- package/dist/skills/hor-resolver-share/SKILL.md +262 -0
- package/dist/skills/hor-resolver-validator/SKILL.md +194 -0
- package/dist/skills/hor-resolver-validator/references/inspector-api.md +115 -0
- package/dist/skills/hor-resolver-validator/references/validator-pattern.md +281 -0
- package/dist/skills/hor-restfulapi-architecture/SKILL.md +275 -0
- package/dist/skills/hor-restfulapi-architecture/references/engine-and-context.md +192 -0
- package/dist/skills/hor-restfulapi-architecture/references/renderers.md +204 -0
- package/dist/skills/hor-restfulapi-architecture/references/response-and-flusher.md +118 -0
- package/dist/skills/hor-restfulapi-architecture/references/validation.md +229 -0
- package/dist/skills/hor-security-audit/SKILL.md +110 -0
- package/dist/skills/hor-security-audit/references/application-surface.md +90 -0
- package/dist/skills/hor-security-audit/references/auth-and-transport.md +147 -0
- package/dist/skills/hor-security-audit/references/code-safety.md +74 -0
- package/dist/skills/hor-security-audit/references/dependencies.md +72 -0
- package/dist/skills/hor-security-audit/references/network-and-logging.md +56 -0
- package/dist/skills/hor-security-audit/references/secrets.md +95 -0
- package/dist/skills/hor-sequelize-migration/SKILL.md +336 -0
- package/dist/skills/hor-sequelize-migration/references/alter-table.md +147 -0
- package/dist/skills/hor-sequelize-migration/references/foreign-keys.md +107 -0
- package/dist/skills/hor-sequelize-migration/references/indexes.md +149 -0
- package/dist/skills/hor-sequelize-migration/references/notation.md +215 -0
- package/dist/skills/hor-sequelize-model/SKILL.md +69 -0
- package/dist/skills/hor-sequelize-model/references/associations.md +218 -0
- package/dist/skills/hor-sequelize-model/references/default-methods.md +244 -0
- package/dist/skills/hor-sequelize-model/references/mixins.md +247 -0
- package/dist/skills/hor-sequelize-model/references/notation.md +225 -0
- package/dist/skills/hor-sequelize-model/references/timestamps.md +74 -0
- package/dist/skills/hor-sequelize-seeder/SKILL.md +275 -0
- package/dist/skills/hor-sequelize-seeder/references/development-coverage.md +74 -0
- package/dist/skills/hor-sequelize-seeder/references/directory-structure.md +113 -0
- package/dist/skills/hor-sequelize-seeder/references/id-numbering.md +133 -0
- package/dist/skills/hor-sequelize-seeder/references/naming.md +59 -0
- package/dist/skills/hor-sequelize-seeder/references/notation.md +170 -0
- package/dist/skills/hor-sequelize-subquery/SKILL.md +369 -0
- package/dist/skills/hor-strategy-pattern/SKILL.md +371 -0
- package/dist/skills/hor-stub-api/SKILL.md +330 -0
- package/dist/skills/hor-subscription-resolver/SKILL.md +105 -0
- package/dist/skills/hor-subscription-resolver/references/authentication.md +99 -0
- package/dist/skills/hor-subscription-resolver/references/basic-notation.md +116 -0
- package/dist/skills/hor-subscription-resolver/references/design-philosophy.md +68 -0
- package/dist/skills/hor-type-interface/SKILL.md +200 -0
- package/docs/skills.ja.md +40 -0
- package/docs/skills.md +40 -0
- package/lib/equip/CommandLineArguments.js +178 -0
- package/lib/equip/HoraSkillsCli.js +590 -0
- package/lib/equip/SkillsInstaller.js +443 -0
- package/lib/equip/SkillsManifestFile.js +260 -0
- package/lib/equip/constants/CLI_COMMAND.js +8 -0
- package/lib/equip/hora-skills-ort-renchan.js +8 -0
- package/package.json +51 -0
|
@@ -0,0 +1,403 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-ai-agent-structure
|
|
3
|
+
description: >
|
|
4
|
+
Structure an app-side AI agent on @openreachtech/mentsu-agent-loop-core in a renchan backend: an
|
|
5
|
+
app/agents/<name>/ directory holding a ProceduralAgentLoop subclass (fixed procedure) plus
|
|
6
|
+
per-step BaseAgentAction subclasses, driven synchronously by a generator tool, each AI step
|
|
7
|
+
making one forced tool call. Use whenever the user asks to add or edit such an agent, an agent
|
|
8
|
+
action, or the generator that runs the loop. The iteration engine itself is a separate
|
|
9
|
+
convention.
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
# AI Agent Structure (app-side agents on mentsu-agent-loop-core)
|
|
13
|
+
|
|
14
|
+
This skill covers **how this backend structures an AI agent as application code** — the directory layout,
|
|
15
|
+
the `ProceduralAgentLoop` subclass, the per-step actions, and the `*Generator` that runs the loop. The
|
|
16
|
+
iteration engine, progress delivery, composition, job execution, and GraphQL integration are provided by
|
|
17
|
+
the `@openreachtech/mentsu-agent-loop-core` package family; see the **`hor-agent-loop` skill** for those. Do
|
|
18
|
+
not re-explain the core package here — this skill is only the app layer on top of it.
|
|
19
|
+
|
|
20
|
+
## Grand principle: the procedure is code, the AI only judges inside a step
|
|
21
|
+
|
|
22
|
+
An app agent here is a **`ProceduralAgentLoop`** whose steps are fixed in code (e.g. `plan → execute →
|
|
23
|
+
compose`), where each step either runs a **single forced AI tool call** or runs **deterministic code** —
|
|
24
|
+
never an open-ended "let the AI decide what to do next" loop.
|
|
25
|
+
|
|
26
|
+
- **Why a procedural loop, not an AI-driven one**: the business shape (search records, fill a form) is
|
|
27
|
+
known; only small judgments (is this a search request? what are the search steps? phrase the answer)
|
|
28
|
+
need the model. Fixing the procedure in `advanceState` keeps the flow reviewable, testable, and cheap
|
|
29
|
+
(usually one iteration), and confines model non-determinism to individual steps.
|
|
30
|
+
- **Why one forced tool call per AI step**: each AI step declares exactly one tool and forces it
|
|
31
|
+
(`toolChoices: [{ name }]`, `isAutoHandleFunctionCall: false`), then reads the function-call arguments
|
|
32
|
+
as the step's typed output. This turns a free-text model into a structured function returning a known
|
|
33
|
+
shape, so the surrounding code can validate and branch on it.
|
|
34
|
+
- **Why load the tool schema from the DB**: the tool JSON (name, description, parameters) lives in the
|
|
35
|
+
`AiTool` table, not in code. The action only holds the tool's **id**; swapping wording or parameters is
|
|
36
|
+
a data change, not a deploy. See the **`hor-ai-prompt-document-store` skill**.
|
|
37
|
+
- **Everything reaches AI / DB / services through `context`.** Actions and the loop never import an AI
|
|
38
|
+
client or a repository directly; they read `context.processor`, `context.recordSearchService`, etc. This
|
|
39
|
+
is the one-way dependency of the agent-loop core — keep it.
|
|
40
|
+
|
|
41
|
+
## Directory layout
|
|
42
|
+
|
|
43
|
+
One directory per agent under `app/agents/<agentName>/`, with the loop at the top and actions in
|
|
44
|
+
`actions/`:
|
|
45
|
+
|
|
46
|
+
```
|
|
47
|
+
app/agents/recordSearch/
|
|
48
|
+
RecordSearchAgentLoop.js extends ProceduralAgentLoop
|
|
49
|
+
actions/
|
|
50
|
+
BaseRecordSearchAgentAction.js extends BaseAgentAction (app base, abstract)
|
|
51
|
+
ClassifySearchIntentAction.js run standalone by the generator (intent gate)
|
|
52
|
+
PlanSearchAction.js registered: 'planSearch'
|
|
53
|
+
ExecuteSearchPlanAction.js registered: 'executeSearchPlan' (no AI — pure code)
|
|
54
|
+
ComposeAnswerAction.js registered: 'composeAnswer'
|
|
55
|
+
```
|
|
56
|
+
|
|
57
|
+
The runner/wiring lives one level up in `app/tools/<Agent>Generator.js` (e.g.
|
|
58
|
+
`RecordSearchGenerator.js`). Keep the layout identical across agents so review attention goes to the
|
|
59
|
+
agent's *procedure*.
|
|
60
|
+
|
|
61
|
+
## 1. The loop — a `ProceduralAgentLoop` subclass
|
|
62
|
+
|
|
63
|
+
Override these members (no constructor, no `static create` — `InlineAgentRunner` instantiates the loop
|
|
64
|
+
with the `context`):
|
|
65
|
+
|
|
66
|
+
| Member | Responsibility |
|
|
67
|
+
| --- | --- |
|
|
68
|
+
| `#get:maxIterations` | Iteration cap (a procedural agent usually finishes in 1; e.g. `4`) |
|
|
69
|
+
| `#get:registry` | `AgentActionRegistry.create({ actions: [...] })` — the actions the procedure can call |
|
|
70
|
+
| `#createInitialState({ input })` | The starting state object (e.g. `{ result: null }`) |
|
|
71
|
+
| `#advanceState({ state })` | **The procedure body** — the ordered steps |
|
|
72
|
+
| `#isComplete({ state })` | Stop condition (e.g. `Boolean(state.result)`) |
|
|
73
|
+
| `#buildResult({ state })` | The final return value (e.g. `state.result`) |
|
|
74
|
+
|
|
75
|
+
`#advanceState()` calls `this.performAction({ name, argumentHash, context })` for each step, matching an
|
|
76
|
+
action by its `#get:name`. Deterministic branches (e.g. "couldn't understand the request") are written as
|
|
77
|
+
plain code between the AI steps.
|
|
78
|
+
|
|
79
|
+
```js
|
|
80
|
+
import {
|
|
81
|
+
ProceduralAgentLoop,
|
|
82
|
+
AgentActionRegistry,
|
|
83
|
+
} from '@openreachtech/mentsu-agent-loop-core'
|
|
84
|
+
|
|
85
|
+
import PlanSearchAction from './actions/PlanSearchAction.js'
|
|
86
|
+
import ExecuteSearchPlanAction from './actions/ExecuteSearchPlanAction.js'
|
|
87
|
+
import ComposeAnswerAction from './actions/ComposeAnswerAction.js'
|
|
88
|
+
|
|
89
|
+
export default class RecordSearchAgentLoop extends ProceduralAgentLoop {
|
|
90
|
+
get maxIterations () {
|
|
91
|
+
return 4
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
get registry () {
|
|
95
|
+
return AgentActionRegistry.create({
|
|
96
|
+
actions: [
|
|
97
|
+
PlanSearchAction.create(),
|
|
98
|
+
ExecuteSearchPlanAction.create(),
|
|
99
|
+
ComposeAnswerAction.create(),
|
|
100
|
+
],
|
|
101
|
+
})
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
createInitialState ({
|
|
105
|
+
input,
|
|
106
|
+
}) {
|
|
107
|
+
return {
|
|
108
|
+
result: null,
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
async advanceState ({
|
|
113
|
+
state,
|
|
114
|
+
}) {
|
|
115
|
+
const plan = await this.performAction({
|
|
116
|
+
name: 'planSearch',
|
|
117
|
+
argumentHash: {
|
|
118
|
+
message: this.context.message,
|
|
119
|
+
searchableCategories: this.context.searchableCategories,
|
|
120
|
+
},
|
|
121
|
+
context: this.context,
|
|
122
|
+
})
|
|
123
|
+
|
|
124
|
+
if (!plan) {
|
|
125
|
+
return {
|
|
126
|
+
...state,
|
|
127
|
+
result: {
|
|
128
|
+
message: 'I could not turn that into a record search. Could you rephrase what you are looking for?',
|
|
129
|
+
targetRecords: [],
|
|
130
|
+
},
|
|
131
|
+
}
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
const executed = await this.performAction({
|
|
135
|
+
name: 'executeSearchPlan',
|
|
136
|
+
argumentHash: {
|
|
137
|
+
plan,
|
|
138
|
+
},
|
|
139
|
+
context: this.context,
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
const answer = await this.performAction({
|
|
143
|
+
name: 'composeAnswer',
|
|
144
|
+
argumentHash: {
|
|
145
|
+
message: this.context.message,
|
|
146
|
+
resultSummary: {
|
|
147
|
+
foundCount: executed.targetRecords.length,
|
|
148
|
+
isTruncated: executed.isTruncated,
|
|
149
|
+
resultCategoryName: this.resolveCategoryName({
|
|
150
|
+
originObjectCategoryId: executed.resultOriginObjectCategoryId,
|
|
151
|
+
}),
|
|
152
|
+
},
|
|
153
|
+
},
|
|
154
|
+
context: this.context,
|
|
155
|
+
})
|
|
156
|
+
|
|
157
|
+
return {
|
|
158
|
+
...state,
|
|
159
|
+
result: {
|
|
160
|
+
message: answer.message,
|
|
161
|
+
targetRecords: executed.targetRecords,
|
|
162
|
+
},
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
isComplete ({
|
|
167
|
+
state,
|
|
168
|
+
}) {
|
|
169
|
+
return Boolean(state.result)
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
buildResult ({
|
|
173
|
+
state,
|
|
174
|
+
}) {
|
|
175
|
+
return state.result
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
- **State is updated immutably** (`{ ...state, ... }`) — never mutate it in place.
|
|
181
|
+
- **`registry` is rebuilt each access** — it is cheap and keeps the getter pure.
|
|
182
|
+
- Progress within the procedure is forwarded through `this.context.notifyProgress?.({ phase, status })`
|
|
183
|
+
(a no-op unless the caller sets it), not through the runner's `onProgress`.
|
|
184
|
+
|
|
185
|
+
## 2. Actions — an app base over `BaseAgentAction`, one forced tool call each
|
|
186
|
+
|
|
187
|
+
Each agent has an abstract app base (e.g. `BaseRecordSearchAgentAction extends BaseAgentAction`) holding
|
|
188
|
+
the shared forced-tool helpers; each concrete action overrides `#get:name`, `#get:description`, and
|
|
189
|
+
`#run()`.
|
|
190
|
+
|
|
191
|
+
App-base helpers (the forced-single-tool machinery):
|
|
192
|
+
|
|
193
|
+
| Method | Responsibility |
|
|
194
|
+
| --- | --- |
|
|
195
|
+
| `#loadToolPayloadObject({ aiToolId })` | `AiTool.findByPk(aiToolId)` → `JSON.parse(payload)`, `null` on missing/parse error |
|
|
196
|
+
| `#sendForcedToolRequest({ context, instruction, toolPayloadObject })` | one AI turn: `context.processor.sendRequestToAi(...)` forcing the single tool |
|
|
197
|
+
| `#extractFunctionCallFromAiResponse({ response, toolName })` | first function call whose name matches, else `null` |
|
|
198
|
+
| `#parseFunctionCallArguments({ functionCall })` | parse `functionCall.arguments` (string→JSON), `null` on error |
|
|
199
|
+
|
|
200
|
+
```js
|
|
201
|
+
import {
|
|
202
|
+
BaseAgentAction,
|
|
203
|
+
} from '@openreachtech/mentsu-agent-loop-core'
|
|
204
|
+
|
|
205
|
+
import AiTool from '../../../../sequelize/models/AiTool.js'
|
|
206
|
+
|
|
207
|
+
/** @abstract */
|
|
208
|
+
export default class BaseRecordSearchAgentAction extends BaseAgentAction {
|
|
209
|
+
async loadToolPayloadObject ({
|
|
210
|
+
aiToolId,
|
|
211
|
+
}) {
|
|
212
|
+
const aiTool = await AiTool.findByPk(aiToolId)
|
|
213
|
+
|
|
214
|
+
if (!aiTool) {
|
|
215
|
+
return null
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
try {
|
|
219
|
+
return JSON.parse(aiTool.payload)
|
|
220
|
+
} catch (error) {
|
|
221
|
+
return null
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
async sendForcedToolRequest ({
|
|
226
|
+
context,
|
|
227
|
+
instruction,
|
|
228
|
+
toolPayloadObject,
|
|
229
|
+
}) {
|
|
230
|
+
return context.processor.sendRequestToAi({
|
|
231
|
+
aiAgent: context.aiAgent,
|
|
232
|
+
documents: context.documents,
|
|
233
|
+
extraToolOptions: {},
|
|
234
|
+
fileUrls: context.files,
|
|
235
|
+
historyMessages: context.historyMessages,
|
|
236
|
+
instruction,
|
|
237
|
+
isAutoHandleFunctionCall: false,
|
|
238
|
+
toolChoices: [
|
|
239
|
+
{
|
|
240
|
+
name: toolPayloadObject.name,
|
|
241
|
+
},
|
|
242
|
+
],
|
|
243
|
+
tools: [
|
|
244
|
+
toolPayloadObject,
|
|
245
|
+
],
|
|
246
|
+
})
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
```
|
|
250
|
+
|
|
251
|
+
A concrete AI action then runs the fixed flow — load tool → build instruction → force the call → extract
|
|
252
|
+
→ parse → return a typed value (return `null` / a fallback on any failure, never `undefined`):
|
|
253
|
+
|
|
254
|
+
```js
|
|
255
|
+
export default class PlanSearchAction extends BaseRecordSearchAgentAction {
|
|
256
|
+
get name () {
|
|
257
|
+
return 'planSearch'
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
get description () {
|
|
261
|
+
return 'Decompose the request into ordered record-search steps'
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
get toolName () {
|
|
265
|
+
return 'plan_record_search'
|
|
266
|
+
}
|
|
267
|
+
|
|
268
|
+
async run ({
|
|
269
|
+
argumentHash: {
|
|
270
|
+
message,
|
|
271
|
+
searchableCategories,
|
|
272
|
+
},
|
|
273
|
+
context,
|
|
274
|
+
}) {
|
|
275
|
+
const toolPayloadObject = await this.loadToolPayloadObject({
|
|
276
|
+
aiToolId: context.planRecordSearchAiToolId,
|
|
277
|
+
})
|
|
278
|
+
|
|
279
|
+
if (!toolPayloadObject) {
|
|
280
|
+
return null
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const instruction = this.buildInstruction({
|
|
284
|
+
message,
|
|
285
|
+
searchableCategories,
|
|
286
|
+
})
|
|
287
|
+
|
|
288
|
+
const response = await this.sendForcedToolRequest({
|
|
289
|
+
context,
|
|
290
|
+
instruction,
|
|
291
|
+
toolPayloadObject,
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
if (response.hasError()) {
|
|
295
|
+
return null
|
|
296
|
+
}
|
|
297
|
+
|
|
298
|
+
const functionCall = this.extractFunctionCallFromAiResponse({
|
|
299
|
+
response,
|
|
300
|
+
toolName: this.toolName,
|
|
301
|
+
})
|
|
302
|
+
|
|
303
|
+
if (!functionCall) {
|
|
304
|
+
return null
|
|
305
|
+
}
|
|
306
|
+
|
|
307
|
+
const parsed = this.parseFunctionCallArguments({
|
|
308
|
+
functionCall,
|
|
309
|
+
})
|
|
310
|
+
|
|
311
|
+
return this.normalizePlan({
|
|
312
|
+
functionCall: parsed,
|
|
313
|
+
searchableCategories,
|
|
314
|
+
})
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
```
|
|
318
|
+
|
|
319
|
+
- **Instructions embed user data in CDATA** (`<user_request><![CDATA[${message}]]></user_request>`) so
|
|
320
|
+
free text cannot break the prompt structure.
|
|
321
|
+
- **The model's output is always re-validated in code** (e.g. `#normalizePlan()` checks every category id
|
|
322
|
+
against the catalog and returns `null` if anything is off) — never trust the raw function-call arguments.
|
|
323
|
+
- **A non-AI action is just code**: `ExecuteSearchPlanAction` has no `toolName` and no AI turn; it
|
|
324
|
+
drives `context.recordSearchService` and returns records.
|
|
325
|
+
|
|
326
|
+
## 3. The generator — build `context` and run via `InlineAgentRunner`
|
|
327
|
+
|
|
328
|
+
The loop is run **synchronously, in-process** (no Redis) by an `app/tools/<Agent>Generator.js`. The
|
|
329
|
+
generator assembles the `context` (all dependencies the loop and actions read), then:
|
|
330
|
+
|
|
331
|
+
```js
|
|
332
|
+
import {
|
|
333
|
+
InlineAgentRunner,
|
|
334
|
+
} from '@openreachtech/mentsu-agent-loop-core'
|
|
335
|
+
|
|
336
|
+
import RecordSearchAgentLoop from '../agents/recordSearch/RecordSearchAgentLoop.js'
|
|
337
|
+
|
|
338
|
+
// inside the generator method:
|
|
339
|
+
const runner = InlineAgentRunner.create({
|
|
340
|
+
AgentLoopCtor: RecordSearchAgentLoop,
|
|
341
|
+
context: {
|
|
342
|
+
...chatContext,
|
|
343
|
+
searchableCategories,
|
|
344
|
+
recordSearchService: this.recordSearchService,
|
|
345
|
+
},
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
const result = await runner.request({
|
|
349
|
+
input: {},
|
|
350
|
+
onProgress: () => {
|
|
351
|
+
// phase progress is forwarded through context.notifyProgress instead
|
|
352
|
+
},
|
|
353
|
+
})
|
|
354
|
+
```
|
|
355
|
+
|
|
356
|
+
The assembled `context` is exactly the object the loop reads as `this.context` and each action receives as
|
|
357
|
+
`context`. Its keys are the agent's dependency contract — for the record-search agent:
|
|
358
|
+
|
|
359
|
+
| Key | What it is |
|
|
360
|
+
| --- | --- |
|
|
361
|
+
| `message` | the user input / question |
|
|
362
|
+
| `aiAgent` | the DB agent config (instruction, model) |
|
|
363
|
+
| `historyMessages`, `files`, `documents` | chat history, attachments, RAG documents |
|
|
364
|
+
| `processor` | the LLM processor (see the `hor-multi-llm-provider` skill) |
|
|
365
|
+
| `searchableCategories` | the catalog the plan/execute steps work over |
|
|
366
|
+
| `recordSearchService` | the deterministic search/traversal service |
|
|
367
|
+
| `<step>AiToolId` | the `AiTool` ids the AI actions load their schema from |
|
|
368
|
+
| `notifyProgress` | optional progress callback (set only by the standalone worker) |
|
|
369
|
+
|
|
370
|
+
Two entrypoints on the generator are common:
|
|
371
|
+
|
|
372
|
+
- **Chat flow** (`#generate(...)`) runs a standalone **intent gate first** — it creates
|
|
373
|
+
`ClassifySearchIntentAction` directly (not in the loop registry) and returns `null` when the input is
|
|
374
|
+
ordinary conversation, so the loop only runs for real requests.
|
|
375
|
+
- **Explicit flow** (`#generateForExplicitSearch(...)`) skips the gate, passes empty history/files, and
|
|
376
|
+
sets `notifyProgress` for streaming.
|
|
377
|
+
|
|
378
|
+
A `static createWithDefaults(...)` wires the concrete services so callers do not hand-assemble them.
|
|
379
|
+
|
|
380
|
+
## 4. Exposing the agent
|
|
381
|
+
|
|
382
|
+
The GraphQL mutation resolvers under `server/graphql/resolvers/user/actual/mutations/` (e.g.
|
|
383
|
+
`SendMessageToChatRoomMutationResolver`, `GenerateRecordFieldValuesByAiMutationResolver`) build the
|
|
384
|
+
processor + context and call the generator. Because the loop runs in-process via `InlineAgentRunner`, no
|
|
385
|
+
job/queue is involved; to run the same loop as a background job with progress streaming, use the
|
|
386
|
+
**`hor-agent-loop` skill** (`renchan-job` / `graphql` adapters) instead of the synchronous runner.
|
|
387
|
+
|
|
388
|
+
## Cross-cutting rules
|
|
389
|
+
|
|
390
|
+
- **All dependencies flow through `context`** — never import an AI client, model, or service inside a loop
|
|
391
|
+
or action.
|
|
392
|
+
- **Return `null` / a fallback for missing values, not `undefined`.** Every AI step must have a
|
|
393
|
+
deterministic fallback (return `null`, or a canned message) so a model failure never crashes the flow.
|
|
394
|
+
- **Re-validate every model output in code** before using it.
|
|
395
|
+
- **One class per file, one `export default`**; getters return a constant/field; the state object is
|
|
396
|
+
updated immutably.
|
|
397
|
+
- Match the surrounding style (no semicolons, one property per line, `map`/`filter`/`reduce` over loops).
|
|
398
|
+
|
|
399
|
+
## Detail files
|
|
400
|
+
|
|
401
|
+
- [loop-and-actions.md](./references/loop-and-actions.md) — the full `RecordSearchAgentLoop` procedure and
|
|
402
|
+
all four actions method-by-method, plus the `RecordFieldValuesAgentLoop` variant (branching procedure,
|
|
403
|
+
no progress) to show what changes between agents.
|
|
@@ -0,0 +1,100 @@
|
|
|
1
|
+
# Loop and actions in full (record-search + record-field-values agents)
|
|
2
|
+
|
|
3
|
+
Referenced from `SKILL.md`. This walks the two concrete agents method-by-method so a new agent can be
|
|
4
|
+
modeled on them. The core-package members (`ProceduralAgentLoop`, `BaseAgentAction`, `AgentActionRegistry`,
|
|
5
|
+
`InlineAgentRunner`) belong to the `hor-agent-loop` skill; here we only show how the app uses them.
|
|
6
|
+
|
|
7
|
+
## Record-search agent — the linear `plan → execute → compose` procedure
|
|
8
|
+
|
|
9
|
+
`RecordSearchAgentLoop extends ProceduralAgentLoop`. Overrides, in order:
|
|
10
|
+
|
|
11
|
+
- `#get:maxIterations` → `4` (the procedure normally completes in one iteration; the cap is a safety net).
|
|
12
|
+
- `#get:registry` → `AgentActionRegistry.create({ actions: [PlanSearchAction.create(), ExecuteSearchPlanAction.create(), ComposeAnswerAction.create()] })`. **`ClassifySearchIntentAction` is intentionally not here** — it is the gate, run by the generator before the loop.
|
|
13
|
+
- `#createInitialState({ input })` → `{ result: null }` (`input` unused).
|
|
14
|
+
- `#advanceState({ state })` — the body:
|
|
15
|
+
1. progress `plan_search / started`
|
|
16
|
+
2. `plan = await this.performAction({ name: 'planSearch', argumentHash: { message, searchableCategories }, context })`
|
|
17
|
+
3. `if (!plan)` → return a canned "couldn't understand" result with empty `targetRecords` (deterministic branch, no more AI)
|
|
18
|
+
4. progress plan completed / execute started; `executed = await this.performAction({ name: 'executeSearchPlan', argumentHash: { plan }, context })`
|
|
19
|
+
5. progress execute completed (`foundCount`) / compose started; `answer = await this.performAction({ name: 'composeAnswer', argumentHash: { message, resultSummary: { foundCount, isTruncated, resultCategoryName } } })`
|
|
20
|
+
6. return `{ ...state, result: { message: answer.message, targetRecords: executed.targetRecords } }`
|
|
21
|
+
- `#isComplete({ state })` → `Boolean(state.result)`.
|
|
22
|
+
- `#buildResult({ state })` → `state.result`.
|
|
23
|
+
|
|
24
|
+
Helpers: `#resolveCategoryName({ originObjectCategoryId })` looks the name up in `context.searchableCategories`
|
|
25
|
+
(`matched?.name ?? null`); `#notifyProgress({ phase, status, foundCount = null })` calls
|
|
26
|
+
`this.context.notifyProgress?.(...)` (no-op in the chat flow, wired only by the standalone search worker).
|
|
27
|
+
|
|
28
|
+
### The four actions
|
|
29
|
+
|
|
30
|
+
All extend `BaseRecordSearchAgentAction` (which holds the forced-tool helpers from `SKILL.md`). Each AI
|
|
31
|
+
action overrides `#get:name`, `#get:description`, `#get:toolName`, and `#run()`.
|
|
32
|
+
|
|
33
|
+
| Action | `name` | `toolName` | AI? | `#run()` returns |
|
|
34
|
+
| --- | --- | --- | --- | --- |
|
|
35
|
+
| `ClassifySearchIntentAction` | `classifySearchIntent` | `classify_search_intent` | yes | `boolean` (`parsed?.isRecordSearch === true`); `false` on any failure |
|
|
36
|
+
| `PlanSearchAction` | `planSearch` | `plan_record_search` | yes | `RecordSearchPlan \| null` (validated) |
|
|
37
|
+
| `ExecuteSearchPlanAction` | `executeSearchPlan` | — | **no** | `{ targetRecords, isTruncated, resultOriginObjectCategoryId }` |
|
|
38
|
+
| `ComposeAnswerAction` | `composeAnswer` | `compose_search_answer` | yes | `{ message }` (always — fallback if AI fails) |
|
|
39
|
+
|
|
40
|
+
- **`ClassifySearchIntentAction#run()`** — loads its tool (`context.classifySearchIntentAiToolId`); on
|
|
41
|
+
missing tool / `response.hasError()` / no function call → `false`; else parse and return
|
|
42
|
+
`parsed?.isRecordSearch === true`. The gate defaults to "not a search" whenever anything is uncertain.
|
|
43
|
+
- **`PlanSearchAction#run()`** — forced-tool flow, then `#normalizePlan({ functionCall, searchableCategories })`.
|
|
44
|
+
Normalization is strict: every step's category id must be in the catalog `Set`; the plan must be
|
|
45
|
+
non-empty; the first step must be `kind: 'anchor'`; `resultStepIndex` must be in range; an
|
|
46
|
+
`association` step's `fromStepIndex` must reference an earlier step (`0 <= fromStepIndex < index`, 1-hop
|
|
47
|
+
only). Any violation → `null`, which the loop turns into the "couldn't understand" branch.
|
|
48
|
+
- **`ExecuteSearchPlanAction#run()`** — **no AI**. `#executeSteps()` runs the steps sequentially with a
|
|
49
|
+
`reduce` over `Promise.resolve([])`, threading prior results; an `anchor` step calls
|
|
50
|
+
`context.recordSearchService.searchAnchorRecords({ originObjectCategoryId, keyword })`, an `association`
|
|
51
|
+
step calls `context.recordSearchService.findAssociatedRecords({ targetOriginObjectCategoryId, sourceRecords })`
|
|
52
|
+
using `priorResults[step.fromStepIndex]`. It then picks `stepResults[plan.resultStepIndex]`.
|
|
53
|
+
- **`ComposeAnswerAction#run()`** — computes a deterministic `#buildFallbackMessage()` first, loads its
|
|
54
|
+
tool, and returns `{ message: parsed.message }` only when the AI produced a non-empty string; otherwise
|
|
55
|
+
returns `{ message: fallbackMessage }`. **This step never returns null** — the user always gets a reply.
|
|
56
|
+
|
|
57
|
+
### Instruction building (shared shape)
|
|
58
|
+
|
|
59
|
+
Each AI action's `#buildInstruction(...)` joins a `lines` array with `\n` and embeds user/catalog data in
|
|
60
|
+
CDATA blocks, e.g. `<user_request><![CDATA[${message}]]></user_request>` and
|
|
61
|
+
`<searchable_categories>${categoriesJson}</searchable_categories>`, and states "call the tool `<toolName>`
|
|
62
|
+
exactly once." Serialized catalogs carry only the minimum fields (`originObjectCategoryId`, `name`).
|
|
63
|
+
|
|
64
|
+
## Record-field-values agent — a branching `narrow → search → fill` procedure
|
|
65
|
+
|
|
66
|
+
`RecordFieldValuesAgentLoop extends ProceduralAgentLoop` follows the same skeleton but shows what varies
|
|
67
|
+
between agents:
|
|
68
|
+
|
|
69
|
+
- `#get:maxIterations` → `3`.
|
|
70
|
+
- `#get:registry` → `SelectSearchTargetsAction`, `SearchEditOptionsAction`, `FillFormAction`.
|
|
71
|
+
- `#createInitialState()` → `{ searchedOptionsByColumnId: {}, result: null }` (richer than record-search).
|
|
72
|
+
- `#advanceState()` has **conditional branches** (not a fixed linear chain):
|
|
73
|
+
- `searchableColumns = context.editableColumns.filter(column => column.searchOption?.hasTextSearch === true)`
|
|
74
|
+
- `targets` = `[]` when there are no searchable columns, else `selectSearchTargets`
|
|
75
|
+
- `searchedOptionsByColumnId` = `{}` when there are no targets, else `searchEditOptions`
|
|
76
|
+
- always `filled = fillForm({ message, editableColumns, currentValues, fixedOptionsByColumnId, searchedOptionsByColumnId })`
|
|
77
|
+
- returns `{ ...state, searchedOptionsByColumnId, result: filled }` where `filled` is `{ message, updateValues }`
|
|
78
|
+
- `#isComplete()` / `#buildResult()` identical to record-search.
|
|
79
|
+
- **No `notifyProgress`** — this agent does not emit phase progress.
|
|
80
|
+
- Context keys used: `editableColumns`, `message`, `currentValues`, `fixedOptionsByColumnId` (vs
|
|
81
|
+
record-search's `message`, `searchableCategories`, `notifyProgress`).
|
|
82
|
+
|
|
83
|
+
The takeaway: the **skeleton is fixed** (six overridden members, immutable state, actions matched by
|
|
84
|
+
`name`), and what an agent customizes is the **procedure in `#advanceState()`**, the **action set in
|
|
85
|
+
`#get:registry`**, and the **context keys** its steps read.
|
|
86
|
+
|
|
87
|
+
## The forced-single-tool turn (shared by every AI action)
|
|
88
|
+
|
|
89
|
+
The pattern, provided once on the app base and reused by all AI actions:
|
|
90
|
+
|
|
91
|
+
1. `toolPayloadObject = await this.loadToolPayloadObject({ aiToolId })` — the tool JSON from the `AiTool`
|
|
92
|
+
table (see the `hor-ai-prompt-document-store` skill); `null` guards the step.
|
|
93
|
+
2. `instruction = this.buildInstruction(...)` — CDATA-wrapped user data + "call `<toolName>` once".
|
|
94
|
+
3. `response = await this.sendForcedToolRequest({ context, instruction, toolPayloadObject })` — one turn
|
|
95
|
+
with `isAutoHandleFunctionCall: false`, `toolChoices: [{ name }]`, `tools: [toolPayloadObject]` (see the
|
|
96
|
+
`hor-multi-llm-provider` skill for `context.processor.sendRequestToAi`).
|
|
97
|
+
4. `if (response.hasError())` → fallback/`null`.
|
|
98
|
+
5. `functionCall = this.extractFunctionCallFromAiResponse({ response, toolName })` → `null` guard.
|
|
99
|
+
6. `parsed = this.parseFunctionCallArguments({ functionCall })` → the typed step output, then
|
|
100
|
+
**re-validated in code** before use.
|