@easbot/llm 0.3.29 → 0.3.36

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 (67) hide show
  1. package/README.en.md +723 -20
  2. package/README.md +750 -19
  3. package/dist/assets/txt/src/agent/generate.txt +75 -0
  4. package/dist/assets/txt/src/agent/prompt/explore.txt +37 -0
  5. package/dist/assets/txt/src/agent/prompt/summary.txt +12 -0
  6. package/dist/assets/txt/src/agent/prompt/title.txt +24 -0
  7. package/dist/assets/txt/src/model/evaluation/templates/completeness.txt +53 -0
  8. package/dist/assets/txt/src/model/evaluation/templates/consistency.txt +52 -0
  9. package/dist/assets/txt/src/model/evaluation/templates/content-quality.txt +72 -0
  10. package/dist/assets/txt/src/model/evaluation/templates/context-relevancy.txt +45 -0
  11. package/dist/assets/txt/src/model/evaluation/templates/correctness.txt +43 -0
  12. package/dist/assets/txt/src/model/evaluation/templates/fact-checking.txt +43 -0
  13. package/dist/assets/txt/src/model/evaluation/templates/faithfulness.txt +53 -0
  14. package/dist/assets/txt/src/model/evaluation/templates/goal-completion.txt +70 -0
  15. package/dist/assets/txt/src/model/evaluation/templates/moderation.txt +80 -0
  16. package/dist/assets/txt/src/model/evaluation/templates/readability.txt +52 -0
  17. package/dist/assets/txt/src/model/evaluation/templates/relevancy.txt +56 -0
  18. package/dist/assets/txt/src/model/knowledge-summary.txt +142 -0
  19. package/dist/assets/txt/src/model/memory-summary.txt +151 -0
  20. package/dist/assets/txt/src/tool/buildin/edit.txt +10 -0
  21. package/dist/assets/txt/src/tool/buildin/glob.txt +42 -0
  22. package/dist/assets/txt/src/tool/buildin/grep.txt +42 -0
  23. package/dist/assets/txt/src/tool/buildin/read.txt +14 -0
  24. package/dist/assets/txt/src/tool/buildin/todo.txt +117 -0
  25. package/dist/assets/txt/src/tool/buildin/webfetch.txt +13 -0
  26. package/dist/assets/txt/src/tool/buildin/websearch.txt +14 -0
  27. package/dist/assets/txt/src/tool/buildin/write.txt +9 -0
  28. package/dist/chunks/chunk-2XQWKCQ4.cjs +1 -0
  29. package/dist/chunks/chunk-3DTBBDPN.mjs +2 -0
  30. package/dist/chunks/chunk-A6QGPYPS.mjs +10 -0
  31. package/dist/chunks/chunk-GHMRMPMO.cjs +1 -0
  32. package/dist/chunks/{chunk-QKEOAEWA.mjs → chunk-JIETUZVR.mjs} +1 -1
  33. package/dist/chunks/chunk-KS3TBDYP.cjs +2 -0
  34. package/dist/chunks/chunk-LCI45SAN.cjs +11 -0
  35. package/dist/chunks/chunk-NX2YVB72.mjs +1 -0
  36. package/dist/chunks/chunk-O2YH4BJL.cjs +10 -0
  37. package/dist/chunks/chunk-QMTIXJ7U.mjs +1 -0
  38. package/dist/chunks/{chunk-4A6CXMF2.cjs → chunk-RW4QUWZ2.cjs} +1 -1
  39. package/dist/chunks/chunk-YUX6P6YF.mjs +11 -0
  40. package/dist/chunks/{copilot-LRTA3GBD.mjs → copilot-7CO2EO6N.mjs} +1 -1
  41. package/dist/chunks/copilot-AOW7FWY3.cjs +1 -0
  42. package/dist/chunks/index.min-PO6HDKHB.mjs +4 -0
  43. package/dist/chunks/index.min-XTHFSCRB.cjs +4 -0
  44. package/dist/chunks/interfaces-2APNUNBK.cjs +1 -0
  45. package/dist/chunks/interfaces-U2BBKCET.mjs +1 -0
  46. package/dist/chunks/loader-AVOX6M4H.mjs +1 -0
  47. package/dist/chunks/loader-UCGPNKVW.cjs +1 -0
  48. package/dist/chunks/localagent-3DJBEVDM.cjs +1 -0
  49. package/dist/chunks/localagent-PNWC6EGM.mjs +1 -0
  50. package/dist/chunks/models-snapshot-CNF7AHMN.mjs +2 -0
  51. package/dist/chunks/models-snapshot-JD2O6VJX.cjs +2 -0
  52. package/dist/chunks/subagent-33FV6UYA.cjs +1 -0
  53. package/dist/chunks/subagent-OVNTI7J4.mjs +1 -0
  54. package/dist/index.cjs +144 -49
  55. package/dist/index.d.cts +7734 -219
  56. package/dist/index.d.ts +7734 -219
  57. package/dist/index.mjs +144 -49
  58. package/package.json +10 -10
  59. package/dist/assets/txt/model/knowledge-summary.txt +0 -86
  60. package/dist/assets/txt/model/memory-summary.txt +0 -85
  61. package/dist/chunks/chunk-KFESJR3T.cjs +0 -1
  62. package/dist/chunks/chunk-S4DPVKMV.mjs +0 -1
  63. package/dist/chunks/copilot-T25BJSTK.cjs +0 -1
  64. package/dist/chunks/models-snapshot-4CLLJLX6.mjs +0 -2
  65. package/dist/chunks/models-snapshot-OF5YAGCK.cjs +0 -2
  66. /package/dist/assets/txt/{model → src/model}/graph-summary.txt +0 -0
  67. /package/dist/assets/txt/{model → src/model}/summary.txt +0 -0
package/README.en.md CHANGED
@@ -6,12 +6,12 @@ English | [中文](./README.md)
6
6
 
7
7
  ## Version
8
8
 
9
- v0.3.29
9
+ v0.3.36
10
10
  ## Current Status (after V4 refactor)
11
11
 
12
12
  This package has evolved from an early placeholder of `@easbot/types` into a production-grade AI gateway layer that hosts two core modules: `provider/*` and `model/*`:
13
13
 
14
- - ✅ **`src/provider/`** (19 files): complete industrial-grade provider abstraction
14
+ - ✅ **`src/provider/`** (7 core files + self-developed Copilot SDK): complete industrial-grade provider abstraction
15
15
  - `Provider` namespace — 25+ built-in SDK (OpenAI / Anthropic / Azure / Bedrock / Vertex / OpenRouter / Copilot / Ollama / local models, etc.) dynamic loaders, `ModelsDev` catalog merging, model caching, SDK instance pooling
16
16
  - `ProviderError` namespace — APICallError parsing (including 25+ "context overflow" regex patterns)
17
17
  - `ProviderAuth` namespace — OAuth + API key dual-track authentication
@@ -19,20 +19,81 @@ This package has evolved from an early placeholder of `@easbot/types` into a pro
19
19
  - `ModelsDev` namespace — models.dev catalog zod schema + loading + remote refresh
20
20
  - `definition.ts` — DEFAULT_ENABLED_PROVIDERS whitelist + CUSTOM_PROVIDER_DEFINITIONS local SDK snapshot + PROVIDER_DISPLAY_NAMES friendly name mapping
21
21
  - `sdk/copilot/` — self-developed GitHub Copilot-compatible SDK (chat + responses + 6 tools)
22
- - ✅ **`src/model/`** (4 namespaces): high-level Model Providers
22
+ - ✅ **`src/model/`** (5 namespaces): high-level Model Providers
23
23
  - `RerankProvider` namespace — LLM-driven document reranking (unified with Memory hybrid search weights)
24
24
  - `GraphProvider` namespace — extract entities and relations from unstructured text (11 EntityType + 9 RelationType)
25
25
  - `SummaryProvider` namespace — note / memory summarization (LLM-based)
26
+ - `EvaluationProvider` namespace (`evaluation/`) — LLM-driven evaluation model (11 evaluation types × dedicated templates × dedicated JSON results)
27
+ - `EmbeddingProvider` namespace — text embedding (single / batch; via AI SDK standard `embed` / `embedMany`; default model `easbot-local/bge-base-zh-v1.5`)
28
+ - `LanguageProvider` namespace (`language/language.ts`) — **general-purpose language model calling entry**:
29
+ - `stream(input)` — streaming generation, returns AI SDK `StreamTextResult` (consume `result.fullStream`)
30
+ - `generate(input)` — non-streaming generation, returns `GenerateTextResult` (`result.text` is a string)
31
+ - `hasToolCalls(messages)` — detect whether message history contains tool-call / tool-result (basis for the `_noop` compatibility tool)
32
+ - `computeUsage(usage, metadata, model)` — token / cost accounting (fixes 3 vendor quirks: cache-write token read path, whether `inputTokens` includes cache, Anthropic-family `totalTokens` being untrustworthy)
33
+ - `resolveModel(input)` — **model input normalization** (`ModelInput` three forms → `Provider.Model`):
34
+ | Form | Input | Handling |
35
+ | ----------------------- | -------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
36
+ | String | `'anthropic/claude-sonnet-4-5'` | Uniformly goes through **`parseModelId`** from `@easbot/utils` (the single source of truth repo-wide, splits on the **first** `/` so model ids themselves may contain slashes: `'z-ai/z-ai/glm-5.1'` → provider `z-ai` + model `z-ai/glm-5.1`); a bare name without provider prefix (`'gpt-4'`) first infers the provider via `Provider.defaultModel()` |
37
+ | Model identifier object | `{ providerId: 'openai', modelId: 'gpt-4' }` | `Provider.getModel(providerId, modelId)` looks up the catalog to complete metadata |
38
+ | Complete model object | `Provider.getModel(...)` return value | Carries `api` / `capabilities` / `limit`, meaning the caller already resolved the catalog — **returned as-is**, no repeated lookup |
39
+ - Shared 14-step processing chain (model normalization → parallel preload → system normalization → variant/options 4-layer merge → Hook `llm.params` → temperature 4-level priority + clamp → Hook `llm.headers` → `maxOutputTokens` → `_noop` compatibility tool → `activeTools` filtering → **input overflow pre-check (throws `ContextWindowExhaustedError` when over the window)** → header assembly → `transformParams` middleware → SDK call)
40
+ - Additional capabilities (relative to the agent-side baseline): `stopSequences` (empty array normalization) / `seed` / `toolChoice` / `timeout` / `presencePenalty` / `frequencyPenalty` / `generate()`
41
+ - **Single-step by default** (`stopWhen = stepCountIs(1)`): multi-step loops require the caller to run cross-cutting logic between steps (permission prompts / context compaction / incremental persistence), so the built-in SDK loop is not used; simple scenarios can explicitly pass `stopWhen` to enable it
42
+ - User message input contract `LanguageUserMessage` — **inherits and extends** `UserMessage` from `@easbot/sdk` (`Omit`s `role` / `time` / `format` / `summary` / `agent` / `system`, extends `temperature`), without introducing a second message definition
43
+ - ✅ **`src/processor/`**: general-purpose stream processor (`StreamProcessor`)
44
+ - Consumes `fullStream` from `LanguageProvider.stream()` and translates vendor-specific stream events into **two channels fired together**: message events (`processor.*`) and Hook events
45
+ - **Part producer**: builds the assistant message internally and produces complete `Message.Part` entities (text / reasoning / tool / step-start / step-finish); the application layer only decides _how_ to persist them
46
+ - Three-state verdict `'stop' | 'continue' | 'compact'`: `'compact'` means **this request's input exceeds the model's context window** (local pre-check or server-side rejection), so the application layer compacts the context and re-enters
47
+ - **Two-level state** (`sessionId → streamId`): one process serves multiple sessions, and a session may run concurrent streams; the handle returned by `create()` exposes snapshots and per-stream `dispose()`, while `Instance.dispose()` reclaims everything
48
+ - **Forced single-step**: any caller-supplied `stopWhen` is stripped; multi-step loops are driven explicitly by the application layer between steps (permission prompts / compaction / persistence)
49
+ - Does **not** handle storage / retry / session state machine / permission prompts / actual compaction — all handed over to the application layer via events and verdicts
50
+ - ✅ **`src/compaction/`**: context overflow detection (`Compaction`)
51
+ - **Pure functions** that only decide whether "one model request's input" exceeds the usable window; actual compaction is a session-layer business action
52
+ - Detection scope = everything actually sent to the model: `system` + `messages` + `tools` (one-to-one with `StreamProcessor.process(streamInput)`)
53
+ - `isOverflow(input)` / `estimateInputTokens(input)` / `getUsableInputWindow(model)`; threshold = `limit.input ?? limit.context` minus the output reserve, floored at 50,000 tokens
54
+ - ✅ **`src/massage/`**: message schemas and events (`Message`) — the single source of truth for agent's `session/message.ts`
26
55
  - ✅ **`src/config/`** (V3 new): independent LLM Config module, mirroring `packages/gateway/src/config/` pattern
27
56
  - `LLMConfig / ProviderConfig / ProviderAuthMethod` — zod schemas (standalone usable, or as source-of-truth for injected Config)
28
57
  - `Config` namespace — `get()` / `provider(id)` (prefer injected, fall back to local loader)
29
- - ✅ **`src/interfaces.ts`** (V3 new / V4 simplified): **Adapter Registry** + Env / Flag namespace
58
+ - ✅ **`src/interfaces.ts`** (V3 new / V4 simplified): **Adapter Registry** + Env / Flag namespace + **Agent triple injection**
30
59
  - 4 Provider interfaces (`IConfigProvider` / `IInstanceProvider` / `IGlobalPathProvider` / `IInstallationProvider`; Auth moved to `@easbot/utils.Auth`)
31
60
  - `setAdapterRegistry(...)` — one-shot injection at agent-package startup, **completely decoupling** this package from agent's internal modules
32
61
  - `getI<X>Provider()` convenient accessors — fail-fast throws when not registered (**no silent degradation**)
33
62
  - `readEnvString / readFlagBool / readFlagNumber` — static readers, avoiding dependency on injection
63
+ - `setGlobalAdapter / resetGlobalAdapter / getGlobal()` — **fallback global-path resolution** (same design as `packages/acp/src/interfaces.ts`):
64
+ - Resolution order: `setGlobalAdapter()` explicit injection → AdapterRegistry `global` Provider → `EASBOT_*_PATH` env → XDG / homedir defaults
65
+ - Difference vs `getIGlobalPathProvider()`: the latter throws fail-fast (business layers with a hard dependency), this function never throws (path lookups should not crash when injection is missing)
66
+ - Typical use: `Truncate.dir()` truncation output directory (lazy evaluation, avoiding freezing the pre-injection default at module top level)
34
67
  - `Env / Flag` namespaces — static literals mirroring `process.env` (for IDE hints / doc generation / config introspection)
68
+ - **Agent triple injection** (consumed by `src/hook/` executors, same design as gateway `interfaces.ts`):
69
+ | Holder | Injection | Standalone CLI fallback | Accessor |
70
+ | ---------- | ------------------------ | ---------------------------------------------- | ------------------------------------- |
71
+ | SDK | `setEasbotClientAdapter` | lazy `createEasbotClient({ directory })` | `getSdk()` / `hasSdk()` |
72
+ | LocalAgent | `setLocalAgentAdapter` | lazy `new LocalAgent(getSdk(), { directory })` | `getLocalAgent()` / `hasLocalAgent()` |
73
+ | SubAgent | `setSubAgentConfig` | lazy `new SubAgent(DEFAULT_SUBAGENT_CONFIG)` | `getSubAgent()` / `hasSubAgent()` |
74
+ - Each holder unifies `override` (host injection, highest priority) / `fallback` (lazy self-build) two fields, bound to the current working directory via `State.holder`
75
+ - Process teardown uniformly calls `disposeLlmAgents()` — shutdown SubAgent / LocalAgent process pools and clear holders
76
+ - `Installation` namespace — version / channel / User-Agent
77
+ - `getVersion()` — prefers host-injected `IInstallationProvider`; when not injected, reads **`version` from this package's `package.json`** (using `import.meta.url` to derive the package root, independent of `process.cwd()`, adapting to both build artifacts and standalone CLI forms)
78
+ - `getChannel()` / `getUserAgent()` — `easbot/<channel>/<version>/<client>`, where client comes from `Flag.client()` (default `cli`)
79
+ - `Flag.client()` — client identifier (`EASBOT_CLIENT`, default `cli`), used for User-Agent and the `x-easbot-client` request header
80
+ - ✅ **`src/hook/`**: Hook mechanism facade (`LlmHookRegistry`)
81
+ - The mechanism layer reuses `HookRegistry` from `@easbot/utils`; this package hosts the **model call chain** builtins (`llm.params` / `llm.headers`)
82
+ - 5 executor types: `function` / `command` / `prompt` (via `getLocalAgent()`) / `http` / `agent` (via `getSubAgent()`)
83
+ - Scope resolution queries `session.contextMode` via `getSdk()`, falling back to `ScopeEnum.General`
84
+ - Builtin ownership principle: **the builtin lives in whichever package raises the event** (memory distillation / context compaction / gateway messages stay in agent / gateway)
85
+ - **Initialization**: `bootstrapLlm()` automatically warms up `LlmHookRegistry` (before model loading, so any `triggerEvent` in the instantiation chain observes the builtin hooks); a failed warm-up degrades to a warn and falls back to `ensureBridge()` on the first `triggerEvent`
35
86
  - ✅ **`src/index.ts`** — aggregate export entry (4 provider namespaces + 3 model namespaces + self-developed Copilot SDK + 3 constants + Config / interfaces + AdapterRegistry + 4 Provider interfaces)
87
+ - ✅ **`src/agent/`** (Agent module): Agent registry (`src/agent/buildin` static builtin baseline + layered overrides) + host injection entry + dynamic generation
88
+ - `Agent` namespace — the Agent module's **only** public API (`state` / `get` / `list` / `defaultAgent` / `isSubagent` / `init` / `resetState` / `registerBuiltin` / `unregisterBuiltin` / `register` / `unregister` / `registerUser` / `unregisterUser` / `base` / `disable` / `enable` / `applyInitialPermission` / `generate`)
89
+ - `AgentRegistry` — **not exported** (internal implementation: layered registration + single merge point)
90
+ - `resolveModel(model)` — normalize `string | AgentModel | undefined` → `AgentModel | undefined`
91
+ - `toModel(model)` / `toRuleset(permission)` — config shape → runtime shape conversion (used before host injection)
92
+ - Cross-package source of truth: paired with `@easbot/types.AgentInfoSchema` (config shape) and `@easbot/utils.Permission.Preset` (permission baseline)
93
+ - Runtime merge: **static builtin → runtime builtin → plugin → user** four-layer **whole-value replacement**; the "initial allow-list" is then overlaid and "disable tombstones" applied uniformly
94
+ - ✅ **`src/agent/localagent/`** — LocalAgent (standalone CLI fallback agent; same `override` / `fallback` two-field design as SubAgent)
95
+ - ✅ **`src/agent/subagent/`** — SubAgent unified entry (`SubAgent` class + `SubAgentRegistry` + Cli / Acp / Remote three transport implementations)
96
+ - ✅ **`src/agent/remoteagent/`** — RemoteAgent unified entry (`RemoteAgent` class + `RemoteAgentHandler`; reuses the ACP remote registry `ACPClientConnectionRegistry`, sharing connection state with gateway and other remote services; see [ADR 0132](../../docs/decisions/0132-remote-agent-unified-entry-and-error-contract.md))
36
97
 
37
98
  ## Core Features
38
99
 
@@ -45,6 +106,111 @@ This package has evolved from an early placeholder of `@easbot/types` into a pro
45
106
  - **Persistent model cache**: build-time generated `models-snapshot.ts`, runtime prefers local to avoid cold-start network calls
46
107
  - **Minimal aggregate export**: a single `@easbot/llm` import line gives you 5+3 namespaces + self-developed SDK + key constants
47
108
 
109
+ ## Tool Module (registry + generic tools)
110
+
111
+ `src/tool/` carries the **tool contract + layered registry + generic tool baseline**:
112
+
113
+ | Module | Path | Description |
114
+ | -------------- | ------------------------ | --------------------------------------------------------------------------- |
115
+ | `Tool` | `src/tool/tool.ts` | Tool contract + `Tool.define()` construction entry |
116
+ | `ToolRegistry` | `src/tool/registry.ts` | Layered registry (static builtin / runtime builtin / plugin / MCP / custom) |
117
+ | `Truncate` | `src/tool/truncation.ts` | Tool output truncation and dumping |
118
+ | `buildin/` | `src/tool/buildin/` | Static built-in baseline of 9 generic tools |
119
+
120
+ ### `ToolRegistry` state contract (mode C, **no fallback**)
121
+
122
+ `ToolRegistry` is the **only mode C module** inside `@easbot/llm` — it mandates `Instance.holder`
123
+ and **forbids** a `try { Instance.directory } catch { '__xxx_global__' }` fallback root.
124
+
125
+ | Method | Semantics |
126
+ | -------------------------------------------- | --------------------------------------------------------------------------------------------- |
127
+ | `ToolRegistry.state()` | Returns the merged tool table (bucketed by `Instance.directory`) |
128
+ | `ToolRegistry.init()` | Idempotent warm-up: triggers the first merge (`log.debug`, library-level) |
129
+ | `ToolRegistry.resetState()` | Clears the holder cache; the next access re-merges |
130
+ | `ToolRegistry.register*()` / `unregister*()` | Layered registration / targeted removal (see the file-header table in `src/tool/registry.ts`) |
131
+
132
+ **Why no fallback** (criterion: **would inconsistent bucketing silently produce a wrong security verdict?**):
133
+
134
+ Tool-related permission evaluation and permission waiting **strongly depend on `Instance.directory`**:
135
+
136
+ - Relative-path normalization of the generic tools uses `Instance.directory` as the base (`read` / `write` / `edit` / `glob` / `grep`)
137
+ - `Permission.ask`'s pending queue and `Permission.approved()`'s project-level grants (`Instance.project.id`)
138
+ - `ExternalDirectory`'s external-directory checks (`Instance.directory` / `Instance.worktree`)
139
+
140
+ Once the holder falls back to a global bucket, the **bucketing semantics split** — the tool table is cached under a "global bucket" (possibly holding definitions from another workspace) while permission evaluation still adjudicates against the "current directory" → the same tool definition points at different files in different workspaces → **out-of-bounds paths that should be blocked may be allowed through**.
141
+
142
+ > **Caller constraint**: every `ToolRegistry` API must be called inside an `Instance.provide` context;
143
+ > without one it **deliberately throws** (`No context found for instance`) instead of degrading silently.
144
+ > See `src/tool/__tests__/registry.test.ts` (wrapped in `Instance.provide({ directory, fn })`).
145
+ >
146
+ > See [`spec/module-pattern.md`](../../spec/module-pattern.md) §2.2.1 and
147
+ > [ADR 0122](../../docs/decisions/0122-tool-registry-instance-holder-mandatory.md).
148
+
149
+ > The agent-side `packages/agent/src/tool/registry.ts` is a **pure forwarder** (holds no state);
150
+ > it overlays the agent's own tools onto the llm registry's `builtin` layer via `registerBuiltin()`.
151
+
152
+ ## Generic Tool Permission Model (judge-only, no prompting)
153
+
154
+ `src/tool/buildin/` is the static built-in baseline of 9 generic tools (read / write / edit / grep / glob / bash / webfetch / websearch / todo).
155
+
156
+ ### Why not `ctx.ask`
157
+
158
+ The generic tool chain has **no UI interaction capability** — `ctx.ask` is a **no-op implementation** in its real consumers (buddy / CLI debug / agent's file-part reading), so `await ctx.ask(...)` does nothing: the permission is **never adjudicated**.
159
+
160
+ Not going through `ctx.ask` means three safety layers all fail (they live inside `Permission.ask`): hardline interception (`rm -rf /` / `mkfs` / fork bomb), dangerous shell prefixes (`bash -c '<anything>'` bypassing allow rulesets), and fine-grained deny rules (`bash: { 'rm *': 'deny' }`).
161
+
162
+ ### Assertion entry points (`@easbot/utils`)
163
+
164
+ | Tool | Dimension | Entry point |
165
+ | ------- | ----------------- | -------------------------------------------------------------------------------------- |
166
+ | `bash` | Command execution | `Permission.assertBashPermitted` (hardline + dangerous prefix + `bash` rules) |
167
+ | `bash` | External paths | `ExternalDirectory.extractExternalDirectories` + `ExternalDirectory.assertDirectories` |
168
+ | Other 7 | Tool call | `Permission.assertToolCallPermitted` (allow pass / deny·ask reject / no-match pass) |
169
+
170
+ ```typescript
171
+ import { Permission, ExternalDirectory } from '@easbot/utils';
172
+
173
+ // Inside a generic tool (ctx.extra.configRuleset is injected by the host tool-builder)
174
+ await Permission.assertToolCallPermitted('read', 'src/index.ts', {
175
+ agent: ctx.agent,
176
+ configRuleset: ctx.extra?.['configRuleset'] as never,
177
+ });
178
+ ```
179
+
180
+ `ctx.ask` stays in the `Tool.Context` contract for **UI-bearing hosts** (the agent side); generic tools should not call it.
181
+
182
+ ### bash tool prompt (shell + working directory + temp directory)
183
+
184
+ The `bash` tool's description is **generated dynamically at init time** (factory-style definition) and states the three facts that most directly affect command correctness:
185
+
186
+ | Information | Why it must be stated |
187
+ | --------------------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------- |
188
+ | **Which shell** | Without it an LLM may hand a PowerShell command to bash (`rm -rf` vs `Remove-Item`), and vice versa |
189
+ | **Working directory** | Without it the LLM can only probe with `cd` — an extra round trip, and `cd` outside the worktree trips the `external_directory` check |
190
+ | **Temp directory** | Without it the LLM may drop intermediate artifacts into the project (polluting the repo) or outside the worktree (tripping the `external_directory` check) |
191
+
192
+ - The shell name comes from `Shell.acceptable()` — **same source as execution**, so the description can never say "bash" while the process actually runs `pwsh`
193
+ - POSIX shells (`bash` / `zsh` / `sh`) additionally get quoting / variable / chaining guidance; others (`pwsh` / `cmd`) are told explicitly **not to assume bash syntax**
194
+ - The working directory is `Instance.directory`, and the prompt states there is **no `workdir` parameter** (use `cd <dir> && <command>` to change directory)
195
+ - The temp directory comes from `Permission.temp()` (defaults to the OS temp dir, switchable via `EASBOT_TEMP_PATH`) — **the same directory** the external-directory check allows
196
+ - Aligned with the agent-side bash wording (`packages/agent/src/tool/bash-prompt.ts` — both `workdirSection` and `intro` carry the shell name); the generic version just omits the async / simple-mode / git sections, so it stays short
197
+
198
+ ### Initial allow-list (cross-layer exemption)
199
+
200
+ `Agent.init()` registers three llm-internal resources as `external_directory` allow rules; **every effective Agent** (static builtin / host-injected / plugin / configured) receives them:
201
+
202
+ | Directory | Produced by |
203
+ | -------------------------- | ----------------------------- |
204
+ | `<data>/tool-output/**` | Tool output overflow dumps |
205
+ | `<data>/context-output/**` | Context / skill summary dumps |
206
+ | `<temp>/**` | Agent temporary files |
207
+
208
+ **User intent wins**: the allow-list is inserted **before** the Agent's explicit definitions (relying on `findLast`'s "later overrides earlier") — so when an Agent explicitly `deny`s / `ask`s the same directory, the **explicit definition beats the allow-list**. Only the fallback baseline (`external_directory: { '**': 'ask' }`) does not count as an "explicit statement", which is what lets the allow-list override it.
209
+
210
+ **Separation of duties for the temp directory**: `Agent.init()` calls `Permission.ensureTemp()` to **create** it with fault tolerance (failures only warn, they never block initialization); path resolution lives in utils' `Global.temp()` (pure resolution, zero I/O); the **env write-back** (`EASBOT_TEMP_PATH`) happens in exactly one place — the host `Global.init()` — because the permission layer must not mutate global env on its own.
211
+
212
+ See [ADR 0116](../../docs/decisions/0116-buildin-tool-judge-only-permission.md) / [ADR 0118](../../docs/decisions/0118-unified-temp-directory-and-agent-definition-priority.md).
213
+
48
214
  ## Installation
49
215
 
50
216
  ```bash
@@ -137,7 +303,106 @@ const summary = await SummaryProvider.summarizeNote({
137
303
  });
138
304
  ```
139
305
 
140
- ### 6. Text embedding (EmbeddingProvider)
306
+ ### 6. Evaluation model (EvaluationProvider)
307
+
308
+ ```typescript
309
+ import { EvaluationProvider } from '@easbot/llm';
310
+
311
+ // Scored evaluation (score 0-1 + passing verdict + feedback)
312
+ const r = await EvaluationProvider.evaluate({
313
+ type: 'completeness',
314
+ query: 'How do I deploy this project?',
315
+ response: 'Run easbot deploy.',
316
+ });
317
+ // r.type === 'completeness' → r.score / r.passing / r.feedback
318
+
319
+ // Binary evaluation (YES/NO)
320
+ const c = await EvaluationProvider.evaluate({
321
+ type: 'correctness',
322
+ query: 'Q',
323
+ response: 'R',
324
+ context: 'C',
325
+ });
326
+ // c.type === 'correctness' → c.passing (true/false)
327
+
328
+ // Fact checking (score + supported flag)
329
+ const f = await EvaluationProvider.evaluate({
330
+ type: 'fact-checking',
331
+ document: 'document body',
332
+ claim: 'claim to verify',
333
+ });
334
+ // f.type === 'fact-checking' → f.score / f.supported / f.feedback
335
+
336
+ // Goal completion quality (query = goal, response = completion result; quality score + achieved + missing)
337
+ const g = await EvaluationProvider.evaluate({
338
+ type: 'goal-completion',
339
+ query: 'Migrate the service and document the rollback',
340
+ response: 'Migration completed, service is live.',
341
+ context: 'tool output: deploy succeeded',
342
+ });
343
+ // g.type === 'goal-completion' → g.score (quality 0-1) / g.passing / g.missing / g.summary
344
+
345
+ // Content quality (query = criteria, response = content under review; unrelated to agent output)
346
+ const c = await EvaluationProvider.evaluate({
347
+ type: 'content-quality',
348
+ query: 'Must cover the migration steps and the rollback strategy, with a clear structure',
349
+ response: 'The document under review…',
350
+ document: 'reference document',
351
+ });
352
+ // c.type === 'content-quality' → c.score (quality 0-1) / c.passing / c.violations / c.summary
353
+
354
+ // Content moderation (flagged + 11 category flags + 11 category scores)
355
+ const m = await EvaluationProvider.evaluate({ type: 'moderation', response: 'content to review' });
356
+ // m.type === 'moderation' → m.flagged / m.categories.violence / m.scores.violence
357
+
358
+ // Custom system prompt (passed through to the model; same semantics as LanguageProvider.CallInput['system'])
359
+ const s = await EvaluationProvider.evaluate({
360
+ type: 'completeness',
361
+ query: 'Q',
362
+ response: 'R',
363
+ system: ['You are a strict reviewer.', 'Focus on factual accuracy.'],
364
+ });
365
+ ```
366
+
367
+ **11 evaluation types × dedicated templates × dedicated JSON results**:
368
+
369
+ | `type` | Template file | Required input | Result shape | Passing threshold |
370
+ | ------------------- | --------------------------------- | --------------------------------------- | --------------------------------------------------------------------- | ----------------- |
371
+ | `correctness` | `templates/correctness.txt` | `query` `response` `context` | `score` `passing` `feedback` (YES/NO) | YES → 1, else 0 |
372
+ | `faithfulness` | `templates/faithfulness.txt` | `context` `response` | `score` `passing` `feedback` | `score > 0` |
373
+ | `relevancy` | `templates/relevancy.txt` | `query` `correctAnswer` `response` | `score` `passing` `feedback` | `score > 0` |
374
+ | `context-relevancy` | `templates/context-relevancy.txt` | `query` `response` `context` | `score` `passing` `relevant` `feedback` | `relevant` |
375
+ | `completeness` | `templates/completeness.txt` | `query` `response` | `score` `passing` `feedback` | `score >= 0.8` |
376
+ | `consistency` | `templates/consistency.txt` | `answers` | `score` `passing` `feedback` | `score >= 0.7` |
377
+ | `readability` | `templates/readability.txt` | `response` | `score` `passing` `feedback` | `score >= 0.7` |
378
+ | `fact-checking` | `templates/fact-checking.txt` | `document` `claim` | `score` `passing` `supported` `feedback` | `supported` |
379
+ | `goal-completion` | `templates/goal-completion.txt` | `query` (goal) `response` (result) | `score` (completion quality) `passing` `missing` `summary` `feedback` | `achieved` |
380
+ | `content-quality` | `templates/content-quality.txt` | `query` (criteria) `response` (content) | `score` (quality) `passing` `violations` `summary` `feedback` | `compliant` |
381
+ | `moderation` | `templates/moderation.txt` | `response` | `flagged` `categories` `scores` `feedback` | `!flagged` |
382
+
383
+ **`goal-completion` (goal completion quality)** — judges whether an agent's output actually achieved its goal:
384
+
385
+ - **Parameter reuse**: `query` is the goal itself, `response` is the agent's completion result; `context` is the environment available for achieving it (tool output / existing state) and `document` is the goal-related spec — the latter two are optional.
386
+ - **Result shape**: `score` is the **completion quality** score (0-1) — an overall judgement of how well the goal was achieved (already covering coverage / correctness / output quality), **not** a bare progress percentage; `passing` is whether the goal was achieved; `missing` lists the uncovered goal checkpoints; `summary` explains the achievement state checkpoint by checkpoint.
387
+ - **`passing` is NOT derived from a `score` threshold**: it is the model's direct verdict (JSON field `achieved`) — a completion quality of 0.95 with one critical checkpoint missing MUST still be reported as not passing.
388
+
389
+ **`content-quality` (content quality)** — a pure content evaluation **unrelated to agent output**:
390
+
391
+ - **Parameter reuse**: `query` is the **evaluation criteria** (the bar the content must meet), `response` is the **content under review**; `context` is the surrounding situation (background / scenario) and `document` is a reference document — the latter two are optional.
392
+ - **Result shape**: `score` is the **content quality** score (0-1) — an overall judgement of the content against the criteria (coverage / correctness / structure / style); `passing` is whether it meets the bar; `violations` lists the unmet requirements and the defects found; `summary` explains each criterion's status.
393
+ - **`passing` is NOT derived from a `score` threshold**: it is the model's direct verdict (JSON field `compliant`) — a quality score of 0.95 that violates one hard requirement MUST still be reported as not passing.
394
+
395
+ **Behaviour contract**:
396
+
397
+ - **Default type**: when `type` is omitted, falls back to `EvaluationProvider.DEFAULT_EVALUATION_TYPE` (`correctness` — shortest output and the most robust parse, ideal for smoke evaluation).
398
+ - **Template loading**: `loadTextFile` lazily loads `./templates/<type>.txt` (after packaging, tsup's `onSuccess` copies them to `dist/assets/txt/model/evaluation/templates/`); variable filling goes through `Markdown.renderTemplate` (`{{var}}` / `{{#if}}` / `{{#each}}`).
399
+ - **Underlying call**: uniformly via `LanguageProvider.generate` (cross-vendor message normalisation / temperature clamp / unified retry and telemetry / input overflow pre-check / `ModelInput` normalisation across all four forms). Temperature uses `Provider.LIMITS.TEMPERATURE.EXTRACTION` (0.2); `activeTools: []` (evaluation needs no tools).
400
+ - **Custom system**: `input.system` (`string[]`) is passed through to `LanguageProvider.generate` verbatim, with the same semantics as `LanguageProvider.CallInput['system']` (multiple entries collapse into one, empty strings filtered); it is **not** template-rendered — pre-fill any variables yourself.
401
+ - **Result parsing**: dispatched by type — `correctness` uses YES/NO text detection; the rest use three-tier JSON extraction (strip markdown fence → grab the first `{...}` → per-line fallback); `score` is clamped to `[0,1]`; `moderation` always returns all 11 categories (model omissions become `false` / `0`).
402
+ - **Error handling**: missing required field → `NameErrors.MissingFieldError` (no LLM call); unparsable output → `NameErrors.OperationFailedError`. **No silent degradation** — a failed evaluation is a business fact, and swallowing it would produce a fake "pass".
403
+ - **Discriminated union**: the return type is `EvaluationResult` (a union narrowed by `type`), so callers reach type-specific fields via `result.type`.
404
+
405
+ ### 7. Text embedding (EmbeddingProvider)
141
406
 
142
407
  ```typescript
143
408
  import { EmbeddingProvider } from '@easbot/llm';
@@ -158,7 +423,45 @@ const customModel = Provider.parseModel('openai/text-embedding-3-small');
158
423
  const r = await EmbeddingProvider.embedText({ value: 'hi', model: customModel });
159
424
  ```
160
425
 
161
- ### 7. Use the self-developed GitHub Copilot SDK
426
+ ### 8. Language model calls (LanguageProvider)
427
+
428
+ ```typescript
429
+ import { LanguageProvider } from '@easbot/llm';
430
+
431
+ // The `model` input accepts all three internal forms — normalized internally:
432
+ // 'anthropic/claude-sonnet-4-5' (string, via parseModelId)
433
+ // { providerId: 'openai', modelId: 'gpt-4' } (model identifier)
434
+ // await Provider.getModel('openai', 'gpt-4') (complete catalog object)
435
+ const result = await LanguageProvider.stream({
436
+ user: { id: 'msg-1', sessionId: 'ses-1', variant: 'general' },
437
+ sessionId: 'ses-1',
438
+ model: 'anthropic/claude-sonnet-4-5',
439
+ agent: { name: 'coder', temperature: 0.6 },
440
+ system: ['You are a helpful assistant.'],
441
+ messages: [{ role: 'user', content: 'Summarize this PR.' }],
442
+ });
443
+
444
+ for await (const chunk of result.fullStream) {
445
+ // consume text / tool-call / tool-result chunks as they arrive
446
+ }
447
+
448
+ // Non-streaming variant shares the exact same input contract
449
+ const gen = await LanguageProvider.generate({/* ...same input... */});
450
+ // gen.text: string
451
+
452
+ // Cost accounting (handles 3 vendor token conventions)
453
+ const usage = LanguageProvider.computeUsage(result.usage, result.providerMetadata, model);
454
+ ```
455
+
456
+ **Input normalization** — `resolveModel()` is also exported standalone so callers can pre-fetch metadata (e.g. read `limit.output` to decide `maxOutputTokens`):
457
+
458
+ ```typescript
459
+ const meta = await LanguageProvider.resolveModel('z-ai/z-ai/glm-5.1');
460
+ // meta.providerId === 'z-ai' (split on the FIRST '/')
461
+ // meta.id === 'z-ai/glm-5.1' (model id keeps its own slashes)
462
+ ```
463
+
464
+ ### 9. Use the self-developed GitHub Copilot SDK
162
465
 
163
466
  ```typescript
164
467
  import { createOpenaiCompatible, openaiCompatible } from '@easbot/llm';
@@ -201,8 +504,103 @@ export * as RerankProvider from './model/rerank';
201
504
  export * as GraphProvider from './model/graph';
202
505
  export * as SummaryProvider from './model/summary';
203
506
  export * as EmbeddingProvider from './model/embedding';
507
+ export { EvaluationProvider } from './model/evaluation';
508
+ export type {
509
+ EvaluationType,
510
+ EvaluationInput,
511
+ EvaluationResult,
512
+ EvaluationBase,
513
+ ScoredEvaluation,
514
+ CorrectnessResult,
515
+ FaithfulnessResult,
516
+ RelevancyResult,
517
+ ContextRelevancyResult,
518
+ CompletenessResult,
519
+ ConsistencyResult,
520
+ ReadabilityResult,
521
+ FactCheckingResult,
522
+ GoalCompletionResult,
523
+ ContentQualityResult,
524
+ ModerationResult,
525
+ ModerationCategory,
526
+ } from './model/evaluation';
527
+
528
+ // General-purpose language model calling entry
529
+ export { LanguageProvider } from './model/language/language';
530
+ export type { LanguageUserMessage } from './model/language/language';
531
+ export type { ModelInput } from './model/language/language';
532
+
533
+ // Model input normalization (shared by Embedding / Rerank / Summary)
534
+ export { resolveModelIdentifier, deriveModelIdentifier, isModelEntity } from './model/model-input';
535
+ export type {
536
+ ModelIdentifier,
537
+ ModelInputLike,
538
+ ModelEntity,
539
+ AnyModelInput,
540
+ } from './model/model-input';
541
+
542
+ // Model identifier types (single source of truth in @easbot/types/native/llm.ts; re-export only)
543
+ export type { ModelRef, EmbeddingModelRef, LanguageModelRef, RerankingModelRef } from './bootstrap';
544
+
545
+ // LLM public contracts (each app package implements its own Llm namespace, asserted via `as ILLM`)
546
+ export type { ILLM, ILLMInitConfig, ILLMModels, ILLMCapabilities } from './bootstrap';
547
+
548
+ // Message namespace (message schema + events + storage + model message conversion)
549
+ export { Message } from './massage';
550
+
551
+ // Tool module (tool contract + layered registry + truncation; see src/tool/index.ts)
552
+ export { Tool, ToolRegistry, Truncate } from './tool';
553
+
554
+ // Agent module facade (see src/agent/agent.ts; `AgentRegistry` is not exported)
555
+ export { Agent, resolveModel, toModel, toRuleset } from './agent';
556
+ export { BUILTIN_AGENTS } from './agent';
557
+
558
+ // LocalAgent (standalone CLI fallback agent; see src/agent/localagent/)
559
+ export { LocalAgent, LocalAgentError } from './agent/localagent';
560
+ export type { LocalAgentConfig } from './agent/localagent';
561
+
562
+ // SubAgent unified entry (see src/agent/subagent/)
563
+ export { SubAgent, SubAgentError } from './agent/subagent';
564
+ export type {
565
+ SubAgentRunInput,
566
+ SubAgentConfig,
567
+ SubAgentExecuteOptions,
568
+ SubAgentInstance,
569
+ SubAgentRegistryConfig,
570
+ } from './agent/subagent';
571
+
572
+ // RemoteAgent unified entry (see src/agent/remoteagent/)
573
+ export { RemoteAgent, RemoteAgentError } from './agent/remoteagent';
574
+ export type { RemoteAgentConfig } from './agent/remoteagent';
575
+ export { RemoteAgentHandler, DEFAULT_REMOTE_TIMEOUT } from './agent/remoteagent';
576
+ export type { RemoteAgentHandlerConfig, RemoteInteractionResult } from './agent/remoteagent';
204
577
  ```
205
578
 
579
+ **Message public contract** (`packages/llm/src/massage/message.ts`):
580
+
581
+ - `Message.Info` / `Message.User` / `Message.Assistant` / `Message.Part` — zod schemas for messages and parts
582
+ - `Message.Event` — `message.updated` / `message.removed` / `message.part.updated` / `message.part.removed`
583
+ - `Message.get({ sessionId, messageId })` / `parts(messageId)` / `stream(sessionId)` — storage access
584
+ - `Message.toModelMessages(input, model, options?)` — messages → AI SDK `ModelMessage[]`
585
+ - `Message.fromError(e, { providerId, aborted })` — any error → persisted `Assistant.error` shape (always returns a `{ name, data }` plain object)
586
+ - Message errors (`OutputLengthError` / `AbortedError` / `StructuredOutputError` / `AuthError` / `APIError` / `ContextOverflowError`) are defined **in the `Message` namespace**, because their wire names are tightly coupled to the `AssistantMessage.error` discriminated union in `@easbot/sdk`. Changing any of them requires regenerating `sdk/openapi.json` + `sdk/src/gen/types.gen.ts`.
587
+
588
+ **Three-layer error division of labour** (see `spec/error-handling-standard.md`):
589
+
590
+ | Layer | Location | Semantics | Representative errors |
591
+ | --------- | ----------------------------- | ------------------------------------------------------ | -------------------------------------------------------------------------------------------- |
592
+ | Thrown | `utils.BusinessErrors` (L1.5) | Business failures shared across packages | `AuthError` / `ContextOverflowError` / `ContextWindowExhaustedError` / `RateLimitedError` |
593
+ | Transport | `ProviderError` (L2) | Provider communication fallback, `providerId` required | `APIError` (`ProviderAPIError`) / `ModelNotFoundError` / `InitError` / `ProbeEmbeddingError` |
594
+ | Persisted | `Message.*` | Written to `Assistant.error` and transported via SDK | `APIError` (`APIError`) / `ContextOverflowError` / `AuthError` (`ProviderAuthError`) |
595
+
596
+ **LanguageProvider public contract** (`packages/llm/src/model/language/language.ts`):
597
+
598
+ - `stream(input) → StreamTextResult` / `generate(input) → GenerateTextResult`
599
+ - `resolveModel(input: ModelInput) → Promise<Provider.Model>` — model input normalization, exported standalone so callers can pre-fetch metadata
600
+ - `hasToolCalls(messages) → boolean`
601
+ - `computeUsage(usage, metadata, model) → { input, output, cache: { read, write }, reasoning, total, cost }`
602
+ - `DEFAULT_MAX_RETRIES` / `OUTPUT_TOKEN_MAX` constants
603
+
206
604
  **EmbeddingProvider public contract** (`packages/llm/src/model/embedding.ts`):
207
605
 
208
606
  - `embedText(input, abortSignal?) → Promise<EmbedOutput>`
@@ -212,7 +610,77 @@ export * as EmbeddingProvider from './model/embedding';
212
610
  - `EmbedBatchOutput = { embeddings: number[][]; usage: { tokens: number } }`
213
611
  - Empty `values` returns `{ embeddings: [], usage: { tokens: 0 } }` **without** calling `ai.embedMany`
214
612
  - Default model: `easbot-local/bge-base-zh-v1.5` (exported as `EmbeddingProvider.DEFAULT_MODEL`)
215
- - `model` input supports three forms: omitted → `Provider.defaultModel` chain; `Provider.Model` → `Provider.getEmbedding`; directly passing an `EmbeddingModel` instance (duck-typed via `specificationVersion`) → skip the Provider chain
613
+ - `model` input supports four forms: omitted → `Provider.defaultModel` chain; string `'provider/model'` → normalized then `Provider.getEmbedding`; `{ providerId, modelId }` / `Provider.Model` → normalized then `Provider.getEmbedding`; directly passing an `EmbeddingModel` instance (duck-typed via `specificationVersion`) → skip the Provider chain
614
+
615
+ **RerankProvider public contract** (`packages/llm/src/model/rerank.ts`):
616
+
617
+ - `rerankDocuments(input, abortSignal?) → Promise<RerankResult[]>`
618
+ - `RerankResult = { index; document; score; reason? }`, length = `min(topN ?? 10, documents.length)`
619
+ - Ordering and slicing are handled uniformly by the `ranking[]` returned from `ai.rerank()`
620
+ - The `model` input supports the **same four forms** as `EmbeddingProvider` (string / `{ providerId, modelId }` / `Provider.Model` / `RerankingModel` instance)
621
+
622
+ **EvaluationProvider public contract** (`packages/llm/src/model/evaluation/evaluation.ts`):
623
+
624
+ - `evaluate(input, abortSignal?) → Promise<EvaluationResult>`
625
+ - `EvaluationInput = { type?; query?; response?; context?; correctAnswer?; answers?; claim?; document?; system?; model?; maxOutputTokens?; abortSignal? }`
626
+ - `EvaluationResult` is a **discriminated union** (narrowed by `type`): `CorrectnessResult` / `FaithfulnessResult` / `RelevancyResult` / `ContextRelevancyResult` / `CompletenessResult` / `ConsistencyResult` / `ReadabilityResult` / `FactCheckingResult` / `GoalCompletionResult` / `ContentQualityResult` / `ModerationResult`
627
+ - `DEFAULT_EVALUATION_TYPE` constant (defaults to `correctness`)
628
+ - Prompt templates: `src/model/evaluation/templates/<type>.txt` (11 files, English, following the `eas-prompt-creator` spec)
629
+ - The `model` input supports the **same four forms** as the other Providers (string / `{ providerId, modelId }` / `Provider.Model` / SDK `LanguageModel` instance), normalised by `LanguageProvider.resolveModel`
630
+
631
+ **Model input normalization** (`packages/llm/src/model/model-input.ts`):
632
+
633
+ | Export | Purpose |
634
+ | -------------------------------- | ------------------------------------------------------------------- |
635
+ | `resolveModelIdentifier(input?)` | Normalize to `{ providerId, modelId }` (**excludes** SDK instances) |
636
+ | `deriveModelIdentifier(input?)` | Same, but **also supports** SDK instances (`provider` + `modelId`) |
637
+ | `isModelEntity(input)` | Detect an AI SDK entity via `specificationVersion` |
638
+
639
+ - `ModelEntity = LanguageModel | EmbeddingModel | RerankingModel` — the three SDK entities share identical identity fields (`specificationVersion` + `provider` + `modelId`), hence a single union type
640
+ - ⚠️ The string form **must carry a provider prefix** (`'openai/gpt-4'`); a bare name (`'gpt-4'`) throws instead of silently guessing the provider
641
+ (intentionally different from `LanguageProvider.resolveModel`, which can infer it via `defaultModel()`)
642
+
643
+ ### Model identifier types (single source of truth in `@easbot/types`)
644
+
645
+ > **Single source of truth**: `@easbot/types` → `native/llm.ts` (see `spec/types-standard.md` §3.10).
646
+ > This package only **re-exports** them — it never redefines them, avoiding drift across 6+ packages.
647
+
648
+ | Type | Meaning | Source |
649
+ | ------------------- | ------------------------------------------------------------ | --------------------- |
650
+ | `ModelIdentifier` | `{ providerId, modelId }` identifier object (= `AgentModel`) | `types/native/llm.ts` |
651
+ | `EmbeddingModelRef` | Embedding usage (string / identifier object / SDK instance) | `types/native/llm.ts` |
652
+ | `LanguageModelRef` | Language usage | `types/native/llm.ts` |
653
+ | `RerankingModelRef` | Rerank usage | `types/native/llm.ts` |
654
+ | `ModelRef` | Union of the three | `types/native/llm.ts` |
655
+
656
+ **Narrowing by usage**: provider interfaces only accept the Ref of the **matching** semantics
657
+ (e.g. `EmbeddingProvider` only accepts `EmbeddingModelRef`) — the earlier three-way union
658
+ `ModelRef` caused type mismatches when SDK instances and string forms were mixed.
659
+
660
+ **Layering rule**: application packages (`codebase` / `note` / `memory` / `buddy`) take these types
661
+ from `@easbot/llm` in their own `src/llm.ts` and must **not** depend on `@easbot/types` directly.
662
+
663
+ ### `ILLMModels` / `ILLMCapabilities` field conventions
664
+
665
+ > `packages/llm/src/bootstrap/illm.ts` — each application package implements its own `Llm` namespace
666
+ > and uses these as a **compile-time assertion** (`as ILLM`).
667
+
668
+ | `ILLMModels` field | Meaning | Used by |
669
+ | ------------------ | ----------------------------------------------------------------------- | -------------- |
670
+ | `embedding` | Embedding model (vector retrieval) | all 4 packages |
671
+ | `graph` | Graph extraction model (entities / relations) | note / memory |
672
+ | `evaluation` | **Evaluation** model (extraction quality) — _not_ a graph builder model | codebase |
673
+ | `rerank` | Rerank model | note |
674
+ | `language` | Language model (pet AI react / hatch / mutate) | buddy |
675
+
676
+ ⚠️ `codebase`'s `evaluation` is **not** a graph construction model — codebase's Property Graph is
677
+ built by tree-sitter **AST parsing**, so no LLM is required; the model is only used by the
678
+ evaluation runner to score extraction quality. The historical name `graph` was highly misleading,
679
+ hence the separate `evaluation` field.
680
+
681
+ `ILLMCapabilities` mirrors the `ILLMModels` fields one-to-one
682
+ (`embedding` / `graph` / `evaluation` / `rerank` / `language`) and is used to render
683
+ capability snapshots in status / doctor output.
216
684
 
217
685
  ## Configuration Injection (migration guide for switching LLM implementation)
218
686
 
@@ -336,6 +804,236 @@ but state caching is fundamentally a **per-process singleton with explicit reset
336
804
  6. **Plugin injection**: plugins can inject special providers via `plugin.auth.loader` (e.g. github-copilot's OAuth)
337
805
  7. **CUSTOM_LOADERS**: each provider's special initialization (anthropic headers, azure baseURL, amazon-bedrock AWS credentials, etc.)
338
806
 
807
+ ## Agent Module (registry + built-in Agents)
808
+
809
+ The Agent module is one of `@easbot/llm`'s core modules — carrying the **layered Agent registry** (same design as `ToolRegistry`) + **6 generic static builtin Agents** (+ 3 host-injected) + **dynamic Agent generation** + **`model` field normalization**.
810
+
811
+ ### 1. Cross-package dependencies
812
+
813
+ | Upstream dependency | Contract provided |
814
+ | -------------------------------- | ----------------------------------------------------------------------------------------------------------- |
815
+ | `@easbot/types.AgentInfoSchema` | Cross-package single source of truth — `name` required, all other fields optional, `.catchall(z.unknown())` |
816
+ | `@easbot/types.AgentModelSchema` | `model` field object form (`{ providerId, modelId }`) |
817
+ | `@easbot/utils.Permission` | `Permission.merge` for cross-layer ruleset merge; `Permission.fromConfig` |
818
+ | `@easbot/utils.Preset` | `Preset.ruleset(name, extra)` — emits the 9 built-in Agent baseline rulesets |
819
+ | `@easbot/utils.State` | `State.holder` (mode B) bucketed by directory to cache merge results |
820
+ | `@easbot/utils.Log` | One-shot `log.debug('AgentRegistry init')` for library-level modules (per `spec/logging-standard.md` §5) |
821
+
822
+ ### 2. `AgentRegistry` — layered registration primitives
823
+
824
+ Same layered design as `ToolRegistry`: layered registration + **single merge point** + `state` / `init` / `resetState` three-method contract (mode B per `spec/module-pattern.md` §2.2).
825
+ The two use **different state modes**: `ToolRegistry` is mode C (mandates `Instance.holder`, no fallback) while `AgentRegistry` is mode B (`State.holder` + root fallback) — see the difference table below.
826
+
827
+ ```
828
+ | Layer | Entry point | Written by |
829
+ | ---------------- | ----------------------------------------------- | -------------------------------------- |
830
+ | static builtin | `BUILTIN_AGENTS` (compile-time constant in `src/agent/buildin`) | llm generic implementation |
831
+ | runtime builtin | `Agent.registerBuiltin(name, info)` | `Agent.init()` (llm built-in resources) + host injection |
832
+ | plugin | `Agent.register(name, info)` | plugin runtime |
833
+ | user | `Agent.registerUser(name, info)` | host (`cfg.agent`) |
834
+ ```
835
+
836
+ Merge order (later overrides earlier) = **static builtin → runtime builtin → plugin → user**; the single merge point is `mergeLayers` inside `_holder` init.
837
+
838
+ **Override semantics = whole-value replacement** (exactly like `ToolRegistry`): a higher layer replaces the lower one entirely — lower-layer fields do **not** survive (a field you omit is a field you deleted).
839
+
840
+ > ⚠️ Therefore the overriding side **must supply all fields** — for a partial override, merge the baseline yourself:
841
+ > `{ ...BUILTIN_AGENTS.find(a => a.name === name), ...overrides }`.
842
+ > The implementation deliberately does no field-level merge: ① "delete a field" is inexpressible under merge semantics;
843
+ > ② the overriding side already carries a complete definition (e.g. host-injected `btw` supplies `Preset.ruleset('btw')` as a whole);
844
+ > ③ mixing fields lets "llm adds a field" leak into the host's Agent.
845
+
846
+ > ⚠️ **`AgentRegistry` is not exported** — it is the internal implementation of `Agent` (layered registration + single merge point). External callers always go through the facade.
847
+ > The registry **never reads Config**: host cfg is registered entry-by-entry by the host via `Agent.registerUser` in `agentInit()`.
848
+ >
849
+ > **Initial allow-list ownership** (zero-config principle for hosts):
850
+ >
851
+ > - llm built-ins (auto-registered by `Agent.init()`): `<data>/tool-output/*`, `<data>/context-output/*`
852
+ > - host business directories (host calls `applyInitialPermission`): skill dirs, plans dir
853
+ >
854
+ > This way, consumers without an agent module (gateway / buddy / standalone CLI) can use llm's truncation output out of the box.
855
+
856
+ ````
857
+
858
+ **Two cross-cutting steps applied after the layered merge** (orthogonal to the layers):
859
+
860
+ | Step | When it applies | Semantics |
861
+ | --------------------- | ------------------------------ | -------------------------------------------------------------------------------------- |
862
+ | Initial allow-list | Uniformly overlaid **after** the layered merge | Cross-layer: the effective definition gets the allow-list no matter which layer it came from; idempotent de-dup; explicit `deny` wins |
863
+ | Disable tombstone | Uniformly removed **after** the layered merge | Final verdict: no layer can resurrect a disabled Agent |
864
+
865
+ > Why not write the allow-list into each Agent's `permission`? ① rewriting every Agent causes **duplicate stacking**;
866
+ > ② Agents registered later never get it (registration order becomes an implicit contract);
867
+ > ③ the allow-list is a **cross-layer environment fact**, not a property of one Agent — when an Agent is
868
+ > wholly replaced by a higher layer, the allow-list would be lost with it.
869
+
870
+ **Field-level merge rules**:
871
+
872
+ | Field | Merge method |
873
+ | ------------- | --------------------------------------------------------------------------------------- |
874
+ | `permission` | `Permission.merge(existing, plugin/user.permission)` (findLast — later overrides earlier) |
875
+ | `options` | `mergeDeep(existing.options, plugin/user.options)` |
876
+ | Other top-level fields | `Object.assign(existing, plugin/user)` (later wins whole-value) |
877
+ | `native` | builtin layer is `true`; plugin / user layer overrides to `false` |
878
+
879
+ **Key differences from ToolRegistry**:
880
+
881
+ | Dimension | ToolRegistry | AgentRegistry |
882
+ | ----------------- | ------------------------------------- | -------------------------------------------------------------- |
883
+ | Field-level merge | Whole-value replace (same name = later overrides) | Field-level merge (`permission` via `Permission.merge`, `options` via `mergeDeep`) |
884
+ | builtin source | `BUILTIN_TOOLS` compile-time constant | `BUILTIN_AGENTS` compile-time constant (`src/agent/buildin`), overridable by runtime builtin |
885
+ | cfg injection | cfg.tools (separate layer) | Host registers entry-by-entry via `Agent.registerUser` in `agentInit()` (**never reads Config**) |
886
+ | State mode | **C** (`Instance.holder`, **no fallback**) | **B** (`State.holder` + root fallback `__agent_registry_global__`) |
887
+ | holder root | Fixed `Instance.directory` (fail-fast without Instance) | `getIInstanceProvider().getDirectory()`, falls back to a global key when not registered |
888
+
889
+ ### 3. `Agent` namespace — public API
890
+
891
+ `Agent` namespace wraps the public-facing API; internally it **delegates as much as possible** to `AgentRegistry`:
892
+
893
+ ```typescript
894
+ import { Agent, resolveModel, toModel, toRuleset } from '@easbot/llm';
895
+ import { type AgentInfo, AgentInfoSchema } from '@easbot/types';
896
+
897
+ // 1) List Agents (filter + sort by contextMode)
898
+ const all = await Agent.list('general'); // → AgentInfo[]
899
+
900
+ // 2) Get one Agent
901
+ const build = await Agent.get('build'); // → AgentInfo | undefined
902
+
903
+ // 3) Default Agent name (cfg.default_agent → first primary visible)
904
+ const name = await Agent.defaultAgent();
905
+
906
+ // 4) Check whether an agent is a subagent
907
+ const isSub = await Agent.isSubagent('explore');
908
+
909
+ // 5) Batch plugin registration (independent error reporting)
910
+ const { registered, skipped } = Agent.registerPluginAgents([
911
+ { name: 'reviewer', prompt: '...', permission: { '*': 'allow' } },
912
+ ]);
913
+ // registered: ['reviewer']; skipped: [{ name, reason: zod error message }]
914
+
915
+ // 6) Model field normalization ('provider/model' | { providerId, modelId } → AgentModel)
916
+ const m = resolveModel('anthropic/claude-sonnet-4-5');
917
+ // { providerId: 'anthropic', modelId: 'claude-sonnet-4-5' }
918
+
919
+ // 7) Dynamically generate a new Agent (via LLM)
920
+ const { identifier, whenToUse, systemPrompt } = await Agent.generate({
921
+ description: 'A code review agent',
922
+ });
923
+
924
+ // 8) Read the baseline definition (for the host's "read → override → register whole" pattern)
925
+ const base = Agent.base('build'); // → AgentInfo | undefined
926
+
927
+ // 9) Override (whole-value replacement: all fields required)
928
+ Agent.registerUser('build', { ...base!, description: 'my build' });
929
+
930
+ // 10) Disable / re-enable (tombstone semantics: no layer can resurrect it)
931
+ Agent.disable('build');
932
+ Agent.enable('build');
933
+
934
+ // 11) Reset (clear holder cache)
935
+ Agent.resetState();
936
+ ````
937
+
938
+ **"Read baseline → override → register whole" pattern** (recommended way for an application to extend an Agent):
939
+
940
+ llm provides only a **minimal** generic baseline (`BUILTIN_AGENTS`); applications override and adjust as needed.
941
+ Since override semantics are **whole-value replacement** (omitted field = deleted field), the application side
942
+ explicitly does three steps:
943
+
944
+ ```typescript
945
+ const base = Agent.base('build')!; // 1) read baseline
946
+ const merged = { ...base, description: 'my build' }; // 2) override / adjust
947
+ Agent.registerUser('build', merged); // 3) register whole
948
+ ```
949
+
950
+ > Why no implicit shallow-merge fallback? ① the base value depends on "what is already in the registry" → the same
951
+ > config yields different results depending on registration timing (reproducibility is lost); ② "delete a field" is
952
+ > inexpressible under shallow merge; ③ the overriding side must know every baseline field, so new fields are easily missed.
953
+ > Explicit merging lays all three concerns out in the application's own code.
954
+
955
+ `Agent.state()` runs `Agent.init()` automatically on the first call:
956
+
957
+ 1. `Agent.applyInitialPermission([Truncate.glob(), TruncateContent.glob()])` — registers the
958
+ **two llm built-in truncation directories** allow-list. Hosts need **zero configuration**: gateway / buddy /
959
+ standalone CLI (consumers without an agent module) work out of the box.
960
+ 2. `AgentRegistry.init()` — warm-up + first merge
961
+
962
+ > ⚠️ Differences from older versions:
963
+ >
964
+ > - Static built-in Agents are **no longer** "cleared and reinstalled" in `init()` — `BUILTIN_AGENTS` is a
965
+ > compile-time constant exported from `src/agent/buildin/index.ts` and read directly by `mergeLayers`
966
+ > (mirroring `BUILTIN_TOOLS`).
967
+ > - **Config is no longer read** — the historical `AgentRegistry.setInput({ cfgAgents, cfgPermission })`
968
+ > injection point was removed (it coupled host config into a generic library). Host cfg is registered
969
+ > entry-by-entry via `Agent.registerUser` in `agentInit()`; host directories (context truncation /
970
+ > skill / plans) are registered by the host via `Agent.applyInitialPermission([...])`.
971
+
972
+ ### 4. Built-in Agents (6 generic + 3 host-injected)
973
+
974
+ **Static builtin baseline** (`BUILTIN_AGENTS` in `src/agent/buildin/index.ts`, compile-time constant):
975
+
976
+ | Agent name | mode | Purpose | Permission baseline (Preset) |
977
+ | ---------- | -------- | ---------------------------------------------------------- | ---------------------------- |
978
+ | `build` | primary | Default agent — execute tools under configured permissions | `Preset.ruleset('build')` |
979
+ | `plan` | primary | Plan mode — disallow all edit tools | `Preset.ruleset('plan')` |
980
+ | `general` | subagent | General-purpose subagent (todo disabled) | `Preset.ruleset('general')` |
981
+ | `explore` | subagent | Code-base exploration: grep / glob / list / read | `Preset.ruleset('explore')` |
982
+ | `title` | subagent | Session title generation (hidden) | `Preset.ruleset('title')` |
983
+ | `summary` | subagent | Session summary generation (hidden) | `Preset.ruleset('summary')` |
984
+
985
+ **Host-injected** (`@easbot/agent` calls `Agent.registerBuiltin` at startup — see `agentInit()` in
986
+ `packages/agent/src/agent/index.ts`):
987
+
988
+ | Agent name | mode | Purpose | Host capability it depends on |
989
+ | ------------ | -------- | --------------------------------------------------- | ------------------------------ |
990
+ | `btw` | primary | Side note / quick answer — read-only tools + search | `/btw` command |
991
+ | `compaction` | subagent | Session context compaction (hidden) | Session compaction persistence |
992
+ | `memory` | subagent | Memory operations (hidden) | `memory` tool (host-only) |
993
+
994
+ > These three depend on host-specific tools and business semantics, so they are not built into llm.
995
+ > After being registered via the `registerBuiltin` override layer they can still be overridden by plugin / user;
996
+ > roll back with `Agent.unregisterBuiltin(name)`.
997
+
998
+ > Permission baselines live in [`packages/utils/src/permission/preset.ts`](../../packages/utils/src/permission/preset.ts) (`@easbot/utils.Preset`); the Agent module only consumes `Preset.ruleset(name)` and does not duplicate rule declarations.
999
+
1000
+ ### 5. State contract (mode B)
1001
+
1002
+ | Method | Semantics |
1003
+ | ------------------------------------- | ------------------------------------------------------------------------------------------------------------------- |
1004
+ | `Agent.state()` | Triggers `Agent.init()` on first call; returns `Record<name, AgentInfo>` (per-directory cached + root fallback key) |
1005
+ | `Agent.init()` | Idempotent warm-up: registers llm's two truncation-dir allow-list entries + triggers the first merge |
1006
+ | `Agent.resetState()` | Clear holder cache + `init` idempotency flag; next `state()` re-inits |
1007
+ | `Agent.registerBuiltin(name, info)` | Register a runtime builtin layer Agent (**whole-value replacement** of the static baseline) |
1008
+ | `Agent.unregisterBuiltin(name)` | Remove the runtime builtin layer; falls back to the static baseline if the name exists there |
1009
+ | `Agent.applyInitialPermission(globs)` | Register initial allow-list dirs → `external_directory` allow (**cross-layer overlay at merge time**, idempotent) |
1010
+ | `Agent.registerUser(name, info)` | Register a user layer Agent (host `cfg.agent`), highest priority; **whole-value replacement** |
1011
+ | `Agent.unregisterUser(name)` | Remove the user layer; the same name automatically falls back to the plugin / builtin layer |
1012
+ | `Agent.base(name)` | Read the **baseline definition** (no allow-list overlay, no disable verdict) — the override base |
1013
+ | `Agent.disable(name)` | Set a **disable tombstone**: the Agent disappears from the result; no layer can resurrect it |
1014
+ | `Agent.enable(name)` | Clear the disable tombstone (restore after a config hot update) |
1015
+ | `Agent.clearInitialPermission()` | Clear the initial allow-list (test isolation / host re-initialization) |
1016
+ | `Agent.clearDisabled()` | Clear disable tombstones (test isolation / host re-initialization) |
1017
+ | `Agent.setDefaultAgent(name)` | Inject `cfg.default_agent` (llm never reads host Config) |
1018
+ | `toRuleset(permission)` | Config-form permission → flat runtime ruleset (convert before host injection) |
1019
+ | `toModel(model)` | Config-form `'provider/model'` string → `AgentModel` object |
1020
+
1021
+ `_holder` root fallback: when `IInstanceProvider` is not registered, falls back to `__agent_registry_global__` so unit tests / standalone CLI (without AdapterRegistry) keep working.
1022
+
1023
+ ### 6. Error system
1024
+
1025
+ - `Agent.registerPluginAgents` — a single failing entry goes into `skipped` and **does not abort** the whole array (standard tradeoff: plugin-wide reachability vs single-entry fault tolerance)
1026
+ - `Agent.defaultAgent()` — throws `NameErrors.NotFoundError` when missing / `NameErrors.InvalidArgumentError` when it's a subagent / `NameErrors.NotFoundError` when hidden
1027
+ - Schema errors are extracted via `errorMeta(err).message` (per `spec/error-handling-standard.md` §5)
1028
+
1029
+ ### 7. Differences from historical versions
1030
+
1031
+ | Version | Key differences |
1032
+ | ------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
1033
+ | **V1 (inside `@easbot/agent`)** | `Agent.Info = z.object(...)` duplicated; 9 built-ins + permissions hardcoded; host strongly coupled to llm |
1034
+ | **V2 (llm took over)** | `AgentInfoSchema` consolidated into `@easbot/types` (one schema for config / runtime / plugin); `Preset.ruleset` sunk to `@easbot/utils`; `AgentRegistry` layered + single merge point |
1035
+ | **V3 (current)** | ① four-layer **whole-value replacement** (aligned with `ToolRegistry`); ② llm **never reads Config** (`InitInput` / `setInput` removed); ③ the initial allow-list is now **overlaid at merge time** (idempotent, order-independent); ④ `disable` becomes **tombstone semantics** (no layer can resurrect it); ⑤ applications extend Agents via "`Agent.base()` read baseline → override → register whole" |
1036
+
339
1037
  ## Testing
340
1038
 
341
1039
  ```bash
@@ -345,22 +1043,27 @@ pnpm --filter @easbot/llm test:run
345
1043
  Test files are in `tests/`:
346
1044
 
347
1045
  - `provider-smoke.test.ts` — validates pure constants in `definition.ts` (whitelist / local SDK snapshot / friendly name mapping) + **AdapterRegistry injection/get/fail-fast** + Env/Flag static fields + LLMConfig/ProviderConfig/ProviderAuthMethod zod schemas
348
- - `interfaces.test.ts` — V4-added: 5 AdapterRegistry interfaces + static reader functions (`readEnvString` / `readFlagBool` / `readFlagNumber`) + `lazyAsync()` reset behavior
1046
+ - `interfaces.test.ts` — V4-added: 5 AdapterRegistry interfaces + static reader functions (`readEnvString` / `readFlagBool` / `readFlagNumber`) + `lazyAsync()` reset behavior + `getGlobal()` three-tier path resolution (injection / registry / env+defaults)
1047
+ - `agents-injection.test.ts` — Agent triple injection (SDK / LocalAgent / SubAgent): host injection priority / lazy standalone-CLI fallback / same-reference reuse / `State.holder` directory binding semantics / `disposeLlmAgents()` release path (22 cases)
349
1048
  - `model-smoke.test.ts` — validates the type export path stability of `model/types.ts`
350
1049
  - `setup.ts` — global test environment (sets NODE_ENV=development + **injects a complete mock AdapterRegistry** to prevent chain import triggering fail-fast)
351
1050
 
352
- **All 75 tests currently green** (across 3 test files). Coverage breakdown:
353
-
354
- | Category | Case count | Validation |
355
- | ---------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------- |
356
- | AdapterRegistry interfaces (V4 new) | 11 | 4 Provider interface contracts / `setAdapterRegistry` injection / `hasAdapterRegistry` boolean / fail-fast throw / static reader functions |
357
- | Provider constants | 11 | DEFAULT_ENABLED_PROVIDERS / CUSTOM_PROVIDER_DEFINITIONS / PROVIDER_DISPLAY_NAMES |
358
- | ProviderAuth lazyAsync behavior (V4 new) | 3 | `registerPluginAuthProvider` triggers `_state.reset()` / `clearPluginAuthProviders` resets cache / `ProviderAuth.resetState()` clears cache |
359
- | Model type export stability | 6 | RerankInput/Result/Response + Entity/Relation/GraphInput + Note/MemorySummary |
360
- | Env / Flag namespace static fields | 6 | Env mirrors process.env keys / Flag contains LLM-package internal flags / reader function signatures (empty string vs undefined) |
361
- | LLMConfig schema | 4 | Empty object passes / Complete fields pass / Invalid model rejected / Non-array enabled_providers rejected |
362
- | ProviderConfig schema | 3 | Minimal config passes / partial design (all fields optional) / options.apiKey type validation |
363
- | ProviderAuthMethod schema | 4 | api / oauth types pass / Invalid type rejected / Missing label rejected |
1051
+ **All 95 tests currently green** in `tests/` (across 4 test files). In addition, `src/**/__tests__/` carries colocated unit tests — most notably `src/model/language/__tests__/language.test.ts` (32 cases: `hasToolCalls` / `computeUsage` three vendor token conventions / cost tiers / `resolveModel` three input forms incl. multi-slash ids), plus `src/hook/**` (36 cases) and `src/provider/**`.
1052
+
1053
+ Coverage breakdown for `tests/`:
1054
+
1055
+ | Category | Case count | Validation |
1056
+ | ---------------------------------------- | ---------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------ |
1057
+ | AdapterRegistry interfaces (V4 new) | 11 | 4 Provider interface contracts / `setAdapterRegistry` injection / `hasAdapterRegistry` boolean / fail-fast throw / static reader functions |
1058
+ | Provider constants | 11 | DEFAULT_ENABLED_PROVIDERS / CUSTOM_PROVIDER_DEFINITIONS / PROVIDER_DISPLAY_NAMES |
1059
+ | ProviderAuth lazyAsync behavior (V4 new) | 3 | `registerPluginAuthProvider` triggers `_state.reset()` / `clearPluginAuthProviders` resets cache / `ProviderAuth.resetState()` clears cache |
1060
+ | Model type export stability | 6 | RerankInput/Result/Response + Entity/Relation/GraphInput + Note/MemorySummary |
1061
+ | Env / Flag namespace static fields | 6 | Env mirrors process.env keys / Flag contains LLM-package internal flags / reader function signatures (empty string vs undefined) |
1062
+ | LLMConfig schema | 4 | Empty object passes / Complete fields pass / Invalid model rejected / Non-array enabled_providers rejected |
1063
+ | ProviderConfig schema | 3 | Minimal config passes / partial design (all fields optional) / options.apiKey type validation |
1064
+ | ProviderAuthMethod schema | 4 | api / oauth types pass / Invalid type rejected / Missing label rejected |
1065
+ | Agent triple injection | 22 | SDK / LocalAgent / SubAgent injection contracts + lazy fallback + holder binding + dispose |
1066
+ | Interfaces / misc | 49 | `interfaces.test.ts` AdapterRegistry interfaces / static readers / `getGlobal()` three-tier resolution / `lazyAsync()` reset + `model-smoke` export path stability |
364
1067
 
365
1068
  **Full integration test boundary**: After the AdapterRegistry decoupling, the llm package can mock all 4 Providers independently, and a complete end-to-end flow of `Provider.list / getModel / parseModel` no longer depends on the agent package. Follow-up task: when the agent package switches LLM implementation, add cross-package integration tests (verifying that real injected Providers match the llm-package contract).
366
1069