@voctiv/agent-runtime 0.4.0 → 0.4.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.
package/README.md CHANGED
@@ -16,7 +16,7 @@ DI-ядро (контейнер, фазы, host диалога, модули з
16
16
 
17
17
  ## Справочник по библиотеке
18
18
 
19
- Полное описание формата агента и движка — папка [`skill/`](./skill) (в установленном пакете — `node_modules/@voctiv/agent-runtime/skill/`). Начинать с [`SKILL.md`](./skill/SKILL.md): что это за библиотека, правила, как создать агента, порядок работы над изменением. Справочник `skill/` написан по-английски; этот README и [`docs/framework`](./docs/framework/README.md) (ядро под движком) — по-русски.
19
+ Полное описание формата агента и движка — папка [`skill/`](./skill) (в установленном пакете — `node_modules/@voctiv/agent-runtime/skill/`). Начинать с [`SKILL.md`](./skill/SKILL.md): это вход для того, кто пишет или меняет агента — что это за библиотека, таблица «какое изменение → какой раздел читать», порядок работы над изменением, грабли. Справочник `skill/` написан по-английски; этот README и [`docs/framework`](./docs/framework/README.md) (ядро под движком) — по-русски.
20
20
 
21
21
  | Раздел | О чём |
22
22
  |--------|-------|
@@ -28,15 +28,23 @@ DI-ядро (контейнер, фазы, host диалога, модули з
28
28
  | `references/business.md` | входные данные звонка, экстракция, итоги, строка отчёта, интеграции |
29
29
  | `references/blocks.md` | блоки со своим движком: `decisionModel`, `knowledgeAnswer`, `catalogMatch` |
30
30
  | `references/locales.md` | языковые пакеты |
31
- | `references/new-agent.md` | новый агент из шаблона `templates/agent` |
32
- | `references/porting.md` | перенос старого скрипта агента на библиотеку |
31
+ | `references/new-agent.md` | новый агент из шаблона `templates/agent`, проверка сборки `voctiv-agent-check` |
32
+ | `references/porting.md` | перенос написанного вручную агента на библиотеку: порядок по шагам, сценарии до и после, когда остановиться и спросить |
33
33
  | `references/examples.md` | примеры агентов |
34
34
  | `references/core.md` | ядро под движком |
35
+ | `references/library-dev.md` | разработка самой библиотеки: правила для её кода, слои, таблица состояния, порядок изменения |
35
36
  | `references/migration.md` | переход на 0.4: со старых subpath (`./asr`, `./barge-in`, `./dialog` …) и набора `kits` на сборщик |
36
37
 
38
+ Пакет сам несёт знание о себе для платформы и помощников: поле `voctivAgentKit` в `package.json` называет справочник (`skill`), типы (`dist`), стартовый шаблон (`templates`) и два фрагмента для `AGENTS.md` агента:
39
+
40
+ - [`skill/AGENTS.md`](./skill/AGENTS.md) — вставляется, когда агент зависит от пакета: логика агента — данные, какая работа требует справочника, как проверить изменение;
41
+ - [`skill/AGENTS.recommend.md`](./skill/AGENTS.recommend.md) — когда пакет рекомендован, но агент от него не зависит: новый агент, правка написанного вручную, перенос по просьбе.
42
+
43
+ Во фрагментах платформа подставляет `{{PACKAGE_NAME}}`, `{{PACKAGE_VERSION}}`, `{{PACKAGE_DIR}}`; состав проверяет `src/agent-kit.spec.ts`.
44
+
37
45
  ## Новый агент
38
46
 
39
- Скопируйте [`templates/agent`](./templates/agent): шаги в его README и в справочнике (`skill/SKILL.md`, «Create a new agent»).
47
+ Скопируйте [`templates/agent`](./templates/agent): шаги в его README и в справочнике (`skill/references/new-agent.md`). Сборка шаблона заканчивается командой пакета `voctiv-agent-check`: она загружает собранного агента, и ошибка сборщика (`Error: voiceAgent "…": путь в данных: что не так`) роняет сборку без звонка и без платформы.
40
48
 
41
49
  ```ts
42
50
  import 'reflect-metadata';
@@ -0,0 +1,98 @@
1
+ #!/usr/bin/env node
2
+ // Build-time check of an agent: loads the built entry, so the builder's `.build()` runs its checks (sections, data
3
+ // forms, names of facts, operators, filters and readers). No call is started and no platform is needed.
4
+ //
5
+ // voctiv-agent-check [path]
6
+ //
7
+ // `path` is the built entry file or the agent's folder; without it the current folder is the agent's folder. In a
8
+ // folder the entry is `main` of its package.json, else dist/index.js, else dist/agent.js.
9
+ // Exit 0 and one `OK:` line when the agent builds; exit 1 and one `Error:` line otherwise.
10
+ 'use strict';
11
+
12
+ const fs = require('node:fs');
13
+ const path = require('node:path');
14
+
15
+ const USAGE = 'Usage: voctiv-agent-check [path to the built entry file or to the agent folder]';
16
+ const DEFAULT_ENTRIES = ['dist/index.js', 'dist/agent.js'];
17
+
18
+ const oneLine = (text) => String(text).split(/\r?\n/).map((l) => l.trim()).filter(Boolean).join(' ');
19
+ const isFile = (p) => fs.existsSync(p) && fs.statSync(p).isFile();
20
+ const isDir = (p) => fs.existsSync(p) && fs.statSync(p).isDirectory();
21
+
22
+ /** The entry file of an agent folder, or `{ error }` saying what was looked for. */
23
+ function entryOfFolder(dir) {
24
+ let main;
25
+ const manifest = path.join(dir, 'package.json');
26
+ if (isFile(manifest)) {
27
+ try {
28
+ main = JSON.parse(fs.readFileSync(manifest, 'utf8')).main;
29
+ } catch (e) {
30
+ return { error: `${manifest}: not readable as JSON (${oneLine(e.message)})` };
31
+ }
32
+ }
33
+ const candidates = typeof main === 'string' && main ? [main, `${main}.js`] : DEFAULT_ENTRIES;
34
+ const found = candidates.map((c) => path.resolve(dir, c)).find(isFile);
35
+ if (found) return { entry: found };
36
+ const looked = typeof main === 'string' && main ? `"main" of package.json (${main})` : DEFAULT_ENTRIES.join(', ');
37
+ return { error: `no built entry in ${dir}: looked for ${looked}; build the agent first` };
38
+ }
39
+
40
+ function resolveEntry(cwd, arg) {
41
+ const target = path.resolve(cwd, arg ?? '.');
42
+ if (isDir(target)) return entryOfFolder(target);
43
+ if (isFile(target)) return { entry: target };
44
+ return { error: `${arg}: no such file or folder` };
45
+ }
46
+
47
+ /**
48
+ * Runs the check. `io`: `cwd`, `out(line)`, `err(line)`, `load(file)` (default: `require`). Returns the exit code.
49
+ */
50
+ async function check(args, io) {
51
+ if (args.includes('-h') || args.includes('--help')) {
52
+ io.out(USAGE);
53
+ return 0;
54
+ }
55
+ if (args.length > 1) {
56
+ io.err(`Error: one path at most. ${USAGE}`);
57
+ return 1;
58
+ }
59
+ const resolved = resolveEntry(io.cwd, args[0]);
60
+ if (resolved.error) {
61
+ io.err(`Error: ${resolved.error}`);
62
+ return 1;
63
+ }
64
+ const shown = path.relative(io.cwd, resolved.entry) || resolved.entry;
65
+ let loaded;
66
+ try {
67
+ loaded = await io.load(resolved.entry);
68
+ } catch (e) {
69
+ // The builder's error already names the agent and the path inside its data.
70
+ if (e && e.name === 'AgentBuildError') io.err(`Error: ${oneLine(e.message)} (${shown})`);
71
+ else io.err(`Error: ${shown}: ${oneLine(String((e && e.message) || e).split(/\r?\n/)[0])}`);
72
+ return 1;
73
+ }
74
+ const script = loaded && loaded.default !== undefined ? loaded.default : loaded;
75
+ if (typeof script !== 'function') {
76
+ io.err(`Error: ${shown}: no agent script exported; the entry ends with "export default agent.build()"`);
77
+ return 1;
78
+ }
79
+ io.out(`OK: ${shown} builds`);
80
+ return 0;
81
+ }
82
+
83
+ module.exports = { check, resolveEntry };
84
+
85
+ if (require.main === module) {
86
+ check(process.argv.slice(2), {
87
+ cwd: process.cwd(),
88
+ out: (line) => process.stdout.write(`${line}\n`),
89
+ err: (line) => process.stderr.write(`${line}\n`),
90
+ load: (file) => require(file),
91
+ }).then(
92
+ (code) => process.exit(code),
93
+ (e) => {
94
+ process.stderr.write(`Error: ${oneLine((e && e.message) || e)}\n`);
95
+ process.exit(1);
96
+ },
97
+ );
98
+ }
@@ -1,3 +1,3 @@
1
1
  /** Package identity. */
2
2
  export declare const AGENT_RUNTIME_PACKAGE: "@voctiv/agent-runtime";
3
- export declare const AGENT_RUNTIME_VERSION: "0.4.0";
3
+ export declare const AGENT_RUNTIME_VERSION: "0.4.1";
@@ -3,4 +3,4 @@ Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.AGENT_RUNTIME_VERSION = exports.AGENT_RUNTIME_PACKAGE = void 0;
4
4
  /** Package identity. */
5
5
  exports.AGENT_RUNTIME_PACKAGE = '@voctiv/agent-runtime';
6
- exports.AGENT_RUNTIME_VERSION = '0.4.0';
6
+ exports.AGENT_RUNTIME_VERSION = '0.4.1';
@@ -17,7 +17,8 @@ voctiv-agent-runtime/
17
17
  voice/ # голос движка: turn timing, speech leak, transfer
18
18
  exports.spec.ts # снимок публичного API
19
19
  templates/agent/ # шаблон нового агента
20
- skill/ # справочник для авторов агентов (SKILL.md + references/), входит в npm-пакет
20
+ bin/ # voctiv-agent-check: проверка собранного агента сборщиком, без звонка
21
+ skill/ # справочник для авторов агентов (SKILL.md + references/) и фрагменты AGENTS.md, входит в npm-пакет
21
22
  docs/
22
23
  ```
23
24
 
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@voctiv/agent-runtime",
3
- "version": "0.4.0",
3
+ "version": "0.4.1",
4
4
  "description": "Voctiv voice-agent runtime: an agent is data (the builder voiceAgent(...).pipe(...blocks).build() of the templates engine) on top of @voctiv/agent-sdk.",
5
5
  "license": "UNLICENSED",
6
6
  "keywords": [
@@ -30,8 +30,19 @@
30
30
  "default": "./dist/templates/index.js"
31
31
  }
32
32
  },
33
+ "bin": {
34
+ "voctiv-agent-check": "./bin/voctiv-agent-check.js"
35
+ },
36
+ "voctivAgentKit": {
37
+ "skill": "skill",
38
+ "agents": "skill/AGENTS.md",
39
+ "agentsRecommend": "skill/AGENTS.recommend.md",
40
+ "types": "dist",
41
+ "templates": "templates"
42
+ },
33
43
  "files": [
34
44
  "dist",
45
+ "bin",
35
46
  "README.md",
36
47
  "docs",
37
48
  "skill",
@@ -42,7 +53,7 @@
42
53
  "typecheck": "tsc -p tsconfig.build.json --noEmit",
43
54
  "test": "vitest run",
44
55
  "test:watch": "vitest",
45
- "prepublishOnly": "npm run build"
56
+ "prepublishOnly": "rm -rf dist && npm run build"
46
57
  },
47
58
  "peerDependencies": {
48
59
  "@voctiv/agent-sdk": "^0.4.0",
@@ -0,0 +1,43 @@
1
+ ## This agent is built on `{{PACKAGE_NAME}}` {{PACKAGE_VERSION}}
2
+
3
+ The agent's logic is **data**: the blocks of `voiceAgent(...).pipe(...).build()` in its entry file (`src/agent.ts`).
4
+ The library runs the call (dialing, recognition, turns, silence, voicemail, transfer, extraction, the report row).
5
+
6
+ - Change behaviour by changing a value of a block. Do not add functions, hooks or hand-written call code: a function
7
+ anywhere in the agent's data does not compile, and the build refuses it.
8
+ - The agent is wholly built by the library. The platform's code-writing skills are for hand-written agents and do not
9
+ apply here.
10
+ - If the data cannot express what is asked, say so and stop: that is a request for a generic block or field of the
11
+ library, not code in this agent.
12
+
13
+ ### When the skill `$voctiv-agent-runtime` is needed
14
+
15
+ Needed — the change touches what the agent says or does in a call:
16
+
17
+ - the opening (hello, greeting, language pick, identity question), rules and their actions;
18
+ - results, the report row, extraction, input fields;
19
+ - integrations (HTTP to client systems), transfer to an operator;
20
+ - silence, voicemail, the farewell and hangup, speech over the agent;
21
+ - languages, recognizer and voice settings.
22
+
23
+ Open the skill's `SKILL.md`, find the change in its table, and read only the file and section it names
24
+ (`references/conversation.md`, `references/business.md`, `references/expressions.md`, `references/agent-file.md`, …).
25
+
26
+ Not needed:
27
+
28
+ - editing only the text of the prompt (keep the signals and the farewell convention the agent file names);
29
+ - reviewing calls, reading transcripts or report rows;
30
+ - statistics and other questions that do not change the agent.
31
+
32
+ ### Where things are
33
+
34
+ - Types of every block and field (`*.d.ts`): `{{PACKAGE_DIR}}/types`.
35
+ - Starter template of an agent (entry file, entities, prompt skeleton, tests): `{{PACKAGE_DIR}}/templates/agent`.
36
+
37
+ ### Checking a change
38
+
39
+ 1. Build the draft. The build ends with the library's check of the agent; a failure is one line starting with
40
+ `Error:` that names the agent and the path inside its data — fix the value at that path.
41
+ 2. Run scenarios on the draft for every behaviour the change touches (at least one per affected result) and read what
42
+ the agent said, the result and the report row.
43
+ 3. Report the diff and the scenario outcomes. Deploy only when asked.
@@ -0,0 +1,27 @@
1
+ ## Voice agents on `{{PACKAGE_NAME}}`
2
+
3
+ This agent does **not** depend on `{{PACKAGE_NAME}}` (recommended version: {{PACKAGE_VERSION}}). On that library an
4
+ agent is data — the blocks of `voiceAgent(...).pipe(...).build()` — and the library runs the call. An agent is either
5
+ wholly built that way or wholly hand-written; the two are never mixed piece by piece. Which case applies:
6
+
7
+ 1. **A new agent, or logic written from scratch** — write it on the library. Start from the starter template
8
+ `{{PACKAGE_DIR}}/templates/agent`, add `{{PACKAGE_NAME}}` to the dependencies, and follow the skill
9
+ `$voctiv-agent-runtime` (`references/new-agent.md`). The platform's code-writing skills are not used for it.
10
+ 2. **An existing hand-written agent** — change it in its own style, with the platform's code-writing skills. Do not
11
+ import the library into it and do not rewrite parts of it with `voiceAgent`. If a move to the library would clearly
12
+ help (the change repeats what a block already does, or the hand-written code is the obstacle), say so in one or two
13
+ lines and propose it; do not do it.
14
+ 3. **The user explicitly asks to move the agent to the library** — follow the porting procedure of the skill
15
+ `$voctiv-agent-runtime` (`references/porting.md`, «The move, step by step»), in this order:
16
+ 1. regression scenarios from real calls, run on the current code (every result, silence, voicemail, transfer);
17
+ 2. the port, in the draft;
18
+ 3. the same scenarios on the draft, compared with the first run (agent lines, results, report row, HTTP to client
19
+ systems);
20
+ 4. show the results and the diff, ask about every difference that changes a result, a row or a request.
21
+
22
+ Deploy only when asked.
23
+
24
+ The skill `$voctiv-agent-runtime` is needed for cases 1 and 3 only. For case 2, and for prompt-only edits, call
25
+ review and statistics, it is not.
26
+
27
+ Types of the library (`*.d.ts`): `{{PACKAGE_DIR}}/types`. Starter template: `{{PACKAGE_DIR}}/templates/agent`.
package/skill/SKILL.md CHANGED
@@ -1,9 +1,9 @@
1
1
  ---
2
2
  name: voctiv-agent-runtime
3
- description: Reference for writing, changing or porting a Voctiv voice agent with @voctiv/agent-runtime — an agent is data only: the builder and its blocks, the agent file format (AgentSpec), the data language, opening/turn/silence/overtalk blocks, rules and actions, results and report, locale packs, the core runtime. For any work on an agent or on this library.
3
+ description: Writing or changing a voice agent built on @voctiv/agent-runtime (its logic is data in voiceAgent(...).pipe(...blocks).build()). Use when a change touches what such an agent says or does in a call — opening, rules, results, report row, integrations, transfer, silence, voicemail, languages — when creating a new agent on the library, or when moving a hand-written agent onto it. Not needed for prompt-only edits, call review or statistics.
4
4
  ---
5
5
 
6
- # @voctiv/agent-runtime — voice agents from templates
6
+ # @voctiv/agent-runtime — writing and changing a voice agent
7
7
 
8
8
  ## What this library is
9
9
 
@@ -14,179 +14,66 @@ forms only (conditions, expressions, texts, matchers as data); a function or a r
14
14
  agent does not compile. Everything else (dialing, attempts, recalls, recognition, interruptions, silence, the LLM turn,
15
15
  voicemail, transfer, extraction, the report row) is generic library code, the same for every agent.
16
16
 
17
- Hard rules for the library itself:
17
+ What follows for an agent author:
18
18
 
19
- - No client, agent or product names in library code, comments or option names.
20
- - No client code anywhere: no client packages, family presets, client helpers or agent code with business rules. What
21
- differs between agents is data in the agent file (`Condition`/`Expr`, template options, locale packs).
22
- - No words of any language in library code: language data lives in locale packs (`src/templates/locales/<code>.ts`).
23
- - A behaviour two agents need differently is a **value** in the agent file, never a flag named after an agent or a
24
- template version.
25
- - **The library works like clockwork: predictable and transparent.** It takes no hidden decisions on the agent's
26
- behalf. Every limit is a documented option with a documented default the agent can set; every outcome is handed to
27
- the agent's data (its configured reaction) and reported honestly in the row (a transfer that did not connect is not
28
- reported as transferred, a call is never hung up by the library unless the agent's data or a documented limit says
29
- so). What an agent does not configure gets the documented default — that is the agent's choice, not the library's.
30
- - **What an agent needs and the data cannot say is added to the library**, never written as code in the agent: a
31
- generic template or field (in `src/templates/spec.ts`, its data-only form follows in `authoring.ts`), chosen by
32
- values, with a default that keeps every other agent unchanged — and documented here.
19
+ - A behaviour is changed by changing a **value of a block**, never by adding a function, a hook or call-handling code.
20
+ - An agent is either wholly built by `voiceAgent(...).build()` or wholly hand-written: the library is not mixed into a
21
+ hand-written agent piece by piece.
22
+ - What the data cannot say is not written as code in the agent: it is a request for a generic block or field of the
23
+ library (say so and stop; do not work around it).
24
+ - The library decides nothing silently: every limit is a documented option with a default, every outcome goes to the
25
+ agent's data and honestly into the report row.
33
26
 
34
- ## Layers
27
+ ## What to read for a change
35
28
 
36
- ```
37
- agent.ts: voiceAgent(id).pipe(...blocks).build() + prompt template
38
- │
39
- ▼
40
- builder ── one block per AgentSpec section, opening step helpers, generic presets → the AgentSpec object
41
- │
42
- ▼
43
- templates ── one conversation engine built from blocks: opening steps, gates, rules/actions, turn, overtalk,
44
- silence, voicemail, closing, transfer; business templates: input, extraction, results, report,
45
- integrations; locale packs
46
- │
47
- ▼
48
- call, voice ── internal: the call's plumbing (call variables, SIP, legs, redials, records, extraction, the report
49
- row, HTTP) and the call media (recognizers, turns, drain floors, transfer)
50
- │
51
- ▼
52
- core ── internal: call-scoped DI, phases, dialog host, media, barge-in, lifecycle (not exported)
53
- │
54
- ▼
55
- @voctiv/agent-sdk (platform API: channel, sip, audio, llm, nlu, http, records)
56
- ```
29
+ Load only the file (and section) the change needs; paths are relative to this skill.
57
30
 
58
- ## Status (keep this table true when you change the library)
59
-
60
- | Part | State | Where |
61
- |---|---|---|
62
- | Agent builder `voiceAgent(...).pipe(...).build()` | the way an agent is written; template agent and examples use it (pinned equal to their earlier `AgentSpec`); `references/builder.md` | `src/templates/builder/` |
63
- | Agent file format `AgentSpec` | the builder's output, data only (the authoring types refuse functions and agent code); one page overview `references/format.md`, every field `references/agent-file.md` | `src/templates/authoring.ts` (data-only types), `src/templates/spec.ts` (the engine's types) |
64
- | Engine (`.build()`) | compiles the data forms into its own functions (`compileDataForms`); one reducer split by block (`engine/turns/*`), one media layer (`src/voice/call-voice.ts`); bounded asynchronous steps; failures end the call with a row | `src/templates/engine/` |
65
- | Business templates: input, extraction, results, report, integrations; call plan (`callPlanFromSpec` → `CallPlan`) | working; safe retries, default time limits, after-call code isolated | `src/templates/business/`, `src/call/` |
66
- | Locale packs ru, kk, en, ms, tl, vi, es, id, hi, ta, te, kn (a pack may point at another pack's lexicon, `{ lexicon: 'hi:voicemail' }`) | golden tests; decimal comma and machine figures parsed | `src/templates/locales/` |
67
- | Data language and data templates: `Condition` / `Expr` / text templates, `facts`, `matchers`; rule lists with `when` (`results.rules`, `extraction.rules`, `turn.replyRules`, `results.catalog`, `extraction.catalog` cases), `variants` / `picks` / A-B arms, `tracking`, `ladders`, `choices`, `closing.guard`, `input.testData.presets`, `annotateCaller.notes`, `prompt.callVars`, integrations as data (`afterLeg`, `trunkPool`, `routeRules`, callbacks), readers and `dayTable` | how every agent difference is written: no agent needs code; `references/expressions.md`, `business.md`, `conversation.md` | `src/templates/expr/`, `business/`, `engine/` |
68
- | Blocks with their own engine: `decisionModel`, `knowledgeAnswer` (KB answers, no LLM), `catalogMatch` + `verify` (a name matched to a two-level list, checked with a client service) | working; wired in by `withBlocks` when the script is built; `references/blocks.md` | `src/templates/decision-model/`, `knowledge/`, `catalog-match/`, `engine/expand.ts` |
69
- | Public API | engine-only: `/templates` (builder, blocks, data-only format types, data language evaluators), `/testing` (test-only and unstable: may change in any minor version, never imported by agent source; `specOf`, `compiledSpecOf`, `compileDataForms`, `decideByRules` …), root name/version; pinned by `src/exports.spec.ts` | `src/templates/index.ts`, `src/testing/` |
70
- | Core runtime | internal (call container, phases, dialog host, media, barge-in, lifecycle); not exported | `src/core`, `src/dialog`, … |
71
-
72
- Verification: every production-derived agent is replayed on a call harness against its earlier journals (rows, HTTP,
73
- LLM and extraction payloads byte for byte, timing at 0 ms); a library change is done when that replay is unchanged or
74
- every difference is explained.
75
-
76
- An agent with a recorded hello and an LLM greeting, or with a fixed-phrase opening, a language pick and an identity
77
- gate, with or without an operator transfer, is its blocks: `export default voiceAgent(id).pipe(…).build()`. An agent written on the removed subpaths
78
- (`./dialog`, `./barge-in` …) or the removed kit moves with `references/migration.md`.
79
-
80
- ## Create a new agent
81
-
82
- Write it with the builder. Copy `templates/agent/` of the library (shipped in the package too:
83
- `node_modules/@voctiv/agent-runtime/templates/agent/`) and fill its `TODO`s. Every block, ordering rules and errors:
84
- `references/builder.md`; step by step, the order of sections, tests and common mistakes: `references/new-agent.md`.
85
-
86
- ```
87
- my-agent/
88
- package.json depends on @voctiv/agent-runtime, @voctiv/agent-sdk, reflect-metadata, rxjs, tsyringe
89
- src/agent.ts voiceAgent(id).pipe(...blocks); export default agent.build() (recorded hello + LLM greeting)
90
- src/variants/fixed-opening.ts agent.override(...): fixed bilingual greeting, language pick, identity gate
91
- src/entities.ts extraction entities
92
- src/prompt.sqrl system instruction of the CMS agent (rendered by the platform, not read by the script)
93
- src/agent.spec.ts the builder and the engine accept the agent; results and report name known results and entities
94
- ```
95
-
96
- 1. Pick the opening (`recordedHelloOpening(…)` + LLM greeting, or the fixed-phrase variant; inbound; no LLM).
97
- 2. Fill first: `voiceAgent({ name, uuid, version })`, `languages(…)` + `voice({ asr, tts })`, `input({ fields })`, the
98
- opening, `prompt({ … })` (with the same signals and farewell convention as `closing.goodbye`), then `extraction` →
99
- `results` → `report` → `integrations`; the conversation blocks keep their defaults until a replayed call shows
100
- otherwise.
101
- 3. `npm run typecheck && npm test && npm run build` (`npm test` builds the agent: a section given twice or missing, or a
102
- combination the engine refuses, fails here naming it), then replay a scenario per result on the stand before the
103
- first real call.
104
-
105
- The template is checked against the packed library (`npm pack` → install → `tsc`, build) and replayed on the call
106
- harness (both openings: hello → greeting → answer → farewell → row); the library test
107
- `src/templates/builder/template-agent.spec.ts` pins its spec. Keep it so when a field changes.
108
-
109
- ### Shape of an agent
110
-
111
- Minimal agent (recorded hello, LLM greeting, LLM conversation, silence ladder, voicemail, extraction, report):
112
-
113
- ```ts
114
- import 'reflect-metadata';
115
- import {
116
- voiceAgent, languages, platform, voice, input, prompt, recordedHelloOpening, silenceLadder, voicemail, closing,
117
- extraction, results, report,
118
- } from '@voctiv/agent-runtime/templates';
119
-
120
- export const agent = voiceAgent({ name: 'example-reminder', uuid: '00000000-0000-0000-0000-000000000000', version: '1.0.0' }).pipe(
121
- languages('en'),
122
- platform({
123
- maxCallMs: 600_000, outboundMode: 'from_invite', links: { host: 'https://cms.example' },
124
- recall: { budget: { from: { platform: true } }, delaySec: { from: { platform: true } } },
125
- }),
126
- voice({
127
- asr: { en: { vendor: 'deepgram', language: 'en-US' } },
128
- tts: { vendor: 'elevenlabs', voiceId: { from: { global: 'voice_id' }, default: 'voice-1' }, strategy: 'sentence' },
129
- vad: { threshold: 0.5 },
130
- }),
131
- input({
132
- timeZone: 'Asia/Manila',
133
- fields: {
134
- customer_name: { from: [{ header: 'customer_name' }, { entity: 'customer_name' }], format: 'name' },
135
- amount: { from: { entity: 'amount' }, format: { kind: 'amount', currency: 'PHP' } },
136
- },
137
- }),
138
- prompt({ template: 'prompt.sqrl', silenceSignal: '…' }),
139
- // Recorded hello; the caller's «hello?» goes to the transcript only; then the greeting the LLM prepared meanwhile.
140
- recordedHelloOpening({
141
- hello: { record: 'HELLO_MAIN', text: 'Hello?' },
142
- retry: { record: 'HELLO_NULL', text: 'Hello, can you hear me?' },
143
- afterMs: 4000,
144
- greeting: { signal: '<<< call_started;', waitMs: 3000, eager: true },
145
- }),
146
- silenceLadder({ afterMs: 4000, prompts: 2, signal: '…', end: { close: 'Sorry, I cannot hear you. Goodbye.', result: 'bad connection' } }),
147
- voicemail({ detectors: [{ by: 'nlu', intents: ['voicemail'], fallback: { lexicon: 'voicemail' } }] }),
148
- closing({ goodbye: { tail: { lexicon: 'goodbye' }, chars: 40 } }),
149
- extraction({
150
- model: 'platform',
151
- entities: [{ name: 'promise_to_pay', description: 'Did the customer promise to pay? Date if yes.', schema: { type: 'object' }, implies: 'PTP', priority: 1 }],
152
- }),
153
- results({ table: { PTP: {}, DEFAULT: { recall: true } } }),
154
- report({ fields: { result: { fact: 'result' }, call_status: { fact: 'status' }, promise: { entity: 'promise_to_pay' } } }),
155
- );
156
-
157
- export default agent.build();
158
- ```
159
-
160
- Read next, by task:
161
-
162
- | Task | Read |
31
+ | The change | Read |
163
32
  |---|---|
164
- | Writing an agent: the builder, every block, presets, ordering rules, errors | `references/builder.md` |
165
- | The format on one page: sections, failure defaults, public API, removed fields | `references/format.md` |
166
- | Every field of the agent file, defaults, units | `references/agent-file.md` |
167
- | The data language: conditions and expressions (every operator with an example, which slots take them, readers, helper options) | `references/expressions.md` |
168
- | Opening steps, gates, rules and actions, silence, overtalk, voicemail, closing, transfer — how they interact in a call | `references/conversation.md` |
169
- | Input fields, prompt, extraction, results, report row, integrations, recalls | `references/business.md` |
170
- | Locale packs: what is in one, adding a language, lexicon names, formatters | `references/locales.md` |
171
- | Moving an agent written on 0.2.x / 0.3 subpaths or the removed kit (`createVoiceAgentScript`): subpaths and options → blocks and fields | `references/migration.md` |
172
- | Public API per subpath; the internal core under the engine (phases, dialog loop, DI) | `references/core.md` |
173
- | A new agent from the template: steps, which fields first, tests, common mistakes | `references/new-agent.md` |
174
- | Porting an existing agent (template copy or fixed-phrase opening) and proving it behaves the same | `references/porting.md` |
175
- | Complete example agent files | `references/examples.md` |
176
-
177
- This reference is in English; the package README and `docs/framework/*` (the core under the engine) are in Russian.
178
-
179
- ## Workflow for a change
180
-
181
- 1. Decide where it belongs: agent data (the agent file) or a generic behaviour (the library). An agent is data only:
182
- what its data cannot say — even one client's rule — becomes a generic library template or field.
183
- 2. For a library change: add the field to `src/templates/spec.ts` with a doc comment and a default that keeps every
184
- other agent unchanged (its data-only form in `authoring.ts` follows; a new data form is compiled in
185
- `src/templates/expr/slots.ts`); implement; add a unit test of the block (reducer-level, no media) and a
186
- replayed-call test; update this reference (field guide + status table).
187
- 3. For an agent change: edit its blocks; run its tests; replay its recorded scenarios and compare (see
188
- `references/porting.md`, «Proving it behaves the same»).
189
- 4. `npm run build && npm test` in the library before any push.
33
+ | The opening: recorded hello, greeting, fixed phrase, language pick, identity or consent question | `references/conversation.md` § Opening steps, § Gates |
34
+ | What the agent answers: the LLM turn, reply filters and rules, verdicts on a reply; the prompt and its variables | `references/conversation.md` § Turn, § Reply rules, § Verdicts on a reply; `references/business.md` § Prompt |
35
+ | Reacting to a caller line or an event: rules and their actions | `references/conversation.md` § Rules, § Actions |
36
+ | The caller speaks over the agent | `references/conversation.md` § Overtalk |
37
+ | Silence: prompts, how many, when to hang up | `references/conversation.md` § Silence |
38
+ | Voicemail detection and what happens then | `references/conversation.md` § Voicemail |
39
+ | The farewell and the hangup | `references/conversation.md` § Closing, § Closing guard re-asks |
40
+ | Transfer to an operator and its outcomes | `references/conversation.md` § Transfer |
41
+ | What the call receives (dialer fields, formats, test data) | `references/business.md` § Input, § Test records as data |
42
+ | What is extracted after the call | `references/business.md` § Extraction |
43
+ | Results: the table, rules, catalog; redials | `references/business.md` § Results, § Recalls and attempts, § Leg policy as data |
44
+ | The report row: fields, order, service fields | `references/business.md` § Report row |
45
+ | HTTP to client systems before, during or after the call | `references/business.md` § Integrations, § Integrations as data, § Lookup at answer |
46
+ | Languages: adding one, wording of numbers and dates, word lists | `references/locales.md`; `references/agent-file.md` § `languages` |
47
+ | Recognizer, voice, VAD, end of turn | `references/agent-file.md` § `voice` |
48
+ | A condition, an expression, a text template, a named fact or matcher | `references/expressions.md` |
49
+ | Per-call counters, ladders, choices, notes on caller lines | `references/blocks.md` § State blocks |
50
+ | Answers from a knowledge base, a decision model, a spoken name matched to a list | `references/blocks.md` |
51
+ | Any single field: meaning, default, units | `references/agent-file.md` |
52
+ | Blocks and sections, presets, variants (`override`), build errors | `references/builder.md`; `references/conversation.md` § What the engine refuses |
53
+ | The whole format on one page; what the library does on failures | `references/format.md` |
54
+ | A new agent: starter template, order of filling, build-time check, tests, common mistakes | `references/new-agent.md`; complete examples: `references/examples.md` |
55
+ | Moving a hand-written agent onto the library and proving it behaves the same | `references/porting.md` |
56
+ | An agent on the 0.2.x / 0.3 subpaths or the removed kit | `references/migration.md` |
57
+
58
+ The starter template is the folder `templates/agent` of the package; the authoring types are the package's `.d.ts`
59
+ files. Where the package is depends on the workspace: among the installed dependencies of a local checkout; an
60
+ assistant's workspace may expose it elsewhere (its instructions say where).
61
+
62
+ Developing the library itself (rules for library code, layers, status table, workflow): `references/library-dev.md`.
63
+
64
+ ## The change loop
65
+
66
+ 1. **Find the block.** Read the agent's entry (`src/agent.ts`): the change is a value in one of its blocks. Read the
67
+ section of the table above for that block before editing.
68
+ 2. **Edit the data.** If the prompt names the same thing (a signal, a farewell convention, a variable), change both.
69
+ 3. **Build.** The build compiles the types (a function or an unknown field does not compile) and then runs
70
+ `voctiv-agent-check`, which loads the built agent so the builder checks it. A failure is one line starting with
71
+ `Error:` that names the agent and the path inside its data (`report.fields.x.fact: unknown fact …`): fix that value.
72
+ Where the agent is built by a platform, this is its draft build; with a local checkout: `npm run build`.
73
+ 4. **Run it.** Run a scenario (a scripted call) for every behaviour the change touches, on the built draft, and read
74
+ what the agent said, the result and the report row. With a local checkout also `npm test`.
75
+ 5. **Report** what changed (the diff), which scenarios ran and their outcome. Releasing or deploying is a separate
76
+ step, done on request.
190
77
 
191
78
  ## Pitfalls
192
79
 
@@ -0,0 +1,84 @@
1
+ # Developing the library itself
2
+
3
+ For work on `@voctiv/agent-runtime` (its engine, blocks, locale packs, the template agent, this reference), not on an
4
+ agent. An agent author does not need this page: an agent is data, see `../SKILL.md`.
5
+
6
+ ## Hard rules for library code
7
+
8
+ - No client, agent or product names in library code, comments or option names.
9
+ - No client code anywhere: no client packages, family presets, client helpers or agent code with business rules. What
10
+ differs between agents is data in the agent file (`Condition`/`Expr`, template options, locale packs).
11
+ - No words of any language in library code: language data lives in locale packs (`src/templates/locales/<code>.ts`).
12
+ - A behaviour two agents need differently is a **value** in the agent file, never a flag named after an agent or a
13
+ template version.
14
+ - **The library works like clockwork: predictable and transparent.** It takes no hidden decisions on the agent's
15
+ behalf. Every limit is a documented option with a documented default the agent can set; every outcome is handed to
16
+ the agent's data (its configured reaction) and reported honestly in the row (a transfer that did not connect is not
17
+ reported as transferred, a call is never hung up by the library unless the agent's data or a documented limit says
18
+ so). What an agent does not configure gets the documented default — that is the agent's choice, not the library's.
19
+ - **What an agent needs and the data cannot say is added to the library**, never written as code in the agent: a
20
+ generic template or field (in `src/templates/spec.ts`, its data-only form follows in `authoring.ts`), chosen by
21
+ values, with a default that keeps every other agent unchanged — and documented here.
22
+
23
+ ## Layers
24
+
25
+ ```
26
+ agent.ts: voiceAgent(id).pipe(...blocks).build() + prompt template
27
+ │
28
+ ▼
29
+ builder ── one block per AgentSpec section, opening step helpers, generic presets → the AgentSpec object
30
+ │
31
+ ▼
32
+ templates ── one conversation engine built from blocks: opening steps, gates, rules/actions, turn, overtalk,
33
+ silence, voicemail, closing, transfer; business templates: input, extraction, results, report,
34
+ integrations; locale packs
35
+ │
36
+ ▼
37
+ call, voice ── internal: the call's plumbing (call variables, SIP, legs, redials, records, extraction, the report
38
+ row, HTTP) and the call media (recognizers, turns, drain floors, transfer)
39
+ │
40
+ ▼
41
+ core ── internal: call-scoped DI, phases, dialog host, media, barge-in, lifecycle (not exported)
42
+ │
43
+ ▼
44
+ @voctiv/agent-sdk (platform API: channel, sip, audio, llm, nlu, http, records)
45
+ ```
46
+
47
+ ## Status (keep this table true when you change the library)
48
+
49
+ | Part | State | Where |
50
+ |---|---|---|
51
+ | Agent builder `voiceAgent(...).pipe(...).build()` | the way an agent is written; template agent and examples use it (pinned equal to their earlier `AgentSpec`); `references/builder.md` | `src/templates/builder/` |
52
+ | Agent file format `AgentSpec` | the builder's output, data only (the authoring types refuse functions and agent code); one page overview `references/format.md`, every field `references/agent-file.md` | `src/templates/authoring.ts` (data-only types), `src/templates/spec.ts` (the engine's types) |
53
+ | Engine (`.build()`) | compiles the data forms into its own functions (`compileDataForms`); one reducer split by block (`engine/turns/*`), one media layer (`src/voice/call-voice.ts`); bounded asynchronous steps; failures end the call with a row | `src/templates/engine/` |
54
+ | Business templates: input, extraction, results, report, integrations; call plan (`callPlanFromSpec` → `CallPlan`) | working; safe retries, default time limits, after-call code isolated | `src/templates/business/`, `src/call/` |
55
+ | Locale packs ru, kk, en, ms, tl, vi, es, id, hi, ta, te, kn (a pack may point at another pack's lexicon, `{ lexicon: 'hi:voicemail' }`) | golden tests; decimal comma and machine figures parsed | `src/templates/locales/` |
56
+ | Data language and data templates: `Condition` / `Expr` / text templates, `facts`, `matchers`; rule lists with `when` (`results.rules`, `extraction.rules`, `turn.replyRules`, `results.catalog`, `extraction.catalog` cases), `variants` / `picks` / A-B arms, `tracking`, `ladders`, `choices`, `closing.guard`, `input.testData.presets`, `annotateCaller.notes`, `prompt.callVars`, integrations as data (`afterLeg`, `trunkPool`, `routeRules`, callbacks), readers and `dayTable` | how every agent difference is written: no agent needs code; `references/expressions.md`, `business.md`, `conversation.md` | `src/templates/expr/`, `business/`, `engine/` |
57
+ | Blocks with their own engine: `decisionModel`, `knowledgeAnswer` (KB answers, no LLM), `catalogMatch` + `verify` (a name matched to a two-level list, checked with a client service) | working; wired in by `withBlocks` when the script is built; `references/blocks.md` | `src/templates/decision-model/`, `knowledge/`, `catalog-match/`, `engine/expand.ts` |
58
+ | Public API | engine-only: `/templates` (builder, blocks, data-only format types, data language evaluators), `/testing` (test-only and unstable: may change in any minor version, never imported by agent source; `specOf`, `compiledSpecOf`, `compileDataForms`, `decideByRules` …), root name/version; pinned by `src/exports.spec.ts` | `src/templates/index.ts`, `src/testing/` |
59
+ | Core runtime | internal (call container, phases, dialog host, media, barge-in, lifecycle); not exported | `src/core`, `src/dialog`, … |
60
+
61
+ Verification: every production-derived agent is replayed on a call harness against its earlier journals (rows, HTTP,
62
+ LLM and extraction payloads byte for byte, timing at 0 ms); a library change is done when that replay is unchanged or
63
+ every difference is explained.
64
+
65
+ ## The template agent
66
+
67
+ The template is checked against the packed library (`npm pack` → install → `tsc`, build) and replayed on the call
68
+ harness (both openings: hello → greeting → answer → farewell → row); the library test
69
+ `src/templates/builder/template-agent.spec.ts` pins its spec. Keep it so when a field changes.
70
+
71
+ ## Workflow for a change
72
+
73
+ 1. Decide where it belongs: agent data (the agent file) or a generic behaviour (the library). An agent is data only:
74
+ what its data cannot say — even one client's rule — becomes a generic library template or field.
75
+ 2. For a library change: add the field to `src/templates/spec.ts` with a doc comment and a default that keeps every
76
+ other agent unchanged (its data-only form in `authoring.ts` follows; a new data form is compiled in
77
+ `src/templates/expr/slots.ts`); implement; add a unit test of the block (reducer-level, no media) and a
78
+ replayed-call test; update this reference (field guide + the status table above).
79
+ 3. For an agent change: edit its blocks; run its tests; replay its recorded scenarios and compare (see
80
+ `porting.md`, «Proving it behaves the same»).
81
+ 4. `npm run build && npm test` in the library before any push.
82
+
83
+ The public API per subpath and the core under the engine (phases, dialog loop, DI, invariants): `core.md`. This
84
+ reference is in English; the package README and `docs/framework/*` (the core under the engine) are in Russian.
@@ -1,9 +1,10 @@
1
1
  # Create a new agent
2
2
 
3
3
  A new agent is written with the builder (`builder.md`): `voiceAgent({ name, uuid, version }).pipe(...blocks)`, one
4
- block per section, `export default agent.build()`. It starts from `templates/agent/` of the library (also shipped in
5
- the package: `node_modules/@voctiv/agent-runtime/templates/agent/`): a working agent with defaults taken from agents in
6
- production; every value only the agent's author knows is marked `TODO`.
4
+ block per section, `export default agent.build()`. It starts from the starter template: the folder
5
+ `templates/agent` of the package (a local install has the package under `node_modules/@voctiv/agent-runtime`; an
6
+ assistant's workspace may expose the package's templates elsewhere — its instructions say where): a working agent with
7
+ defaults taken from agents in production; every value only the agent's author knows is marked `TODO`.
7
8
 
8
9
  ```
9
10
  templates/agent/
@@ -17,6 +18,73 @@ templates/agent/
17
18
  src/agent.spec.ts the builder and the engine accept the agent; results / report name known results and entities
18
19
  ```
19
20
 
21
+ ## In short
22
+
23
+ 1. Pick the opening (`recordedHelloOpening(…)` + LLM greeting, or the fixed-phrase variant; inbound; no LLM).
24
+ 2. Fill first: `voiceAgent({ name, uuid, version })`, `languages(…)` + `voice({ asr, tts })`, `input({ fields })`, the
25
+ opening, `prompt({ … })` (with the same signals and farewell convention as `closing.goodbye`), then `extraction` →
26
+ `results` → `report` → `integrations`; the conversation blocks keep their defaults until a replayed call shows
27
+ otherwise.
28
+ 3. Typecheck, test and build (with a local checkout: `npm run typecheck && npm test && npm run build`; the build and
29
+ `npm test` build the agent: a section given twice or missing, or a combination the engine refuses, fails here
30
+ naming it), then replay a scenario per result on the stand before the
31
+ first real call.
32
+
33
+ An agent with a recorded hello and an LLM greeting, or with a fixed-phrase opening, a language pick and an identity
34
+ gate, with or without an operator transfer, is its blocks: `export default voiceAgent(id).pipe(…).build()`. An agent written on the removed subpaths
35
+ (`./dialog`, `./barge-in` …) or the removed kit moves with `migration.md`.
36
+
37
+ ## Shape of an agent
38
+
39
+ Minimal agent (recorded hello, LLM greeting, LLM conversation, silence ladder, voicemail, extraction, report):
40
+
41
+ ```ts
42
+ import 'reflect-metadata';
43
+ import {
44
+ voiceAgent, languages, platform, voice, input, prompt, recordedHelloOpening, silenceLadder, voicemail, closing,
45
+ extraction, results, report,
46
+ } from '@voctiv/agent-runtime/templates';
47
+
48
+ export const agent = voiceAgent({ name: 'example-reminder', uuid: '00000000-0000-0000-0000-000000000000', version: '1.0.0' }).pipe(
49
+ languages('en'),
50
+ platform({
51
+ maxCallMs: 600_000, outboundMode: 'from_invite', links: { host: 'https://cms.example' },
52
+ recall: { budget: { from: { platform: true } }, delaySec: { from: { platform: true } } },
53
+ }),
54
+ voice({
55
+ asr: { en: { vendor: 'deepgram', language: 'en-US' } },
56
+ tts: { vendor: 'elevenlabs', voiceId: { from: { global: 'voice_id' }, default: 'voice-1' }, strategy: 'sentence' },
57
+ vad: { threshold: 0.5 },
58
+ }),
59
+ input({
60
+ timeZone: 'Asia/Manila',
61
+ fields: {
62
+ customer_name: { from: [{ header: 'customer_name' }, { entity: 'customer_name' }], format: 'name' },
63
+ amount: { from: { entity: 'amount' }, format: { kind: 'amount', currency: 'PHP' } },
64
+ },
65
+ }),
66
+ prompt({ template: 'prompt.sqrl', silenceSignal: '…' }),
67
+ // Recorded hello; the caller's «hello?» goes to the transcript only; then the greeting the LLM prepared meanwhile.
68
+ recordedHelloOpening({
69
+ hello: { record: 'HELLO_MAIN', text: 'Hello?' },
70
+ retry: { record: 'HELLO_NULL', text: 'Hello, can you hear me?' },
71
+ afterMs: 4000,
72
+ greeting: { signal: '<<< call_started;', waitMs: 3000, eager: true },
73
+ }),
74
+ silenceLadder({ afterMs: 4000, prompts: 2, signal: '…', end: { close: 'Sorry, I cannot hear you. Goodbye.', result: 'bad connection' } }),
75
+ voicemail({ detectors: [{ by: 'nlu', intents: ['voicemail'], fallback: { lexicon: 'voicemail' } }] }),
76
+ closing({ goodbye: { tail: { lexicon: 'goodbye' }, chars: 40 } }),
77
+ extraction({
78
+ model: 'platform',
79
+ entities: [{ name: 'promise_to_pay', description: 'Did the customer promise to pay? Date if yes.', schema: { type: 'object' }, implies: 'PTP', priority: 1 }],
80
+ }),
81
+ results({ table: { PTP: {}, DEFAULT: { recall: true } } }),
82
+ report({ fields: { result: { fact: 'result' }, call_status: { fact: 'status' }, promise: { entity: 'promise_to_pay' } } }),
83
+ );
84
+
85
+ export default agent.build();
86
+ ```
87
+
20
88
  ## Steps
21
89
 
22
90
  1. **Pick the opening.** The caller hears a recorded «hello?» and then an LLM greeting → `recordedHelloOpening(…)` of
@@ -44,9 +112,30 @@ templates/agent/
44
112
  does not compile. A need the format lacks is added to the library as a generic template or field with a default
45
113
  that keeps every other agent unchanged (ask for it).
46
114
 
115
+ ## The build-time check: `voctiv-agent-check`
116
+
117
+ The package ships a command that loads the built agent entry, so `agent.build()` runs every check of the builder and
118
+ the engine (a section given twice or missing, a function in the data, an unknown fact, operator, template filter or
119
+ reader, a combination the engine refuses). It starts no call and needs no platform, network or environment variables.
120
+
121
+ ```
122
+ voctiv-agent-check [path] path: the built entry file or the agent's folder; default: the current folder
123
+ ```
124
+
125
+ - In a folder the entry is `main` of its `package.json`, else `dist/index.js`, else `dist/agent.js`.
126
+ - The agent builds → exit code 0 and one line: `OK: dist/agent.js builds`.
127
+ - It does not → exit code 1 and one line starting with `Error:`; a refusal of the builder names the agent and the path
128
+ inside its data: `Error: voiceAgent "my-agent": report.fields.outcome.fact: unknown fact "outcom" (not built in, not
129
+ in AgentSpec.facts) (dist/agent.js)`. Fix the value at that path and build again.
130
+ - The template runs it at the end of its build (`"build": "tsc -p tsconfig.build.json && voctiv-agent-check"`), so a
131
+ build that passes means the engine accepts the agent — wherever the build runs (a local checkout, a platform's draft
132
+ build). An agent not made from the template adds the same to its own `build` script. The command is a `bin` of the
133
+ package: it is there after any install, `npm install --ignore-scripts` included.
134
+
47
135
  ## Test
48
136
 
49
- 1. `npm run typecheck && npm test && npm run build`. `npm test` builds the agent (`agent.build()`): a section given
137
+ 1. `npm run typecheck && npm test && npm run build`. The build ends with `voctiv-agent-check` and `npm test` builds
138
+ the agent (`agent.build()`) too: a section given
50
139
  twice or missing (`builder.md` § Errors) or a field the engine refuses (`conversation.md` § What the engine
51
140
  refuses) throws here with its name. Agent tests read the spec with `specOf(agent)` and import only
52
141
  `@voctiv/agent-runtime/templates` and `@voctiv/agent-runtime/testing` (the payload, report row, matchers and texts
@@ -1,6 +1,62 @@
1
1
  # Porting an existing agent
2
2
 
3
- Existing agents come in three shapes. Identify the shape first:
3
+ ## Before anything: is this a move?
4
+
5
+ A hand-written agent is moved onto the library only when the user asked for the move in so many words. Otherwise it is
6
+ changed in its own style: the library cannot be mixed in piece by piece (an agent is either wholly built by
7
+ `voiceAgent(...).build()` or wholly hand-written). When a move would clearly help, propose it and wait.
8
+
9
+ ## The move, step by step
10
+
11
+ The order is fixed: scenarios on the current code first, then the port, then the same scenarios on the port. Nothing is
12
+ deployed along the way. **Stop and ask** means: write what you found and what you need, and wait for the answer.
13
+
14
+ 1. **Fix the starting point.** Note which version of the agent serves calls (it may be newer than the copy at hand) and
15
+ work from that one. Identify its shape («Shapes of existing agents»).
16
+ *Stop and ask* if the serving version cannot be told, or the copy at hand differs from it.
17
+ 2. **Capture regression scenarios from real calls, on the current code.** For each scenario: the call's input fields,
18
+ the caller's lines with their timings, the replies of the LLM, the answers of client systems. Take at least:
19
+ - one real call for **every result** the agent has reported in the recent period (take the list of results from
20
+ the agent's result table and from its real report rows, not from memory);
21
+ - **silence**: the caller says nothing after the greeting, and falls silent mid-call (every rung of the ladder up to
22
+ the hangup);
23
+ - **voicemail**: one call per way the agent detects it;
24
+ - **transfer**, where the agent has it: connected, not answered, refused;
25
+ - what the agent guards on: speech over the greeting, a wrong person, a refused identity or consent question;
26
+ - a failed dial and a client system that does not answer.
27
+ *Stop and ask* if a result, a transfer outcome or a voicemail detector has no real call to take: the user either
28
+ points at one or agrees to a synthetic scenario (mark it as such).
29
+ 3. **Run the scenarios on the current code and keep the output** as the baseline: every agent line in order, the
30
+ result, the report row field by field, every HTTP request to client systems (method, URL, headers without secrets,
31
+ body), the LLM requests.
32
+ *Stop and ask* if the current code fails a scenario or two runs of one scenario differ: the baseline must be stable
33
+ before anything is ported.
34
+ 4. **List the agent's behaviours and map each to a block** («Steps» below, items 1–3). Write the list down: behaviour →
35
+ block and field.
36
+ *Stop and ask* if a behaviour maps to no block or field: that is a request to the library, not code in the agent,
37
+ and the move waits for it. Do not approximate it with a nearby field.
38
+ 5. **Write the port in a draft**, next to the current code, not in place of it: the builder's blocks, the prompt
39
+ unchanged unless a signal's name must change. Build it; the build-time check must pass (`new-agent.md`).
40
+ Secrets found in the old code are not copied («Steps», item 4).
41
+ 6. **Run the same scenarios on the draft and compare with the baseline**, scenario by scenario:
42
+ - **agent lines**: the same texts and clips in the same order;
43
+ - **results**: the same result label, the same recall decision;
44
+ - **report row**: every field equal, the same set of fields in the same order;
45
+ - **HTTP to client systems**: the same requests in the same order, bodies equal byte for byte;
46
+ - LLM requests and timings as in «Proving it behaves the same».
47
+ 7. **Sort every difference** into: intended and harmless (listed in «Proving it behaves the same»), a mistake of the
48
+ port (fix it, rerun), or a behaviour of the old agent that looks like a bug.
49
+ *Stop and ask* for every difference that changes a result, a report row field or a request to a client system, and
50
+ for every suspected bug of the old agent: the user decides whether the port keeps it or fixes it. Never decide this
51
+ yourself, in either direction.
52
+ 8. **Show the outcome**: the scenario table (scenario → same / different, with the difference and its reason), the
53
+ diff of the code, the list of behaviours and where each went, what was not covered by a scenario.
54
+ 9. **Stop.** Deploying or releasing the port happens only on the user's request, as a separate step. The old code stays
55
+ until the user says the port replaces it.
56
+
57
+ ## Shapes of existing agents
58
+
59
+ Existing agents come in three shapes (step 1 of the move identifies the shape):
4
60
 
5
61
  | Shape | How to recognize | Typical size |
6
62
  |---|---|---|
@@ -26,12 +26,17 @@ src/agent.spec.ts build-time checks of the agent
26
26
  prompt's signals (`<<< call_started;`, `…`) and its farewell convention (a goodbye ends with «…») in sync with the
27
27
  agent file.
28
28
  6. `npm run typecheck && npm test && npm run build`. `npm test` builds the agent: a section given twice or missing,
29
- or a combination the engine does not run, fails here naming it.
29
+ or a combination the engine does not run, fails here naming it. `npm run build` ends with the same check on the
30
+ built files (`voctiv-agent-check`, below).
30
31
  7. Replay calls on the stand before the first real call (`Test`).
31
32
  8. Release: bump `id.version` (it goes to every report row), deploy `dist/` with `node_modules`.
32
33
 
33
34
  ## Test
34
35
 
36
+ - `npm run build`: after `tsc`, `voctiv-agent-check` (a command of the library, no call and no platform needed) loads
37
+ `dist/agent.js` so the builder checks the agent. It prints `OK: dist/agent.js builds`, or one line starting with
38
+ `Error:` that names the agent and the path inside its data (`Error: voiceAgent "my-voice-agent":
39
+ report.fields.promise_date…: unknown fact "…"`) and fails the build. By hand: `npx voctiv-agent-check [path]`.
35
40
  - `npm test`: the builder and the engine accept the agent; results and report fields name only known results and entities.
36
41
  - Replay: scripted calls on a fake host with a virtual clock (answer, caller lines with timings, LLM replies, HTTP
37
42
  answers) and the journal of what the agent did. Cover at least: the happy path per result, silence at every rung,
@@ -46,5 +51,5 @@ src/agent.spec.ts build-time checks of the agent
46
51
  the data cannot say is added to the library as a generic template with a default that keeps every other agent
47
52
  unchanged.
48
53
 
49
- Field guide: the library reference, `skill/` of the library (also in the installed package:
50
- `node_modules/@voctiv/agent-runtime/skill/`); start with `SKILL.md`, «Create a new agent».
54
+ Field guide: the library reference, the folder `skill` of the package (after `npm install`:
55
+ `node_modules/@voctiv/agent-runtime/skill/`); start with `SKILL.md`, then `references/new-agent.md`.
@@ -5,12 +5,12 @@
5
5
  "description": "TODO: one line on what the agent does (written with the voiceAgent builder of @voctiv/agent-runtime).",
6
6
  "main": "dist/agent.js",
7
7
  "scripts": {
8
- "build": "tsc -p tsconfig.build.json",
8
+ "build": "tsc -p tsconfig.build.json && voctiv-agent-check",
9
9
  "typecheck": "tsc -p tsconfig.json --noEmit",
10
10
  "test": "vitest run"
11
11
  },
12
12
  "dependencies": {
13
- "@voctiv/agent-runtime": "^0.4.0",
13
+ "@voctiv/agent-runtime": "^0.4.1",
14
14
  "@voctiv/agent-sdk": "^0.4.0",
15
15
  "reflect-metadata": "^0.2.2",
16
16
  "rxjs": "7.8.1",