@rsconcept/rstool 0.10.2 → 1.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (112) hide show
  1. package/README.md +41 -31
  2. package/dist/agent-workflow-D-PSIb-m.d.ts +70 -0
  3. package/dist/analysis-LLnPhmGa.d.ts +23 -0
  4. package/dist/{common-DxLg3eXX.d.ts → common-DHJalS-Q.d.ts} +6 -1
  5. package/dist/constituenta-DnGR6bnM.d.ts +54 -0
  6. package/dist/diagnostic-D9yl_mEL.d.ts +19 -0
  7. package/dist/evaluation-Cns8BFm4.d.ts +31 -0
  8. package/dist/index.d.ts +11 -11
  9. package/dist/index.js +1 -1
  10. package/dist/mappers/model-adapter.d.ts +3 -3
  11. package/dist/mappers/schema-adapter.d.ts +4 -4
  12. package/dist/mappers/types.d.ts +6 -2
  13. package/dist/mappers/types.js +2 -0
  14. package/dist/mappers/types.js.map +1 -1
  15. package/dist/{model-value-SFAVj0dw.d.ts → model-value-BbonPzMz.d.ts} +14 -3
  16. package/dist/models/agent-workflow.d.ts +2 -0
  17. package/dist/models/agent-workflow.js +1 -0
  18. package/dist/models/analysis.d.ts +1 -1
  19. package/dist/models/common.d.ts +1 -1
  20. package/dist/models/constituenta.d.ts +2 -2
  21. package/dist/models/diagnostic.d.ts +1 -1
  22. package/dist/models/evaluation.d.ts +2 -2
  23. package/dist/models/index.d.ts +11 -11
  24. package/dist/models/index.js +2 -2
  25. package/dist/models/model-value.d.ts +2 -2
  26. package/dist/models/rstool-agent.d.ts +1 -1
  27. package/dist/models/rstool-agent.js +1 -1
  28. package/dist/models/session.d.ts +1 -1
  29. package/dist/models/tool-contract.d.ts +2 -2
  30. package/dist/models/tool-contract.js +2 -1
  31. package/dist/models/tool-contract.js.map +1 -1
  32. package/dist/rstool-agent-_8bplZnb.d.ts +71 -0
  33. package/dist/rstool-agent-kijHA9ML.js +476 -0
  34. package/dist/rstool-agent-kijHA9ML.js.map +1 -0
  35. package/dist/session/session-store.d.ts +18 -5
  36. package/dist/session/session-store.js +1 -64
  37. package/dist/{session-BPgsE80c.d.ts → session-ChexW8i7.d.ts} +11 -8
  38. package/dist/session-store-C3jyOSqI.js +142 -0
  39. package/dist/session-store-C3jyOSqI.js.map +1 -0
  40. package/dist/tool-contract-5_Q44DGE.d.ts +164 -0
  41. package/dist/wrapper/client.d.ts +23 -0
  42. package/dist/wrapper/client.js +17 -0
  43. package/dist/wrapper/client.js.map +1 -1
  44. package/dist/wrapper/stdio-wrapper.js +62 -52
  45. package/dist/wrapper/stdio-wrapper.js.map +1 -1
  46. package/docs/CONSTITUENTA.md +2 -2
  47. package/docs/DIAGNOSTICS.md +20 -18
  48. package/docs/MODEL-TESTING.md +3 -3
  49. package/docs/PORTAL-API.md +24 -18
  50. package/examples/README.md +1 -1
  51. package/examples/agent-client.ts +11 -41
  52. package/examples/build-chocolate-nim-rsform.ts +23 -18
  53. package/examples/chocolate-nim/build-rsform.ts +23 -18
  54. package/examples/chocolate-nim/build-rsmodel.ts +10 -12
  55. package/examples/chocolate-nim/rsform-session.json +290 -290
  56. package/examples/chocolate-nim/rsmodel-session.json +291 -291
  57. package/examples/expression-bank/bank-constituents.ts +304 -53
  58. package/examples/expression-bank/build-rsform.ts +19 -16
  59. package/examples/expression-bank/rsform-session.json +1551 -1551
  60. package/examples/kinship/build-rsform.ts +23 -18
  61. package/examples/kinship/build-rsmodel.ts +13 -15
  62. package/examples/kinship/rsform-session.json +219 -219
  63. package/examples/kinship/rsmodel-session.json +221 -221
  64. package/examples/kinship/session.ts +19 -21
  65. package/examples/movd/build-rsform.ts +23 -18
  66. package/examples/movd/build-rsmodel.ts +18 -20
  67. package/examples/movd/rsform-session.json +262 -262
  68. package/examples/movd/rsmodel-session.json +264 -264
  69. package/examples/sample/build-rsform.ts +19 -50
  70. package/examples/sample/build-rsmodel.ts +25 -44
  71. package/examples/sample/rsform-session.json +36 -33
  72. package/examples/sample/rsmodel-session.json +36 -33
  73. package/examples/template-apply/build-rsform.ts +27 -24
  74. package/examples/template-apply/rsform-session.json +48 -48
  75. package/package.json +3 -3
  76. package/skills/rstool-helper/EXAMPLES.md +44 -116
  77. package/skills/rstool-helper/GUIDE.md +40 -25
  78. package/skills/rstool-helper/REFERENCE.md +40 -177
  79. package/src/index.ts +24 -17
  80. package/src/mappers/portal-adapter.ts +43 -0
  81. package/src/mappers/types.ts +4 -0
  82. package/src/models/agent-workflow.ts +78 -0
  83. package/src/models/analysis.ts +7 -0
  84. package/src/models/common.ts +7 -0
  85. package/src/models/constituenta.ts +24 -6
  86. package/src/models/diagnostic.ts +4 -0
  87. package/src/models/evaluation.ts +11 -0
  88. package/src/models/import-detect.ts +39 -0
  89. package/src/models/import-export.ts +24 -0
  90. package/src/models/index.ts +22 -14
  91. package/src/models/model-value.ts +12 -0
  92. package/src/models/portal-json.ts +44 -0
  93. package/src/models/rstool-agent.test.ts +300 -147
  94. package/src/models/rstool-agent.ts +350 -93
  95. package/src/models/session.ts +8 -5
  96. package/src/models/tool-contract.ts +81 -42
  97. package/src/session/batch-apply.test.ts +28 -0
  98. package/src/session/batch-apply.ts +47 -0
  99. package/src/session/persistence.ts +56 -0
  100. package/src/session/session-store.ts +67 -4
  101. package/src/wrapper/client.ts +23 -0
  102. package/src/wrapper/stdio-wrapper.ts +59 -49
  103. package/dist/analysis-JiwOYDKx.d.ts +0 -16
  104. package/dist/constituenta-Dnd6iToB.d.ts +0 -36
  105. package/dist/diagnostic-BMYvciz8.d.ts +0 -15
  106. package/dist/evaluation-CCVYH0wA.d.ts +0 -21
  107. package/dist/index-uhkmwruf.d.ts +0 -46
  108. package/dist/rstool-agent-BZi5jO1y.js +0 -158
  109. package/dist/rstool-agent-BZi5jO1y.js.map +0 -1
  110. package/dist/rstool-agent-pRaPnZay.d.ts +0 -35
  111. package/dist/session/session-store.js.map +0 -1
  112. package/dist/tool-contract-n1ghUOrK.d.ts +0 -32
@@ -3,199 +3,62 @@
3
3
  ## Контракт rstool
4
4
 
5
5
  - Пакет: `@rsconcept/rstool`
6
- - Версия контракта: `1.4.0` (`CONTRACT_VERSION`)
6
+ - Версия контракта: `2.0.0` (`CONTRACT_VERSION`)
7
7
  - Основной класс: `RSToolAgent`
8
8
  - Публичные импорты: `@rsconcept/rstool` и `@rsconcept/rstool/wrapper`
9
9
 
10
- ### Методы
11
-
12
- | Метод | Назначение |
13
- | ----------------------------------------------------------- | ----------------------------------------------------------------------------- |
14
- | `createSession(initial?)` | Новая in-memory сессия `{ sessionId, contractVersion }` |
15
- | `addOrUpdateConstituenta(sessionId, { draft })` | Слияние черновика; анализ в контексте сессии → `{ state, diagnostics }` |
16
- | `analyzeExpression(sessionId, { expression, cstType })` | Разбор/типизация фрагмента без сохранения конституенты |
17
- | `getFormState(sessionId)` | Клон полного состояния сессии |
18
- | `listDiagnostics(sessionId, filters?)` | Накопленные диагностики; опциональный фильтр `constituentId` |
19
- | `commitStep(sessionId, message?)` | Зафиксировать контрольную точку ревизии |
20
- | `exportSession(sessionId)` | JSON-строка `{ contractVersion, state, diagnostics }` |
21
- | `exportPortalSchema(sessionId)` | JSON импорта схемы Portal |
22
- | `exportPortalModel(sessionId)` | JSON импорта модели Portal |
23
- | `importSession(payload)` | Новая сессия из экспорта |
24
- | `setConstituentaValue(sessionId, { target, type?, value })` | Одна привязка базового понятия или структурное значение → `SessionModelState` |
25
- | `setConstituentaValues(sessionId, { items })` | Пакетная установка значений → `SessionModelState` |
26
- | `clearConstituentaValues(sessionId, { items })` | Очистка значений по id конституент → `SessionModelState` |
27
- | `getModelState(sessionId)` | Клон состояния интерпретации сессии |
28
- | `evaluateExpression(sessionId, { expression, cstType })` | Вычисление фрагмента в контексте сессии → `EvaluationResult` |
29
- | `evaluateConstituenta(sessionId, { constituentId })` | Вычисление сохранённого определения → `EvaluationResult` |
30
- | `recalculateModel(sessionId)` | Пересчёт всех выводимых конституент → `{ items[] }` |
31
-
32
- ### `ConstituentaDraft`
33
-
34
- ```ts
35
- {
36
- id: number; // стабильный id внутри сессии
37
- alias: string;
38
- cstType: CstType;
39
- definitionFormal: string;
40
- term?: string;
41
- definitionText?: string;
42
- convention?: string;
43
- }
44
- ```
45
-
46
- Пропущенные текстовые поля в сохранённом состоянии по умолчанию `''`.
47
-
48
- ### Метаданные `SessionState`
49
-
50
- Задаются в `createSession(initial?)` или через `importSession`:
51
-
52
- ```ts
53
- {
54
- alias: string; // alias объекта библиотеки
55
- title: string; // отображаемое название
56
- comment: string; // заметки разработчика
57
- }
58
- ```
59
-
60
- При опускании все поля по умолчанию `''`.
61
-
62
- ### Типы модели и вычисления
10
+ ### Методы library API
11
+
12
+ | Метод | Назначение |
13
+ | ---------------------------------------------- | -------------------------------------------- |
14
+ | `ensureSession(initial?)` | Вернуть текущую сессию или создать новую |
15
+ | `createSession(initial?)` | Новая in-memory сессия |
16
+ | `getCurrentSession()` | Текущая активная сессия или `null` |
17
+ | `setCurrentSession(sessionId)` | Сделать сессию текущей |
18
+ | `applySchemaPatch(input, sessionId?)` | Единственный путь правки схемы |
19
+ | `getSessionState(detail?, sessionId?)` | `summary` (default) или `full` |
20
+ | `listDiagnostics(filters?, sessionId?)` | Активные диагностики |
21
+ | `analyzeExpression(input, sessionId?)` | Разбор без сохранения (`recordDiagnostics?`) |
22
+ | `commitStep(message?, sessionId?)` | Ревизия |
23
+ | `exportSession(sessionId?)` | JSON сессии |
24
+ | `exportPortal({ kind, format? }, sessionId?)` | Portal Load from JSON |
25
+ | `importData(payload, kind?)` | Импорт сессии / Portal |
26
+ | `setModelValues({ set?, clear? }, sessionId?)` | Значения модели |
27
+ | `getModelState(sessionId?)` | Состояние интерпретации |
28
+ | `evaluate(input, sessionId?)` | Scratch или конституента |
29
+ | `recalculateModel(sessionId?)` | Пересчёт |
30
+
31
+ ### `applySchemaPatch`
63
32
 
64
33
  ```ts
65
- type RSToolValue = number | RSToolValue[]; // значение во время выполнения
66
- type BasicBinding = Record<number, string>; // подписи элементов базового множества
67
-
68
- interface SessionModelState {
69
- items: { id: number; type: string; value: RSToolValue | BasicBinding }[];
70
- }
71
-
72
- interface EvaluationResult {
73
- success: boolean;
74
- value: RSToolValue | BasicBinding | null;
75
- status: EvalStatus; // 1=NO_EVAL … 7=HAS_DATA
76
- iterations: number;
77
- cacheHits: number;
78
- diagnostics: { code: number; from: number; to: number; params?: string[] }[];
79
- }
34
+ tool.applySchemaPatch({
35
+ initial: { title: 'Kinship' },
36
+ commitMessage: 'initial schema',
37
+ items: [{ alias: 'X1' }, { alias: 'S1', definitionFormal: 'ℬ(X1×X1)' }, { alias: 'D1', definitionFormal: 'Pr1(S1)' }]
38
+ });
80
39
  ```
81
40
 
82
- Привязки `basic`/`constant` используют `type: "basic"` и `value: { "0": "label", … }`. Структурные значения — нормализованная типизация в `type` и вложенные массивы для множеств/кортежей.
83
-
84
41
  ### Протокол stdio
85
42
 
86
- Процесс: `npx rstool-wrapper`
87
-
88
- 1. **Ready** (без запроса): `{"id":null,"ok":true,"result":{"ready":true,"wrapper":"rstool-stdio","contractVersion":"1.4.0"}}`
89
- 2. **Запрос**: `{"id":"<unique>","method":"<name>","params":{...}}`
90
- 3. **Ответ**: `{"id":"<same>","ok":true,"result":...}` или `{"id":"...","ok":false,"error":{"code":"...","message":"..."}}`
43
+ Плоские `params` (без `input`). Опционально: переменная окружения `RSTOOL_PERSISTENCE_DIR` — каталог для сохранения сессий между перезапусками обёртки (в library API — `new RSToolAgent({ persistenceDir })`).
91
44
 
92
- Дополнительные методы: `ping`, `methods`.
45
+ Служебные методы:
93
46
 
94
- Пример цепочки:
47
+ - `ping` — liveness и `contractVersion`.
48
+ - `methods` — список доступных stdio-методов.
95
49
 
96
50
  ```json
97
- {"id":"1","method":"createSession","params":{}}
98
- {"id":"2","method":"addOrUpdateConstituenta","params":{"sessionId":"…","input":{"draft":{"id":2,"alias":"S1","cstType":"structure","definitionFormal":"ℬ(X1×X1)"}}}}
99
- {"id":"2b","method":"addOrUpdateConstituenta","params":{"sessionId":"…","input":{"draft":{"id":3,"alias":"D1","cstType":"term","definitionFormal":"Pr1(S1)"}}}}
100
- {"id":"3","method":"analyzeExpression","params":{"sessionId":"","input":{"expression":"1+2","cstType":"term"}}}
101
- {"id":"4","method":"listDiagnostics","params":{"sessionId":""}}
102
- {"id":"5","method":"commitStep","params":{"sessionId":"…","message":"checkpoint"}}
103
- {"id":"6","method":"exportSession","params":{"sessionId":"…"}}
104
- {"id":"6a","method":"exportPortalSchema","params":{"sessionId":"…"}}
105
- {"id":"6b","method":"exportPortalModel","params":{"sessionId":"…"}}
106
- {"id":"7","method":"setConstituentaValue","params":{"sessionId":"…","input":{"target":1,"value":{"0":"a","1":"b"}}}}
107
- {"id":"8","method":"evaluateExpression","params":{"sessionId":"…","input":{"expression":"1+2","cstType":"term"}}}
108
- {"id":"9","method":"evaluateConstituenta","params":{"sessionId":"…","input":{"constituentId":3}}}
109
- ```
110
-
111
- `RSToolWrapperClient`: по умолчанию запускает `rstool-wrapper`; методы `waitUntilReady()`, `call(method, params)`, `close()`.
112
-
113
- ### Результат анализа
114
-
115
- ```ts
116
- interface AnalysisResult {
117
- success: boolean;
118
- type: Record<string, unknown> | null;
119
- valueClass: 'value' | 'property' | null;
120
- diagnostics: { code: number; from: number; to: number; params?: string[] }[];
121
- }
51
+ {"id":"2","method":"applySchemaPatch","params":{"items":[{"alias":"X1"}]}}
52
+ {"id":"7","method":"setModelValues","params":{"set":[{"target":1,"value":{"0":"a"}}]}}
53
+ {"id":"8","method":"evaluate","params":{"constituentId":3}}
54
+ {"id":"9","method":"exportPortal","params":{"kind":"schema"}}
55
+ {"id":"10","method":"importData","params":{"payload":"..."}}
122
56
  ```
123
57
 
124
- ## RSLang
125
-
126
- Кратко: язык на базе логики первого порядка; разделение множественных и логических выражений; параметризованные шаблоны для функций и предикатов.
127
-
128
- - **Типизация**: структурный тип выражения; ступени включают элементы (`Xi`, `Ci`), `Z`, кортежи `(H1×…×Hn)`, множества `ℬ(H)`, логику `Logic`, параметризованные `Hr 🠔 [H1,…,Hi]`. У `structure` (`S#`) поле `definitionFormal` **задаёт** типизацию. У `term` (`D#`) типизация **выводится** из определения.
129
-
130
- ## Токены грамматики
58
+ ### MCP tools
131
59
 
132
- Из `rslang.grammar`:
133
-
134
- | Категория | Токены / формы |
135
- | ------------------- | ------------------------------------------------------- |
136
- | Глобальные | `X`, `C`, `S`, `D`, `A`, `T` + цифры (правило `Global`) |
137
- | Функции / предикаты | `F<n>`, `P<n>` |
138
- | Радикалы | `R<n>` |
139
- | Локальные | `_a-zα-ω` + опциональные цифры |
140
- | Логика | `¬` `∀` `∃` `⇔` `⇒` `∨` `&` |
141
- | Множества | `ℬ` `∪` `\` `∆` `∩` `×` `∈` `∉` `⊆` `⊂` … |
142
- | Операции | `Pr`, `pr`, `Fi`, `card`, `bool`, `debool`, `red` |
143
- | Литералы | цифры, `Z`, `∅` |
144
-
145
- Полная грамматика и приоритеты: `docs/GRAMMAR-REF.md`.
60
+ 17 tools — см. `rstool-mcp/README.md`.
146
61
 
147
62
  ## Документация
148
63
 
149
- | Тема | Документ |
150
- | ---------------------------------------- | ------------------------------------------------------------ |
151
- | Идентификаторы, литералы | `docs/SYNTAX.md` § «Имена и литералы» |
152
- | Ступени, `Logic`, параметризованные типы | `docs/TYPIFICATION.md` § «Ступени» |
153
- | Логические выражения | `docs/SYNTAX.md` § «Логические выражения (LE)» |
154
- | Операторы над множествами | `docs/SYNTAX.md` § «Теоретико-множественные выражения (STE)» |
155
- | Целочисленная арифметика | `docs/SYNTAX.md` § «Арифметика» |
156
- | Дополнительные и производные типизации | `docs/TYPIFICATION.md` § «Дополнительные типизации» |
157
- | Кванторы | `docs/SYNTAX.md` § «Кванторы» |
158
- | Параметризованные функции, шаблоны | `docs/SYNTAX.md` § «Параметризованные выражения» |
159
- | Модель корректности / валидация | `docs/SYNTAX.md` § «Корректность» |
160
- | Семантические тесты определений | `docs/MODEL-TESTING.md` |
161
- | Словарь предметной области | `docs/DOMAIN.md` |
162
- | Поля конституент и порядок | `docs/CONSTITUENTA.md` |
163
- | REST API Portal | `docs/PORTAL-API.md` |
164
- | Токены грамматики / приоритеты | `docs/GRAMMAR-REF.md` |
165
-
166
- Воркфлоу и чеклисты — `skills/rstool-helper/GUIDE.md`.
167
-
168
- ## Коды ошибок
169
-
170
- Категории и исправления по коду: `docs/DIAGNOSTICS.md`.
171
-
172
- Категории:
173
-
174
- - `0x84xx` — синтаксис / разбор
175
- - `0x28xx` — предупреждения локальных объявлений
176
- - `0x88xx` — семантика / типы
177
- - `0x886x` — уровень конституент (пустая производная, запрещённое определение)
178
- - `0x81xx` — вычисление (runtime; из `evaluateExpression` / `evaluateConstituenta`)
179
-
180
- ## Форма экспорта сессии
181
-
182
- `exportSession(sessionId)` возвращает JSON-строку `{ contractVersion, state, diagnostics }`.
183
-
184
- - `state.alias`, `state.title`, `state.comment` — метаданные объекта библиотеки для экспорта в Portal (`comment` → JSON `description`).
185
- - `state.items[]` — каждая конституента с `id`, `alias`, `cstType`, `definitionFormal`, опциональными текстовыми полями и вложенным результатом анализа.
186
- - `state.model.items[]` — присутствует, если заданы значения интерпретации.
187
- - `diagnostics[]` — накопленные диагностики со смещениями и кодами.
188
-
189
- `importSession(payload)` принимает только этот формат `exportSession`. JSON Portal из
190
- `GET /api/rsforms/:id/details` сначала переноси в сессию через `createSession` и
191
- `addOrUpdateConstituenta`; поля и REST-пути описаны в `docs/PORTAL-API.md`.
192
-
193
- ## JSON импорта Portal
194
-
195
- Для **Load from JSON** на существующей схеме или модели Portal:
196
-
197
- - `exportPortalSchema(sessionId)` — файл схемы
198
- - `exportPortalModel(sessionId)` — файл модели
199
-
200
- - Схема `items[]`: поля конституент (`cst_type`, `definition_formal`, `term_raw`, …).
201
- - Модель `items[]`: `{ id, type, value }` на каждую привязку.
64
+ Воркфлоу: `GUIDE.md`. Примеры: `EXAMPLES.md`. Язык: `docs/*.md`.
package/src/index.ts CHANGED
@@ -1,9 +1,10 @@
1
- export {
2
- toPublicAnalysis,
3
- toPublicError,
4
- type DomainAnalysisLike,
5
- type DomainErrorLike
6
- } from './mappers/types';
1
+ /**
2
+ * Public API for `@rsconcept/rstool`.
3
+ *
4
+ * Primary entry points: {@link RSToolAgent} (in-process) and {@link RSToolWrapperClient}
5
+ * (stdio child process). Types describe the v2 agent contract.
6
+ */
7
+ export { toPublicAnalysis, toPublicError, type DomainAnalysisLike, type DomainErrorLike } from './mappers/types';
7
8
  export {
8
9
  CONTRACT_VERSION,
9
10
  CstType,
@@ -11,39 +12,45 @@ export {
11
12
  RSErrorCode,
12
13
  RSToolAgent,
13
14
  ValueClass,
14
- type AddOrUpdateConstituentaInput,
15
- type AddOrUpdateConstituentaResult,
15
+ type AgentConstituentaPatch,
16
16
  type AnalysisResult,
17
17
  type AnalyzeExpressionInput,
18
+ type ApplySchemaPatchInput,
19
+ type ApplySchemaPatchResult,
18
20
  type BasicBinding,
19
- type ClearConstituentaValuesInput,
20
21
  type ConstituentaDraft,
21
22
  type ConstituentaState,
22
23
  type DiagnosticRecord,
23
- type EvaluateConstituentaInput,
24
- type EvaluateExpressionInput,
24
+ type EvaluateInput,
25
25
  type EvaluationResult,
26
+ type ExportFormat,
27
+ type ExportPortalInput,
28
+ type ExportPortalResult,
29
+ type ImportDataKind,
26
30
  type ListDiagnosticsFilters,
27
31
  type ModelValueState,
28
32
  PORTAL_JSON_CONTRACT_VERSION,
33
+ type PortalExportKind,
29
34
  type PortalImportMetadata,
30
35
  type PortalModelImportData,
36
+ type PortalRsformDetails,
31
37
  type PortalSchemaConstituenta,
32
38
  type PortalSchemaImportData,
33
39
  type PortalTermForm,
34
40
  type RecalculateModelResult,
35
41
  type RSToolAgentContract,
42
+ type RSToolAgentOptions,
36
43
  type RSToolErrorDescription,
37
44
  type RSToolValue,
38
45
  type SessionHandle,
39
46
  type SessionModelState,
40
47
  type SessionRevision,
48
+ type SessionStateDetail,
49
+ type SessionStateResult,
50
+ type SessionSummary,
51
+ type SessionSummaryItem,
41
52
  type SessionState,
42
53
  type SetConstituentaValueInput,
43
- type SetConstituentaValuesInput
54
+ type SetModelValuesInput
44
55
  } from './models';
45
- export {
46
- RSToolWrapperClient,
47
- type RSToolWrapperClientOptions,
48
- type WrapperResponse
49
- } from './wrapper/client';
56
+ export { RSToolWrapperClient, type RSToolWrapperClientOptions, type WrapperResponse } from './wrapper/client';
@@ -0,0 +1,43 @@
1
+ import { type ConstituentaDraft } from '../models/constituenta';
2
+ import { type PortalRsformDetails, type PortalSchemaImportData, portalItemToDraft } from '../models/portal-json';
3
+ import { type SessionState } from '../models/session';
4
+
5
+ export function portalSchemaToSessionSeed(data: PortalSchemaImportData): Partial<SessionState> {
6
+ return {
7
+ alias: data.alias ?? '',
8
+ title: data.title ?? '',
9
+ comment: data.description ?? '',
10
+ items: []
11
+ };
12
+ }
13
+
14
+ export function portalDetailsToSessionSeed(data: PortalRsformDetails): Partial<SessionState> {
15
+ return {
16
+ alias: data.alias ?? '',
17
+ title: data.title ?? '',
18
+ comment: data.description ?? '',
19
+ items: []
20
+ };
21
+ }
22
+
23
+ export function portalItemsToDrafts(
24
+ items: Array<{
25
+ id: number;
26
+ alias: string;
27
+ cst_type: string;
28
+ definition_formal?: string;
29
+ term_raw?: string;
30
+ definition_raw?: string;
31
+ convention?: string;
32
+ }>
33
+ ): ConstituentaDraft[] {
34
+ return items.map(item => portalItemToDraft(item));
35
+ }
36
+
37
+ export function portalSchemaToDrafts(data: PortalSchemaImportData): ConstituentaDraft[] {
38
+ return portalItemsToDrafts(data.items);
39
+ }
40
+
41
+ export function portalDetailsToDrafts(data: PortalRsformDetails): ConstituentaDraft[] {
42
+ return portalItemsToDrafts(data.items);
43
+ }
@@ -2,6 +2,7 @@ import { type ValueClass } from '@rsconcept/domain/rslang';
2
2
 
3
3
  import { type AnalysisResult, type RSToolErrorDescription } from '../models';
4
4
 
5
+ /** Minimal domain error shape before mapping to {@link RSToolErrorDescription}. */
5
6
  export interface DomainErrorLike {
6
7
  code: number;
7
8
  from: number;
@@ -9,6 +10,7 @@ export interface DomainErrorLike {
9
10
  params?: readonly string[];
10
11
  }
11
12
 
13
+ /** Minimal domain analysis shape before mapping to {@link AnalysisResult}. */
12
14
  export interface DomainAnalysisLike {
13
15
  success: boolean;
14
16
  type: Record<string, unknown> | null;
@@ -16,6 +18,7 @@ export interface DomainAnalysisLike {
16
18
  errors: DomainErrorLike[];
17
19
  }
18
20
 
21
+ /** Map a domain parser/semantic error to the public diagnostic shape. */
19
22
  export function toPublicError(error: DomainErrorLike): RSToolErrorDescription {
20
23
  return {
21
24
  code: error.code,
@@ -25,6 +28,7 @@ export function toPublicError(error: DomainErrorLike): RSToolErrorDescription {
25
28
  };
26
29
  }
27
30
 
31
+ /** Map a domain analysis result to the public {@link AnalysisResult} shape. */
28
32
  export function toPublicAnalysis(analysis: DomainAnalysisLike): AnalysisResult {
29
33
  return {
30
34
  success: analysis.success,
@@ -0,0 +1,78 @@
1
+ import { type CstType } from './common';
2
+ import {
3
+ type ApplyConstituentsMode,
4
+ type ApplyConstituentsResult,
5
+ type ConstituentaDraft,
6
+ type ConstituentaState
7
+ } from './constituenta';
8
+ import { type DiagnosticRecord } from './diagnostic';
9
+ import { type SessionHandle, type SessionRevision, type SessionState } from './session';
10
+
11
+ /** Level of detail returned by {@link RSToolAgent.getSessionState}. */
12
+ export type SessionStateDetail = 'summary' | 'full';
13
+
14
+ /** Result of `getSessionState`: compact summary or full cloned session state. */
15
+ export type SessionStateResult = SessionSummary | SessionState;
16
+
17
+ /**
18
+ * Partial constituent update used in {@link ApplySchemaPatchInput}.
19
+ *
20
+ * `alias` is required; other fields are merged with any existing constituent
21
+ * or inferred from the alias prefix when omitted.
22
+ */
23
+ export interface AgentConstituentaPatch extends Omit<Partial<ConstituentaDraft>, 'alias'> {
24
+ alias: string;
25
+ }
26
+
27
+ /** Input for {@link RSToolAgent.applySchemaPatch}. */
28
+ export interface ApplySchemaPatchInput {
29
+ /** Metadata used only when a new session is created for this patch. */
30
+ initial?: {
31
+ alias?: string;
32
+ title?: string;
33
+ comment?: string;
34
+ };
35
+ /** Constituent patches to apply in dependency order. */
36
+ items: AgentConstituentaPatch[];
37
+ /** atomic: rollback on first failure; best_effort applies valid drafts. Default: atomic. */
38
+ mode?: ApplyConstituentsMode;
39
+ /** When set, a revision is recorded after a successful patch. */
40
+ commitMessage?: string;
41
+ }
42
+
43
+ /** Compact view of one constituent in a session summary. */
44
+ export interface SessionSummaryItem {
45
+ id: number;
46
+ alias: string;
47
+ cstType: CstType;
48
+ analysisSuccess: boolean;
49
+ }
50
+
51
+ /** Compact session overview returned by default from `getSessionState`. */
52
+ export interface SessionSummary {
53
+ sessionId: string;
54
+ contractVersion: string;
55
+ alias: string;
56
+ title: string;
57
+ comment: string;
58
+ itemCount: number;
59
+ modelItemCount: number;
60
+ diagnosticsCount: number;
61
+ items: SessionSummaryItem[];
62
+ diagnostics: DiagnosticRecord[];
63
+ lastRevision?: SessionRevision;
64
+ }
65
+
66
+ /** Result of {@link RSToolAgent.applySchemaPatch}. */
67
+ export interface ApplySchemaPatchResult extends ApplyConstituentsResult {
68
+ session: SessionHandle;
69
+ summary: SessionSummary;
70
+ revision?: SessionRevision;
71
+ }
72
+
73
+ /** Internal: resolved patch with previous state for undo bookkeeping. */
74
+ export interface ResolvedAgentPatch {
75
+ patch: AgentConstituentaPatch;
76
+ draft: ConstituentaDraft;
77
+ previous?: ConstituentaState;
78
+ }
@@ -1,12 +1,19 @@
1
1
  import { type CstType, type RSToolErrorDescription, type ValueClass } from './common';
2
2
 
3
+ /** Input for {@link RSToolAgent.analyzeExpression}. */
3
4
  export interface AnalyzeExpressionInput {
5
+ /** RSLang expression to parse and type-check. */
4
6
  expression: string;
7
+ /** Expected constituent type context for the expression. */
5
8
  cstType: CstType;
9
+ /** When true, append diagnostics to the session log. Default: false. */
10
+ recordDiagnostics?: boolean;
6
11
  }
7
12
 
13
+ /** Outcome of parsing and semantic analysis for one expression. */
8
14
  export interface AnalysisResult {
9
15
  success: boolean;
16
+ /** Inferred RS type AST as a plain object, or `null` on failure. */
10
17
  type: Record<string, unknown> | null;
11
18
  valueClass: ValueClass | null;
12
19
  diagnostics: RSToolErrorDescription[];
@@ -3,15 +3,22 @@ import { EvalStatus, type BasicBinding } from '@rsconcept/domain/library/rsmodel
3
3
  import { ValueClass } from '@rsconcept/domain/rslang';
4
4
  import { RSErrorCode } from '@rsconcept/domain/rslang/error';
5
5
 
6
+ /** Constituent type enum (X, D, C, …). Re-exported from `@rsconcept/domain`. */
6
7
  export { CstType, EvalStatus, RSErrorCode, ValueClass };
8
+ /** Named binding used in model evaluation. Re-exported from `@rsconcept/domain`. */
7
9
  export type { BasicBinding };
8
10
 
9
11
  /** Runtime evaluation value: number, nested array (set/tuple), or boolean 0/1. */
10
12
  export type RSToolValue = number | RSToolValue[];
11
13
 
14
+ /** Language or validation error with source span and optional format parameters. */
12
15
  export interface RSToolErrorDescription {
16
+ /** Numeric error code (see {@link RSErrorCode}). */
13
17
  code: number;
18
+ /** Start offset in the analyzed expression. */
14
19
  from: number;
20
+ /** End offset in the analyzed expression. */
15
21
  to: number;
22
+ /** Interpolation values for localized error messages. */
16
23
  params?: readonly string[];
17
24
  }
@@ -2,22 +2,24 @@ import { type AnalysisResult } from './analysis';
2
2
  import { type CstType } from './common';
3
3
  import { type DiagnosticRecord } from './diagnostic';
4
4
 
5
+ /** Constituent payload before analysis and merge into session state. */
5
6
  export interface ConstituentaDraft {
6
7
  id: number;
7
- /** Alias */
8
+ /** Unique alias (e.g. `X1`, `D2`). */
8
9
  alias: string;
9
- /** CST type */
10
+ /** Constituent type. */
10
11
  cstType: CstType;
11
- /** Formal definition */
12
+ /** Formal RSLang definition. */
12
13
  definitionFormal: string;
13
- /** Natural-language term */
14
+ /** Natural-language term. */
14
15
  term?: string;
15
- /** Natural-language definition */
16
+ /** Natural-language definition. */
16
17
  definitionText?: string;
17
- /** Convention or comment */
18
+ /** Convention or comment. */
18
19
  convention?: string;
19
20
  }
20
21
 
22
+ /** Constituent stored in session state after analysis. */
21
23
  export interface ConstituentaState extends Omit<ConstituentaDraft, 'term' | 'definitionText' | 'convention'> {
22
24
  term: string;
23
25
  definitionText: string;
@@ -33,3 +35,19 @@ export interface AddOrUpdateConstituentaResult {
33
35
  state: ConstituentaState;
34
36
  diagnostics: DiagnosticRecord[];
35
37
  }
38
+
39
+ /** How a multi-draft apply handles partial failures. */
40
+ export type ApplyConstituentsMode = 'atomic' | 'best_effort';
41
+
42
+ export interface ApplyConstituentsInput {
43
+ drafts: ConstituentaDraft[];
44
+ /** atomic: rollback on first failure; best_effort: apply valid drafts. Default: atomic. */
45
+ mode?: ApplyConstituentsMode;
46
+ }
47
+
48
+ export interface ApplyConstituentsResult {
49
+ success: boolean;
50
+ applied: ConstituentaState[];
51
+ failed: Array<{ draft: ConstituentaDraft; diagnostics: DiagnosticRecord[] }>;
52
+ diagnostics: DiagnosticRecord[];
53
+ }
@@ -1,12 +1,16 @@
1
1
  import { type RSToolErrorDescription } from './common';
2
2
 
3
+ /** Persisted diagnostic for a failed or warned expression in a session. */
3
4
  export interface DiagnosticRecord {
4
5
  sessionId: string;
6
+ /** Constituent id when the diagnostic is tied to a stored item; omitted for scratch analysis. */
5
7
  constituentId?: number;
8
+ /** Expression text that was analyzed. */
6
9
  expression: string;
7
10
  error: RSToolErrorDescription;
8
11
  }
9
12
 
13
+ /** Filters for {@link RSToolAgent.listDiagnostics}. */
10
14
  export interface ListDiagnosticsFilters {
11
15
  constituentId?: number;
12
16
  }
@@ -15,6 +15,17 @@ export interface EvaluateConstituentaInput {
15
15
  constituentId: number;
16
16
  }
17
17
 
18
+ /** Evaluate a scratch expression or a stored constituent (provide one variant). */
19
+ export interface EvaluateInput {
20
+ /** Scratch expression; requires `cstType`. */
21
+ expression?: string;
22
+ /** Type context when evaluating `expression`. */
23
+ cstType?: CstType;
24
+ /** Stored constituent id to evaluate. */
25
+ constituentId?: number;
26
+ }
27
+
28
+ /** Outcome of model evaluation for one expression or constituent. */
18
29
  export interface EvaluationResult {
19
30
  success: boolean;
20
31
  value: RSToolValue | BasicBinding | null;
@@ -0,0 +1,39 @@
1
+ import { type ImportDataKind } from './import-export';
2
+
3
+ function isRecord(value: unknown): value is Record<string, unknown> {
4
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
5
+ }
6
+
7
+ export function parseImportPayload(payload: string | object): unknown {
8
+ if (typeof payload === 'string') {
9
+ return JSON.parse(payload) as unknown;
10
+ }
11
+ return payload;
12
+ }
13
+
14
+ export function detectImportKind(data: unknown): Exclude<ImportDataKind, 'auto'> {
15
+ if (!isRecord(data)) {
16
+ throw new Error('Invalid import payload');
17
+ }
18
+
19
+ if ('contractVersion' in data && 'state' in data) {
20
+ return 'session';
21
+ }
22
+
23
+ if ('contract_version' in data && Array.isArray(data.items)) {
24
+ const items = data.items as unknown[];
25
+ if (items.length > 0 && isRecord(items[0]) && 'cst_type' in items[0]) {
26
+ return 'portal-schema';
27
+ }
28
+ throw new Error('Portal model JSON cannot be imported as a schema session');
29
+ }
30
+
31
+ if (Array.isArray(data.items) && data.items.length > 0) {
32
+ const first = data.items[0];
33
+ if (isRecord(first) && 'cst_type' in first) {
34
+ return 'portal-details';
35
+ }
36
+ }
37
+
38
+ throw new Error('Cannot detect import kind; pass kind explicitly');
39
+ }