@openreachtech/hora-skills-ort-renchan 0.5.0 → 0.6.1

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.
@@ -231,16 +231,16 @@ assert that invalid input raises the matching `InvalidXxx` through the run entry
231
231
  describe('EmailInsertableVariablesInputValidator', () => {
232
232
  describe('isValidOriginObjectCategoryId', () => {
233
233
  /* eslint-disable */
234
- },
235
- {
236
- input: {
237
- originObjectCategory const cases = [
234
+ const cases = [
238
235
  {
239
236
  input: {
240
237
  originObjectCategoryId: 1,
241
238
  },
242
239
  expected: true,
243
- Id: '1',
240
+ },
241
+ {
242
+ input: {
243
+ originObjectCategoryId: '1',
244
244
  },
245
245
  expected: true,
246
246
  },
package/docs/skills.ja.md CHANGED
@@ -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
@@ -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.5.0",
3
+ "version": "0.6.1",
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,