@jangts/agent-core 0.2.0 → 0.2.5

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 (78) hide show
  1. package/CHANGELOG.md +14 -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 +290 -257
  20. package/development/docs/api/support.en.md +252 -0
  21. package/development/docs/api/types.en.md +181 -0
  22. package/development/docs/api/workflow.en.md +198 -0
  23. package/development/docs/api/workflow.md +22 -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/SKILL.md +4 -0
  39. package/development/skills/agent-core-app/scripts/create-app.mjs +19 -0
  40. package/development/skills/agent-core-app/scripts/lib/knowledge.mjs +37 -1
  41. package/development/skills/agent-core-app/scripts/plan.mjs +9 -0
  42. package/development/skills/agent-core-app/scripts/resources.mjs +17 -0
  43. package/dist/cjs/diagnostics/catalog.js +6 -0
  44. package/dist/cjs/execution/cache.js +162 -0
  45. package/dist/cjs/execution/engine.js +10 -0
  46. package/dist/cjs/kits/vector-search.js +4 -7
  47. package/dist/cjs/structs/execution/cache.js +6 -0
  48. package/dist/cjs/support/model/chat-completions.js +1 -1
  49. package/dist/cjs/support/model/completion/default.js +1 -0
  50. package/dist/cjs/support/model/completion/session.js +5 -0
  51. package/dist/esm/diagnostics/catalog.d.ts +6 -0
  52. package/dist/esm/diagnostics/catalog.js +6 -0
  53. package/dist/esm/execution/cache.d.ts +20 -0
  54. package/dist/esm/execution/cache.js +156 -0
  55. package/dist/esm/execution/engine.d.ts +5 -0
  56. package/dist/esm/execution/engine.js +10 -0
  57. package/dist/esm/kits/vector-search.js +4 -7
  58. package/dist/esm/structs/execution/cache.d.ts +54 -0
  59. package/dist/esm/structs/execution/cache.js +5 -0
  60. package/dist/esm/structs/execution/engine.d.ts +6 -1
  61. package/dist/esm/structs/execution/workflow.d.ts +2 -1
  62. package/dist/esm/structs/index.d.ts +1 -0
  63. package/dist/esm/structs/kits/retrieval.d.ts +1 -0
  64. package/dist/esm/structs/kits/search.d.ts +2 -0
  65. package/dist/esm/structs/model/messages.d.ts +4 -0
  66. package/dist/esm/structs/support/model/messages.d.ts +2 -0
  67. package/dist/esm/support/context/nodes.d.ts +16 -0
  68. package/dist/esm/support/context/processing.d.ts +7 -0
  69. package/dist/esm/support/model/chat-completions.js +1 -1
  70. package/dist/esm/support/model/children.d.ts +2 -0
  71. package/dist/esm/support/model/completion/default.d.ts +1 -0
  72. package/dist/esm/support/model/completion/default.js +1 -0
  73. package/dist/esm/support/model/completion/session.d.ts +5 -0
  74. package/dist/esm/support/model/completion/session.js +5 -0
  75. package/dist/esm/support/model/preview-rules.d.ts +6 -0
  76. package/dist/esm/support/model/reply-preview.d.ts +7 -0
  77. package/dist/esm/support/model/strategies.d.ts +4 -0
  78. package/package.json +7 -4
@@ -0,0 +1,273 @@
1
+ # Complete Offline Example: Service Status Q&A
2
+
3
+ [Back to example index](../examples.md) · [Model and tool integration](../basic-usage.md) · [How it works](../mechanisms.md)
4
+
5
+ The code below can be copied into a project with the SDK installed and run without model credentials, a database, network access, or extra example files. The Provider only assembles strings from fixed data, so it serves to explain the execution process and has no real semantic understanding; the tool likewise returns only offline demo data.
6
+
7
+ ## Preparation
8
+
9
+ First obtain the SDK and its real dependencies through the [installation guide](../getting-started.md). Save the complete JavaScript code as `app.mjs` and run `node app.mjs`. Save TypeScript as `app.ts` and use the compilation flow already present in your project; a standalone Node project can set type to module in package.json and install typescript/@types/node:
10
+
11
+ ```sh
12
+ npx tsc --module nodenext --target es2022 --strict --outDir dist app.ts
13
+ node dist/app.js
14
+ ```
15
+
16
+ The two stages are separate code files; do not paste declarations from multiple stages into the same file.
17
+
18
+ ## Stage One: Configure a Single Node
19
+
20
+ Start by getting state updates and final delivery working end to end. The Workflow entry defaults to the first node, nodes return partial updates, and `route.deliver` reads the final field.
21
+
22
+ ### TypeScript
23
+
24
+ ```ts
25
+ import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core';
26
+
27
+ type State = { question: string; answer?: string };
28
+ const workflow = defineWorkflow<State, string>({
29
+ id: 'service-helpdesk',
30
+ nodes: [{
31
+ id: 'answer',
32
+ description: '回答演示服务状态',
33
+ run: () => ({ answer: '演示服务在线。' }),
34
+ routes: [route.deliver('answer')],
35
+ }],
36
+ });
37
+ const agent = new AgentCoreEngine({ workflow });
38
+ const answer = await agent.run({ question: '演示服务在线吗?' });
39
+ console.log(answer);
40
+ ```
41
+
42
+ ### JavaScript
43
+
44
+ ```js
45
+ import { AgentCoreEngine, defineWorkflow, route } from '@jangts/agent-core';
46
+
47
+ const workflow = defineWorkflow({
48
+ id: 'service-helpdesk',
49
+ nodes: [{
50
+ id: 'answer',
51
+ description: '回答演示服务状态',
52
+ run: () => ({ answer: '演示服务在线。' }),
53
+ routes: [route.deliver('answer')],
54
+ }],
55
+ });
56
+ const agent = new AgentCoreEngine({ workflow });
57
+ const answer = await agent.run({ question: '演示服务在线吗?' });
58
+ console.log(answer);
59
+ ```
60
+
61
+ The expected output is `演示服务在线。`. No model is needed at this point.
62
+
63
+ ## Stage Two: Add Tools, a Model, and Observation
64
+
65
+ This stage still uses the same defineWorkflow, AgentCoreEngine, and agent.run. The new lookup node first executes the tool and obtains a validated result, and the answer node then calls the already bound model. Listening only receives metadata and explicitly approved node progress, and no persistent log is configured.
66
+
67
+ `createServiceAgent` is the assembly function of the App in this example, not a new SDK entry point; the fixed tool definition and Workflow are reused outside the function. Each call establishes an independent tool runtime and Engine, which can be used to give a request its own observation and lifecycle. The authorize of a production tool must be connected to real server-side identity and rules; the empty authorization here applies only to the public offline constants in this example.
68
+
69
+ ### TypeScript
70
+
71
+ ```ts
72
+ import { AgentCoreEngine, Support, defineWorkflow, route } from '@jangts/agent-core';
73
+ import type { ChatProvider, ExecutionOptions } from '@jangts/agent-core/types';
74
+
75
+ type Status = { status: 'online'; latencyMs: number };
76
+ type State = { question: string; service?: Status; answer?: string };
77
+
78
+ // 固定定义只写一次;这个离线公开资料工具不需要用户身份。
79
+ const tools = Support.defineToolCatalog([{
80
+ id: 'get_status',
81
+ kind: 'read',
82
+ description: '读取演示服务的当前状态',
83
+ inputSchema: {
84
+ jsonSchema: { type: 'object', properties: {}, additionalProperties: false },
85
+ parse(value: unknown) {
86
+ if (!value || typeof value !== 'object' || Array.isArray(value)
87
+ || Object.keys(value).length !== 0) throw new TypeError('状态查询不接受参数');
88
+ return {};
89
+ },
90
+ },
91
+ authorize() {
92
+ // 仅适用于本例的公开离线数据;真实用户数据必须在这里校验授权。
93
+ },
94
+ execute: (): Status => ({ status: 'online', latencyMs: 12 }),
95
+ parseOutput(value: unknown): Status {
96
+ if (!value || typeof value !== 'object') throw new TypeError('状态结果无效');
97
+ const status = value as Partial<Status>;
98
+ if (status.status !== 'online' || typeof status.latencyMs !== 'number'
99
+ || !Number.isFinite(status.latencyMs) || status.latencyMs < 0) {
100
+ throw new TypeError('状态结果无效');
101
+ }
102
+ return { status: status.status, latencyMs: status.latencyMs };
103
+ },
104
+ }]);
105
+
106
+ const provider: ChatProvider = {
107
+ async *stream(messages, context) {
108
+ context.signal.throwIfAborted();
109
+ // 固定模拟协议,仅用于离线教程;不是语义理解或事实校验器。
110
+ const input = JSON.parse(messages.at(-1)?.content ?? '{}');
111
+ yield `演示服务${input.service.status === 'online' ? '在线' : '不可用'},延迟 ${input.service.latencyMs}ms。`;
112
+ },
113
+ };
114
+
115
+ const workflow = defineWorkflow<State, string>({
116
+ id: 'service-helpdesk',
117
+ nodes: [
118
+ {
119
+ id: 'lookup',
120
+ description: '执行状态查询工具',
121
+ provides: ['service'],
122
+ async run(_state, { tools, report }) {
123
+ report({ payload: { phase: 'lookup', message: '正在查询服务状态' } });
124
+ const { value } = await tools.invoke({ toolId: 'get_status', input: {} });
125
+ return { service: value as Status };
126
+ },
127
+ routes: [route.to('answer')],
128
+ },
129
+ {
130
+ id: 'answer',
131
+ description: '根据查询回执组织回答',
132
+ requires: ['service'],
133
+ provides: ['answer'],
134
+ async run(state, { model }) {
135
+ const { value } = await model.invoke({
136
+ input: JSON.stringify({ question: state.question, service: state.service }),
137
+ });
138
+ return { answer: value };
139
+ },
140
+ routes: [route.deliver('answer')],
141
+ },
142
+ ],
143
+ });
144
+
145
+ export function createServiceAgent(execution: ExecutionOptions = {}) {
146
+ const runtime = tools.bind({ app: {} });
147
+ return new AgentCoreEngine({
148
+ workflow,
149
+ model: { provider, maxCalls: 1 },
150
+ maxRounds: 1,
151
+ execution,
152
+ }).bindToolRuntime(runtime);
153
+ }
154
+
155
+ const agent = createServiceAgent({
156
+ observe: {
157
+ accepts: ({ event, content }) => content === 'metadata' || event === 'node.progress',
158
+ event(fact) {
159
+ if (fact.type === 'node.progress') console.log('[进度]', fact.payload.payload);
160
+ if (fact.type === 'model.start') console.log('[进度] 正在组织回答');
161
+ },
162
+ },
163
+ });
164
+ console.log(await agent.run({ question: '演示服务在线吗?' }));
165
+ ```
166
+
167
+ ### JavaScript
168
+
169
+ ```js
170
+ import { AgentCoreEngine, Support, defineWorkflow, route } from '@jangts/agent-core';
171
+
172
+ const tools = Support.defineToolCatalog([{
173
+ id: 'get_status',
174
+ kind: 'read',
175
+ description: '读取演示服务的当前状态',
176
+ inputSchema: {
177
+ jsonSchema: { type: 'object', properties: {}, additionalProperties: false },
178
+ parse(value) {
179
+ if (!value || typeof value !== 'object' || Array.isArray(value)
180
+ || Object.keys(value).length !== 0) throw new TypeError('状态查询不接受参数');
181
+ return {};
182
+ },
183
+ },
184
+ authorize() {
185
+ // 仅适用于本例的公开离线数据;真实用户数据必须在这里校验授权。
186
+ },
187
+ execute: () => ({ status: 'online', latencyMs: 12 }),
188
+ parseOutput(value) {
189
+ if (!value || typeof value !== 'object' || value.status !== 'online'
190
+ || typeof value.latencyMs !== 'number' || !Number.isFinite(value.latencyMs)
191
+ || value.latencyMs < 0) throw new TypeError('状态结果无效');
192
+ return { status: value.status, latencyMs: value.latencyMs };
193
+ },
194
+ }]);
195
+
196
+ const provider = {
197
+ async *stream(messages, context) {
198
+ context.signal.throwIfAborted();
199
+ const input = JSON.parse(messages.at(-1)?.content ?? '{}');
200
+ yield `演示服务${input.service.status === 'online' ? '在线' : '不可用'},延迟 ${input.service.latencyMs}ms。`;
201
+ },
202
+ };
203
+
204
+ const workflow = defineWorkflow({
205
+ id: 'service-helpdesk',
206
+ nodes: [
207
+ {
208
+ id: 'lookup',
209
+ description: '执行状态查询工具',
210
+ provides: ['service'],
211
+ async run(_state, { tools, report }) {
212
+ report({ payload: { phase: 'lookup', message: '正在查询服务状态' } });
213
+ const { value } = await tools.invoke({ toolId: 'get_status', input: {} });
214
+ return { service: value };
215
+ },
216
+ routes: [route.to('answer')],
217
+ },
218
+ {
219
+ id: 'answer',
220
+ description: '根据查询回执组织回答',
221
+ requires: ['service'],
222
+ provides: ['answer'],
223
+ async run(state, { model }) {
224
+ const { value } = await model.invoke({
225
+ input: JSON.stringify({ question: state.question, service: state.service }),
226
+ });
227
+ return { answer: value };
228
+ },
229
+ routes: [route.deliver('answer')],
230
+ },
231
+ ],
232
+ });
233
+
234
+ export function createServiceAgent(execution = {}) {
235
+ const runtime = tools.bind({ app: {} });
236
+ return new AgentCoreEngine({
237
+ workflow,
238
+ model: { provider, maxCalls: 1 },
239
+ maxRounds: 1,
240
+ execution,
241
+ }).bindToolRuntime(runtime);
242
+ }
243
+
244
+ const agent = createServiceAgent({
245
+ observe: {
246
+ accepts: ({ event, content }) => content === 'metadata' || event === 'node.progress',
247
+ event(fact) {
248
+ if (fact.type === 'node.progress') console.log('[进度]', fact.payload.payload);
249
+ if (fact.type === 'model.start') console.log('[进度] 正在组织回答');
250
+ },
251
+ },
252
+ });
253
+ console.log(await agent.run({ question: '演示服务在线吗?' }));
254
+ ```
255
+
256
+ Lookup and model progress appear first, and the final output is:
257
+
258
+ ```text
259
+ 演示服务在线,延迟 12ms。
260
+ ```
261
+
262
+ Tool and model invocations each return `{ value, invocation }`; the final Result of the current Workflow is a string. These two boundaries do not need to share the same shape. Nodes report only a payload, and the Loop handles execution identity, time, and correlation.
263
+
264
+ The `as Status` in the TypeScript example does not perform runtime validation. Real validation is done by the tool's parseOutput, which then associates the result of a known demo tool with the state type. When integrating with Node/NestJS or another host, you still need to establish identity, authorization, and signal per request, and must not hand a client's permission flag directly to the model or tool as a trusted condition.
265
+
266
+ ## Keep Configuring Without Changing the Entry Point
267
+
268
+ - Cancel this run: `agent.run({ question }, { signal })`.
269
+ - Add a real model: replace the bound Provider and keep the same node calls and result reads.
270
+ - Add conditional branches: use raw routes or route builders in the ordinary routes array.
271
+ - Handle over-limit input: add an explicit node per the [context node contract](../api/context-processing.md); the final model call remains subject to the Core budget check.
272
+
273
+ The tool order in this example is configured by the Workflow, not chosen by the model. Model capability selection should register a capability schema, a transport, and a real authorized execution entry separately, and a model claiming it "looked it up" must not be taken as a real tool receipt.
@@ -0,0 +1,36 @@
1
+ # Integration references and maintenance tools
2
+
3
+ [Back to development handbook](README.md) · [Manual maintenance](maintenance.md) · [Shared flow](flows/knowledge-maintenance.md)
4
+
5
+ This kit provides [new project initialization](create-app.md), integration references for existing projects, copy-and-run offline code, and knowledge maintenance tools.
6
+
7
+ ## Integration code references
8
+
9
+ For the overall flow and call timing see [How the mechanism works](mechanisms.md); the knowledge answering diagram there is an illustration of an App composing local Kit contracts.
10
+
11
+ | Reference | What it offers an existing project |
12
+ | --- | --- |
13
+ | [Offline complete service answering](examples/offline-agent.md) | The same contract in TS/JS, from single node to tools, models, and process observation; no credentials needed |
14
+ | [Basic model and tool calls](basic-usage.md) | Named calls, static tool catalogs, real authorization and execution, Provider stream boundaries |
15
+ | [Core API](api/core.md) | Executor, model, tool, and cancellation/budget contracts |
16
+ | [Support Context](api/support.md#context) | Assembling existing knowledge and profiles into model input |
17
+ | [Knowledge API](api/knowledge-answering.md#knowledge) | Text parsing, section reading, and snapshots |
18
+ | [Knowledge answering contract](api/knowledge-answering.md) | Connecting reading, generation, checks, and output through local Kit interfaces |
19
+
20
+ The above are module call references; they do not create project directories, install dependencies, or start applications. Actual side effects are still carried by the existing project's ports.
21
+
22
+ ## Maintenance tools
23
+
24
+ The following paths are relative to the installed package's `development/`. Scripts require Node 22+ and a resolvable Core build.
25
+
26
+ | Entry | Input | Output and side effects |
27
+ | --- | --- | --- |
28
+ | `skills/agent-core-app/scripts/validate-knowledge.mjs PROJECT` | Existing project knowledge manifest, sources, and required read references | Check results; does not modify files |
29
+ | `skills/agent-core-app/scripts/prepare-source.mjs PROJECT --source UTF8_FILE --id DOCUMENT_ID` | Existing project, explicitly provided source, and stable document id | Source awaiting review and a proposal; does not overwrite effective knowledge or configuration |
30
+ | `skills/agent-core-app/scripts/plan.mjs PROJECT [--source UTF8_FILE]` | Existing project, optional source path | Agent development plan; see the Skill for specific behavior |
31
+ | `skills/agent-core-app/scripts/create-app.mjs TARGET [--write]` | Empty target directory, name and purpose, optional real source | Read-only plan by default; explicitly creates a TypeScript/Node project and unpublished source candidates |
32
+ | `skills/agent-core-app/scripts/create-app.mjs TARGET --check` | Generation receipt, current managed files, and the selected template | Read-only diff report; does not overwrite user modifications |
33
+
34
+ Knowledge maintenance tools work from configuration explicitly provided by the project and do not scan or execute project code. For initialization and diff checks see [Create an App](create-app.md). For knowledge format, flow, and publication responsibility see the [Maintenance guide](maintenance.md). Failures exit with a non-zero code and an error report; invalid UTF-8, budget, or section errors cannot be bypassed by relaxing validation.
35
+
36
+ The tools do not replace document review, resource authorization, database write-back, or publication, and they do not by default take on PDF/OCR, web crawling, or arbitrary material ingestion.
@@ -0,0 +1,38 @@
1
+ # Knowledge Preparation, Maintenance, and Publication Flow
2
+
3
+ This flow is referenced by the development-time knowledge preparation tools, the manual maintenance process, and the App's runtime knowledge growth implementation. It is not a prompt or state machine that Core executes automatically, and it grants no read or write permission. In an existing project, development-time verification and runtime loading reuse the same knowledge.config.json and compileApplicationKnowledge. When there is only an idea and no source, keep an empty file and an empty document list, and do not generate initial facts.
4
+
5
+ ## Shared Process
6
+
7
+ | Stage | What must be obtained | Execution responsibility |
8
+ | --- | --- | --- |
9
+ | Obtain sources | Originals or references, source entity, time, usage/access scope | Organized by developers, or received by the App under authorization |
10
+ | Form candidates | Locatable body text/fields; unknowns and conflicts retained | Human or App extractor; model output is only a candidate |
11
+ | Assign identity | Stable document/section IDs, explicit revision and locale | The App's maintenance policy; not the model inventing new program handlers at will |
12
+ | Check structure and references | Documents, sections, task reads, and budgets all usable | The same application compile entry and local validators such as Knowledge/Task |
13
+ | Approve for publication | Human/business verification decided from sources and risk; authorization scope not widened | The App's own publication policy; the library does not build in generic approval |
14
+ | Publish the version | Persistent records and the concurrent version commit succeed, then the new catalog becomes available | Controlled publication during development, or a transactional/CAS implementation at runtime |
15
+ | Use and trace | Requests bind the catalog and source snapshot; corrections can find the old version | App handler and storage; Core maintains execution budget and cancellation |
16
+
17
+ ## Shared Rules
18
+
19
+ 1. Document IDs are unique within the catalog; section IDs are globally unique within a document. A title or file path does not replace identity.
20
+ 2. Changing body text or metadata that affects interpretation requires changing the revision. A snapshot does not replace source material, approval records, or a content hash.
21
+ 3. Validate references to tasks, readers, sections, outputs, and checks. A knowledge file passing syntax parsing does not mean the whole Agent integration is correct.
22
+ 4. Source material, user preferences, experience candidates, published knowledge, and tool receipts are handled separately; a user statement does not automatically become a public fact.
23
+ 5. Use the smallest complete read scope; when the budget is insufficient, report an error explicitly or read in batches, and do not silently truncate rules or necessary evidence.
24
+ 6. A failed check or publication does not overwrite the old version. Existing requests keep using their own old snapshot, and knowledge is not swapped out behind the scenes between generation and review.
25
+ 7. A data update does not automatically add execution permission. Dynamic knowledge references and program capability registration are two different flows.
26
+
27
+ ## Where the Shared Rules Are Enforced
28
+
29
+ The example knowledge.config.json is an **App-owned configuration template**, not a new protocol in the library. It declares source files, read budgets, and read references that must be valid. compileApplicationKnowledge in development/skills/agent-core-app/scripts/lib/knowledge.mjs is used by both the validation tool and runtime loading; when the App copies or rewrites the template, it keeps the same entry:
30
+
31
+ ```text
32
+ 开发者/开发期脚本 → 源稿和配置 → 共享编译校验 → 发布应用资料
33
+ 运行期增长适配器 → 经审定的新版本 → 共享编译校验 → 持久提交/切换可用版本
34
+ ```
35
+
36
+ The example implements only reading local source files, version computation, reference checks, and in-memory catalog construction. Runtime candidate extraction, review, persistence transactions, CAS, deletion, and permission filtering remain the App's responsibility; writing a flow in this file does not mean those capabilities are integrated.
37
+
38
+ When integrating other formats, databases, or retrieval services, keep this flow and the same structure/reference checks, and replace only the input and commit adapters. There is no need to hard-code storage paths or one product's data tables into Core.
@@ -0,0 +1,71 @@
1
+ # Installation and integration
2
+
3
+ [Back to development handbook](README.md) · [API handbook](api/README.md)
4
+
5
+ Install Agent Core as a dependency in your application, then integrate models, tools, and workflows as needed.
6
+
7
+ When starting from an empty directory, you can first generate a TypeScript/Node project following [Create an App](create-app.md), then complete dependency and model integration along this page.
8
+
9
+ ## Installation
10
+
11
+ Install from npm:
12
+
13
+ ```sh
14
+ npm install @jangts/agent-core
15
+ ```
16
+
17
+ Dependencies are installed by the package manager according to `package.json`. When using a local package provided by the maintainer, specify the tarball path:
18
+
19
+ ```sh
20
+ npm install /artifacts/jangts-agent-core-0.1.0.tgz
21
+ ```
22
+
23
+ Replace the path and version according to the actual delivery. Offline installation requires the maintainer to provide a complete local dependency source, and the package manager resolves all dependencies.
24
+
25
+ The package provides ESM, CommonJS, and TypeScript declarations. Use Node.js 22.12.0 or later; the runtime must provide the APIs in use such as `fetch`, `AbortSignal`, and `ReadableStream`. Model credentials are managed by the application's server-side configuration.
26
+
27
+ ## Wire up the first call
28
+
29
+ First provide a ChatProvider that the App has already configured, then pass the raw question; all other run settings have defaults:
30
+
31
+ ```ts
32
+ import { Support, ModelRunner } from '@jangts/agent-core';
33
+
34
+ const provider = new Support.CompatibleModelProvider({ config: {
35
+ baseUrl: process.env.AI_BASE_URL!,
36
+ apiKey: process.env.AI_API_KEY!,
37
+ model: process.env.AI_MODEL!,
38
+ } });
39
+ const model = new ModelRunner({ provider });
40
+ const text = (await model.invoke('你好')).value;
41
+ ```
42
+
43
+ The above uses the application's existing environment configuration, and the service must be compatible with Chat Completions; baseUrl does not include /chat/completions. The Provider handles HTTP/SSE itself, so you do not need to implement stream separately. Run the [Offline complete example](examples/offline-agent.md) first without model credentials; it does not call a real model. Plain text calls need no Knowledge, tools, or workflows. Kits are imported from `@jangts/agent-core/kits/<name>` as needed; see the corresponding task documentation for specific compositions.
44
+
45
+ | Provided by the App | Executed by existing interfaces |
46
+ | --- | --- |
47
+ | The Provider's real connection configuration and user input; signal/budget overrides as needed | ModelRunner checks budget, handles cancellation/timeout, and calls the model |
48
+ | Centralized tool declarations, server-side identity, and business implementation | Core ToolRegistry executes registrations; optional Support reduces repeated wiring, and authorization constraints come from the actual declarations |
49
+ | Continue/end conditions and business error exits | AgentCoreEngine executes according to registered flows |
50
+ | Knowledge reading, visibility scope, sources and versions | Kits such as Knowledge process provided data under local contracts |
51
+
52
+ Next, follow [Model and tool integration](basic-usage.md) to complete text calls, tool proposals, and real execution in order. ModelRunner.invoke is one complete model call; multi-step execution is explicitly orchestrated by the App with existing Core APIs. For parameters and errors see [Core](api/core.md), [Support](api/support.md), and [Kit](api/kits.md).
53
+
54
+ ## Knowledge and output integration
55
+
56
+ - [Knowledge documents](knowledge.md): sections, versions, selection, and snapshots; parse/define process only in-memory data and create no storage.
57
+ - [Knowledge answering contract](api/knowledge-answering.md): the local interfaces of Knowledge, Answering, and Presentation, connected by the App through reader, authorization, model, review, and output.
58
+ - [Manual maintenance](maintenance.md) and [Agent-assisted development](agent-development.md): shared rules and scripts for maintaining existing code and knowledge.
59
+ - [Operations](operations.md): Core output, Support observer, App logs, cancellation, and budget.
60
+
61
+ Prepare knowledge faithfully when raw material exists; when there is only an idea, keep knowledge empty with open items, and do not write speculation or demo text as facts. Knowledge growth is carried by the existing App's authorization, storage, and update flows.
62
+
63
+ ## Lifecycle wiring
64
+
65
+ Static declarations can be validated during the existing project's assembly stage; user materials, read evidence, consumed budget, and session state should have explicit request/session ownership. Do not store mutable current-request state in objects shared across users.
66
+
67
+ Before integration, verify small-scope behavior that has no real side effects, then verify real models and business execution as needed. The call code in the documentation is not a standalone application template, and it does not automatically grant publication or operation permissions.
68
+
69
+ ## Debug with a mock model
70
+
71
+ When there are no model credentials, use the [MockGPT Kit](api/mock.md) to configure fixed replies, input-dependent generators, tool proposals, and failures. Direct calls are imported from `@jangts/agent-core/mock`; when a standalone HTTP model service is needed, use createMockServer from `@jangts/agent-core/mock/node`. Point the model client at its local address, and the application's workflow, tool authorization, and budget contracts stay the same.
@@ -0,0 +1,89 @@
1
+ # Knowledge documents, sections, and versions
2
+
3
+ [Back to development handbook](README.md) · [Knowledge API](api/knowledge-answering.md#knowledge) · [Complete answering chain](api/knowledge-answering.md)
4
+
5
+ ## How the library learns your knowledge structure
6
+
7
+ Core does not scan knowledge directories, infer a knowledge base from file names, or automatically generate sections from Markdown headings. The App explicitly executes the following chain:
8
+
9
+ ```text
10
+ App reads controlled sources
11
+ → provides id, revision, locale, and body/structure
12
+ → Knowledge.parseKnowledgeDocument (only when text anchors are used)
13
+ → Knowledge.defineKnowledgeCatalog
14
+ → App checks the task's document/section references
15
+ → catalog.read with the reads allowed for this round
16
+ → passes the KnowledgeSnapshot as evidence to subsequent handlers
17
+ ```
18
+
19
+ This structure is a local specification after adopting the Knowledge Kit, not a document format every Agent must store. The App can generate `KnowledgeDocument.parts` directly without Markdown parsing.
20
+
21
+ ## Development-time preparation tools and runtime assembly functions
22
+
23
+ | Entry/asset | Purpose | What it does not do |
24
+ | --- | --- | --- |
25
+ | [Maintenance guide](maintenance.md) | Prepare knowledge in the project; organize faithfully when sources exist, keep empty when none | Knowledge must have real sources; ideas are not facts |
26
+ | `Knowledge.parseKnowledgeDocument({id, revision, text, locale?})` | Parse paired section anchors into a document tree | Does not read files, compute revision, or complete all catalog validation |
27
+ | `Knowledge.defineKnowledgeCatalog(documents, options?)` | Compile/freeze an in-memory document catalog, providing ids, sectionIds, assertSelection, read | Does not create databases, watch files, import uploads, or automatically learn or write back |
28
+ | [Section marker notes](#text-section-anchors) | Local code fragment explaining paired anchors and nesting rules | Not initial knowledge and not loaded automatically |
29
+ | [knowledge.mjs](../skills/agent-core-app/scripts/lib/knowledge.mjs) | App-side template shipped with the Skill for explicitly reading files, computing versions, and compiling catalogs | Not a built-in persistent initializer of the library |
30
+
31
+ Minimal document JSON structure:
32
+
33
+ ```json
34
+ {
35
+ "id": "service-guide",
36
+ "revision": "content-version-1",
37
+ "locale": "zh-CN",
38
+ "parts": [
39
+ "全局引言。",
40
+ { "id": "delivery", "parts": [
41
+ "本章节自身正文。",
42
+ { "id": "delivery.timing", "parts": ["时机说明。"] }
43
+ ] }
44
+ ]
45
+ }
46
+ ```
47
+
48
+ `parts` may mix raw text strings and subsections. Structured section IDs must be non-empty strings and **globally unique within the same document**, not merely unique among adjacent siblings. Document IDs are unique within the catalog; catalog compilation rejects duplicate sections and cycles. Do not run only the text parser and skip catalog compilation.
49
+
50
+ ## Text section anchors
51
+
52
+ Sources use paired markers on their own lines, with no indentation:
53
+
54
+ ```md
55
+ <!-- agent-section:delivery -->
56
+ 本章节自身正文。
57
+ <!-- agent-section:delivery.timing -->
58
+ 子章节正文。
59
+ <!-- /agent-section:delivery.timing -->
60
+ <!-- /agent-section:delivery -->
61
+ ```
62
+
63
+ The characters accepted in IDs by the text adapter are English letters, digits, `_`, `.`, `:`, and `-`. Markers must keep spaces as in the example and occupy their own line; opening and closing IDs must match and nest correctly. Markdown `#` headings are merely body text. The parser recognizes anchors from raw text and is not a full Markdown interpreter; do not put example anchors on their own lines inside code fences in sources, or they will also be recognized as real sections.
64
+
65
+ Stable IDs represent content identity. Changing a title does not require changing the ID; when splitting/deleting sections, migrate task mappings and historical reference policies at the same time. Characters such as `.` are only part of the ID; parent-child relationships are determined by the actual nesting in `parts` and cannot be guessed from names.
66
+
67
+ ## Three ways to read
68
+
69
+ | Request | Returned scope |
70
+ | --- | --- |
71
+ | `{documentId:'service-guide', selection:{mode:'document'}}` | The whole body text and all descendants, in source order |
72
+ | `{documentId:'service-guide', selection:{mode:'self', sectionIds:['delivery']}}` | The selected section's own string body, excluding subsections |
73
+ | `{documentId:'service-guide', selection:{mode:'subtree', sectionIds:['delivery']}}` | The selected section and all its descendants |
74
+
75
+ Sections explicitly selected are joined by two newlines in the order of the request array; duplicate IDs are rejected. If a parent section and its child are both selected into a subtree as two different IDs, the child text may still be included twice; the library does not automatically eliminate this ancestor overlap. The App should choose the appropriate minimal complete scope.
76
+
77
+ `maxChars` limits the selected, trimmed body text of this call; exceeding it throws rather than silently cutting off the latter half. Document size, storage capacity, and model context budget are different limits. Unknown fields, identity, and file paths coming from the client are not trustworthy just because catalog.assertSelection passes; cross-boundary input is still parsed and authorized by the App according to its own schema.
78
+
79
+ ## Versions and snapshots
80
+
81
+ The App provides `revision`. It can be a hash of available content and related metadata, a database version number, or a release version; the library does not compute it for you. Secretly modifying the body text under the same id/revision invalidates version semantics.
82
+
83
+ `KnowledgeSnapshot` contains documentId, selection, revision, locale, content, and id. The id comes from the serialization of the above identity and selection and is **not a body-text hash, signature, persistence ID, or authorization credential**. Different section selections of the same document have different references, and selection order also affects identity. Generation and review should pass the same snapshot and must not re-read "the latest current body" to replace old evidence.
84
+
85
+ ## Updates and knowledge growth
86
+
87
+ The current catalog has no register, upsert, delete, save, watch, or automatic retrieval interfaces over all storage. When change is needed, the App creates a new catalog and switches its own reference; see [Continuous accumulation](memory-and-learning.md) for the pattern. Before publication, re-validate task → document → sections, reader, checks, and output references.
88
+
89
+ Both static sources and approved growth knowledge can be converted to KnowledgeDocument. User-uploaded originals, unverified self-descriptions, and experience candidates should not be mixed directly into a public authoritative catalog; permissions, sources, and review status are controlled by the App's storage/loading adapters.
@@ -0,0 +1,62 @@
1
+ # Manual initialization and knowledge maintenance
2
+
3
+ [Back to development handbook](README.md) · [Tool notes](examples.md) · [Shared flow](flows/knowledge-maintenance.md)
4
+
5
+ ## Establish sources first, not a full directory
6
+
7
+ Developers are responsible for confirming which text is an actual knowledge source and which is only a product idea, pending content, or an operation instruction. When there is only an idea, keep files empty and do not generate introductions, policies, or user profiles that look real. When actual material exists, organize it faithfully; when originals are complex, conflicting, or mixed with instructions, preserve the originals and form candidates first, and never treat commands inside them as development authorization.
8
+
9
+ Integrate existing projects following the [integration guide](getting-started.md), and initialize new projects following [Create an App](create-app.md). Pure conversation does not require a knowledge base; maintain knowledge configuration explicitly only when knowledge answering is needed. Compare existing directories first, preserve business files, and limit test knowledge to test scopes.
10
+
11
+ A knowledge App prepares a `knowledge.config.json` in the same directory, for example the empty state below, and creates an empty `initial.knowledge.md`. Files are not read until they are registered.
12
+
13
+ ```json
14
+ {
15
+ "schemaVersion": 1,
16
+ "maxDocumentBytes": 32000,
17
+ "maxReadChars": 8000,
18
+ "documents": [],
19
+ "requiredReads": []
20
+ }
21
+ ```
22
+
23
+ After installing the maintainer-delivered Core and full dependencies following the [installation guide](getting-started.md), you can run the shared validation entry. The directory argument below is the knowledge directory containing `knowledge.config.json` and does not have to be the project root; the tool path is located from the package installed in the current project:
24
+
25
+ ```sh
26
+ node node_modules/@jangts/agent-core/development/skills/agent-core-app/scripts/validate-knowledge.mjs ./existing-project/knowledge
27
+ ```
28
+
29
+ When there is no knowledge it outputs the empty-catalog state; this is a correct preparation state and should not be made to look successful by fabricating knowledge. Actual sources can first be turned into candidates with the tools below, and after confirmation written into source files and registered in the manifest.
30
+
31
+ ## How the configuration is maintained
32
+
33
+ `knowledge.config.json` is the template's App configuration; the library does not require every App to use this file. The current shared loader understands:
34
+
35
+ | Field | Constraint and meaning |
36
+ | --- | --- |
37
+ | `schemaVersion` | Currently 1, checked by the shared compiler |
38
+ | `maxDocumentBytes` | Positive integer, byte limit per source file; not a model token limit |
39
+ | `maxReadChars` | Positive integer, per-read character limit for Knowledge |
40
+ | `documents` | May be empty; entries are `{id,file,locale?}`; currently only lowercase `*.knowledge.md` file names in the same directory are allowed, and model-supplied paths are not accepted |
41
+ | `requiredReads` | `{documentId,selection}` actually depended on by tasks; all references are checked at compile time |
42
+
43
+ Document IDs must be unique; see [Knowledge documents](knowledge.md) for section rules. Newly added files must be registered explicitly; being on disk does not automatically grant publication or read eligibility. Source and subsequent version traceability are carried by the maintainer's own change records; candidate tools do not replace complete publication records.
44
+
45
+ ## Adding and updating reuse the same validation
46
+
47
+ ```sh
48
+ node node_modules/@jangts/agent-core/development/skills/agent-core-app/scripts/prepare-source.mjs ./existing-project/knowledge --source ./revision.md --id initial-doc
49
+ node node_modules/@jangts/agent-core/development/skills/agent-core-app/scripts/validate-knowledge.mjs ./existing-project/knowledge
50
+ ```
51
+
52
+ The first command only generates a candidate; the second checks the **currently effective configuration** and does not publish the candidate. The candidate contains the original file, document ID, suggested addition/replacement, source hash, revision, as well as the configuration hash at preparation time and existing document versions. Candidate validation also checks existing required section references; deleting a referenced section fails, and the task and configuration must be explicitly adjusted and the candidate prepared again—errors cannot be skipped automatically.
53
+
54
+ The configuration hash comes from the raw bytes actually parsed this time, sharing a single configuration read with the candidate's budget and required-read validation, so it is not re-read after validation and marked against a different baseline. Each source file version comes from content read this time; this does not constitute an atomic multi-file filesystem snapshot.
55
+
56
+ Publication is done by the maintainer: verify sources, body diffs, task references, and permissions → save the candidate to a controlled source file → add the new document to the manifest or update an existing file → use the same check entry → publish one complete version. Before publishing, compare the effective configuration and the revisions of replaced documents against the candidate baseline; if stale, redo the comparison. A single-file write is not a multi-file transaction; production systems should use their own versioned publication, transactions, or atomic switching.
57
+
58
+ Direct editing follows the same flow. A failed validation keeps the published version; generation and review use the same snapshot; a failed update does not delete the original file. Manual and runtime growth can share `compileApplicationKnowledge`, replacing only the input and commit adapters.
59
+
60
+ ## What maintenance does not happen automatically
61
+
62
+ The tools have no automatic approval, publication, file watching, indexing, scheduled learning, or database writes. User profiles and business experience are different application data; define their sources, updates, and deletions according to [Continuous accumulation](memory-and-learning.md), then decide whether to convert them into readable Knowledge documents.
@@ -0,0 +1,38 @@
1
+ # User materials and data boundaries
2
+
3
+ [Back to development handbook](README.md) · [Continuous accumulation](memory-and-learning.md)
4
+
5
+ Receiving material, extracting body text, using it within a round, storing it in a personal profile, and publishing it as shared knowledge are different operations. Core does not automatically convert uploads into long-term memory, nor does it trust instructions in material just because the material contains section anchors.
6
+
7
+ ## Minimal processing chain
8
+
9
+ ```text
10
+ Server confirms identity and material ownership
11
+ → App checks format/size, saves necessary source information
12
+ → Controlled parser extracts body text, records extraction failures or gaps
13
+ → Selects content according to this round's authorization
14
+ → Support context fragment marks it as user data and sets a budget
15
+ → Handler uses the material and binds output to actual evidence
16
+ ```
17
+
18
+ Parsing and saving are provided by App adapters. The plain text example does not mean PDF, image OCR, audio transcription, web crawling, or archives are supported. When these formats are needed, register parsing capabilities and acceptable results explicitly; parsing failure must not be treated as empty content and then followed by a complete conclusion.
19
+
20
+ | Field to be made explicit | Purpose |
21
+ | --- | --- |
22
+ | Material ID, owning user/tenant, access scope | The server establishes permissions and does not trust client-claimed owners |
23
+ | Original reference, type, source time, content hash | Retrieve the original and determine versions; do not treat file names as stable identity |
24
+ | Extraction version, body text, gaps, and parsing status | Distinguish originals from model/parser output |
25
+ | Lifecycle, retention, and deletion method | Whether this round, the session, or persistent storage is decided by the product |
26
+ | Review/publication status | Candidate material cannot automatically become shared authoritative knowledge |
27
+
28
+ See [Material record](records.md#material-record) for a reference. It is an App-owned record sample with no corresponding Core persistence API.
29
+
30
+ ## Context and tools
31
+
32
+ Use Support fragments to note the real source, `trust: 'user'`, and the corresponding lifecycle. The trust label is part of the assembly contract, not a sandbox; the App still needs to prevent material body text from being treated as higher-privilege instructions or executable code. Do not dynamically add one executable tool per uploaded file; usually keep a controlled `material.read` whose parameters reference IDs authorized for this round.
33
+
34
+ When continuing use across rounds, pass only references available to the session and re-confirm permissions and lifecycle. When persistent storage is needed, enter the application's own candidate and publication flow. After deleting an original, also clean up extracted text, summaries, indexes, and references according to the App policy—do not delete only the UI list.
35
+
36
+ ## Delivery limits
37
+
38
+ Do not output the full material text by default in errors, logs, or receipts. Partial reads, insufficient budget, and incomplete parsing should become explicit check results; retries cannot widen the visible scope. Source references, file download URLs, and cross-end presentation are chosen by the App; the Interaction Kit is optional, and front and back ends are not forced to use InteractionProtocol/CommandCatalog uniformly.