@jangts/agent-core 0.1.1 → 0.2.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.
Files changed (558) hide show
  1. package/CHANGELOG.md +25 -0
  2. package/LICENSE +55 -0
  3. package/NOTICE +6 -0
  4. package/README.md +8 -0
  5. package/development/docs/README.en.md +70 -0
  6. package/development/docs/README.md +1 -1
  7. package/development/docs/acceptance.en.md +34 -0
  8. package/development/docs/agent-development.en.md +42 -0
  9. package/development/docs/api/README.en.md +62 -0
  10. package/development/docs/api/advanced-agents.en.md +135 -0
  11. package/development/docs/api/context-processing.en.md +110 -0
  12. package/development/docs/api/core.en.md +274 -0
  13. package/development/docs/api/examples.en.md +118 -0
  14. package/development/docs/api/kits.en.md +183 -0
  15. package/development/docs/api/knowledge-answering.en.md +166 -0
  16. package/development/docs/api/mock.en.md +186 -0
  17. package/development/docs/api/observability.en.md +166 -0
  18. package/development/docs/api/reference.en.md +2235 -0
  19. package/development/docs/api/reference.md +1907 -1874
  20. package/development/docs/api/support.en.md +252 -0
  21. package/development/docs/api/support.md +27 -0
  22. package/development/docs/api/types.en.md +181 -0
  23. package/development/docs/api/workflow.en.md +188 -0
  24. package/development/docs/basic-usage.en.md +78 -0
  25. package/development/docs/create-app.en.md +76 -0
  26. package/development/docs/examples/offline-agent.en.md +273 -0
  27. package/development/docs/examples.en.md +36 -0
  28. package/development/docs/flows/knowledge-maintenance.en.md +38 -0
  29. package/development/docs/getting-started.en.md +71 -0
  30. package/development/docs/knowledge.en.md +89 -0
  31. package/development/docs/maintenance.en.md +62 -0
  32. package/development/docs/materials.en.md +38 -0
  33. package/development/docs/mechanisms.en.md +227 -0
  34. package/development/docs/memory-and-learning.en.md +42 -0
  35. package/development/docs/operations.en.md +51 -0
  36. package/development/docs/records.en.md +63 -0
  37. package/development/docs/registration.en.md +63 -0
  38. package/development/skills/agent-core-app/scripts/create-app.mjs +286 -70
  39. package/development/skills/agent-core-app/scripts/lib/knowledge.mjs +77 -16
  40. package/development/skills/agent-core-app/scripts/lib/source.mjs +30 -2
  41. package/development/skills/agent-core-app/scripts/plan.mjs +46 -12
  42. package/development/skills/agent-core-app/scripts/prepare-source.mjs +61 -10
  43. package/development/skills/agent-core-app/scripts/resources.mjs +62 -17
  44. package/development/skills/agent-core-app/scripts/validate-knowledge.mjs +18 -1
  45. package/development/skills/agent-core-app/templates/catalog.json +36 -22
  46. package/dist/cjs/capabilities/index.js +13 -0
  47. package/dist/cjs/capabilities/invocation.js +80 -10
  48. package/dist/cjs/capabilities/model.js +126 -13
  49. package/dist/cjs/capabilities/tool-runtime.js +64 -12
  50. package/dist/cjs/capabilities/tools.js +266 -31
  51. package/dist/cjs/context/assembly.js +46 -5
  52. package/dist/cjs/context/audit.js +31 -6
  53. package/dist/cjs/context/fragments.js +54 -11
  54. package/dist/cjs/context/index.js +12 -0
  55. package/dist/cjs/context/journal.js +84 -7
  56. package/dist/cjs/context/plan.js +30 -2
  57. package/dist/cjs/diagnostics/catalog.js +17 -3
  58. package/dist/cjs/diagnostics/index.js +149 -29
  59. package/dist/cjs/diagnostics/sub-flow.js +240 -40
  60. package/dist/cjs/errors.js +99 -17
  61. package/dist/cjs/execution/branch.js +20 -4
  62. package/dist/cjs/execution/engine.js +470 -56
  63. package/dist/cjs/execution/events.js +136 -18
  64. package/dist/cjs/execution/index.js +7 -0
  65. package/dist/cjs/execution/reporting.js +75 -6
  66. package/dist/cjs/execution/state.js +161 -22
  67. package/dist/cjs/execution/workflow.js +224 -32
  68. package/dist/cjs/index.js +18 -0
  69. package/dist/cjs/kits/aggregation.js +45 -3
  70. package/dist/cjs/kits/answering/batch.js +23 -4
  71. package/dist/cjs/kits/answering/check-result.js +31 -8
  72. package/dist/cjs/kits/answering/checks.js +24 -3
  73. package/dist/cjs/kits/answering/flow.js +192 -36
  74. package/dist/cjs/kits/answering/index.js +19 -1
  75. package/dist/cjs/kits/answering/tasks.js +88 -13
  76. package/dist/cjs/kits/artifacts.js +36 -4
  77. package/dist/cjs/kits/candidates.js +47 -5
  78. package/dist/cjs/kits/delivery.js +40 -5
  79. package/dist/cjs/kits/durable.js +155 -31
  80. package/dist/cjs/kits/evidence.js +66 -15
  81. package/dist/cjs/kits/family.js +152 -22
  82. package/dist/cjs/kits/index.js +12 -1
  83. package/dist/cjs/kits/inference.js +104 -16
  84. package/dist/cjs/kits/intents/catalog.js +67 -16
  85. package/dist/cjs/kits/intents/index.js +11 -0
  86. package/dist/cjs/kits/intents/registry.js +188 -43
  87. package/dist/cjs/kits/intents/scopes.js +215 -46
  88. package/dist/cjs/kits/interaction/command.js +140 -36
  89. package/dist/cjs/kits/interaction/commands.js +86 -11
  90. package/dist/cjs/kits/interaction/handlers.js +27 -10
  91. package/dist/cjs/kits/interaction/index.js +10 -0
  92. package/dist/cjs/kits/interaction/transfer.js +80 -14
  93. package/dist/cjs/kits/knowledge/catalog.js +62 -11
  94. package/dist/cjs/kits/knowledge/index.js +16 -1
  95. package/dist/cjs/kits/knowledge/publication.js +99 -23
  96. package/dist/cjs/kits/knowledge/sections.js +33 -4
  97. package/dist/cjs/kits/normalization.js +51 -7
  98. package/dist/cjs/kits/policies.js +79 -15
  99. package/dist/cjs/kits/presentation/events.js +54 -10
  100. package/dist/cjs/kits/presentation/index.js +24 -1
  101. package/dist/cjs/kits/presentation/outputs.js +176 -38
  102. package/dist/cjs/kits/presentation/templates.js +33 -5
  103. package/dist/cjs/kits/presentation/variants.js +31 -2
  104. package/dist/cjs/kits/projection.js +63 -8
  105. package/dist/cjs/kits/rank-fusion.js +27 -4
  106. package/dist/cjs/kits/reflection-log-source.js +89 -16
  107. package/dist/cjs/kits/reflection.js +234 -60
  108. package/dist/cjs/kits/retrieval.js +98 -18
  109. package/dist/cjs/kits/search.js +180 -27
  110. package/dist/cjs/kits/text-skills.js +104 -19
  111. package/dist/cjs/kits/tools.js +415 -74
  112. package/dist/cjs/kits/vector-search.js +50 -16
  113. package/dist/cjs/mock/node.js +7 -1
  114. package/dist/cjs/mock/web.js +7 -1
  115. package/dist/cjs/mock.js +7 -1
  116. package/dist/cjs/model/binding.js +68 -17
  117. package/dist/cjs/model/call-budget.js +45 -4
  118. package/dist/cjs/model/decision-retry.js +19 -1
  119. package/dist/cjs/model/defaults.js +27 -4
  120. package/dist/cjs/model/index.js +7 -0
  121. package/dist/cjs/model/interactions/arguments.js +36 -1
  122. package/dist/cjs/model/interactions/json-object.js +48 -12
  123. package/dist/cjs/model/interactions/native-functions.js +52 -10
  124. package/dist/cjs/model/message-diagnostics.js +17 -4
  125. package/dist/cjs/model/options.js +9 -1
  126. package/dist/cjs/model/preparation.js +86 -12
  127. package/dist/cjs/model/runner.js +413 -79
  128. package/dist/cjs/model/selection-transport.js +48 -8
  129. package/dist/cjs/model/settings.js +67 -13
  130. package/dist/cjs/model/token-budget.js +69 -11
  131. package/dist/cjs/model/transports.js +59 -6
  132. package/dist/cjs/structs/common.js +11 -0
  133. package/dist/cjs/structs/debug.js +34 -5
  134. package/dist/cjs/structs/errors.js +26 -1
  135. package/dist/cjs/structs/index.js +11 -1
  136. package/dist/cjs/structs/kits/durable.js +7 -0
  137. package/dist/cjs/structs/kits/family.js +1 -0
  138. package/dist/cjs/structs/kits/interaction.js +8 -1
  139. package/dist/cjs/structs/kits/knowledge-publication.js +1 -0
  140. package/dist/cjs/structs/kits/reflection.js +18 -3
  141. package/dist/cjs/structs/model/chat-provider.js +6 -0
  142. package/dist/cjs/structs/support/model/completion.js +2 -0
  143. package/dist/cjs/structs/support/model/messages.js +2 -0
  144. package/dist/cjs/support/capabilities.js +43 -6
  145. package/dist/cjs/support/context/assembly.js +88 -16
  146. package/dist/cjs/support/context/compression.js +48 -6
  147. package/dist/cjs/support/context/fragments.js +6 -0
  148. package/dist/cjs/support/context/history.js +36 -1
  149. package/dist/cjs/support/context/index.js +11 -0
  150. package/dist/cjs/support/context/nodes.js +164 -35
  151. package/dist/cjs/support/context/processing.js +319 -61
  152. package/dist/cjs/support/context/selection-policy.js +98 -21
  153. package/dist/cjs/support/context/selection.js +61 -10
  154. package/dist/cjs/support/context/snapshot.js +29 -7
  155. package/dist/cjs/support/context/strategies.js +120 -28
  156. package/dist/cjs/support/index.js +9 -1
  157. package/dist/cjs/support/model/capabilities.js +20 -1
  158. package/dist/cjs/support/model/chat-completions.js +92 -20
  159. package/dist/cjs/support/model/children.js +34 -6
  160. package/dist/cjs/support/model/compatible-provider.js +189 -59
  161. package/dist/cjs/support/model/completion/calls.js +61 -0
  162. package/dist/cjs/support/model/completion/default.js +33 -0
  163. package/dist/cjs/support/model/completion/index.js +28 -0
  164. package/dist/cjs/support/model/completion/session.js +107 -0
  165. package/dist/cjs/support/model/index.js +12 -0
  166. package/dist/cjs/support/model/interactions/index.js +12 -1
  167. package/dist/cjs/support/model/interactions/json-object.js +6 -0
  168. package/dist/cjs/support/model/interactions/native-functions.js +6 -0
  169. package/dist/cjs/support/model/observer.js +32 -6
  170. package/dist/cjs/support/model/preview-rules.js +66 -16
  171. package/dist/cjs/support/model/reply-preview.js +77 -17
  172. package/dist/cjs/support/model/stage-transport.js +33 -7
  173. package/dist/cjs/support/model/strategies.js +75 -14
  174. package/dist/cjs/support/model/transports.js +53 -11
  175. package/dist/cjs/support/registration.js +49 -7
  176. package/dist/cjs/support/schema.js +46 -4
  177. package/dist/cjs/support/stream-events.js +60 -8
  178. package/dist/cjs/support/tool-runtime.js +6 -0
  179. package/dist/cjs/support/tools.js +79 -10
  180. package/dist/cjs/support/transport/index.js +7 -0
  181. package/dist/cjs/support/transport/json.js +28 -4
  182. package/dist/cjs/support/transport/sse.js +25 -2
  183. package/dist/cjs/utils/break-observer.js +20 -2
  184. package/dist/cjs/utils/cancellation.js +77 -9
  185. package/dist/cjs/utils/catalog.js +19 -4
  186. package/dist/cjs/utils/debug.js +14 -2
  187. package/dist/cjs/utils/index.js +8 -0
  188. package/dist/cjs/utils/interaction-definition.js +26 -6
  189. package/dist/cjs/utils/invocation.js +42 -4
  190. package/dist/cjs/utils/model-protocol.js +20 -1
  191. package/dist/cjs/utils/object.js +16 -0
  192. package/dist/cjs/utils/observer.js +22 -2
  193. package/dist/cjs/utils/protocol-registry.js +47 -4
  194. package/dist/cjs/utils/query-key.js +21 -2
  195. package/dist/cjs/utils/registration.js +18 -2
  196. package/dist/cjs/utils/rules.js +39 -11
  197. package/dist/cjs/utils/schema-adapter.js +25 -2
  198. package/dist/cjs/utils/synchronous.js +64 -7
  199. package/dist/cjs/utils/text.js +15 -1
  200. package/dist/esm/capabilities/index.d.ts +13 -0
  201. package/dist/esm/capabilities/index.js +13 -0
  202. package/dist/esm/capabilities/invocation.d.ts +16 -2
  203. package/dist/esm/capabilities/invocation.js +80 -10
  204. package/dist/esm/capabilities/model.d.ts +68 -1
  205. package/dist/esm/capabilities/model.js +126 -13
  206. package/dist/esm/capabilities/tool-runtime.d.ts +11 -0
  207. package/dist/esm/capabilities/tool-runtime.js +64 -12
  208. package/dist/esm/capabilities/tools.d.ts +96 -3
  209. package/dist/esm/capabilities/tools.js +267 -32
  210. package/dist/esm/context/assembly.d.ts +13 -2
  211. package/dist/esm/context/assembly.js +46 -5
  212. package/dist/esm/context/audit.d.ts +23 -1
  213. package/dist/esm/context/audit.js +31 -6
  214. package/dist/esm/context/fragments.d.ts +37 -3
  215. package/dist/esm/context/fragments.js +54 -11
  216. package/dist/esm/context/index.d.ts +12 -0
  217. package/dist/esm/context/index.js +12 -0
  218. package/dist/esm/context/journal.d.ts +32 -1
  219. package/dist/esm/context/journal.js +84 -7
  220. package/dist/esm/context/plan.d.ts +11 -1
  221. package/dist/esm/context/plan.js +30 -2
  222. package/dist/esm/diagnostics/catalog.d.ts +6 -0
  223. package/dist/esm/diagnostics/catalog.js +17 -3
  224. package/dist/esm/diagnostics/index.d.ts +30 -2
  225. package/dist/esm/diagnostics/index.js +149 -29
  226. package/dist/esm/diagnostics/sub-flow.d.ts +41 -3
  227. package/dist/esm/diagnostics/sub-flow.js +240 -40
  228. package/dist/esm/errors.d.ts +22 -2
  229. package/dist/esm/errors.js +99 -17
  230. package/dist/esm/execution/branch.d.ts +19 -1
  231. package/dist/esm/execution/branch.js +20 -4
  232. package/dist/esm/execution/engine.d.ts +291 -5
  233. package/dist/esm/execution/engine.js +471 -57
  234. package/dist/esm/execution/events.d.ts +16 -2
  235. package/dist/esm/execution/events.js +136 -18
  236. package/dist/esm/execution/index.d.ts +7 -0
  237. package/dist/esm/execution/index.js +7 -0
  238. package/dist/esm/execution/reporting.d.ts +49 -1
  239. package/dist/esm/execution/reporting.js +75 -6
  240. package/dist/esm/execution/state.d.ts +126 -10
  241. package/dist/esm/execution/state.js +161 -22
  242. package/dist/esm/execution/workflow.d.ts +121 -3
  243. package/dist/esm/execution/workflow.js +224 -32
  244. package/dist/esm/index.d.ts +17 -1
  245. package/dist/esm/index.js +18 -0
  246. package/dist/esm/kits/aggregation.d.ts +34 -2
  247. package/dist/esm/kits/aggregation.js +45 -3
  248. package/dist/esm/kits/answering/batch.d.ts +17 -0
  249. package/dist/esm/kits/answering/batch.js +23 -4
  250. package/dist/esm/kits/answering/check-result.d.ts +18 -1
  251. package/dist/esm/kits/answering/check-result.js +31 -8
  252. package/dist/esm/kits/answering/checks.d.ts +11 -0
  253. package/dist/esm/kits/answering/checks.js +24 -3
  254. package/dist/esm/kits/answering/flow.d.ts +25 -2
  255. package/dist/esm/kits/answering/flow.js +192 -36
  256. package/dist/esm/kits/answering/index.d.ts +12 -0
  257. package/dist/esm/kits/answering/index.js +19 -1
  258. package/dist/esm/kits/answering/tasks.d.ts +32 -1
  259. package/dist/esm/kits/answering/tasks.js +88 -13
  260. package/dist/esm/kits/artifacts.d.ts +11 -0
  261. package/dist/esm/kits/artifacts.js +36 -4
  262. package/dist/esm/kits/candidates.d.ts +23 -1
  263. package/dist/esm/kits/candidates.js +47 -5
  264. package/dist/esm/kits/delivery.d.ts +34 -0
  265. package/dist/esm/kits/delivery.js +40 -5
  266. package/dist/esm/kits/durable.d.ts +19 -0
  267. package/dist/esm/kits/durable.js +155 -31
  268. package/dist/esm/kits/evidence.d.ts +28 -5
  269. package/dist/esm/kits/evidence.js +66 -15
  270. package/dist/esm/kits/family.d.ts +17 -1
  271. package/dist/esm/kits/family.js +152 -22
  272. package/dist/esm/kits/index.d.ts +12 -1
  273. package/dist/esm/kits/index.js +12 -1
  274. package/dist/esm/kits/inference.d.ts +64 -0
  275. package/dist/esm/kits/inference.js +104 -16
  276. package/dist/esm/kits/intents/catalog.d.ts +13 -1
  277. package/dist/esm/kits/intents/catalog.js +67 -16
  278. package/dist/esm/kits/intents/index.d.ts +11 -0
  279. package/dist/esm/kits/intents/index.js +11 -0
  280. package/dist/esm/kits/intents/registry.d.ts +61 -3
  281. package/dist/esm/kits/intents/registry.js +188 -43
  282. package/dist/esm/kits/intents/scopes.d.ts +73 -3
  283. package/dist/esm/kits/intents/scopes.js +215 -46
  284. package/dist/esm/kits/interaction/command.d.ts +38 -4
  285. package/dist/esm/kits/interaction/command.js +140 -36
  286. package/dist/esm/kits/interaction/commands.d.ts +66 -2
  287. package/dist/esm/kits/interaction/commands.js +86 -11
  288. package/dist/esm/kits/interaction/handlers.d.ts +19 -2
  289. package/dist/esm/kits/interaction/handlers.js +27 -10
  290. package/dist/esm/kits/interaction/index.d.ts +10 -0
  291. package/dist/esm/kits/interaction/index.js +10 -0
  292. package/dist/esm/kits/interaction/transfer.d.ts +39 -2
  293. package/dist/esm/kits/interaction/transfer.js +80 -14
  294. package/dist/esm/kits/knowledge/catalog.d.ts +13 -0
  295. package/dist/esm/kits/knowledge/catalog.js +62 -11
  296. package/dist/esm/kits/knowledge/index.d.ts +11 -0
  297. package/dist/esm/kits/knowledge/index.js +16 -1
  298. package/dist/esm/kits/knowledge/publication.d.ts +15 -1
  299. package/dist/esm/kits/knowledge/publication.js +99 -23
  300. package/dist/esm/kits/knowledge/sections.d.ts +31 -1
  301. package/dist/esm/kits/knowledge/sections.js +33 -4
  302. package/dist/esm/kits/normalization.d.ts +25 -2
  303. package/dist/esm/kits/normalization.js +51 -7
  304. package/dist/esm/kits/policies.d.ts +26 -3
  305. package/dist/esm/kits/policies.js +79 -15
  306. package/dist/esm/kits/presentation/events.d.ts +51 -4
  307. package/dist/esm/kits/presentation/events.js +54 -10
  308. package/dist/esm/kits/presentation/index.d.ts +12 -0
  309. package/dist/esm/kits/presentation/index.js +25 -2
  310. package/dist/esm/kits/presentation/outputs.d.ts +30 -1
  311. package/dist/esm/kits/presentation/outputs.js +176 -38
  312. package/dist/esm/kits/presentation/templates.d.ts +32 -3
  313. package/dist/esm/kits/presentation/templates.js +33 -5
  314. package/dist/esm/kits/presentation/variants.d.ts +29 -0
  315. package/dist/esm/kits/presentation/variants.js +31 -2
  316. package/dist/esm/kits/projection.d.ts +42 -5
  317. package/dist/esm/kits/projection.js +63 -8
  318. package/dist/esm/kits/rank-fusion.d.ts +21 -1
  319. package/dist/esm/kits/rank-fusion.js +28 -5
  320. package/dist/esm/kits/reflection-log-source.d.ts +28 -1
  321. package/dist/esm/kits/reflection-log-source.js +89 -16
  322. package/dist/esm/kits/reflection.d.ts +17 -1
  323. package/dist/esm/kits/reflection.js +235 -61
  324. package/dist/esm/kits/retrieval.d.ts +18 -2
  325. package/dist/esm/kits/retrieval.js +98 -18
  326. package/dist/esm/kits/search.d.ts +56 -3
  327. package/dist/esm/kits/search.js +180 -27
  328. package/dist/esm/kits/text-skills.d.ts +16 -2
  329. package/dist/esm/kits/text-skills.js +104 -19
  330. package/dist/esm/kits/tools.d.ts +122 -2
  331. package/dist/esm/kits/tools.js +416 -74
  332. package/dist/esm/kits/vector-search.d.ts +47 -1
  333. package/dist/esm/kits/vector-search.js +51 -17
  334. package/dist/esm/mock/node.d.ts +7 -0
  335. package/dist/esm/mock/node.js +7 -1
  336. package/dist/esm/mock/web.d.ts +7 -0
  337. package/dist/esm/mock/web.js +7 -1
  338. package/dist/esm/mock.d.ts +7 -0
  339. package/dist/esm/mock.js +7 -1
  340. package/dist/esm/model/binding.d.ts +32 -3
  341. package/dist/esm/model/binding.js +68 -17
  342. package/dist/esm/model/call-budget.d.ts +30 -2
  343. package/dist/esm/model/call-budget.js +45 -4
  344. package/dist/esm/model/decision-retry.d.ts +10 -1
  345. package/dist/esm/model/decision-retry.js +19 -1
  346. package/dist/esm/model/defaults.d.ts +13 -2
  347. package/dist/esm/model/defaults.js +27 -4
  348. package/dist/esm/model/index.d.ts +7 -0
  349. package/dist/esm/model/index.js +7 -0
  350. package/dist/esm/model/interactions/arguments.d.ts +27 -0
  351. package/dist/esm/model/interactions/arguments.js +36 -1
  352. package/dist/esm/model/interactions/json-object.d.ts +7 -1
  353. package/dist/esm/model/interactions/json-object.js +48 -12
  354. package/dist/esm/model/interactions/native-functions.d.ts +6 -0
  355. package/dist/esm/model/interactions/native-functions.js +52 -10
  356. package/dist/esm/model/message-diagnostics.d.ts +17 -1
  357. package/dist/esm/model/message-diagnostics.js +17 -4
  358. package/dist/esm/model/options.d.ts +18 -1
  359. package/dist/esm/model/options.js +9 -1
  360. package/dist/esm/model/preparation.d.ts +30 -2
  361. package/dist/esm/model/preparation.js +86 -12
  362. package/dist/esm/model/runner.d.ts +129 -5
  363. package/dist/esm/model/runner.js +414 -80
  364. package/dist/esm/model/selection-transport.d.ts +14 -1
  365. package/dist/esm/model/selection-transport.js +48 -8
  366. package/dist/esm/model/settings.d.ts +11 -0
  367. package/dist/esm/model/settings.js +67 -13
  368. package/dist/esm/model/token-budget.d.ts +59 -1
  369. package/dist/esm/model/token-budget.js +69 -11
  370. package/dist/esm/model/transports.d.ts +20 -2
  371. package/dist/esm/model/transports.js +59 -6
  372. package/dist/esm/structs/capabilities/invocation.d.ts +36 -0
  373. package/dist/esm/structs/capabilities/model.d.ts +27 -0
  374. package/dist/esm/structs/capabilities/tools.d.ts +38 -0
  375. package/dist/esm/structs/common.d.ts +62 -2
  376. package/dist/esm/structs/common.js +11 -0
  377. package/dist/esm/structs/context/fragments.d.ts +28 -0
  378. package/dist/esm/structs/context/journal.d.ts +28 -3
  379. package/dist/esm/structs/context/processing.d.ts +11 -0
  380. package/dist/esm/structs/debug.d.ts +58 -1
  381. package/dist/esm/structs/debug.js +34 -5
  382. package/dist/esm/structs/diagnostics.d.ts +119 -1
  383. package/dist/esm/structs/errors.d.ts +42 -1
  384. package/dist/esm/structs/errors.js +26 -1
  385. package/dist/esm/structs/execution/engine.d.ts +24 -1
  386. package/dist/esm/structs/execution/events.d.ts +12 -0
  387. package/dist/esm/structs/execution/workflow.d.ts +71 -0
  388. package/dist/esm/structs/index.d.ts +11 -1
  389. package/dist/esm/structs/index.js +11 -1
  390. package/dist/esm/structs/invocation.d.ts +30 -0
  391. package/dist/esm/structs/kits/aggregation.d.ts +12 -0
  392. package/dist/esm/structs/kits/answering/checks.d.ts +11 -0
  393. package/dist/esm/structs/kits/answering/flow.d.ts +35 -1
  394. package/dist/esm/structs/kits/answering/state.d.ts +21 -0
  395. package/dist/esm/structs/kits/answering/tasks.d.ts +21 -0
  396. package/dist/esm/structs/kits/artifacts.d.ts +14 -0
  397. package/dist/esm/structs/kits/candidates.d.ts +19 -0
  398. package/dist/esm/structs/kits/delivery.d.ts +22 -0
  399. package/dist/esm/structs/kits/durable.d.ts +56 -3
  400. package/dist/esm/structs/kits/durable.js +7 -0
  401. package/dist/esm/structs/kits/evidence.d.ts +23 -0
  402. package/dist/esm/structs/kits/family.d.ts +49 -1
  403. package/dist/esm/structs/kits/family.js +1 -0
  404. package/dist/esm/structs/kits/intents/catalog.d.ts +26 -0
  405. package/dist/esm/structs/kits/intents/registry.d.ts +34 -0
  406. package/dist/esm/structs/kits/intents/scopes.d.ts +36 -1
  407. package/dist/esm/structs/kits/interaction.d.ts +64 -0
  408. package/dist/esm/structs/kits/interaction.js +8 -1
  409. package/dist/esm/structs/kits/knowledge-publication.d.ts +43 -1
  410. package/dist/esm/structs/kits/knowledge-publication.js +1 -0
  411. package/dist/esm/structs/kits/knowledge.d.ts +39 -2
  412. package/dist/esm/structs/kits/normalization.d.ts +15 -0
  413. package/dist/esm/structs/kits/policies.d.ts +25 -1
  414. package/dist/esm/structs/kits/presentation/events.d.ts +28 -4
  415. package/dist/esm/structs/kits/presentation/outputs.d.ts +38 -1
  416. package/dist/esm/structs/kits/presentation/templates.d.ts +15 -0
  417. package/dist/esm/structs/kits/projection.d.ts +21 -0
  418. package/dist/esm/structs/kits/reflection.d.ts +61 -2
  419. package/dist/esm/structs/kits/reflection.js +18 -3
  420. package/dist/esm/structs/kits/retrieval.d.ts +39 -0
  421. package/dist/esm/structs/kits/search.d.ts +24 -0
  422. package/dist/esm/structs/kits/text-skills.d.ts +36 -0
  423. package/dist/esm/structs/kits/tools.d.ts +87 -0
  424. package/dist/esm/structs/model/chat-provider.d.ts +24 -1
  425. package/dist/esm/structs/model/chat-provider.js +6 -0
  426. package/dist/esm/structs/model/interactions.d.ts +38 -0
  427. package/dist/esm/structs/model/messages.d.ts +34 -0
  428. package/dist/esm/structs/model/runtime.d.ts +104 -6
  429. package/dist/esm/structs/support/capabilities.d.ts +19 -2
  430. package/dist/esm/structs/support/context-processing.d.ts +88 -9
  431. package/dist/esm/structs/support/context.d.ts +29 -1
  432. package/dist/esm/structs/support/model/completion.d.ts +50 -0
  433. package/dist/esm/structs/support/model/completion.js +1 -0
  434. package/dist/esm/structs/support/model/interactions.d.ts +13 -1
  435. package/dist/esm/structs/support/model/messages.d.ts +54 -0
  436. package/dist/esm/structs/support/model/messages.js +1 -0
  437. package/dist/esm/structs/support/model/provider-observer.d.ts +22 -1
  438. package/dist/esm/structs/support/model/provider.d.ts +71 -6
  439. package/dist/esm/structs/support/registration.d.ts +13 -0
  440. package/dist/esm/structs/support/schema.d.ts +14 -0
  441. package/dist/esm/structs/support/tools.d.ts +28 -0
  442. package/dist/esm/structs/support/transport/json.d.ts +16 -0
  443. package/dist/esm/structs/support/transport/sse.d.ts +15 -0
  444. package/dist/esm/structs/utils/rules.d.ts +19 -0
  445. package/dist/esm/support/capabilities.d.ts +25 -2
  446. package/dist/esm/support/capabilities.js +43 -6
  447. package/dist/esm/support/context/assembly.d.ts +35 -4
  448. package/dist/esm/support/context/assembly.js +88 -16
  449. package/dist/esm/support/context/compression.d.ts +17 -1
  450. package/dist/esm/support/context/compression.js +48 -6
  451. package/dist/esm/support/context/fragments.d.ts +6 -0
  452. package/dist/esm/support/context/fragments.js +6 -0
  453. package/dist/esm/support/context/history.d.ts +43 -0
  454. package/dist/esm/support/context/history.js +36 -1
  455. package/dist/esm/support/context/index.d.ts +13 -2
  456. package/dist/esm/support/context/index.js +12 -1
  457. package/dist/esm/support/context/nodes.d.ts +65 -3
  458. package/dist/esm/support/context/nodes.js +165 -36
  459. package/dist/esm/support/context/processing.d.ts +152 -1
  460. package/dist/esm/support/context/processing.js +320 -62
  461. package/dist/esm/support/context/selection-policy.d.ts +42 -2
  462. package/dist/esm/support/context/selection-policy.js +98 -21
  463. package/dist/esm/support/context/selection.d.ts +14 -1
  464. package/dist/esm/support/context/selection.js +61 -10
  465. package/dist/esm/support/context/snapshot.d.ts +23 -1
  466. package/dist/esm/support/context/snapshot.js +29 -7
  467. package/dist/esm/support/context/strategies.d.ts +35 -2
  468. package/dist/esm/support/context/strategies.js +120 -28
  469. package/dist/esm/support/index.d.ts +9 -1
  470. package/dist/esm/support/index.js +9 -1
  471. package/dist/esm/support/model/capabilities.d.ts +10 -0
  472. package/dist/esm/support/model/capabilities.js +20 -1
  473. package/dist/esm/support/model/chat-completions.d.ts +44 -15
  474. package/dist/esm/support/model/chat-completions.js +92 -20
  475. package/dist/esm/support/model/children.d.ts +34 -2
  476. package/dist/esm/support/model/children.js +34 -6
  477. package/dist/esm/support/model/compatible-provider.d.ts +29 -3
  478. package/dist/esm/support/model/compatible-provider.js +190 -60
  479. package/dist/esm/support/model/completion/calls.d.ts +40 -0
  480. package/dist/esm/support/model/completion/calls.js +58 -0
  481. package/dist/esm/support/model/completion/default.d.ts +11 -0
  482. package/dist/esm/support/model/completion/default.js +30 -0
  483. package/dist/esm/support/model/completion/index.d.ts +10 -0
  484. package/dist/esm/support/model/completion/index.js +22 -0
  485. package/dist/esm/support/model/completion/session.d.ts +16 -0
  486. package/dist/esm/support/model/completion/session.js +104 -0
  487. package/dist/esm/support/model/index.d.ts +14 -0
  488. package/dist/esm/support/model/index.js +12 -0
  489. package/dist/esm/support/model/interactions/index.d.ts +1 -1
  490. package/dist/esm/support/model/interactions/index.js +12 -1
  491. package/dist/esm/support/model/interactions/json-object.d.ts +6 -0
  492. package/dist/esm/support/model/interactions/json-object.js +6 -0
  493. package/dist/esm/support/model/interactions/native-functions.d.ts +6 -0
  494. package/dist/esm/support/model/interactions/native-functions.js +6 -0
  495. package/dist/esm/support/model/observer.d.ts +25 -2
  496. package/dist/esm/support/model/observer.js +32 -6
  497. package/dist/esm/support/model/preview-rules.d.ts +26 -2
  498. package/dist/esm/support/model/preview-rules.js +66 -16
  499. package/dist/esm/support/model/reply-preview.d.ts +22 -1
  500. package/dist/esm/support/model/reply-preview.js +77 -17
  501. package/dist/esm/support/model/stage-transport.d.ts +9 -1
  502. package/dist/esm/support/model/stage-transport.js +33 -7
  503. package/dist/esm/support/model/strategies.d.ts +28 -2
  504. package/dist/esm/support/model/strategies.js +75 -14
  505. package/dist/esm/support/model/transports.d.ts +17 -1
  506. package/dist/esm/support/model/transports.js +53 -11
  507. package/dist/esm/support/registration.d.ts +20 -1
  508. package/dist/esm/support/registration.js +49 -7
  509. package/dist/esm/support/schema.d.ts +31 -1
  510. package/dist/esm/support/schema.js +46 -4
  511. package/dist/esm/support/stream-events.d.ts +22 -1
  512. package/dist/esm/support/stream-events.js +60 -8
  513. package/dist/esm/support/tool-runtime.d.ts +6 -0
  514. package/dist/esm/support/tool-runtime.js +6 -0
  515. package/dist/esm/support/tools.d.ts +22 -0
  516. package/dist/esm/support/tools.js +79 -10
  517. package/dist/esm/support/transport/index.d.ts +7 -0
  518. package/dist/esm/support/transport/index.js +7 -0
  519. package/dist/esm/support/transport/json.d.ts +29 -2
  520. package/dist/esm/support/transport/json.js +28 -4
  521. package/dist/esm/support/transport/sse.d.ts +31 -1
  522. package/dist/esm/support/transport/sse.js +25 -2
  523. package/dist/esm/types.d.ts +9 -1
  524. package/dist/esm/utils/break-observer.d.ts +27 -2
  525. package/dist/esm/utils/break-observer.js +20 -2
  526. package/dist/esm/utils/cancellation.d.ts +56 -5
  527. package/dist/esm/utils/cancellation.js +77 -9
  528. package/dist/esm/utils/catalog.d.ts +20 -1
  529. package/dist/esm/utils/catalog.js +19 -4
  530. package/dist/esm/utils/debug.d.ts +20 -1
  531. package/dist/esm/utils/debug.js +14 -2
  532. package/dist/esm/utils/index.d.ts +8 -0
  533. package/dist/esm/utils/index.js +8 -0
  534. package/dist/esm/utils/interaction-definition.d.ts +18 -1
  535. package/dist/esm/utils/interaction-definition.js +26 -6
  536. package/dist/esm/utils/invocation.d.ts +36 -1
  537. package/dist/esm/utils/invocation.js +42 -4
  538. package/dist/esm/utils/model-protocol.d.ts +8 -0
  539. package/dist/esm/utils/model-protocol.js +20 -1
  540. package/dist/esm/utils/object.d.ts +16 -0
  541. package/dist/esm/utils/object.js +16 -0
  542. package/dist/esm/utils/observer.d.ts +19 -1
  543. package/dist/esm/utils/observer.js +22 -2
  544. package/dist/esm/utils/protocol-registry.d.ts +38 -1
  545. package/dist/esm/utils/protocol-registry.js +47 -4
  546. package/dist/esm/utils/query-key.d.ts +11 -1
  547. package/dist/esm/utils/query-key.js +21 -2
  548. package/dist/esm/utils/registration.d.ts +34 -2
  549. package/dist/esm/utils/registration.js +18 -2
  550. package/dist/esm/utils/rules.d.ts +81 -4
  551. package/dist/esm/utils/rules.js +39 -11
  552. package/dist/esm/utils/schema-adapter.d.ts +12 -1
  553. package/dist/esm/utils/schema-adapter.js +25 -2
  554. package/dist/esm/utils/synchronous.d.ts +60 -4
  555. package/dist/esm/utils/synchronous.js +64 -7
  556. package/dist/esm/utils/text.d.ts +15 -1
  557. package/dist/esm/utils/text.js +15 -1
  558. package/package.json +7 -3
@@ -0,0 +1,166 @@
1
+ # Knowledge, Answering, and Presentation
2
+
3
+ [Shared types](types.md) · [Back to home](README.md). The three Kits compose through ordinary inputs and outputs.
4
+
5
+ ## Knowledge
6
+
7
+ ```ts
8
+ defineKnowledgeCatalog(documents, options?): KnowledgeCatalog
9
+ parseKnowledgeDocument({ id, revision, locale?, text }): KnowledgeDocument
10
+ ```
11
+
12
+ A document is still `{ id, revision, locale?, parts }`, and a section is still `{ id, parts }`. Catalog extends ReadonlyCatalog<KnowledgeDocument> and adds:
13
+
14
+ ```ts
15
+ catalog.sectionIds(documentId): readonly string[]
16
+ catalog.assertSelection(request: KnowledgeRead): void
17
+ catalog.read(request: KnowledgeRead): KnowledgeSnapshot
18
+ interface KnowledgeRead {
19
+ readonly documentId: string;
20
+ readonly selection:
21
+ | { readonly mode: 'document' }
22
+ | { readonly mode: 'self' | 'subtree'; readonly sectionIds: readonly string[] };
23
+ }
24
+ interface KnowledgeSnapshot extends KnowledgeRead {
25
+ readonly id: string;
26
+ readonly revision: string;
27
+ readonly locale?: string;
28
+ readonly content: string;
29
+ }
30
+ ```
31
+
32
+ Reads remain synchronous in-memory operations that do not read files, access the network, or decide material permissions. The snapshot id distinguishes document, revision, language, and selection range. Unknown documents/sections or duplicate selections are rejected; exceeding maxChars is rejected without truncating facts. The observation callback is at options.observe, and failures are isolated.
33
+
34
+ Read requests use KnowledgeRead. maxChars and observe are bound at catalog construction; structured documents, requests, and observers may be implemented by classes. Section snapshot IDs are opaque source identities.
35
+
36
+ Observation callbacks for knowledge, output composition, and answer flows receive only an independent structuredClone data snapshot and retain no prototypes or methods of business values. Observable payloads that cannot be copied skip notification; observation failures do not change business results and never leak internal object references as a fallback. Answer observation cannot modify already checked body text or source data.
37
+
38
+ ## AnswerTaskCatalog
39
+
40
+ ```ts
41
+ defineAnswerTaskCatalog(definitions, ports): AnswerTaskCatalog
42
+ interface AnswerTaskDefinition<Input, Metadata> {
43
+ readonly id: string;
44
+ readonly description: string;
45
+ readonly inputSchema: SchemaAdapter<Input>;
46
+ readonly intentIds: readonly string[];
47
+ readonly scopeId?: string;
48
+ readonly readerId: string;
49
+ readonly outputId: string;
50
+ readonly checkIds: readonly string[];
51
+ readonly metadata: Metadata;
52
+ }
53
+ ```
54
+
55
+ ports contains readers, outputs, checks, and optional assertDefinition. readers/outputs/checks all receive the registration set interface.
56
+
57
+ ```ts
58
+ defineAnswerReaderCatalog(definitions): AnswerReaderCatalog
59
+ reader.read(input, context): MaybePromise<Evidence>
60
+ catalog.read({ taskId, input }, context): Evidence
61
+ catalog.readAsync({ taskId, input }, context): Promise<Evidence>
62
+ ```
63
+
64
+ context extends OperationContext and includes the read-only task definition selected for this run. Synchronous read rejects thenables; readers with I/O use readAsync. The input schema is parsed first, and the reader is still responsible for real authorization and reading. Registration checks IDs and reader/output/check references and never implicitly selects another task.
65
+
66
+ ## Check catalog
67
+
68
+ ```ts
69
+ defineAnswerCheckCatalog(definitions): AnswerCheckCatalog
70
+ interface AnswerChecker<Value, App> {
71
+ readonly id: string;
72
+ check(value: Value, context: OperationContext<App>): CheckResult<Value>;
73
+ }
74
+ checks.check({ checkIds, value }, context): CheckResult<Value>
75
+ ```
76
+
77
+ value comes first and context second. The catalog runs in checkIds order, preserves explicit corrected values, merges issues in execution order, and marks the check source; program errors are not wrapped as model factual errors. Synchronous checkers must not accidentally return a Promise.
78
+
79
+ ## AnswerFlow
80
+
81
+ ```ts
82
+ defineAnswerFlow<Data, Value, App>(definition): AnswerFlow<Data, Value, App>
83
+ flow.run({ inputIds, items }, context): Promise<readonly AnswerResult<Data, Value>[]>
84
+ ```
85
+
86
+ definition contains reusable maxItems, maxRepairs, reviewPolicy, canInvoke, and named handlers. signal, diagnostics, and this run's App dependencies are passed through run's context; canInvoke(context) reads the real balance of these dependencies when a call is actually needed.
87
+
88
+ | handler | Input | Returns |
89
+ | --- | --- | --- |
90
+ | generate | `{ items, repairs?, previous? }` | `Promise<ReadonlyMap<itemId, Value>>` |
91
+ | check | `{ item, value }` | Synchronous CheckResult<Value> |
92
+ | review | `{ items: readonly { item, value }[] }` | `Promise<ReadonlyMap<itemId, CheckResult<Value>>>` |
93
+ | fallback | `{ item, issues }` | `{ handled: true; value: Value }` or `{ handled: false }` |
94
+
95
+ The handler's second argument is uniformly OperationContext<App>. The App may provide the same ModelRunner through context.app; the Kit does not create models or add model quota. Handlers are bound at definition time and compiled into a fixed Workflow; each run builds independent task state and repair quota, and the same flow can be reused concurrently. Handlers receive the current node's cancellation signal and diagnostics scope, and stage runs are recorded by the Core Loop.
96
+
97
+ ```ts
98
+ interface AnswerItem<Data> {
99
+ readonly id: string;
100
+ readonly inputIds: readonly string[];
101
+ readonly sourceStatus: 'ready' | 'unavailable' | 'conflict';
102
+ readonly data: Data;
103
+ }
104
+ interface AnswerResult<Data, Value> {
105
+ readonly item: AnswerItem<Data>;
106
+ readonly value?: Value;
107
+ readonly status: 'accepted' | 'fallback' | 'blocked';
108
+ readonly issues: readonly Issue[];
109
+ readonly checks: Readonly<{ local: CheckResult<Value>; review: CheckResult<Value> }>;
110
+ }
111
+ ```
112
+
113
+ Generation/review use a Map to support partial correction and lookup by ID; final results use an array to preserve input delivery order. This is a difference in purpose, not arbitrary reshaping of a same-named collection field.
114
+
115
+ Standalone issues must be covered; unknown itemIds, duplicate ownership, and illegal references are rejected. reviewPolicy preserves the required/optional/off semantics: a confirmed factual error cannot be released just because later review is unavailable. Repairs apply only to failed items, and fallback must be produced from real evidence. Cancellation, model calls, and repair quota continue to share the upper-layer boundary.
116
+
117
+ ## OutputCatalog
118
+
119
+ ```ts
120
+ defineOutputCatalog(definitions, { providers?, observe? }): OutputCatalog
121
+ catalog.toModelSchema(outputId): JsonSchema
122
+ catalog.check({ outputId, value }): CheckResult<Readonly<Record<string, unknown>>>
123
+ catalog.compose({ outputId, input }, context): OutputResult // 同步provider;误返thenable拒绝
124
+ ```
125
+
126
+ Catalog extends the shared has/get/require/ids/values. Definitions still have the four kinds text/master/record/group and do not make them outputs required across all of Core.
127
+
128
+ | Declared field | Contract |
129
+ | --- | --- |
130
+ | id | Output or field identity |
131
+ | owner | generated/bound/constant/semantic, indicating the value owner, not the handler's this |
132
+ | valueSchema | Optional SchemaAdapter; defaults to string; both model and program values go through the real parser |
133
+ | providerId | Provider reference for program binding or semantic resolution |
134
+ | constantValue | Program fixed value, snapshotted at registration |
135
+ | semanticKeys | Exposes only the optional keys, never private mapping values |
136
+ | allowedOutputIds | Output IDs allowed by a group |
137
+
138
+ A provider uses `resolve({ key? }, context)`; the first argument describes the selection and the second provides the execution context. toModelSchema projects only generated fields and semantic keys; the program is responsible for bound/constant and real links. check can retain valid fields for partial repair, but compose re-parses/re-checks input internally, and only a passed result can continue composing. A check result is not a permission credential, and partially usable values cannot complete an overall output.
139
+
140
+ OutputResult is `{ outputId, kind, value }`. Group children use program-assigned ids and outputId references; the model cannot register outputs, providers, or permissions on its own.
141
+
142
+ ## Masters, semantic slots, and bubbles
143
+
144
+ | Factory/method | Shared contract |
145
+ | --- | --- |
146
+ | defineTextTemplate(master, options) | Pure compilation; render(values) substitutes once synchronously; errors.missingField creates an error |
147
+ | defineSemanticSlots(definition) | namespace, keys, maxOccurrences; isValid(text): boolean |
148
+ | replyBubbleTexts(input) | Keeps the existing plain-text/bubble extraction responsibility and returns readonly string[]; count and length limits are enforced by the registered output contract |
149
+ | publishReplyEvents({ text, delivery }, context) | Returns AsyncIterable<AgentOutputEvent>, preserving backpressure and cancellation as consumers pull; pacing continues to use *Ms |
150
+ | serializeOutputEvents(events) / textOutputEvents(chunks) | Preserves explicit conversion between events and text streams and is not an invoke return mode |
151
+
152
+ Presentation handling is not responsible for fact verification or authorization. Generation requirements are called prompt/template; a program-held substitution structure is called master, and model body text must not be treated as an executable master.
153
+
154
+ Full exports, exact reloads, and declaration sources are in the [public symbol reference](reference.md). Signatures in the examples are for reading only; omitted fields do not imply arbitrary extra options.
155
+
156
+ ### Content and check boundaries
157
+
158
+ AnswerTask.describe projects the executable inputSchema as inputJsonSchema, avoiding the case where a same-named field is sometimes an adapter and sometimes bare JSON. For a generated field in OutputCatalog, an ordinary valueSchema parse failure forms a repairable Issue; AbortError, TimeoutError, and program provider exceptions continue to propagate. Final values for kind=text/master must be strings; record/group preserve their own structure.
159
+
160
+ Knowledge document parts allow paragraph strings and named sections, and sections recursively contain parts; self reads only the section's direct paragraphs, while subtree includes subsections. document reads the whole document; sectionIds must be non-empty, deduplicated, and all existing; exceeding maxChars is rejected without truncating evidence. The same definition, revision, language, and selection produce a stable snapshot identity. Read operations only work on existing in-memory documents and provide no file or account authorization.
161
+
162
+ Presentation's publishReplyEvents uses `({ text, delivery? }, context)`, with delivery defaulting to chunkSize=240, intervalMs=0, bubblePauseMs=0, maxDurationMs=3000. It slices by Unicode characters; intentional pacing is constrained by maxDurationMs, and consumer pulling still provides backpressure. serializeOutputEvents converts for consumers that explicitly need a text stream protocol; it is not another output mode of invoke.
163
+
164
+ Check results must include an issues array; it is empty when passed and contains at least one item when failed. The check catalog, local checks, and review use the same contract, with path as a string/number array. Explicitly returning value: undefined is still a sanitizer update and must not be confused with a missing value.
165
+
166
+ signal/diagnostics are passed through the execution context. See [Basic example](../examples/offline-agent.md) for complete offline App integration of models and tools; configure the local contracts of Knowledge/Answering according to this page.
@@ -0,0 +1,186 @@
1
+ # The MockGPT simulated model Kit
2
+
3
+ MockGPT simulates model replies with fixed data, functions and lightweight text algorithms, and is suited to debugging protocols, tool selection, streaming output, failure and cancellation. It does not perform real LLM inference. Ordinary rules do not use the network; the web source is an explicit optional network capability.
4
+
5
+ ## Entry points and public exports
6
+
7
+ | Entry | Runtime exports | Type exports |
8
+ | --- | --- | --- |
9
+ | `@jangts/agent-core/mock` | `MockGPT`, `generators`, `generatorNames`, `responses`, `ResponseDescription`, `MockGPTError`, `routes`, `encodeModelResponse` | `JsonValue`, `Message`, `ModelRequest`, `GenerationInput`, `GenerationOptions`, `GenerationContext`, `Generator`, `Generated`, `Rule`, `MockGPTOptions`, `CallRecord`, `ToolCall`, `OutputOptions`, `ModelOutput`, `HttpFault`, `Usage`, `TextSource`, `TextOptions` |
10
+ | `@jangts/agent-core/mock/node` | `createMockServer`, `createMockHandler` | `ServerOptions`, `HandlerOptions` |
11
+ | `@jangts/agent-core/mock/web` | `sources`, `isPublicAddress` | `WebOptions`, `LoadedPage`, `WebProfile` |
12
+
13
+ Node HTTP and web extraction are imported from separate sub-entries; the root entry can generate data directly on the frontend or server. The three entries forward the same implementation and do not define a separate rule protocol.
14
+
15
+ ## Starting from a fixed reply
16
+
17
+ ### TypeScript
18
+
19
+ ```ts
20
+ import { MockGPT, type MockGPTOptions } from '@jangts/agent-core/mock';
21
+
22
+ const options: MockGPTOptions = {
23
+ rules: [{ id: 'greeting', prompt: '你好', generator: '你好,有什么可以帮你?' }],
24
+ };
25
+ const mock = new MockGPT(options);
26
+ const value = await mock.generate({
27
+ model: 'demo', messages: [{ role: 'user', content: '你好' }],
28
+ });
29
+ console.log(value);
30
+ ```
31
+
32
+ ### JavaScript
33
+
34
+ ```js
35
+ import { MockGPT } from '@jangts/agent-core/mock';
36
+ const mock = new MockGPT({
37
+ rules: [{ prompt: '你好', generator: '你好,有什么可以帮你?' }],
38
+ });
39
+ console.log(await mock.generate({
40
+ model: 'demo', messages: [{ role: 'user', content: '你好' }],
41
+ }));
42
+ ```
43
+
44
+ `generate(input, options?) → Promise<Generated>`: input contains `model: string` and `messages: readonly Message[]` and may carry additional JSON condition fields; options accepts `signal`. Message has a required role, plus content, tool_calls, tool_call_id and extension fields.
45
+
46
+ The return value is a standalone frozen snapshot of a string, native JSON or an explicit ResponseDescription. generate does not create an HTTP response and does not perform the delays, chunking or faults in the description; the caller interprets the description itself. Optional undefined fields of the input object are omitted; array holes, undefined array elements, circular references and non-JSON data are rejected. Output must likewise be complete valid JSON and cannot contain undefined.
47
+
48
+ JSON snapshots are limited to 64 levels and 100,000 value nodes; an over-limit request is `MOCK_REQUEST` (400), and an over-limit generation result is `MOCK_GENERATION`. Fields are read once and no hidden `toJSON` is executed; names such as `__proto__` are kept as ordinary own data fields.
49
+
50
+ `encodeModelResponse(request, output, id, created, signal, finish)` encodes a validated model result as a Chat Completions JSON/SSE Response. `created` uses Unix seconds; `finish(error?, cancelled?)` is called when the response completes, fails or is cancelled. The adapter owns request validation, first-packet delay, ID and lifecycle; the encoder owns content chunking, backpressure, tools, usage and the terminal frame, and does not execute rules or modify MockGPT records.
51
+
52
+ ## Instance configuration and rules
53
+
54
+ | MockGPTOptions | Semantics/default |
55
+ | --- | --- |
56
+ | rules | Required, ordered Rule array |
57
+ | fallback | Optional Generator; fails when nothing matches and there is no fallback, and does not forward to a real model |
58
+ | selectPrompt(request) | Synchronously returns the matching text; by default takes the text blocks of the last user message and joins them with newlines in their original order |
59
+ | stream | Instance defaults chunkSize=24, intervalMs=0, optional wireChunkSize |
60
+ | seed | Random initial value, default 1; 0 to 4294967295 |
61
+ | clock | Function returning milliseconds, default current time |
62
+ | recordLimit | Maximum number of retained records, default 100; 0 to 10000 |
63
+ | maxBodyBytes | Byte limit for fetch request bodies, default 1048576, positive safe integer |
64
+ | maxOutputChars | Output character limit, default 1000000, positive safe integer |
65
+
66
+ Rule requires `generator`; `id` may be omitted and is generated from position, and explicit IDs must be unique. `prompt` accepts an exact string or a regular expression, `model` restricts the model name, `when(request)` is a synchronous boolean predicate, and `times` is a positive integer hit limit. Declaration order determines priority: the first rule that satisfies all conditions and is not exhausted runs.
67
+
68
+ A Generator is JSON/string/ResponseDescription, or `(context) => Generated | Promise<Generated>`. context contains the frozen request, the projected prompt, the regex match, the global callIndex, the hit ruleIndex of the current rule, signal, random, clock and report(metadata). request is a standard request containing model, messages, stream and optional tools/stream_options.
69
+
70
+ On a hit, the hit count and sequence number are allocated and are not refunded on failure or cancellation. A fixed seed reproduces output verbatim only when the call order, clock, callbacks and external environment are also fixed. Configuration is stored as a snapshot; external state captured by callback closures remains the caller's responsibility.
71
+
72
+ ## Input-dependent generators
73
+
74
+ All generators come from `generators`; `generatorNames` gives the names in that same registry.
75
+
76
+ | Method | Parameters and result |
77
+ | --- | --- |
78
+ | summary(options?) | Extracts representative sentences; default at most 240 code points and 3 sentences |
79
+ | bullets(options?) | Bullet text; default at most 500 code points and 3 items |
80
+ | keywords(options?) | JSON string array sorted by word frequency; count defaults to 3 |
81
+ | title(options?) | Title from the first sentence; default at most 24 code points |
82
+ | reply(options?) | Simulated reply; default at most 500 code points; may provide template({ text, previous }) |
83
+ | extract(options?) | Returns a field object; fields is a dictionary from name to regular expression, taking the first capture group or the full match, and null when there is no match; defaults to email/date/amount |
84
+ | integer(min?, max?)/float(min?, max?) | Returns a number generator function; integers default 0 to 100, floats default 0 to 1 |
85
+ | boolean()/pick(items) | Returns a boolean/option generator function; items must be non-empty |
86
+ | id(prefix?)/date()/sentence() | Returns an ID/ISO date/built-in sentence generator function; the ID prefix defaults to mock |
87
+ | imageUrl({ width?, height? }?) | Returns a local SVG data URL generator function; default 320×180, side lengths 1 to 4096 |
88
+ | sequence(items) | Selects a Generator from a non-empty list by rule hit sequence number, and fails when exhausted |
89
+ | toolCall(name, arguments, options?) | Generates an explicit tool proposal and does not execute the tool |
90
+
91
+ TextOptions supports `source: string | (context => string | Promise<string>)`, `maxChars` (1 to 30000) and `count` (1 to 100); source defaults to prompt. summary/bullets use sentence ranking and repetition control, analyze at most 30000 code points and 180 distribution candidate sentences, and sample over-long sources from the beginning/middle/end; the other text generators analyze at most the first 30000 code points. JSON arrays and objects are not truncated into invalid JSON for character limits. These algorithms provide no guarantee of semantic reasoning accuracy.
92
+
93
+ ```ts
94
+ import { MockGPT, generators } from '@jangts/agent-core/mock';
95
+ const age = generators.integer(18, 60);
96
+ const mock = new MockGPT({
97
+ seed: 42,
98
+ rules: [
99
+ { prompt: /总结/, generator: generators.summary({ maxChars: 120 }) },
100
+ { prompt: '用户资料', generator: context => ({ age: age(context) }) },
101
+ ],
102
+ });
103
+ ```
104
+
105
+ The example above also works directly as JavaScript. Field generator functions should be evaluated with the current context inside the generator callback and cannot be returned directly as JSON fields.
106
+
107
+ ## Explicit responses and faults
108
+
109
+ `ResponseDescription` distinguishes model, http and reject by kind and value; ordinary JSON does not become transport control because of a field with the same name.
110
+
111
+ | helper | Input/product |
112
+ | --- | --- |
113
+ | responses.text(content, options?) | Text ModelOutput description |
114
+ | responses.toolCalls(tools, options?) | Tool array description with content=null; each item contains name, JSON arguments and an optional id |
115
+ | responses.httpError(status, body?) | HTTP 400 to 599; the default error.message is a simulated error description |
116
+ | responses.reject(message?) | Network failure description |
117
+
118
+ OutputOptions: `finishReason` is stop/length/tool_calls/content_filter; `usage` contains prompt_tokens, completion_tokens and total_tokens, all non-negative safe integers whose total is consistent. `delayMs` is the first-response delay and `intervalMs` the frame interval, both default 0; `chunkSize` controls the code points of content/tool deltas, and `wireChunkSize` splits SSE further by bytes; `interruptAfter` interrupts after the specified data frame without sending a successful end marker. Chunk sizes are 1 to 1000000, delays/intervals 0 to 60000 milliseconds, and the interrupt frame count 0 to 60000.
119
+
120
+ ```js
121
+ import { MockGPT, responses } from '@jangts/agent-core/mock';
122
+ const mock = new MockGPT({ rules: [
123
+ { prompt: '限流', generator: responses.httpError(429, { error: { message: 'limited' } }) },
124
+ { prompt: '中断', generator: responses.text('逐步输出', { chunkSize: 1, interruptAfter: 2 }) },
125
+ { generator: responses.toolCalls([{ name: 'lookup', arguments: { id: 'demo' } }]) },
126
+ ] });
127
+ ```
128
+
129
+ ## fetch and the streaming protocol
130
+
131
+ `mock.fetch(input, init?) → Promise<Response>` is a bound standard fetch callback that can be injected directly into clients that accept a custom fetch. `routes` lists the supported routes: POST `/v1/chat/completions` and `/chat/completions`. Plain JSON returns a single choice, and a plain JSON product is encoded as JSON text in message.content; stream=true returns SSE. Only n=1 is supported, and explicit usage enters the SSE usage chunk only when the request sets stream_options.include_usage; real tokens are not estimated.
132
+
133
+ ```js
134
+ const response = await mock.fetch('https://mock.local/v1/chat/completions', {
135
+ method: 'POST',
136
+ body: JSON.stringify({ model: 'demo', messages: [{ role: 'user', content: '你好' }] }),
137
+ });
138
+ console.log(await response.json());
139
+ ```
140
+
141
+ It does not intercept the network globally and does not forward to a real model. HTTP errors return the corresponding Response; network faults reject fetch; a stream interruption is expressed by a failed read of response.body. Request cancellation prevents generators that have not started and aborts delays, streams and waits; external side effects already emitted are not rolled back automatically, and custom generators should cooperate with signal.
142
+
143
+ ## Node HTTP server
144
+
145
+ ```ts
146
+ import { MockGPT } from '@jangts/agent-core/mock';
147
+ import { createMockServer } from '@jangts/agent-core/mock/node';
148
+ const mock = new MockGPT({ rules: [{ generator: '调试回复' }] });
149
+ const server = createMockServer({ mock });
150
+ const address = await server.listen({ port: 4317 });
151
+ console.log(address);
152
+ // 调试结束:await server.close();
153
+ ```
154
+
155
+ JavaScript uses the same form. HandlerOptions contains the required mock, maxBodyBytes (default 1048576), requestTimeoutMs (default 30000), allowedHosts and allowedOrigins; ServerOptions additionally has closeTimeoutMs (default 1000 milliseconds). `createMockHandler(options)` returns a Node IncomingMessage/ServerResponse handler that can be mounted on an existing HTTP server.
156
+
157
+ `listen({ host?, port? }?)` defaults to the loopback host and port 4317, and port=0 is for temporary tests; it returns `{ host: string, port: number, url: string }`. Closing cancels in-flight requests and is bounded by the close deadline; repeated listen while starting, listening or closing is rejected with MOCK_ACTIVE; concurrent close waits for the same shutdown, and the server can listen again after it closes.
158
+
159
+ Host is validated before Origin. By default only localhost, loopback addresses and the local address the connection arrived on are accepted; an explicitly bound host name is also usable. allowedHosts explicitly lists proxy host names and does not support wildcards; allowedOrigins authorizes cross-origin sources separately and does not relax Host. A proxy cannot bypass target validation by forging Origin.
160
+
161
+ ## Web source
162
+
163
+ ```js
164
+ import { MockGPT, generators } from '@jangts/agent-core/mock';
165
+ import { sources } from '@jangts/agent-core/mock/web';
166
+ const mock = new MockGPT({ rules: [{
167
+ generator: generators.summary({ source: sources.web({
168
+ url: 'https://example.com/', timeoutMs: 20000,
169
+ fallback: '无法取得网页正文,请提供文字材料。',
170
+ }) }),
171
+ }] });
172
+ ```
173
+
174
+ `sources.web(options?) → TextSource` fetches HTML or plain text and extracts the body; it is not a browser and does not log in, carry cookies or carry model credentials. WebOptions: url is a fixed HTTP(S) URL or a synchronous context selector function; when omitted, the prompt must contain exactly one URL. profile uses browser; the type also accepts crawler (identical request headers); headers are used only for restricted content negotiation. timeoutMs defaults to 20000 and covers the full download; maxBytes defaults to 2097152, maxChars to 30000 and maxRedirects to 3.
175
+
176
+ Only public addresses are allowed, and DNS and redirects are checked hop by hop; `isPublicAddress(address)` returns a boolean for whether the address is usable. Local, private, special-purpose addresses and URLs carrying credentials are rejected. fallback is the alternative source text used when reading fails; it still passes through the text generators and records sourceFallback; cancellation, invalid URL and target address rejection are not turned into a successful fallback. Verification pages, login redirects, firewalls and upstream HTTP failures keep their real cause.
177
+
178
+ A trusted `load(url: URL, signal, maxBytes) → Promise<LoadedPage>` can be injected for offline or custom reads; LoadedPage is `{ bytes: Uint8Array, url: string, contentType: string, status?: number }`, and an omitted status is treated as 200. A custom load owns its own target access policy and cannot be injected by a remote request.
179
+
180
+ ## Records, cancellation and errors
181
+
182
+ `mock.records` returns a CallRecord snapshot: id, index, model, optional path/ruleId, fallback, status (pending/completed/error/cancelled), optional errorCode, metadata. Requests and generated bodies are not stored by default, and report accepts only bounded JSON metadata. `mock.counts` returns rule hit counts, and `activeRequests` contains streams that have not completed. `reset()` clears records, counts and random state; it is rejected with MOCK_ACTIVE while requests or streams are active.
183
+
184
+ MockGPTError carries code, status and optional details. Common codes: MOCK_CONFIG invalid configuration, MOCK_REQUEST invalid request, MOCK_BODY_LIMIT/MOCK_OUTPUT_LIMIT budget exceeded, MOCK_RULE_NOT_FOUND no match, MOCK_SEQUENCE_EXHAUSTED sequence exhausted, MOCK_NETWORK network fault, MOCK_HTTP simulated HTTP fault, MOCK_ACTIVE active lifecycle conflict. Cancellation preserves the caller's signal reason; fetch may encode a respondable error as an error response, and custom generator exceptions are recorded as failures without fabricating successful content.
185
+
186
+ These budgets limit simulated execution and do not replace the Agent's real model/tool budgets and permissions. Tool proposals are always authorized and executed by the caller; low-level negative cases such as hand-written broken SSE and invalid bytes are still expressed by dedicated fixtures.
@@ -0,0 +1,166 @@
1
+ # Requests, call chains, events and Journal
2
+
3
+ [Back to the API handbook](README.md) · [Core](core.md#journal-and-diagnostics). Core records runs, calls and registered entities. An App's accounts, HTTP requests and Q&A records are linked to runId in its own data model.
4
+
5
+ ## One fact per record, relations at the top level
6
+
7
+ Core emits events one by one through the optional CoreLogOutput; it neither packs the whole call tree into a single JSON nor keeps only one summary per model Q&A. Model request/output, tool start/completion and workflow transition/failure each have their own event; they share the same v2 outer layer, and payload expresses differences by type:
8
+
9
+ ```ts
10
+ interface CoreDiagnosticRecord extends DiagnosticIdentity {
11
+ readonly version: 2;
12
+ readonly eventId: string;
13
+ readonly type: CoreEventName;
14
+ readonly producerSequence: number;
15
+ readonly occurredAtMs: number;
16
+ readonly payload: unknown; // 未可信存储输入;CoreEvent按type关联具体载荷
17
+ readonly usedModel?: boolean; // 本次节点自身上报;未上报保持未知
18
+ readonly subSteps: readonly RecordedSubStep[];
19
+ readonly subStepsDropped: number;
20
+ readonly subStepsTruncated: boolean;
21
+ }
22
+ ```
23
+
24
+ | Field | Responsibility |
25
+ | --- | --- |
26
+ | runId | Identity of one Core run, obtained by the caller before the run; not automatically equal to requestId or messageId |
27
+ | spanId/parentSpanId | Current execution boundary and its direct parent boundary; queries do not rely on parsing span paths |
28
+ | invocationId/parentInvocationId | Real model or tool call and its calling parent; not a provider function-call ID |
29
+ | workflowInvocationId | Scope of one explicit workflow call; nested workflows have their own identity and parent relation |
30
+ | eventId | Identity of this execution fact; consistent with the fact ID seen by the workflow observer |
31
+ | producerSequence | Sequence starting at 1 within the Core diagnostics context tree; it cannot stand in for a cross-source total order or a causal proof |
32
+ | occurredAtMs | Millisecond time at which the Core fact was produced |
33
+ | definitionId/definitionKind/definitionRevision | Registered entity and available revision information |
34
+ | nodeId/nodeName/nodeKind/nodeDescription | Basic description of this boundary; storing the whole historical configuration is not required |
35
+ | nodeRole | workflow-node/workflow-boundary/invocation/loop-step, preventing a local call from being taken for main-flow dispatch |
36
+
37
+ The invocation in a successful tool or model return, the corresponding event and the Journal share the same call identity. Compression models and real nested tool calls each have their own invocationId and are linked to the parent call; pure wrapping does not create an already executed business operation out of nowhere. Re-entering the same workflow node has a different span; an identical static nodeId does not mean the same visit.
38
+
39
+ ## The Journal is not a second persistent log
40
+
41
+ ContextJournal is the in-memory context projection for this round, used so that the model can keep referring to real call receipts; it does not create a database or store a separate execution history. Model and tool start records share the invocationId deduplication scope, so duplicate model records or model/tool identity collisions are rejected; a failed snapshot does not occupy that identity. Records use type, producerSequence, occurredAtMs and InvocationMetadata:
42
+
43
+ ```ts
44
+ journal.model({ stageId, value, invocation }): void
45
+ journal.beginTool({ toolId, input, invocation? }): string
46
+ journal.finishTool({ invocationId, status, value }): void
47
+ journal.snapshot(): readonly ContextRecord[]
48
+ ```
49
+
50
+ The model submits value after parsing, delivery and cancellation checks; tool start/end reuse the same invocationId. By default no numbers such as call-1 that cannot be correlated across instances are produced. A missing call or a duplicate end is rejected. snapshot is a copy. Only named requests and the success/error/cancelled statuses are accepted, and records use type, value, toolId/stageId.
51
+
52
+ The Journal and diagnostics project the same actual execution boundary but are not guaranteed to have identical contents: the Journal keeps the business values needed for this round, diagnostics record execution facts per collection rules, and closing diagnostics does not change the Journal or business execution. When persistence is required, the App wires up CoreLogOutput and must not treat a Journal sequence number as a new real call.
53
+
54
+ ## Real workflows, failures and boundaries not entered
55
+
56
+ WorkflowEvent has required eventId, workflowId, workflowInvocationId, nodeId, roundIndex and type. The targetSpanId of transition/error points to the **selected next visit**; only the corresponding enter event proves actual entry. When cancellation, budget rejection or log loss happens after selection, the target must not be drawn as executed.
57
+
58
+ The errorEventId of an error event is passed along the recovery context; the failure phase and failedRouteId locate the problem. Cancellation, budget and contract errors cannot be recovered into a success that was never executed. A failure before node entry is marked workflow-boundary and does not fabricate a second enter. The raw engine.run produces only loop.event and does not borrow the identity of the main workflow node.
59
+
60
+ ModelCallTrace and ToolExecutionEvent use success/error/cancelled; check passed/failed belongs to business checks and does not override whether the model call completed successfully. ToolRegistry keeps tool identity and start/completion facts under metadata collection; input/value, detailed errors and subSteps are attached only when content collection is permitted. Pre-check rejections and accepted attempts are recorded separately, and a single error does not imply that the provider necessarily received the request.
61
+
62
+ ## State and output during a run
63
+
64
+ Core invokes the receivers registered by the App and does not manipulate the interface directly. Fixed flows, model/tool calls and dynamic node progress use the same `CoreEvent` outer layer and are distinguished by `type`. The same fact received by logs and listeners has the same eventId, time and call relations; content collection rules and copies are isolated from one another.
65
+
66
+ ```ts
67
+ const agent = new AgentCoreEngine({
68
+ workflow, model: { provider },
69
+ execution: { observe: {
70
+ // 默认只接元数据。仅对明确需要的进度报告开放内容。
71
+ accepts: ({ event, content }) => content === 'metadata' || event === 'node.progress',
72
+ event(fact) {
73
+ if (fact.type === 'model.start') showStatus(fact.workflowNodeId);
74
+ if (fact.type === 'node.progress') showProgress(fact.payload.payload);
75
+ },
76
+ } },
77
+ });
78
+ await agent.run(state);
79
+ ```
80
+
81
+ | Access point | Content | Guarantee |
82
+ | --- | --- | --- |
83
+ | execution.observe.event | Loop/Workflow, model.start/end, tool start/end and permitted dynamic reports | Side channel; a synchronous throw, async rejection or hang does not change execution; still effective when persistent logging is closed |
84
+ | execution.diagnostics → CoreLogOutput.write | Optional persistent projection of the same fact | The App decides fields, body, storage and retention; it gains no content authorization from other listeners |
85
+ | ModelRunner.sink.output | model.start/output/parsed of the same outer layer, plus model.end on success, failure or cancellation | Body waits in order, propagates failures and preserves backpressure; the end notification is limited to 250 milliseconds independently, and its failure does not override the result or the original exception |
86
+ | context.report({ usedModel, payload, subs }) | Immediate report during the current node's run | usedModel is optional boolean metadata, payload/subs are read only when content is permitted; Core fills in identity, time and sequence, and reports after the node ends or is cancelled are dropped |
87
+ | node report(update, context) | usedModel/payload/subs on completion/transition | Evaluated only when content is permitted; does not replace immediate reports during the run |
88
+ | context.createSubFlowLogger() | Sub-log instance bound to this execution | write records first, fix completes later, readAll obtains a fixed-format snapshot; reuses the existing node.progress outlet |
89
+
90
+ Listeners can filter by metadata such as event, nodeId and workflowNodeId. workflowNodeId keeps the owning Workflow node, while model/tool boundaries still have their own nodeId and invocationId. Repeated visits to the same node have different spans, and concurrent runs do not correlate through lastCall or a shared "current request". `withObserver` can be called on an existing request scope to add a listener, inherited along sub-scopes; this is immutable wiring and leaves the original scope unaffected. Canonical methods are bound to their original receivers at assembly time. When a reusable Engine has no request scope configured, each run is assigned an independent identity.
91
+
92
+ Listeners without accepts receive metadata only. Content events, payload and subs are collected only after the corresponding consumer explicitly accepts them; other metadata consumers do not gain the body as a side effect. Each consumer receives an independent copy. The result snapshot is isolated from the actual return value, so preview edits do not rewrite the final value; model results must still satisfy the existing Journal snapshot contract.
93
+
94
+ ModelPart does not provide separate reasoning content chunks. State, process notes explicitly provided by the model, tool facts, transient previews and the final answer each keep their own meaning; internal hidden reasoning or the raw protocol must not be treated as a user reply. Selection, compression and assembly can be registered as ordinary nodes separately and use real lifecycle facts; algorithmic reports are delivered as permitted node.progress.
95
+
96
+ Adding a listener only changes assembly configuration; the original Workflow, run and model result contracts are unchanged.
97
+
98
+ ## Sub-log instances and record-first-then-complete
99
+
100
+ Workflow nodes, simple run(step), ToolRegistry/Support tools and the execution context of executeInvocation all provide `createSubFlowLogger()` and `report()`. Each node visit or call has one instance, and repeated create returns the same instance; no global logger is shared. subs accepts only SubFlowLogger instances belonging to that execution; plain objects, objects imitating readAll, hand-written arrays and readAll() snapshots are rejected; invalid material does not become a main execution fact. The normalized stored field subSteps is still an array, so reading historical data does not require re-creating a logger.
101
+
102
+ ```ts
103
+ async run(state, context) {
104
+ const subs = context.createSubFlowLogger();
105
+ const id = subs.write({ name: '查询资料', kind: 'retrieval', payload: { query: state.question } });
106
+ // write 已记录意图;即使后续短路,也保留这条计划。
107
+ if (!state.canRead) {
108
+ subs.fix(id, { status: 'skipped', usedModel: false });
109
+ return;
110
+ }
111
+ subs.fix(id, { status: 'running' });
112
+ try {
113
+ const result = await readSource(state.question);
114
+ subs.fix(id, { status: 'success', usedModel: false, payload: { result } });
115
+ } catch (error) {
116
+ if (!context.signal.aborted) subs.fix(id, { status: 'error' });
117
+ throw error;
118
+ }
119
+ context.report({ usedModel: false, subs });
120
+ }
121
+ ```
122
+
123
+ | Method | Fixed contract |
124
+ | --- | --- |
125
+ | write(input): string | name and kind are required, status defaults to planned; stepId, sequence, createdAtMs and initial revision=1 are allocated automatically. Optional parentStepId, relatedDefinitionId, caseId, nextStepIds, status, time, summary, payload and usedModel. startedAtMs is recorded automatically only when running is reported explicitly, so planned time does not pass for an actual start. |
126
+ | fix(stepId, patch): void | Completes status, model usage, pending times, summary, successors or payload fields for a record in the same instance; a terminal state cannot be reopened, but missing result fields can still be filled while execution is active. Keeps the ID, first order and original times, incrementing revision each time. payload merges missing keys recursively and existing facts cannot be overwritten; a given summary, time or successor cannot be rewritten. |
127
+ | readAll(): readonly RecordedSubStep[] | Returns an immutable snapshot in first-write order; later fix calls do not change an earlier snapshot. With no steps it is [], and the snapshot remains readable after the execution is closed. |
128
+
129
+ The fixed record fields are origin=reported, stepId, sequence, name, kind, status, createdAtMs and revision, plus the optional fields above. planned/unknown can advance to an actual status, while running cannot go back to planned or skipped; success/error/cancelled/skipped are terminal, the status and established facts cannot be rewritten, but pending result fields can still be filled while the owning node is active. Statuses and legal transitions come from the same reportedStepStatusCatalog. A retry writes another record and does not reopen a terminal state. The parent and successors must belong to the same logger; when the successor ID is not yet available, nextStepIds can be completed in one later fix. Pending payload fields are omitted first and are not represented by null or an empty array as an overwritable placeholder. By default at most 256 records, 65536 JSON characters for the full snapshot and 1024 write/fix calls; payload accepts only bounded-depth JSON data and does not accept functions, service instances, circular references or internal getters.
130
+
131
+ write and fix emit the initial/completion event through the existing node.progress at that moment, with payload.subStep holding operation, stepId, sequence, revision, createdAtMs, status and optional usedModel metadata. When content is permitted, the event carries the fixed-format subSteps snapshot at that point; node end/failure events also carry the last snapshot. The log appends revisions, and events already emitted are not updated in place. Results returning out of order do not change the initial order, and replay can distinguish "only a plan at the time" from "a result later". When only a plan or start was received without a result, the original status is kept; success, failure or an actual model call cannot be inferred.
132
+
133
+ The main node reports through context.report({ usedModel: true | false }) whether it used the model this time, and the outer usedModel in the log is kept as metadata; sub-steps report their own usedModel through write/fix. Unreported stays unknown and does not default to false; a reported true cannot change back to false. A child's true is not automatically aggregated into the main node's original marker. This is a node report: a field of true does not fabricate model.start/end or call counts, and model internal hidden reasoning is not collected. The end report(update, context) is still evaluated only when content collection is permitted; markers that must be kept in metadata mode should be submitted during the run with context.report.
134
+
135
+ Content permission continues to be decided per event and per consumer. Without content authorization, payload/summary getters are not read, nor are the private payload/subs getters in reports; only permitted status, revision and boolean metadata are kept. The instance closes when execution ends or is cancelled, and write/fix reject late modifications. Log shutdown, outlet failure or a process crash still follow the original failure isolation and incomplete mechanism; recording intent first does not constitute a transactional audit guarantee.
136
+
137
+ ## File adaptation and relational table mapping
138
+
139
+ An App can connect CoreLogOutput.write to its own file or database adapter. Core events are stored flattened, and the App/storage fields source, traceId, app, sequence and recordedAtMs are filled in by the adapter, which Core does not depend on; other application diagnostics can still use the original record interface. Files can be segmented by source; they belong to the same run session and are not another Journal persistence ledger.
140
+
141
+ The collector sequence links the persisted observation order of sources such as App and Core; producerSequence keeps the producer's original sequence. occurredAtMs and recordedAtMs are preserved separately. The adapter continues to use the existing redaction, body switch, bounded queue, segmented/large-payload files and retention period; side-channel failures do not change business results, and queue drops or write failures mark incomplete. This interface provides no transactional audit or exactly-once guarantee.
142
+
143
+ Relational databases can record this without mesh JSON and map it directly:
144
+
145
+ | Object | Main relation columns | Details |
146
+ | --- | --- | --- |
147
+ | runs | run_id, started_at_ms, ended_at_ms, status, incomplete | Run summary |
148
+ | spans | run_id, span_id, parent_span_id, invocation_id, parent_invocation_id, definition_id | Boundary summary |
149
+ | events | event_id, run_id, span_id, invocation_id, type, sequence, producer_sequence, occurred_at_ms, recorded_at_ms | payload JSON per type; necessary bodies stored as separate references |
150
+ | App message_run_links | message_id, run_id, relation and account isolation columns | App-owned user Q&A links |
151
+
152
+ This is a feasible mapping, not a created SQL table or an SDK built-in repository. Queries are authorized by the App; one input can trigger multiple runs, and a failed/cancelled run without final output can still be linked to the input message; Core does not query App message tables back. Parent/child keys can be used for recursive upstream/downstream queries; do not guess relations from time proximity or text similarity. Storage may idempotently project summaries of the same fact and handle out-of-order and missing data, but the last persisted row cannot be treated as the authoritative completion state.
153
+
154
+ ## Event format validation
155
+
156
+ normalizeDiagnosticEvent(input) accepts version=2, validates identity, time, sequence and reported steps, and produces an independent copy. Missing identity or unsupported versions are rejected.
157
+
158
+ The payload at the read boundary is unknown, and outer validation does not equal validating arbitrary business JSON. The write interface CoreEvent associates CoreEventPayloads by type; for the exact event catalog and fields see the [public declarations](reference.md).
159
+
160
+ ## Difference between facts and reports
161
+
162
+ Only workflow nodes actually dispatched by the Loop are primary visits; a node calling a local function does not produce an additional dispatched node. subSteps is optional, bounded reported material and must not be treated as a Core dispatch fact or a static subgraph. Only the target enter event proves entry; a selected route target or the last persisted row must not be treated as proof of execution. The App owns user input/final output and message links itself.
163
+
164
+ ## Large records in file adaptation
165
+
166
+ When the `@jangts/diagnostics` file adapter is used, payload, subSteps and redactions in a large record are stored as body domains of the same validated attachment; the reference row keeps identity and index information. The reader restores the record after validating the attachment scope, size, SHA-256 and applicable identity. Attachments and return budgets are still configured explicitly by the App; Core itself does not own file storage.