@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,227 @@
1
+ # How the mechanism works
2
+
3
+ [Back to development handbook](README.md) · [API handbook](api/README.md) · [Knowledge answering contract](api/knowledge-answering.md)
4
+
5
+ This document explains the current implementation with diagrams. Flows labeled "App composition example" are explicitly orchestrated by the application, not a fixed Agent flow built into Core; Core does not require the App to use Support, Kit, or task decomposition.
6
+
7
+ ## 1. Overall collaboration relationship
8
+
9
+ ```mermaid
10
+ flowchart LR
11
+ User[User input] --> App[App: identity, configuration, business orchestration and delivery]
12
+ App -->|calls runtime APIs, registers handlers| Core[Core: execution, model, tools, context contracts]
13
+ Core -->|calls back according to registered contracts| Handler[App handler: business processing and actual ports]
14
+ Handler -->|state updates, results or errors| Core
15
+ App -->|optional integration assistance| Support[Support: builds configuration, adapters and handlers]
16
+ Support -->|artifacts handed to the App for registration| App
17
+ Handler -->|calls as needed| Kit[Optional Kit: knowledge, answering, presentation, interaction, etc.]
18
+ Kit -->|local business results| Handler
19
+ Handler --> IO[App databases, files and external services]
20
+ Core -->|ChatProvider contract| Provider[Model connection provided by the App]
21
+ Provider --> Model[Model service]
22
+ App --> Output[User-visible output]
23
+ ```
24
+
25
+ Core and App have a call/callback relationship. Support assists the App in integrating the same set of contracts; Kit is chosen one-way by the App, and a Kit may call Core APIs internally, still bound by the same budget, cancellation, and error contracts.
26
+
27
+ ## 2. How task concepts map to execution mechanisms
28
+
29
+ ```mermaid
30
+ flowchart TD
31
+ Question[User question] --> Compose[App organizes this round's processing by business]
32
+ Catalog[Central capability manifest: purpose, schema, constraints, handler] --> View[Capability view visible this round]
33
+ Identity[Server-side identity and resource permissions] --> View
34
+ View --> Compose
35
+ Compose --> Workflow[Optional AgentWorkflow: declares execution nodes and routing]
36
+ Workflow --> Node[Node: requires, run, provides, routes, onErrorNodeId]
37
+ Node --> Handler[App handler]
38
+ Handler --> Model[ModelRunner: obtains model proposals or answers]
39
+ Handler --> Tool[ToolRegistry: executes registered tools]
40
+ Handler --> Tasks[Optional Answering: domain answering tasks]
41
+ Tasks --> Definition[Task declaration: id, inputSchema, readerId, outputId, checkIds, intentIds, scopeId]
42
+ Definition --> Evidence[App reader: authorization, actual reading and evidence]
43
+ Evidence --> Items[AnswerItem: source status and owning input ID]
44
+ Items --> Answer[Generation, checks, local repair and delivery status]
45
+ Model --> Update[Handler returns results or local state updates]
46
+ Tool --> Update
47
+ Answer --> Update
48
+ Update --> Route[Core commits compliant updates, then selects a route per declarations]
49
+ Route -->|continue| Node
50
+ Route -->|complete| Result[Return to App for delivery]
51
+ ```
52
+
53
+ The three concepts here are different: the **user question** is input, a **workflow node** is an execution stage, and an **answering task/item** is a domain object of the Answering Kit. One node can process multiple answer items; model proposals do not automatically create workflow nodes or install new handlers. A basic `ModelRunner.invoke` call needs neither a workflow nor answering tasks.
54
+
55
+ ## 3. How a Core workflow advances
56
+
57
+ Corresponds to the actual rules of `AgentWorkflow` and a bound `AgentCoreEngine.run`.
58
+
59
+ ```mermaid
60
+ flowchart TD
61
+ Definition[App declares workflow manifest] --> Validate[Validate on construction: nodes, route references, reachability, bounded cycles]
62
+ Validate --> Entry[entryNodeId corresponds to a startsRound node]
63
+ Entry --> Abort[Check cancellation, obtain target node]
64
+ Abort --> Round{Node marked startsRound?}
65
+ Round -->|yes| Budget{Enough round budget?}
66
+ Budget -->|no| Exhaust[Throw budget exhausted error]
67
+ Budget -->|yes| Count[Consume one round]
68
+ Round -->|no| Enter[Emit enter event]
69
+ Count --> Enter
70
+ Enter --> Requires[Check requires fields]
71
+ Requires --> Run[Call node run, obtain local updates]
72
+ Run --> Commit[Check cancellation, update shape and provides, then commit updates]
73
+ Commit --> Select[Select the first match in routes order]
74
+ Select --> Route{Match result}
75
+ Route -->|target node| Transition[Emit transition, clear previous node error]
76
+ Transition --> Abort
77
+ Route -->|complete| Complete[Compute result, isResult, check cancellation]
78
+ Complete --> End[Emit complete and return]
79
+ Route -->|no match| Contract[Workflow contract error]
80
+ Requires -.->|exception| Error[Error handling within the node try scope]
81
+ Run -.->|exception| Error
82
+ Commit -.->|exception| Error
83
+ Complete -.->|exception| Error
84
+ Contract --> Error
85
+ Error --> Recover{Not cancelled, not a contract error, and onErrorNodeId present?}
86
+ Recover -->|yes| ErrorNode[Move to the error node with context.error]
87
+ ErrorNode --> Abort
88
+ Recover -->|no| Throw[Throw to the caller]
89
+ ```
90
+
91
+ Only entering a node with `startsRound: true` consumes a round; other stages in the same round do not count separately. Every possible cycle (including error routing) must pass through a round boundary. When the entry node omits the field, it starts a round by default. The budget entry check is outside the node's try scope, so exhaustion is not routed to that node's onErrorNodeId. `run(step)` uses an explicit StepOutcome: `{ type: 'continue' }` to continue, `{ type: 'complete', value }` to complete; value may legitimately be undefined.
92
+
93
+ The commit guard covers only local state updates managed by Core; it does not roll back external writes that the handler has already performed. A failed diagnostic observation does not change business execution.
94
+
95
+ ## 4. Timing from model proposal to actual tool execution
96
+
97
+ **App composition example**: uses the Support tool catalog, ModelRunner, and the Core tool executor.
98
+
99
+ ```mermaid
100
+ sequenceDiagram
101
+ actor U as User
102
+ participant A as App orchestration
103
+ participant S as Support tool catalog
104
+ participant M as ModelRunner
105
+ participant P as ChatProvider / model
106
+ participant T as Core ToolRegistry
107
+ participant H as App tool handler
108
+ U->>A: asks a question
109
+ A->>S: Obtains capability view and in-request runtime from the same manifest
110
+ S-->>A: Model declarations, parsers, real execution registration
111
+ A->>M: invoke (input and registered transport)
112
+ M->>M: Check cancellation, call quota, input and schema budget
113
+ M->>P: stream (input and visible capabilities)
114
+ P-->>M: Model chunks
115
+ M->>M: Full collection, protocol parsing
116
+ M-->>A: ToolProposal (tool name and raw parameters)
117
+ A->>T: runtime.invoke (tool name, parameters)
118
+ T->>T: Look up registered tool, parseInput
119
+ T->>H: authorize (parameters, server-side context, signal)
120
+ alt Authorization passes
121
+ H-->>T: Allowed
122
+ T->>H: execute, and wait for actual I/O
123
+ H-->>T: Actual result
124
+ T->>T: parseOutput, record success event
125
+ T-->>A: Validated result
126
+ opt App needs to continue generation based on the result
127
+ A->>M: invoke (tool result and follow-up input)
128
+ M->>P: Generate within the remaining quota
129
+ P-->>M: Complete response
130
+ M-->>A: Parsed result
131
+ end
132
+ A->>A: Business checks, bind facts and deliver
133
+ A-->>U: Final reply
134
+ else Authorization denied or execution/output check fails
135
+ H-->>T: Denied or exception
136
+ T-->>A: Error and failure event
137
+ A-->>U: App handles the failure according to the actual cause
138
+ end
139
+ ```
140
+
141
+ The error branch in the diagram also covers input/output check failures in the Registry itself, where a handler call may not occur. A model proposal is not a success receipt, and Core does not automatically execute a tool just because the model proposed its name; whether to call it subsequently, generate again, or end is decided by the App handler/workflow. A failed tool output check also does not mean side effects that already occurred are rolled back.
142
+
143
+ ## 5. Internal flow of one model call
144
+
145
+ ```mermaid
146
+ flowchart TD
147
+ Invoke[invoke: normalize input, select registered transport] --> Initial[Check cancellation and remaining call quota]
148
+ Initial --> Prepare[Prepare or reuse this transport snapshot]
149
+ Prepare --> Assemble[Core assembles text, messages, BuiltContext or ContextPlan]
150
+ Assemble --> Check[Actual message, transport instruction, Schema and optional token budget checks]
151
+ Check --> Consume[Obtain model call quota, set call deadline]
152
+ Consume --> Stream[Provider stream: collect chunks and check output budget]
153
+ Stream --> Finish[Complete response: finish, parse, resolve]
154
+ Finish --> Deliver[Await content delivery in order, check cancellation]
155
+ Deliver --> Journal[Commit Journal and completion information]
156
+ Journal --> Result[Return value and invocation]
157
+ Stream -.->|cancellation, timeout, upstream or output error| Error[Mark stage and error code and throw]
158
+ Finish -.->|protocol parsing failure| Error
159
+ ```
160
+
161
+ Core is responsible for generic input assembly and final budget checks and does not implicitly select or compress. When processing is needed, the App registers Support or custom processing nodes into the same Workflow and uses ordinary routes to decide when to execute them. Model calls inside processing nodes share the request quota, cancellation, and deadlines; see [Context nodes](api/context-processing.md) for details.
162
+
163
+ An ordinary invoke does not require prepare in advance. When early measurement is needed, use `model.prepare(...)` to obtain a single snapshot, call `prepared.measure(input)` repeatedly, then still consume the same handle through `model.invoke({ input, prepared })`. Measurement covers the actual transport instructions and Schema; the final check remains in effect, and the handle is not a quota reservation.
164
+
165
+ `ModelRunner.sink.output` waits in order for consumers of generated chunks, and the fully parsed value is still returned through invoke; `execution.observe.event` is side-channel observation with isolated failures. Chunk preview and final business delivery are different boundaries.
166
+
167
+ ## 6. Task checks and local repair in the Answering Kit
168
+
169
+ Corresponds to the seven nodes currently registered by `defineAnswerFlow`; this flow exists only when the Kit is adopted.
170
+
171
+ ```mermaid
172
+ flowchart TD
173
+ Input[Validate input IDs, item ownership and count] --> Generate[generate: generate only source=ready items]
174
+ Generate --> Validate[validate: local checks and keep normalized values]
175
+ Validate --> Review[review: review per off / optional / required policy]
176
+ Review --> Select[select-repair: select items that are ready and still have issues]
177
+ Select --> Can{Failed items, repair count and call quota available?}
178
+ Can -->|yes| Repair[repair: consume one repair chance, submit only failed items and issues]
179
+ Repair --> Recheck[recheck: re-check only items generated this time]
180
+ Recheck --> Select
181
+ Can -->|no| Deliver[deliver: judge item by item]
182
+ Deliver --> Accepted[accepted: source ready, value present and checks satisfied]
183
+ Deliver --> Fallback[fallback: App fallback provided a value]
184
+ Deliver --> Blocked[blocked: no deliverable value]
185
+ ```
186
+
187
+ Initial generation and each repair consume one workflow round; `maxRepairs` additionally limits the number of repairs. `canInvoke` reads the real quota provided by the App, and the Kit does not create an extra model budget. Non-ready sources do not enter generation or repair; items whose review has explicitly failed cannot become passing because review later becomes unavailable. Cancellation, invalid item ownership, and program contract errors throw, and are not automatically disguised as fallback.
188
+
189
+ ## 7. Composition timing of App knowledge answering
190
+
191
+ The diagram below illustrates an App composition organized by the [Knowledge, Answering, and Presentation contracts](api/knowledge-answering.md); the concrete orchestration and ports are provided by the App. For complete code that can be copied and run directly see [Offline service answering](examples/offline-agent.md); that code does not enable Knowledge/Answering.
192
+
193
+ ```mermaid
194
+ sequenceDiagram
195
+ actor U as User
196
+ participant A as App answer
197
+ participant T as Answering task catalog
198
+ participant K as Knowledge / App reader
199
+ participant F as Answering Flow
200
+ participant M as Same ModelRunner
201
+ participant C as App checks and review
202
+ participant O as Presentation
203
+ U->>A: question, signal
204
+ A->>T: Parse task parameters and read
205
+ T->>K: Call the registered reader
206
+ K->>K: App authorize, read the fixed revision snapshot
207
+ K-->>A: Question and source evidence
208
+ A->>F: Run declared answer items
209
+ F->>M: generate: call with evidence
210
+ M-->>F: Draft
211
+ F->>C: Local checks and policy review
212
+ C-->>F: Check results and issues
213
+ loop issues remain and repair count, real quota allow
214
+ F->>M: Repair only failed items
215
+ M-->>F: Repaired draft
216
+ F->>C: Re-check and review
217
+ C-->>F: Latest check results
218
+ end
219
+ F-->>A: accepted / fallback / blocked
220
+ opt A deliverable value exists
221
+ A->>O: Bind program source fields and render the template
222
+ O-->>A: Body text and sources
223
+ end
224
+ A-->>U: status, text (if any), issues
225
+ ```
226
+
227
+ If review uses a model, it should consume quota through the same ModelRunner passed in. Fallback evidence and allowed wording are provided by the App; when no deliverable value is provided, blocked is returned. Authorization, reading, cancellation, or contract errors may be thrown directly, with no guarantee of reaching final delivery.
@@ -0,0 +1,42 @@
1
+ # Memory and continuous accumulation
2
+
3
+ [Back to development handbook](README.md) · [Shared flow](flows/knowledge-maintenance.md) · [Record templates](records.md)
4
+
5
+ The library has no out-of-the-box long-term memory database, user profile merging service, or automatic learner of business experience. Core provides execution contracts, Support helps assemble context and calls, and Kits such as Knowledge/Answering provide local processing once adopted. Whether to record, how to assign ownership, and when to update and delete are all explicitly implemented by the App; not recording is also a valid choice.
6
+
7
+ ## Different data needs different rules
8
+
9
+ | Data | Recommended use | Should not be equated with |
10
+ | --- | --- | --- |
11
+ | Recent Q&A | Session continuity, disambiguation | Tool execution logs, permanent knowledge |
12
+ | Accumulated user preferences | Addressing, expression preferences, ongoing topics | Identity, permissions, public facts |
13
+ | Business experience candidates | Inducing reusable suggestions and failure patterns from results | Proven rules, automatic authorization |
14
+ | Published knowledge | Business facts with explicit sources, scope, and versions | Unverified user self-descriptions |
15
+ | Original materials and extraction results | Current task evidence or authorized archives | Automatically shared knowledge |
16
+
17
+ Do not use one source-less large summary to hold all categories. Each record category should at least have stable identity, ownership, source, version, status, and retention policy. Template fields are only a starting point; the App defines and validates them, and they are not a new Core protocol that all consumers must follow.
18
+
19
+ ## Application flow for updating user preferences
20
+
21
+ ```text
22
+ Select final Q&A allowed to be recorded, and the watermark
23
+ → Old summary + new Q&A + explicit merge rules
24
+ → Model extraction of candidates under budget constraints
25
+ → Parsing and length/source/sensitive-scope checks
26
+ → Commit summary and new watermark on the premise of the old version
27
+ → Subsequent requests read by identity and mark it as low-trust memory
28
+ ```
29
+
30
+ Do not mix the model's internal reasoning, corrections, or unexecuted actions into user profiles. When new expressions conflict with old preferences, apply the App's explicit rules; authoritative human facts are still provided by the corresponding data source. On model failure or version conflict, keep the old summary and the unconsumed watermark and retry with bounds, avoiding lost messages or duplicate merges. Scheduled tasks, storage transactions/CAS, leases, and retries are implemented by the App; the Core per-request budget cannot be assumed to cover background jobs.
31
+
32
+ ## Application flow for experience growth
33
+
34
+ Register extraction, validation, query, and publication implementations with a fixed task type; adding an experience record is only a data change and does not automatically add a handler. Candidates should be associated with actual sources and results, retain applicability scope, counterexamples, and conflicts, and not treat one success as a universal rule.
35
+
36
+ Candidate formation → deduplication/conflict checks → business validation or human confirmation → versioned publication → controlled reading, consistent with the [shared flow](flows/knowledge-maintenance.md). To integrate with Knowledge, the App converts permitted records into `KnowledgeDocument`, compiles a new catalog, and switches the request reference; active requests keep using the old snapshot.
37
+
38
+ `prepare-source.mjs` is used to organize text candidates during development. Runtime persistent learning can reuse its compilation logic and source constraints, while storage, concurrency, and publication policies are provided by the App.
39
+
40
+ ## Decisions required before runtime integration
41
+
42
+ Record scope and user choices, tenant isolation, visibility scope, retention and deletion, source priority, update conflicts, idempotency keys/consumption watermarks, failure recovery, and which content is forever candidate-only. Without these implementations, documentation and interfaces should state clearly "used for this round/session" or "manually maintained", and must not claim automatic learning.
@@ -0,0 +1,51 @@
1
+ # Result delivery, diagnostics, and operations
2
+
3
+ [Back to development handbook](README.md) · [Core API](api/core.md) · [Support API](api/support.md)
4
+
5
+ ## Boundary of each run
6
+
7
+ Keep startup manifests separate from per-request state. For each request, establish identity, the allowed knowledge view, an `AbortSignal`, model/tool budget, and source and output state. Credentials, endpoints, model characteristics, and error mapping for connecting to the Provider are managed by the App server, and user materials or model parameters are not allowed to override these configurations.
8
+
9
+ Consider rounds, model call counts, timeouts, message and output characters, schema size, and business tool quotas separately. Repair, review, and fallback also consume budget; a step called "recovery" cannot mean unlimited retries. Core's model call budget covers only calls that actually pass through that runner; external HTTP, background jobs, and model calls made by the App itself must be limited by the App.
10
+
11
+ Cancellation must reach the actual model and business I/O; for writes already started, cancellation does not mean rollback. The App should be able to judge whether an operation has executed by idempotency key/real receipt, and query state before retrying. Synchronous ToolRegistry does not wait for arbitrary Promises; asynchronous business logic should be placed in suitable asynchronous handlers/nodes and must not fake synchronous success.
12
+
13
+ ## Verify facts first, then form presentable output
14
+
15
+ ```text
16
+ Parsed model proposal
17
+ → authorization and real execution
18
+ → input/output contracts and source checks
19
+ → generate candidate reply
20
+ → completeness/business fact checks
21
+ → program binds sources, action states, and links
22
+ → deliver in the form chosen by the App
23
+ ```
24
+
25
+ A Knowledge Snapshot is a source reference, a tool event is an execution record, and model text is a candidate explanation; the three do not substitute for each other. Answering's tasks, checks, and bounded repair help organize this chain; the concrete fact checks are provided by the App. See the [knowledge answering API](api/knowledge-answering.md) for the relevant local contracts.
26
+
27
+ Presentation/Interaction is an optional Kit. InteractionProtocol/CommandCatalog does not determine how the App exchanges data between front end and back end; when used, the App registers commands, parsing, and presentation implementations, and still needs actual receipts from the peer. The App may also directly adopt its own HTTP/SSE/event protocol.
28
+
29
+ ## Error exits
30
+
31
+ | Actual cause | Program handling | Direction of user-facing wording |
32
+ | --- | --- | --- |
33
+ | Source not provided or not allowed to read | Do not widen permissions, do not generate fake facts | State which kind of available knowledge is missing |
34
+ | Parameters or output violate the contract | Record the specific stage and code; repair or end within budget | State the actual action not completed this time |
35
+ | Provider stream break/timeout | Save known execution state, retry with bounds | Reply incomplete, can retry |
36
+ | Insufficient budget/read limit exceeded | Narrow the legal scope or split the task | State the scope limit; no silent truncation |
37
+ | User cancellation | Stop cancellable work, verify executed operations | State clearly that it stopped and what is confirmed |
38
+
39
+ Error messages should not show internal schemas, tokens, call protocols, or stack traces verbatim. Logs keep machine-locatable fields, and user copy keeps the accurate cause; not every failure should be described as a connectivity problem.
40
+
41
+ ## What observation and persistence each own
42
+
43
+ Core's run records/diagnostics and Support's Provider observer provide observation boundaries; they do not automatically create a log database. The App decides whether to output to the console, files, telemetry systems, or a persistent repository, and how to authorize queries, redaction, and retention. `breakWhile` tags are classification hints for interruption, not permission or rule filtering switches; follow the [Support reference](api/support.md).
44
+
45
+ It is recommended to correlate request/run, stage, model or tool call ID, business error code, knowledge revision/snapshot id, and actual duration. By default do not collect credentials, full prompts, user materials, or model body text; when body-text diagnostics are needed, the product must explicitly enable and limit the scope. Observation callbacks should not change business returns or escalate a record failure into duplicate execution.
46
+
47
+ ## Publication and recovery
48
+
49
+ Deliver code manifests, knowledge, task references, and configuration as one verifiable version. Validate references before publication and prepare a rollback version; new requests switch to the new catalog while existing requests hold old snapshots. Whether multi-file or database publication is atomic is implemented by the App; the Knowledge in-memory catalog itself provides no storage transactions.
50
+
51
+ When the App publishes, also state the enabled capabilities, knowledge version, configuration, and changes in externally visible behavior; the new version must still preserve the original permissions, budget, cancellation, and delivery guarantees.
@@ -0,0 +1,63 @@
1
+ # App data format examples
2
+
3
+ The JSON below only explains field design for App-owned records; it does not participate in runtime loading, register capabilities, or create data tables. Core does not require this storage format.
4
+
5
+ Use null/empty arrays to indicate not yet provided, and do not fabricate facts from example default values. Field names, states, and versions are defined and validated by the App itself.
6
+
7
+ ## Material record
8
+
9
+ Original, extraction status, ownership, lifecycle, and publication status.
10
+
11
+ ```json
12
+ {
13
+ "schemaVersion": 1,
14
+ "id": null,
15
+ "ownerId": null,
16
+ "scope": "private",
17
+ "original": { "reference": null, "mediaType": null, "contentSha256": null, "receivedAt": null },
18
+ "extraction": { "status": "pending", "revision": null, "text": null, "caveats": [] },
19
+ "lifetime": "turn",
20
+ "expiresAt": null,
21
+ "publication": { "status": "unpublished", "documentId": null }
22
+ }
23
+ ```
24
+
25
+ ## User preferences
26
+
27
+ Accumulated interaction preferences, source watermark, and version.
28
+
29
+ ```json
30
+ {
31
+ "schemaVersion": 1,
32
+ "ownerId": null,
33
+ "revision": null,
34
+ "summary": null,
35
+ "sourceWindow": { "after": null, "through": null, "references": [] },
36
+ "updatedAt": null,
37
+ "expiresAt": null,
38
+ "status": "uninitialized"
39
+ }
40
+ ```
41
+
42
+ ## Experience candidate
43
+
44
+ Experience source, applicability, validation, and publication status.
45
+
46
+ ```json
47
+ {
48
+ "schemaVersion": 1,
49
+ "id": null,
50
+ "ownerId": null,
51
+ "revision": null,
52
+ "status": "candidate",
53
+ "claim": null,
54
+ "applicability": [],
55
+ "sources": [],
56
+ "counterexamples": [],
57
+ "conflicts": [],
58
+ "validation": { "status": "pending", "references": [] },
59
+ "publication": { "approvedBy": null, "approvedAt": null, "documentId": null }
60
+ }
61
+ ```
62
+
63
+ User preferences cannot carry identity and permissions; experience candidates are not published automatically; raw materials do not automatically enter shared knowledge. See [Knowledge maintenance](maintenance.md), [Materials](materials.md), and [Continuous accumulation](memory-and-learning.md).
@@ -0,0 +1,63 @@
1
+ # Registration, assembly, and execution
2
+
3
+ [Back to development handbook](README.md)
4
+
5
+ ## Ordinary tool integration
6
+
7
+ Prefer putting static tool definitions in a separate, readable, typed manifest, preserving item types with Support.defineTool, and assembling with Support.defineToolCatalog. Each item contains id, kind, description, inputSchema, authorize, execute, and parseOutput; inputSchema provides both jsonSchema and parse; model capabilities and execution registration consume the same definition. For complete code see [Tool integration](basic-usage.md#tools-are-declared-only-once).
8
+
9
+ Create catalog.bind({ app: context, execution: { signal } }) per request; the model first produces a ToolProposal, and the App then calls runtime.invoke. The latter reuses Core ToolRegistry.invokeAsync, performing input parsing, actual authorization, execution, and output checks in order. When the available set changes, use catalog.select(ids) to project the same manifest, and still check the real identity at execution. This Support adapter does not replace workflows or the business specifications of Kits.
10
+
11
+ ## Two different kinds of registration
12
+
13
+ | Registered object | Purpose | Update method |
14
+ | --- | --- | --- |
15
+ | Tools/model capabilities/workflows/checks/output | Declare what the program can do, when it is available, what it accepts, and who implements it | The App compiles manifests and provides the available set by stage and real identity |
16
+ | Documents/sections/knowledge versions | Declare what content a given read can see | The App loads sources and creates a Knowledge catalog; on update, explicitly rebuild the catalog and related views |
17
+
18
+ Adding one knowledge document usually does not require adding a tool. Keep a single `knowledge.read`, and let the catalog authorized for this round provide legal document/section IDs. The model may propose read requests from the provided set, but cannot use them to register arbitrary new handlers, discover disk directories, or publish knowledge.
19
+
20
+ ## What a manifest should state
21
+
22
+ At minimum it should be possible to read: stable identifier, purpose, input and output, real execution entry, availability conditions, read scope, side effects, errors, and receipts. Derive the model-visible catalog, schema, and reference validation from the manifest wherever possible; do not maintain one prompt capability list and another actual execution list.
23
+
24
+ - `ModelCapabilityRegistry` registers the structures the model can propose along with `inputSchema` and `resolve`. inputSchema.jsonSchema is used for model declarations; business parsing, value ranges, and authorization must still be enforced by the program.
25
+ - `ToolRegistry` registers `id/kind/parseInput/execute/parseOutput`. invoke is for synchronous implementations; invokeAsync waits for asynchronous execution before checking output and recording results; do not hand a Promise to the synchronous entry as a completed result.
26
+ - `AgentCoreEngine` workflow nodes declare `requires/provides/routes/onErrorNodeId`. Only updates that pass cancellation and state contract checks are committed; branches are selected in declaration order.
27
+ - `Support.defineContextFragments` assembles request input and fragments. Trust, source, and budget must be correctly labeled by the App; client self-reporting alone is not acceptable.
28
+ - Knowledge, Answering, Presentation, Interaction, Intents, and Tools each own local contracts and are chosen according to business needs. They are not automatically installed by Core.
29
+
30
+ For named constructors, static helpers, and instance methods see [Core](api/core.md), [Support](api/support.md), and [Kit](api/kits.md).
31
+
32
+ ## Separate model proposals from actual execution
33
+
34
+ ```text
35
+ Server establishes identity and the available capability view
36
+ → model proposes capability + parameters
37
+ → Core collects the complete response, validates with inputSchema.parse, then calls the registered resolve
38
+ → App selects the actual execution entry
39
+ → tool parameter parsing → authorization by server-side identity → execute → output checks
40
+ → program records actual sources/execution receipts
41
+ → generation, checks, binding, and delivery
42
+ ```
43
+
44
+ `parse` should not incidentally perform writes, send messages, or call business tools. Nor should a success receipt be generated merely because the model says it is "done". Using the Interaction Kit for cross-end actions merely selects an optional exchange specification; the App still needs to implement peer handlers, identity, permissions, and confirmation of actual results.
45
+
46
+ ## Static manifests and in-request views
47
+
48
+ Known tools and local protocols are suitable for registration at startup. Authorization, page environment, current tenant, and allowed knowledge change per request and should be projected into the visible set during this round's assembly. Model visibility limits do not replace execution-time authorization.
49
+
50
+ When new documents must be available immediately: load new knowledge → validate catalog and task references → build a new version catalog → atomically switch the App's current reference. Existing requests keep their old catalog and snapshots; new requests use the new catalog. Do not mix body text, schema, sources, and revisions from before and after the reload within the same answer.
51
+
52
+ When program capabilities must genuinely be added dynamically, the App explicitly decides the code source, publication, and registration point, and reconstructs the corresponding registry. The library has no model-driven arbitrary code installation, automatic file discovery, or hot-unloading platform.
53
+
54
+ ## Checks at startup and per request
55
+
56
+ | Timing | What to check |
57
+ | --- | --- |
58
+ | Startup/publication | Whether handlers exist; whether node and output references are valid; whether knowledge/sections exist; whether the Skill's tools are actually registered; whether parameter schema and parser agree |
59
+ | Request start | Identity, knowledge access scope, budget, signal, current catalog revision, and capability set |
60
+ | Before real execution | Current permissions, resource ownership, parameter value ranges, and necessary confirmation |
61
+ | Before delivery | Tool result contracts, sources and numbers, generated fields, program-bound fields, output completeness |
62
+
63
+ A Kit's validator can only validate the local structure it knows about. It does not know your tenants, storage paths, data permissions, or business facts; these checks cannot be omitted just because "a creator was used".
@@ -70,3 +70,7 @@ Use `docs.acceptance` to select checks for concrete uncertainties, while followi
70
70
  ## Custom model transport boundaries
71
71
 
72
72
  A custom response collector is synchronous and request-local. Its outputChars must be a nonnegative safe integer after creation, each push and finish. An explicit infinite maxOutputChars budget does not permit infinite or invalid collector counts. Core records the largest valid observed count; finish may release buffers. Optional call metadata is read once on a best-effort basis and cannot replace the actual result, original failure or cancellation. Prefer Support transports for standard native calls and JSON; custom transports must preserve complete parsing, budgets and cancellation before any tool execution.
73
+
74
+ ## Node cache ownership
75
+
76
+ Use context.cache for bounded Engine memory; its default capacity is 1024, partitions are node-local and only get may name another node. The low-level step partition is `$step`. An App may explicitly inject an asynchronous AgentCachePort for context.agentCache. Persistence must be supported explicitly, is separate from volatile storage and never falls back. The App owns user isolation, serialization, capacity and expiry; do not cache authorization decisions. Forks start with empty Engine memory and only regain an App port when resume explicitly supplies agentCache. Keep durable facts in state/App storage, not caches.
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Scaffold or compare an App that uses `@jangts/agent-core`.
3
+ *
4
+ * Resolves the SDK the target project depends on, renders the selected template into a staging
5
+ * directory and only then renames it into place, so a failed or concurrent run never leaves a
6
+ * half-written app. `--check` compares the managed files against the recorded receipt instead of
7
+ * writing. Nothing here installs dependencies, calls a model or publishes content.
8
+ *
9
+ * Usage: see `usage` below; run directly or import `createApplication`.
10
+ */
1
11
  import { createHash } from 'node:crypto';
2
12
  import { execFile } from 'node:child_process';
3
13
  import { promisify } from 'node:util';
@@ -215,6 +225,15 @@ async function compare(target, resources, definition) {
215
225
  };
216
226
  }
217
227
  const manifestName = '@jangts/agent-core';
228
+ /**
229
+ * Create or check a generated application directory.
230
+ *
231
+ * @param args CLI arguments: `TARGET` plus optional flags described by `usage`.
232
+ * @param cwd Directory relative paths are resolved against; defaults to the process cwd.
233
+ * @returns A plan (`--write` omitted), a comparison (`--check`) or the creation result.
234
+ * @throws {TypeError} When arguments, names, the target or the source file are invalid.
235
+ * @throws {Error} When the template, receipt or SDK manifest is unsupported or inconsistent.
236
+ */
218
237
  export async function createApplication(args, cwd = process.cwd()) {
219
238
  const { target, values } = parse(args, cwd);
220
239
  if (basename(target) === '.local')
@@ -1,8 +1,25 @@
1
+ /**
2
+ * App-owned knowledge loading for the `agent-core-app` Skill.
3
+ *
4
+ * Reads the App's `knowledge.config.json` allowlist, verifies each referenced document against the
5
+ * configured byte limit, and compiles the documents into a Knowledge Kit catalog. This is App
6
+ * configuration code, not a Core file-store API: no model or request may supply a filesystem path.
7
+ *
8
+ * Exports: `compileApplicationKnowledge`, `readApplicationKnowledge`, `loadApplicationKnowledge`.
9
+ */
1
10
  import { readFile } from 'node:fs/promises';
2
11
  import { createHash } from 'node:crypto';
3
12
  import { Knowledge } from '@jangts/agent-core/kits/knowledge';
4
13
 
5
- // This is App-owned configuration and loading code, not a Core file-store API.
14
+ /**
15
+ * Compile parsed documents into a Knowledge catalog.
16
+ *
17
+ * @param documents Documents produced by `Knowledge.parseKnowledgeDocument`.
18
+ * @param policy Validated `knowledge.config.json` content (`schemaVersion`, `maxReadChars`,
19
+ * `requiredReads`).
20
+ * @returns The compiled catalog; required reads are resolved so a missing read fails here.
21
+ * @throws {TypeError} When the policy shape or a required read is invalid.
22
+ */
6
23
  export function compileApplicationKnowledge(documents, policy) {
7
24
  if (
8
25
  !policy ||
@@ -18,6 +35,17 @@ export function compileApplicationKnowledge(documents, policy) {
18
35
  return catalog;
19
36
  }
20
37
 
38
+ /**
39
+ * Read the knowledge config and its allowed documents from one directory.
40
+ *
41
+ * The config hash is computed over the exact bytes parsed below, so a proposal identity cannot
42
+ * drift from the document catalog it was derived from.
43
+ *
44
+ * @param directory Directory holding `knowledge.config.json` and the listed documents.
45
+ * @returns Parsed `documents`, the raw `policy` and the `baseConfigSha256` of the config file.
46
+ * @throws {TypeError} When the config or a document entry fails validation.
47
+ * @throws {RangeError} When a source document exceeds `maxDocumentBytes`.
48
+ */
21
49
  export async function readApplicationKnowledge(directory = new URL('./', import.meta.url)) {
22
50
  // Bind validation and proposal identity to the exact bytes parsed below.
23
51
  const configBytes = await readFile(new URL('knowledge.config.json', directory));
@@ -58,6 +86,14 @@ export async function readApplicationKnowledge(directory = new URL('./', import.
58
86
  return { documents, policy, baseConfigSha256 };
59
87
  }
60
88
 
89
+ /**
90
+ * Read and compile the App knowledge catalog in one step.
91
+ *
92
+ * @param directory Directory holding `knowledge.config.json` and the listed documents.
93
+ * @returns The compiled Knowledge catalog.
94
+ * @throws {TypeError | RangeError} Same validation failures as `readApplicationKnowledge` and
95
+ * `compileApplicationKnowledge`.
96
+ */
61
97
  export async function loadApplicationKnowledge(directory = new URL('./', import.meta.url)) {
62
98
  const { documents, policy } = await readApplicationKnowledge(directory);
63
99
  return compileApplicationKnowledge(documents, policy);
@@ -1,3 +1,12 @@
1
+ /**
2
+ * Read-only planning entry for the `agent-core-app` Skill.
3
+ *
4
+ * Reports whether a project exists, which SDK it resolves, the state of its knowledge catalog and
5
+ * the SDK tools/docs that may be used next. It never evaluates project code, calls a model or
6
+ * writes files; the printed JSON is guidance for the agent, not a permission grant.
7
+ *
8
+ * Usage: `node plan.mjs PROJECT [--source UTF8_FILE]`.
9
+ */
1
10
  import { stat } from 'node:fs/promises';
2
11
  import { resolve, sep } from 'node:path';
3
12
  import { pathToFileURL } from 'node:url';
@@ -1,3 +1,13 @@
1
+ /**
2
+ * Locate the SDK installation and the Skill assets it ships.
3
+ *
4
+ * The Skill never downloads or copies files: it resolves the `@jangts/agent-core` installation the
5
+ * target project already depends on, or — only when this Skill runs from inside the distributed
6
+ * SDK — the bundled sibling assets. Every returned path is verified to be a regular file so a
7
+ * broken or foreign package cannot silently supply a different asset.
8
+ *
9
+ * Exports: `resolveSdkResources`.
10
+ */
1
11
  import { createRequire } from 'node:module';
2
12
  import { readFile, stat } from 'node:fs/promises';
3
13
  import { dirname, join, resolve } from 'node:path';
@@ -69,6 +79,13 @@ async function requiredFile(root, relative) {
69
79
  return filename;
70
80
  }
71
81
 
82
+ /**
83
+ * Resolve the SDK root and every Skill resource path for one project.
84
+ *
85
+ * @param project Project directory used to resolve the installed SDK.
86
+ * @returns `sdk` (`root`, `version`, `source`), the `tools`/`docs` file paths and `knowledgeLoader`.
87
+ * @throws {Error} When the SDK cannot be resolved, or a declared resource is missing or not a file.
88
+ */
72
89
  export async function resolveSdkResources(project) {
73
90
  let sdk = await installedPackage(resolve(project));
74
91
  if (!sdk) {
@@ -1,6 +1,12 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.coreEventCatalog = void 0;
4
+ /**
5
+ * Default visibility tier for every event Core can emit.
6
+ *
7
+ * The same object is the allow-list used when normalizing persisted records; adding an event to
8
+ * `CoreEventName` without a tier here fails type checking.
9
+ */
4
10
  exports.coreEventCatalog = {
5
11
  'node.progress': 'metadata',
6
12
  'model.start': 'metadata',