@openreachtech/hora-skills-ort-renchan 0.4.0 → 0.6.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.
|
@@ -17,6 +17,9 @@ iteration engine, progress delivery, composition, job execution, and GraphQL int
|
|
|
17
17
|
the `@openreachtech/mentsu-agent-loop-core` package family; see the **`hor-agent-loop` skill** for those. Do
|
|
18
18
|
not re-explain the core package here — this skill is only the app layer on top of it.
|
|
19
19
|
|
|
20
|
+
If what a turn needs is not known until the message is read (an open chat assistant), see
|
|
21
|
+
**`/hor-chat-agent-loop`**.
|
|
22
|
+
|
|
20
23
|
## Grand principle: the procedure is code, the AI only judges inside a step
|
|
21
24
|
|
|
22
25
|
An app agent here is a **`ProceduralAgentLoop`** whose steps are fixed in code (e.g. `plan → execute →
|
|
@@ -0,0 +1,287 @@
|
|
|
1
|
+
---
|
|
2
|
+
name: hor-chat-agent-loop
|
|
3
|
+
description: "How to build a conversational AI agent whose turn the model decides — planner, executor, loop monitor, responder — and where code ends and the prompt begins. Use when adding or changing a chat assistant, its tools, its choice chips or its fixed actions. A fixed step-by-step procedure belongs to the AI agent structure convention; the iteration engine and job/progress plumbing to the agent loop convention."
|
|
4
|
+
---
|
|
5
|
+
|
|
6
|
+
# Chat Agent Loop (a conversation the model plans, turn by turn)
|
|
7
|
+
|
|
8
|
+
This skill covers **how a chat assistant decides what one turn does** — ask back, answer from a tool,
|
|
9
|
+
answer with no tool, or run a fixed action — and how that decision is split between the model and the
|
|
10
|
+
code. It is for an assistant the person can ask *anything*: what a turn needs is not known until the
|
|
11
|
+
message is read.
|
|
12
|
+
|
|
13
|
+
Where this skill stops:
|
|
14
|
+
|
|
15
|
+
- **A procedure whose steps are known in advance** (search records, fill a form) is a fixed
|
|
16
|
+
`ProceduralAgentLoop` with one forced tool call per step. That is `/hor-ai-agent-structure`. Reach
|
|
17
|
+
for this skill only when what is left after fixing the steps is still "it depends on what was
|
|
18
|
+
asked".
|
|
19
|
+
- **Running the loop** — the iteration engine, running it as a job, streaming its progress — is
|
|
20
|
+
`/hor-agent-loop`. This skill says what the loop decides, not how it is executed.
|
|
21
|
+
- **Calling the model** (providers, request shapes) is `/hor-multi-llm-provider`.
|
|
22
|
+
|
|
23
|
+
## Grand principle: the model decides what the turn needs, the code decides whether it goes on
|
|
24
|
+
|
|
25
|
+
- **The model judges.** Whether to ask back, which tools to call, with which arguments, and what the
|
|
26
|
+
answer says are the model's decisions. Code never adds a tool the model did not choose, and never
|
|
27
|
+
rewrites the person's words.
|
|
28
|
+
- **The code has the last word on what must hold whatever the model says** — and only on that.
|
|
29
|
+
Every model output is re-validated for shape; cost and time limits (rounds, tool calls, timeouts)
|
|
30
|
+
are enforced; whether the loop retries after an empty round is a code rule. What needs the
|
|
31
|
+
conversation's meaning is never decided in code (next section).
|
|
32
|
+
- **One flow for every turn.** A typed message, a choice chip and a follow-up all go through the same
|
|
33
|
+
planner. The only turns that bypass it are fixed actions, which say so with an `actionKey`
|
|
34
|
+
(below) — never by special-casing words.
|
|
35
|
+
|
|
36
|
+
The failures this prevents:
|
|
37
|
+
|
|
38
|
+
| Failure | What it did | Rule that prevents it |
|
|
39
|
+
| --- | --- | --- |
|
|
40
|
+
| A chip glued a request onto the choice ("Not decided yet" → "Show me items about not decided yet") | The conversation's subject was lost; the planner searched for the glued sentence | A reply chip sends its words as they are |
|
|
41
|
+
| The search tool ran on every answered turn | "What is my role?" and "Say that in one line" got item cards | The executor runs only what the planner chose; zero calls is valid |
|
|
42
|
+
| Tool rules lived in the planner's instruction | Adding a tool meant editing the global prompt; rules for one tool leaked into every turn | Each tool carries its own usage rules |
|
|
43
|
+
| "Searching…" was shown before the plan existed | A turn that searched nothing said it was searching | Openers are published only after the plan calls a presenting tool |
|
|
44
|
+
|
|
45
|
+
## What code decides, what the prompt decides
|
|
46
|
+
|
|
47
|
+
This is the line every other rule in this skill sits on. Draw it before writing either.
|
|
48
|
+
|
|
49
|
+
**The test: does deciding it require reading what the conversation means?** If it does, the model
|
|
50
|
+
decides it, and the rule is written in the prompt. Code never approximates a meaning with a count,
|
|
51
|
+
a length, a keyword or a string match. If it does not — it must hold whatever the model says, or it
|
|
52
|
+
is about money, time, permission or shape — code enforces it.
|
|
53
|
+
|
|
54
|
+
| Code enforces | The prompt decides |
|
|
55
|
+
| --- | --- |
|
|
56
|
+
| Whose data a tool may read (the engine fixes the person; the model never names one) | Whether to ask back, and how many times for this concern |
|
|
57
|
+
| Input validation at the API boundary, including `actionKey` | Whether a message opens a new concern or continues the last one |
|
|
58
|
+
| The shape of every model output (JSON, known handling, known tool, argument types, length caps) | What the subject is, and what the standalone query says |
|
|
59
|
+
| Cost and time caps: rounds, tool calls per round, timeouts | Which tools to call, or none |
|
|
60
|
+
| A safe fallback when the model fails or its reply is unreadable | Whether an answer ends with a question, and which |
|
|
61
|
+
| Fixed actions behind an `actionKey` | What to say when nothing was found |
|
|
62
|
+
| How many cards are drawn | Which answer options a question back offers |
|
|
63
|
+
| How much history is read (a cost cap — set it wide enough for the judgments above) | Tone, length, wording |
|
|
64
|
+
|
|
65
|
+
**Typical ways code ends up judging meaning**, and where each rule belongs instead:
|
|
66
|
+
|
|
67
|
+
| Code that judged meaning | What goes wrong | Where it belongs |
|
|
68
|
+
| --- | --- | --- |
|
|
69
|
+
| "From the person's Nth message on, always answer" | A new concern raised late in the chat gets no clarification: a count of messages stood in for "how often was *this concern* asked about" | The prompt: a few questions per concern, counted by the model from the conversation |
|
|
70
|
+
| "A question back is a short line ending in `?`" | A heuristic for the same judgment, one step closer and still wrong | The same prompt rule; delete the heuristic |
|
|
71
|
+
| A chip's topic derived from the majority category of the shown results | A follow-up offered on a subject the person never raised | The chip sends plain words; the planner resolves the subject |
|
|
72
|
+
| "The previous question" picked by string matching | The chip points at whatever message last failed the match | The chip says "Also show items related to my previous question"; the planner reads the conversation |
|
|
73
|
+
| A canned question when nothing was found | The same fixed sentence whatever was asked | The responder says nothing was found and may ask one question of its own |
|
|
74
|
+
| The model's answer options discarded when another field was empty | The person loses the choices that answered the question | Keep the model's options; only their format is checked |
|
|
75
|
+
| Per-variant behaviour written into the orchestrator | Adding a variant means editing the worker; the worker grows variant-key literals | The tool's own settings (section 2) |
|
|
76
|
+
| A history window of a few exchanges | Two questions back and an answer fill it; the earlier concern is out of sight | A wider window; it is a cost cap, so set it for the judgments it serves |
|
|
77
|
+
|
|
78
|
+
**Signs a rule is on the wrong side:** a constant named `MAX_…_BEFORE_…` that changes what the
|
|
79
|
+
assistant says; a regular expression over the person's or the assistant's words; a suffix glued onto
|
|
80
|
+
text the model or the person will read; a `variantKey === '…'` outside the tool's settings.
|
|
81
|
+
|
|
82
|
+
## The four layers
|
|
83
|
+
|
|
84
|
+
| Layer | Owns | Must not |
|
|
85
|
+
| --- | --- | --- |
|
|
86
|
+
| **Planner** | One model call per turn: the handling, the tool calls with their arguments, a standalone query, a question back | Write the answer; run anything |
|
|
87
|
+
| **Executor** | Running exactly the planned calls, side by side | Add, drop or reword a call |
|
|
88
|
+
| **Loop monitor** | Deciding after each round: respond, retry, ask back — from an ordered table of code rules | Call the model |
|
|
89
|
+
| **Responder** | Writing the reply from what the tools observed, with or without cards | Decide which tools run |
|
|
90
|
+
|
|
91
|
+
A turn is: plan → (round → monitor)* → respond, with at most a fixed number of rounds (two is usually
|
|
92
|
+
enough: the planner's calls, then one retry the monitor asked for).
|
|
93
|
+
|
|
94
|
+
## 1. The planner — one structured decision
|
|
95
|
+
|
|
96
|
+
The planner returns one JSON object (or one forced tool call — see the mapping section). A shape that
|
|
97
|
+
holds up:
|
|
98
|
+
|
|
99
|
+
```json
|
|
100
|
+
{
|
|
101
|
+
"handling": "answer | clarify | small_talk | refuse | refer_to_human",
|
|
102
|
+
"acknowledgment": "opening line, only when a presenting tool is called",
|
|
103
|
+
"question": "the one question back, only for clarify",
|
|
104
|
+
"options": ["short answers the person can tap"],
|
|
105
|
+
"reply": "only for small_talk",
|
|
106
|
+
"standaloneQuery": "the request rewritten to stand on its own",
|
|
107
|
+
"toolCalls": [{ "toolName": "...", "arguments": {} }]
|
|
108
|
+
}
|
|
109
|
+
```
|
|
110
|
+
|
|
111
|
+
- **`answer` covers answering with tools and without.** A general question, a reply in the
|
|
112
|
+
conversation, or a question about the person's own record is `answer` with no presenting tool —
|
|
113
|
+
often with an empty `toolCalls`.
|
|
114
|
+
- **The instruction is about the turn, never about one tool.** It says how to choose a handling, how
|
|
115
|
+
to ask back, how to write the standalone query, and "use the tools as the catalogue's usage rules
|
|
116
|
+
say". A sentence naming a specific tool belongs in that tool's `usageRules` (section 2).
|
|
117
|
+
- **The catalogue is built from the registered tools** and appended to the instruction: one line per
|
|
118
|
+
tool, its parameters, and its usage rules underneath. Registering a tool is the only change needed
|
|
119
|
+
for the planner to know it.
|
|
120
|
+
- **Code re-validates the plan:**
|
|
121
|
+
- an unknown `handling` becomes `answer`;
|
|
122
|
+
- tool calls are kept only when well-formed and named in the catalogue, and cut to the round's cap;
|
|
123
|
+
- a `clarify` with no question in it becomes `answer` — there is nothing to ask. How many times to
|
|
124
|
+
ask is not checked here;
|
|
125
|
+
- **a reply that cannot be read at all falls back to the turn's default tool** (e.g. the main search
|
|
126
|
+
for `standaloneQuery`). A readable plan with no tool call is the model's choice and is kept —
|
|
127
|
+
the fallback is for "no plan", not for "no tools".
|
|
128
|
+
- **Asking back is the planner's call, entirely.** The instruction says when a concern is too vague
|
|
129
|
+
to answer, how many questions a concern gets (counted from the conversation), that a new concern
|
|
130
|
+
starts again from none, and that a reply to an answer's closing question continues the same
|
|
131
|
+
concern. The conversation window must be wide enough for the model to see all of that.
|
|
132
|
+
|
|
133
|
+
## 2. Tools — each tool owns its rules
|
|
134
|
+
|
|
135
|
+
A tool is a class over one base. It carries everything about itself, so the planner's instruction
|
|
136
|
+
never has to:
|
|
137
|
+
|
|
138
|
+
| Member | What it is |
|
|
139
|
+
| --- | --- |
|
|
140
|
+
| `get toolName` | The name the planner writes |
|
|
141
|
+
| `get oneLine` | One line for the catalogue |
|
|
142
|
+
| `usageRules` | When to call it, when not to, how to fill its arguments — printed under it in the catalogue |
|
|
143
|
+
| `answerRules` | Rules added to the responder's instruction only on a turn whose answer used this tool |
|
|
144
|
+
| `get producesItems` | Whether it returns things to present (cards). `false` for a tool that only states facts |
|
|
145
|
+
| `findArgumentViolation()` | Why the model's arguments cannot run, or `null` |
|
|
146
|
+
| `runTool()` | Runs and returns `{ count, titles, factLines, payload }` |
|
|
147
|
+
|
|
148
|
+
- **A tool that only states facts returns `factLines`** ("The person's role: store manager") and
|
|
149
|
+
`producesItems: false`. The responder states the facts; no card is drawn.
|
|
150
|
+
- **Whose data a tool reads is fixed by the engine, never by the model.** A tool about "me" takes no
|
|
151
|
+
person argument at all, and rejects any argument it is given.
|
|
152
|
+
- **An argument copied from the person's words is checked against them** where a single changed
|
|
153
|
+
character would change the result (a name, a code), and the call is rejected when it does not
|
|
154
|
+
appear in what the person wrote.
|
|
155
|
+
- Settings that cannot live in the tool's class (one generic class serving many data-defined
|
|
156
|
+
variants) live in a code-side hash keyed by the variant key: usage rules, answer rules, how its
|
|
157
|
+
results are shown, what to say when it finds nothing. A fact a variant needs computed (from the
|
|
158
|
+
database) comes from a class looked up by variant key. **The orchestrator holds no variant key
|
|
159
|
+
literal**: adding a variant never edits the worker.
|
|
160
|
+
|
|
161
|
+
## 3. The executor — only what was planned
|
|
162
|
+
|
|
163
|
+
- Run the planned calls **concurrently**: they are independent reads the person waits through.
|
|
164
|
+
- **Zero calls is a valid round.** It produces no observation, and the monitor sends the turn to the
|
|
165
|
+
responder (section 4, rule 2).
|
|
166
|
+
- Each call becomes an **observation**: `{ toolName, status (ok | empty | rejected | error), count,
|
|
167
|
+
producesItems, factLines, resultId, roundNumber }`. Payloads are kept aside under `resultId`, so the
|
|
168
|
+
monitor and the trace see the shape, not the data.
|
|
169
|
+
- A failing tool is an `error` observation, never a thrown turn.
|
|
170
|
+
- *Optional speed-up:* the default tool may be started on the raw message **before** the planner
|
|
171
|
+
answers and its result reused when the planner's query is the same text (or the message is the
|
|
172
|
+
first of the conversation). It must never be presented unless the plan called that tool.
|
|
173
|
+
|
|
174
|
+
## 4. The loop monitor — an ordered table of code rules
|
|
175
|
+
|
|
176
|
+
After each round, the monitor walks a table and the first rule met decides. Each entry is
|
|
177
|
+
`{ conditionNumber, isMet: () => boolean, decision }`. A table that holds up:
|
|
178
|
+
|
|
179
|
+
| # | Condition | Decision |
|
|
180
|
+
| --- | --- | --- |
|
|
181
|
+
| 1 | The plan asks back | ask back |
|
|
182
|
+
| 2 | No tool that presents items was called | respond |
|
|
183
|
+
| 3 | A presenting tool found something adoptable | respond |
|
|
184
|
+
| 4 | A retry is still allowed (rounds and time left) | retry |
|
|
185
|
+
| 5 | Otherwise | respond |
|
|
186
|
+
|
|
187
|
+
- **Adding a rule is adding a row**, never editing a condition in place (open–closed). The numbers
|
|
188
|
+
are recorded in the trace, so a change of order shows up in the data.
|
|
189
|
+
- A retry asks the model once for different calls (a separate small selector), then runs them as
|
|
190
|
+
round two. The monitor itself never calls the model.
|
|
191
|
+
|
|
192
|
+
## 5. The responder — two paths
|
|
193
|
+
|
|
194
|
+
| Path | When | Writes | Publishes |
|
|
195
|
+
| --- | --- | --- | --- |
|
|
196
|
+
| **Result-backed answer** | A presenting tool ran | From the adopted results, with cards | "searching" opener, cards, answer, follow-up chips |
|
|
197
|
+
| **Direct reply** | No presenting tool ran | From the conversation and `factLines` | The answer only — no opener, no cards |
|
|
198
|
+
|
|
199
|
+
- **The system instruction is assembled, not hard-coded:** the assistant's standing character, the
|
|
200
|
+
conversation rules, the glossary, then the `answerRules` of the tools the answer used. The direct
|
|
201
|
+
reply adds a rule that it must not mention items it never looked for.
|
|
202
|
+
- **Nothing found is the responder's to say.** It says so plainly and, when it helps, asks one
|
|
203
|
+
question of its own. Code never substitutes a fixed question.
|
|
204
|
+
- **Openers depend on the plan.** "Looking for items…" is published only once the plan calls a
|
|
205
|
+
presenting tool.
|
|
206
|
+
|
|
207
|
+
## Choice chips and fixed actions — the `actionKey`
|
|
208
|
+
|
|
209
|
+
A chip is either a **reply** or an **action**, and the wire says which:
|
|
210
|
+
|
|
211
|
+
```graphql
|
|
212
|
+
type ChatSuggestion {
|
|
213
|
+
label: String!
|
|
214
|
+
message: String!
|
|
215
|
+
actionKey: String # null: a reply chip
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
input RequestChatInput {
|
|
219
|
+
# ...
|
|
220
|
+
message: String!
|
|
221
|
+
actionKey: String # set only when an action chip was pressed
|
|
222
|
+
}
|
|
223
|
+
```
|
|
224
|
+
|
|
225
|
+
- **A reply chip sends its words as the person's own reply** — `message` equals `label`, nothing
|
|
226
|
+
added. The planner reads it inside the conversation, so "Not decided yet" after "Which area do you
|
|
227
|
+
want to work on?" stays about that area.
|
|
228
|
+
- **An action chip has a fixed meaning** ("What people in the same role are viewing", "Create a
|
|
229
|
+
study plan"). Its `actionKey` names the action, not the implementation; a hash maps it to what runs.
|
|
230
|
+
Pressing it runs that action directly — **no planner call**.
|
|
231
|
+
- Validate `actionKey` at the API boundary against the hash (`Object.hasOwn`, so `toString` is not a
|
|
232
|
+
key) and reject unknown keys with an input error.
|
|
233
|
+
- **An action that cannot run now** (its variant is inactive, the person cannot be resolved) falls
|
|
234
|
+
back to the planner, which reads the chip's words like any message.
|
|
235
|
+
- Do not add an action for something the planner can decide. An action exists because the person
|
|
236
|
+
pressed a button whose meaning must not be reinterpreted.
|
|
237
|
+
|
|
238
|
+
## Conversation and vocabulary
|
|
239
|
+
|
|
240
|
+
- The planner and the responder both read a **window of the conversation** (both speakers, oldest
|
|
241
|
+
first) — around a dozen turns is a sensible start. It is a cost cap, so size it for what the model
|
|
242
|
+
must judge from it: two or three questions back plus an answer already take three exchanges. The
|
|
243
|
+
client's limit on what it sends, and the API's limit on what it accepts, are raised with it. Text
|
|
244
|
+
copied into a tool argument comes only from the person's own messages: the assistant's are already
|
|
245
|
+
paraphrased.
|
|
246
|
+
- `standaloneQuery` resolves what a follow-up points back to ("And for refunds?" → "How to handle a
|
|
247
|
+
refund request at the counter").
|
|
248
|
+
- **A domain glossary** (terms the model would misread: an abbreviation that is a job title in this
|
|
249
|
+
domain, not its common meaning) is one block given to the planner, the retry selector and the
|
|
250
|
+
responder, and used by tools that rank results.
|
|
251
|
+
|
|
252
|
+
## Trace and regression
|
|
253
|
+
|
|
254
|
+
- **One trace record per turn**: planned and final handling, standalone query, planned tool names,
|
|
255
|
+
each observation's shape, each monitor decision with its condition number, whether a presenting tool
|
|
256
|
+
ran, prompt section sizes, elapsed time. This is what tuning reads.
|
|
257
|
+
- **Unit tests stub the model**; they prove the code obeys a given plan, not that the model plans
|
|
258
|
+
well.
|
|
259
|
+
- **A regression script plans fixed conversations against the real model** and judges each plan:
|
|
260
|
+
expected handling, words the standalone query must include or exclude, tools that must or must not
|
|
261
|
+
be called. **Every conversation reported as wrong is added to it** before the fix is merged. It is
|
|
262
|
+
read-only (plans only, runs no tool) and is run wherever the model key lives.
|
|
263
|
+
|
|
264
|
+
## Mapping onto `mentsu-agent-loop-core`
|
|
265
|
+
|
|
266
|
+
The four layers fit the `ProceduralAgentLoop` of `/hor-ai-agent-structure` without new machinery:
|
|
267
|
+
|
|
268
|
+
| Layer | In the loop |
|
|
269
|
+
| --- | --- |
|
|
270
|
+
| Planner | An action making one forced tool call (`plan_turn`) whose arguments are the plan JSON; re-validated in its `run()` |
|
|
271
|
+
| Tools | One `BaseAgentAction` each, registered in `get registry`; `usageRules` and `producesItems` as getters |
|
|
272
|
+
| Executor | `advanceState()` performs each planned action by name with `this.performAction(...)` |
|
|
273
|
+
| Loop monitor | Plain code in `advanceState()` after the round; its decision goes into the state |
|
|
274
|
+
| Round cap | `get maxIterations` |
|
|
275
|
+
| Responder | A final action, chosen by whether a presenting tool ran |
|
|
276
|
+
| Fixed action | Handled by the generator before the loop starts, like the intent gate there |
|
|
277
|
+
|
|
278
|
+
Keep everything flowing through `context`, as that skill requires.
|
|
279
|
+
|
|
280
|
+
## Checklist for a change
|
|
281
|
+
|
|
282
|
+
- A new tool: its own class, `oneLine`, `usageRules`, `producesItems`; registered; nothing added to
|
|
283
|
+
the planner's instruction.
|
|
284
|
+
- A new chip: is its meaning fixed? Then an `actionKey` and an entry in the action hash. Otherwise
|
|
285
|
+
`actionKey: null` and `message` equal to `label`.
|
|
286
|
+
- A new monitor rule: a new row, numbered, with a test for met and not met.
|
|
287
|
+
- A reported bad conversation: added to the regression script first.
|
|
@@ -3,10 +3,9 @@ name: hor-graphql-server-engine
|
|
|
3
3
|
description: >
|
|
4
4
|
Implement and wire a GraphQL server engine, the per-endpoint *GraphqlServerEngine class under
|
|
5
5
|
server/graphql/ that declares one endpoint's routing, Share and Context DI, auth filter,
|
|
6
|
-
middleware, scalars and
|
|
7
|
-
reads env. Use whenever the user
|
|
8
|
-
|
|
9
|
-
PubSub.
|
|
6
|
+
middleware, scalars, error codes and WebSocket server, and decide what the engine and its Share
|
|
7
|
+
may hold and who reads env. Use whenever the user adds a GraphQL endpoint, pairs a stub engine,
|
|
8
|
+
changes its auth policy or credential route, enables Redis PubSub, or limits its WebSocket server.
|
|
10
9
|
---
|
|
11
10
|
|
|
12
11
|
# GraphQL Server Engine
|
|
@@ -14,7 +13,8 @@ description: >
|
|
|
14
13
|
A skill for the **`*GraphqlServerEngine` classes under `server/graphql/`**. An engine is the one
|
|
15
14
|
object that **wires a single GraphQL endpoint**: its URL and port, which schema and resolver
|
|
16
15
|
directories to load, the Share / Context dependency-injection classes, the authentication filter,
|
|
17
|
-
the Express middleware, the custom scalars,
|
|
16
|
+
the Express middleware, the custom scalars, the error-code hash, and the WebSocket server's hooks and
|
|
17
|
+
switches. `server/index.js` then boots
|
|
18
18
|
**one HTTP server per engine** through `GraphqlServerBuilder`.
|
|
19
19
|
|
|
20
20
|
The engine sits *above* the pieces other skills build: resolvers (`hor-resolver-validator`
|
|
@@ -39,6 +39,7 @@ one of these settings — nothing more:
|
|
|
39
39
|
| Custom scalars | `collectScalars()` | [§6](#6-middleware-scalars-error-codes) |
|
|
40
40
|
| Auth policy — the **no-auth (public) operations** + the filter | `schemasToSkipFiltering` + `generateFilterHandler()` | [§4](#4-authentication-schemastoskipfiltering--generatefilterhandler) |
|
|
41
41
|
| Shared error codes | `standardErrorCodeHash` | [§6](#6-middleware-scalars-error-codes) |
|
|
42
|
+
| WebSocket server (`graphql-ws` hooks, skip switch, `ConnectionInit` timeout) | `composeServerHookHash()` + `config.graphqlServer` | [§9](#9-the-websocket-server-composeserverhookhash--graphqlserver) |
|
|
42
43
|
|
|
43
44
|
**App-common settings are not repeated per engine** — they are lifted into an **app base class**
|
|
44
45
|
(`BaseAppGraphqlServerEngine`) that every engine extends ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)).
|
|
@@ -132,6 +133,7 @@ export default class PartnerGraphqlServerEngine extends BaseAppGraphqlServerEngi
|
|
|
132
133
|
| `actualResolversPath` | Directory of the real resolvers (`.../resolvers/<role>/actual/`), or `null`. |
|
|
133
134
|
| `stubResolversPath` | Directory of stub resolvers (`.../resolvers/<role>/stub/`), or `null`. |
|
|
134
135
|
| `postWorkersPath` | Directory of post-workers, or `null` when unused ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)). |
|
|
136
|
+
| `graphqlServer?` | Settings of the WebSocket server mounted on the endpoint: `skipsWebSocket` and `connectionInitWaitTimeout` ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)). |
|
|
135
137
|
| `redisOptions?` | Redis connection for subscription PubSub, read by the subscription broker. The engine leaves it out; the Share adds it from `env` when it creates the broker ([§3](#3-share-and-context--the-di-the-engine-hands-to-every-resolver)). `null` → in-process `LocalPubSub` ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)). |
|
|
136
138
|
|
|
137
139
|
```js
|
|
@@ -672,6 +674,169 @@ An endpoint → port layout looks like this (roles, paths, and ports are illustr
|
|
|
672
674
|
as a REST server).
|
|
673
675
|
- Pair the actual engine with its stub engine here too (both get their own `createAsync` + `listen`).
|
|
674
676
|
|
|
677
|
+
## 9. The WebSocket server: `composeServerHookHash()` + `graphqlServer`
|
|
678
|
+
|
|
679
|
+
`GraphqlServerBuilder` mounts a `graphql-ws` server on the endpoint's `graphqlEndpoint` path, next to
|
|
680
|
+
the HTTP handler. The engine shapes it through two members, from `@openreachtech/renchan` `2.12.0`.
|
|
681
|
+
A WebSocket connection never passes through the Express middleware of
|
|
682
|
+
[§6](#6-middleware-scalars-error-codes), so a rule that lives there (a sign-in rate limit, a CORS
|
|
683
|
+
check) does not see an operation that arrives over the socket.
|
|
684
|
+
|
|
685
|
+
| Member | Kind | What it decides |
|
|
686
|
+
| --- | --- | --- |
|
|
687
|
+
| `composeServerHookHash()` | instance method | The `graphql-ws` server hooks (`onConnect`, `onSubscribe`, `onClose`, ...). Default `{}`. Type `GraphqlType.WebSocketServerHookHash`. |
|
|
688
|
+
| `config.graphqlServer.skipsWebSocket` | boolean | `true` leaves the WebSocket server unmounted. Default `false`. |
|
|
689
|
+
| `config.graphqlServer.connectionInitWaitTimeout` | number (ms) | How long the server waits for `ConnectionInit` after a connection opens. A positive finite number only; anything else (omitted, `null`, `0`, `Infinity`, `NaN`, a string) leaves the `graphql-ws` default of 3000. |
|
|
690
|
+
|
|
691
|
+
- **A switch goes in `config`, and a hook never overrides what the builder wires.** The builder drops
|
|
692
|
+
these keys from whatever `composeServerHookHash()` returns: `execute`, `subscribe`, `context`,
|
|
693
|
+
`schema`, `roots`, `validate`, `connectionInitWaitTimeout`, `jsonMessageReviver` and
|
|
694
|
+
`jsonMessageReplacer`. The type omits the same keys, and the builder ignores one that slips
|
|
695
|
+
through. Set the wait through `config`, never through the hash.
|
|
696
|
+
- **`0` and `Infinity` do not turn the wait off.** `graphql-ws` itself treats them as "do not wait",
|
|
697
|
+
but the builder resolves them to its default, so an endpoint always waits for `ConnectionInit`.
|
|
698
|
+
- **Skip the server on an endpoint that serves no subscription.** An endpoint whose schema has no
|
|
699
|
+
`Subscription` type, such as a role that only queries and mutates, mounts a WebSocket server
|
|
700
|
+
nobody needs, and an open door is attack surface. `skipsWebSocket: true` is the switch; do not
|
|
701
|
+
emulate it with a hook that refuses everything.
|
|
702
|
+
- **`composeServerHookHash()` is a method, so it may build the hash.** The getter rule of
|
|
703
|
+
[§3](#what-the-engine-the-share-and-env-may-each-hold) holds: a getter calls no method. The method
|
|
704
|
+
returns hook functions that decide allow or deny and nothing else, like `generateFilterHandler()`
|
|
705
|
+
([§4](#4-authentication-schemastoskipfiltering--generatefilterhandler)). Anything that needs `env`
|
|
706
|
+
reads it through `this.share.env`, because only the Share imports `env`.
|
|
707
|
+
- **Refuse an operation by returning `GraphQLError`s from `onSubscribe`.** Return `void` to let the
|
|
708
|
+
operation go on. Return an array of at least one `GraphQLError` (from `graphql`) to refuse it:
|
|
709
|
+
`graphql-ws` sends the client an error message for that operation and the socket stays open.
|
|
710
|
+
An error from `this.errorHash` does not qualify, because it extends `Error` and is not a
|
|
711
|
+
`GraphQLError`.
|
|
712
|
+
- **Never return `ExecutionArgs` from `onSubscribe`.** It skips the builder's validation, so the
|
|
713
|
+
endpoint's own validation rules stop applying to that operation.
|
|
714
|
+
- **Throwing from `onSubscribe` closes the whole socket.** `parse()` throws on a syntax error, so the
|
|
715
|
+
example below ends the connection on a malformed query, as `graphql-ws` does when no hook is set.
|
|
716
|
+
|
|
717
|
+
```js
|
|
718
|
+
// Good: a WebSocket carries subscriptions only; a query or a mutation must go through HTTP
|
|
719
|
+
import {
|
|
720
|
+
GraphQLError,
|
|
721
|
+
getOperationAST,
|
|
722
|
+
parse,
|
|
723
|
+
} from 'graphql'
|
|
724
|
+
|
|
725
|
+
/** @override */
|
|
726
|
+
composeServerHookHash () {
|
|
727
|
+
return {
|
|
728
|
+
onSubscribe: (context, message) => {
|
|
729
|
+
const operationAst = getOperationAST(
|
|
730
|
+
parse(message.payload.query),
|
|
731
|
+
message.payload.operationName
|
|
732
|
+
)
|
|
733
|
+
|
|
734
|
+
if (operationAst?.operation === 'subscription') {
|
|
735
|
+
return undefined
|
|
736
|
+
}
|
|
737
|
+
|
|
738
|
+
return [
|
|
739
|
+
new GraphQLError('Only a subscription is accepted over WebSocket.'),
|
|
740
|
+
]
|
|
741
|
+
},
|
|
742
|
+
}
|
|
743
|
+
}
|
|
744
|
+
```
|
|
745
|
+
|
|
746
|
+
An operation the hook refuses never reaches a resolver, so a sign-in mutation sent over the socket
|
|
747
|
+
cannot dodge the sign-in rate limit that the Express middleware applies over HTTP. The check fails
|
|
748
|
+
closed: anything other than a subscription, including an operation the AST cannot identify
|
|
749
|
+
(`operationAst` is `null`), is refused.
|
|
750
|
+
|
|
751
|
+
### Check the `Origin` of a WebSocket connection in `onConnect`
|
|
752
|
+
|
|
753
|
+
The CORS middleware of [§3](#what-the-engine-the-share-and-env-may-each-hold) never sees the
|
|
754
|
+
WebSocket handshake either, so a page on any origin can open a socket to the endpoint. `onConnect`
|
|
755
|
+
runs when the client sends `ConnectionInit`: `graphql-ws` allows the connection when it returns
|
|
756
|
+
`true` (or nothing), and closes the socket with `4403: Forbidden` when it returns `false`. With the
|
|
757
|
+
`ws` server, `context.extra.request` is the handshake `IncomingMessage`, so the origin is
|
|
758
|
+
`context.extra.request.headers.origin`.
|
|
759
|
+
|
|
760
|
+
The allowed origins already live in the endpoint's `CorsExpressMiddleware` derived class, which
|
|
761
|
+
reads its env key through `this.share.env`. Give that class the one predicate the hook needs, and
|
|
762
|
+
create the class in the engine with `Ctor.create({ engine: this })`, as
|
|
763
|
+
`composeExpressMiddleware()` does. The engine then imports no `env`, parses nothing and keeps one
|
|
764
|
+
list of origins for HTTP and WebSocket.
|
|
765
|
+
|
|
766
|
+
```js
|
|
767
|
+
// Good: the middleware class owns the origin list, so the hook only asks it
|
|
768
|
+
// server/middleware/CorsExpressMiddleware.js
|
|
769
|
+
allowsOrigin ({
|
|
770
|
+
origin,
|
|
771
|
+
}) {
|
|
772
|
+
return this.createAllowedCorsOriginCollection()
|
|
773
|
+
.extractOrigins()
|
|
774
|
+
.includes(origin)
|
|
775
|
+
}
|
|
776
|
+
```
|
|
777
|
+
|
|
778
|
+
```js
|
|
779
|
+
// Good: the engine composes the hook; a missing or foreign Origin is refused with 4403
|
|
780
|
+
import AdminCorsExpressMiddleware from '../middleware/AdminCorsExpressMiddleware.js'
|
|
781
|
+
|
|
782
|
+
/** @override */
|
|
783
|
+
composeServerHookHash () {
|
|
784
|
+
const corsExpressMiddleware = AdminCorsExpressMiddleware.create({
|
|
785
|
+
engine: this,
|
|
786
|
+
})
|
|
787
|
+
|
|
788
|
+
return {
|
|
789
|
+
onConnect: context => corsExpressMiddleware.allowsOrigin({
|
|
790
|
+
origin: context.extra.request.headers.origin,
|
|
791
|
+
}),
|
|
792
|
+
}
|
|
793
|
+
}
|
|
794
|
+
```
|
|
795
|
+
|
|
796
|
+
- **A browser always sends `Origin` on a WebSocket handshake; a script or a server client sends none.**
|
|
797
|
+
The hook above refuses a connection with no `Origin`. An endpoint that serves such a client
|
|
798
|
+
decides that case on purpose, never by loosening the list.
|
|
799
|
+
- **`onConnect` and `onSubscribe` live in the same hash.** Return both from one
|
|
800
|
+
`composeServerHookHash()`.
|
|
801
|
+
|
|
802
|
+
```js
|
|
803
|
+
// Good: a switch is a config value
|
|
804
|
+
/** @override */
|
|
805
|
+
static get config () {
|
|
806
|
+
return {
|
|
807
|
+
graphqlEndpoint: '/graphql-admin',
|
|
808
|
+
// ...
|
|
809
|
+
graphqlServer: {
|
|
810
|
+
skipsWebSocket: false,
|
|
811
|
+
connectionInitWaitTimeout: 5000,
|
|
812
|
+
},
|
|
813
|
+
}
|
|
814
|
+
}
|
|
815
|
+
```
|
|
816
|
+
|
|
817
|
+
```js
|
|
818
|
+
// Bad: the wait is a config value, so the builder drops it from the hash
|
|
819
|
+
/** @override */
|
|
820
|
+
composeServerHookHash () {
|
|
821
|
+
return {
|
|
822
|
+
connectionInitWaitTimeout: 5000,
|
|
823
|
+
}
|
|
824
|
+
}
|
|
825
|
+
```
|
|
826
|
+
|
|
827
|
+
```js
|
|
828
|
+
// Bad: ExecutionArgs from onSubscribe skips the builder's validation
|
|
829
|
+
/** @override */
|
|
830
|
+
composeServerHookHash () {
|
|
831
|
+
return {
|
|
832
|
+
onSubscribe: (context, message) => ({
|
|
833
|
+
schema,
|
|
834
|
+
document: parse(message.payload.query),
|
|
835
|
+
}),
|
|
836
|
+
}
|
|
837
|
+
}
|
|
838
|
+
```
|
|
839
|
+
|
|
675
840
|
## Finishing checklist
|
|
676
841
|
|
|
677
842
|
- [ ] One engine per endpoint, extending the **app base** ([§1](#1-two-base-classes-put-app-common-settings-in-an-app-base-and-extend-it)); a member moves to the app base only when it is always the same for every endpoint, and `collectMiddleware()` stays in each engine.
|
|
@@ -686,3 +851,5 @@ An endpoint → port layout looks like this (roles, paths, and ports are illustr
|
|
|
686
851
|
- [ ] Redis PubSub enabled on endpoints whose subscriptions are published by **another process** ([§5](#5-stub-vs-actual-engines-and-subscriptions-redis-vs-local)).
|
|
687
852
|
- [ ] `postWorkersPath` set when the endpoint needs post-workers (`null` disables them) ([§7](#7-post-resolve-hooks-defineonresolved--postworkerspath)).
|
|
688
853
|
- [ ] Engine **registered in `server/index.js`** with a unique port ([§8](#8-wiring-into-serverindexjs)).
|
|
854
|
+
- [ ] An endpoint's `onConnect` refuses an `Origin` outside the list its `CorsExpressMiddleware` derived class reads, and the engine imports no `env` for it ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)).
|
|
855
|
+
- [ ] An endpoint that serves no subscription sets `config.graphqlServer.skipsWebSocket: true`; one that does refuses every non-subscription operation in `composeServerHookHash()`'s `onSubscribe`, returns `GraphQLError`s (never `ExecutionArgs`), and keeps `connectionInitWaitTimeout` in `config` ([§9](#9-the-websocket-server-composeserverhookhash--graphqlserver)).
|
package/docs/skills.ja.md
CHANGED
|
@@ -22,7 +22,7 @@
|
|
|
22
22
|
| スキル | 概要 |
|
|
23
23
|
| :-- | :-- |
|
|
24
24
|
| `hor-graphql-schema` | renchan サーバの GraphQL SDL(`.graphql`)を書きます。オーディエンス別スキーマ、ドメイン別の番号付きファイル、カスタムスカラー、命名・null 許容・enum・ページネーションの規約。 |
|
|
25
|
-
| `hor-graphql-server-engine` | エンドポイントごとの `*GraphqlServerEngine` を実装・起動します。URL、スキーマパス、リゾルバディレクトリ、Share/Context の DI
|
|
25
|
+
| `hor-graphql-server-engine` | エンドポイントごとの `*GraphqlServerEngine` を実装・起動します。URL、スキーマパス、リゾルバディレクトリ、Share/Context の DI、認証フィルタ、ミドルウェア、スカラー、エラーコード、WebSocket サーバーの制限。 |
|
|
26
26
|
| `hor-query-resolver` | `BaseQueryResolver` を継承した GraphQL Query リゾルバを書きます。ページネーション、関連の include、ドメインエラーの throw、actual と stub のペア。 |
|
|
27
27
|
| `hor-mutation-resolver` | `BaseMutationResolver` を継承した GraphQL Mutation リゾルバを実装します。状態を変更する操作と、それが動く単一トランザクション。 |
|
|
28
28
|
| `hor-subscription-resolver` | GraphQL subscription リゾルバを実装します。操作の宣言、購読者ごとのチャンネルのスコープ、購読可否のゲート、イベントを push する publish 側の配線。 |
|
|
@@ -56,6 +56,7 @@
|
|
|
56
56
|
| スキル | 概要 |
|
|
57
57
|
| :-- | :-- |
|
|
58
58
|
| `hor-ai-agent-structure` | `mentsu-agent-loop-core` 上にアプリ側 AI エージェントを構成します。`app/agents/<name>/` に `ProceduralAgentLoop` サブクラスとステップごとの `BaseAgentAction` サブクラスを置きます。 |
|
|
59
|
+
| `hor-chat-agent-loop` | ターンの中身をモデルが決めるチャットアシスタントを構築します。プランナー・実行役・ループ監視・回答役の 4 層と、コードが守ることとプロンプトが決めることの境界を定めます。 |
|
|
59
60
|
| `hor-agent-loop` | `@openreachtech/mentsu-agent-loop` の 3 パッケージで LLM エージェントループを構築します。core(反復エンジン)、BullMQ ジョブ実行、GraphQL の起動 mutation と進捗 subscription。 |
|
|
60
61
|
| `hor-multi-llm-provider` | Claude / OpenAI / Gemini を 1 つの抽象の下で扱います。抽象モデルプロセッサ、ベンダーごとの基底、モデルごとの具象クラス、モデル名で選択するローダー、モデルへの到達方法ごとのアクセスルート(ベンダー API キー、サービスアカウントによる Vertex AI、Amazon Bedrock)。 |
|
|
61
62
|
| `hor-light-rag` | ベクタ DB なしで AI エージェント向けの軽量 RAG を追加します。ローカル埋め込みによる vector-first / LLM フォールバックのランキングと、MySQL の n-gram 全文検索インデックス。 |
|
package/docs/skills.md
CHANGED
|
@@ -22,7 +22,7 @@ Each skill lives at `kit/skills/<name>/`, directly under the skills directory, a
|
|
|
22
22
|
| Skill | Summary |
|
|
23
23
|
| :-- | :-- |
|
|
24
24
|
| `hor-graphql-schema` | Author GraphQL SDL files for a renchan server — per-audience schemas, numbered per-domain files, custom scalars, and naming, nullability, enum and pagination conventions. |
|
|
25
|
-
| `hor-graphql-server-engine` | Implement a per-endpoint `*GraphqlServerEngine`: its URL, schema path, resolver directories, Share/Context DI, auth filter, middleware, scalars and
|
|
25
|
+
| `hor-graphql-server-engine` | Implement a per-endpoint `*GraphqlServerEngine`: its URL, schema path, resolver directories, Share/Context DI, auth filter, middleware, scalars, error codes and WebSocket server limits. |
|
|
26
26
|
| `hor-query-resolver` | Write GraphQL Query resolvers extending `BaseQueryResolver` — pagination, association includes, domain-error throwing, and the actual-vs-stub pair. |
|
|
27
27
|
| `hor-mutation-resolver` | Implement GraphQL Mutation resolvers extending `BaseMutationResolver` — state-changing operations and the single transaction each runs in. |
|
|
28
28
|
| `hor-subscription-resolver` | Implement a GraphQL subscription resolver — declare the operation, scope its channel per subscriber, gate who may subscribe, and wire the publish side. |
|
|
@@ -56,6 +56,7 @@ Each skill lives at `kit/skills/<name>/`, directly under the skills directory, a
|
|
|
56
56
|
| Skill | Summary |
|
|
57
57
|
| :-- | :-- |
|
|
58
58
|
| `hor-ai-agent-structure` | Structure an app-side AI agent on `mentsu-agent-loop-core`: a `ProceduralAgentLoop` subclass plus per-step `BaseAgentAction` subclasses under `app/agents/<name>/`. |
|
|
59
|
+
| `hor-chat-agent-loop` | Build a chat assistant whose turn the model plans — planner, executor, loop monitor, responder — and draw the line between what code enforces and what the prompt decides. |
|
|
59
60
|
| `hor-agent-loop` | Build an LLM agent loop with the three `@openreachtech/mentsu-agent-loop` packages — the core iteration engine, a BullMQ job runner, and a GraphQL mutation plus progress subscription. |
|
|
60
61
|
| `hor-multi-llm-provider` | Support Claude / OpenAI / Gemini behind one abstraction: an abstract model processor, a base per vendor, a concrete class per model, a loader that picks one by model name, and an access route per way of reaching it (vendor API key, Vertex AI service account, Amazon Bedrock). |
|
|
61
62
|
| `hor-light-rag` | Add lightweight RAG for agent documents without a vector database — a vector-first / LLM-fallback ranker over stored `Document` rows, plus a MySQL n-gram fulltext keyword index. |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@openreachtech/hora-skills-ort-renchan",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.6.0",
|
|
4
4
|
"description": "Distributes the renchan backend skills used to develop with Hora Kit.",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"files": [
|
|
@@ -56,9 +56,14 @@
|
|
|
56
56
|
"@istanbuljs/load-nyc-config": {
|
|
57
57
|
"js-yaml": "^4.3.2"
|
|
58
58
|
},
|
|
59
|
+
"babel-plugin-istanbul": {
|
|
60
|
+
"test-exclude": "^8.0.0"
|
|
61
|
+
},
|
|
59
62
|
"brace-expansion@1": "^1.1.21",
|
|
60
63
|
"brace-expansion@5": "^5.0.12",
|
|
61
|
-
"flatted": "^3.4.4"
|
|
64
|
+
"flatted": "^3.4.4",
|
|
65
|
+
"glob@13": "^14.0.5",
|
|
66
|
+
"minimatch@10": "^11.0.8"
|
|
62
67
|
},
|
|
63
68
|
"allowScripts": {
|
|
64
69
|
"@parcel/watcher": false,
|