@ai-zen/agents-sdk 2.0.0-alpha.0 → 2.0.0-alpha.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +73 -16
- package/README.md +397 -113
- package/README.zh.md +314 -112
- package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
- package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
- package/dist/agent-plugins/AutoMigratePlugin.d.ts +35 -14
- package/dist/agent-plugins/AutoMigratePlugin.js +36 -36
- package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +6 -6
- package/dist/agent-plugins/AutoRefreshToolsPlugin.js +2 -2
- package/dist/agent-plugins/ContextGuardPlugin.d.ts +20 -24
- package/dist/agent-plugins/ContextGuardPlugin.js +25 -24
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +25 -35
- package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +26 -41
- package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +14 -9
- package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -13
- package/dist/config/ConfigManager.d.ts +13 -5
- package/dist/config/ConfigManager.js +58 -39
- package/dist/config/constants.d.ts +1 -1
- package/dist/config/constants.js +2 -2
- package/dist/config/factory-skills.js +2 -2
- package/dist/config/normalize.d.ts +93 -0
- package/dist/config/normalize.js +158 -0
- package/dist/crud/AgentRepository.d.ts +3 -1
- package/dist/crud/AgentRepository.js +4 -2
- package/dist/index.d.ts +19 -9
- package/dist/index.js +14 -7
- package/dist/runtime/AgentRuntime.d.ts +293 -0
- package/dist/runtime/AgentRuntime.js +457 -0
- package/dist/runtime/HandoffGuardPlugin.d.ts +82 -15
- package/dist/runtime/HandoffGuardPlugin.js +136 -17
- package/dist/runtime/HandoffService.d.ts +244 -119
- package/dist/runtime/HandoffService.js +373 -251
- package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
- package/dist/runtime/RuntimePeerSessions.js +50 -0
- package/dist/runtime/Scopes.d.ts +123 -0
- package/dist/runtime/Scopes.js +169 -0
- package/dist/runtime/SdkAgent.d.ts +19 -8
- package/dist/runtime/SdkAgent.js +23 -6
- package/dist/runtime/completeOnce.d.ts +3 -3
- package/dist/runtime/completeOnce.js +3 -3
- package/dist/runtime/createAgent.d.ts +29 -7
- package/dist/runtime/createAgent.js +57 -12
- package/dist/runtime/createModel.d.ts +4 -4
- package/dist/runtime/createModel.js +6 -6
- package/dist/runtime/lastPromptTokens.d.ts +18 -0
- package/dist/runtime/lastPromptTokens.js +26 -0
- package/dist/runtime/resolveModel.d.ts +9 -9
- package/dist/runtime/resolveModel.js +8 -8
- package/dist/scope/Scope.d.ts +10 -9
- package/dist/scope/Scope.js +6 -6
- package/dist/scope/ScopePlugin.d.ts +2 -8
- package/dist/scope/disclosure.d.ts +1 -1
- package/dist/scope/disclosure.js +1 -1
- package/dist/scope/plugins/allInOne.d.ts +13 -1
- package/dist/scope/plugins/allInOne.js +9 -5
- package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
- package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
- package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
- package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
- package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
- package/dist/scope/plugins/builtin/ExecTool.js +10 -199
- package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
- package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
- package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
- package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
- package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
- package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
- package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
- package/dist/scope/plugins/builtin/SleepTool.js +2 -3
- package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
- package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
- package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
- package/dist/scope/plugins/builtin/WriteTool.js +8 -1
- package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
- package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
- package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
- package/dist/scope/plugins/builtin/commandOutput.js +55 -0
- package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
- package/dist/scope/plugins/builtin/commandRun.js +169 -0
- package/dist/scope/plugins/builtin/discover.d.ts +1 -3
- package/dist/scope/plugins/builtin/discover.js +1 -3
- package/dist/scope/plugins/builtin/index.d.ts +5 -7
- package/dist/scope/plugins/builtin/index.js +7 -7
- package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
- package/dist/scope/plugins/builtin/outputGuard.js +1 -5
- package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +56 -11
- package/dist/scope/plugins/mcp/McpConnectionManager.js +169 -74
- package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +17 -7
- package/dist/scope/plugins/mcp/McpScopePlugin.js +36 -12
- package/dist/scope/plugins/mcp/discover.d.ts +9 -2
- package/dist/scope/plugins/mcp/discover.js +12 -14
- package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
- package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
- package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
- package/dist/scope/plugins/mcp/mcpTools.js +220 -39
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +4 -7
- package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +4 -7
- package/dist/scope/plugins/peers/peerSessionTools.d.ts +97 -46
- package/dist/scope/plugins/peers/peerSessionTools.js +147 -121
- package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
- package/dist/scope/plugins/skills/discover.d.ts +15 -8
- package/dist/scope/plugins/skills/discover.js +15 -26
- package/dist/scope/plugins/skills/skillTools.d.ts +8 -7
- package/dist/scope/plugins/skills/skillTools.js +18 -14
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
- package/dist/scope/plugins/subagents/discover.d.ts +7 -1
- package/dist/scope/plugins/subagents/discover.js +7 -3
- package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
- package/dist/scope/plugins/subagents/subAgentTools.js +11 -1
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
- package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
- package/dist/scope/plugins/usertools/discover.d.ts +7 -8
- package/dist/scope/plugins/usertools/discover.js +17 -27
- package/dist/shared/EntityRepository.d.ts +22 -5
- package/dist/shared/EntityRepository.js +45 -29
- package/dist/shared/content-blocks.d.ts +9 -3
- package/dist/shared/content-blocks.js +12 -19
- package/dist/shared/errors.d.ts +5 -7
- package/dist/shared/errors.js +6 -8
- package/dist/shared/logger.d.ts +21 -10
- package/dist/shared/logger.js +9 -15
- package/dist/types/index.d.ts +36 -13
- package/package.json +2 -2
- package/dist/config/migrate.d.ts +0 -115
- package/dist/config/migrate.js +0 -200
- package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
- package/dist/scope/plugins/builtin/test-helpers.js +0 -4
package/README.md
CHANGED
|
@@ -1,150 +1,434 @@
|
|
|
1
1
|
# @ai-zen/agents-sdk
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Two halves behind one package name.
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
- The capability face turns the kernel into an agent that can do something: capabilities discovered
|
|
6
|
+
from disk, a model resolved from configuration, permissions, handoff.
|
|
7
|
+
- The runtime keeps those agents alive and lets them talk to each other: one resident agent per
|
|
8
|
+
session, facts forwarded outward, `post` from one session to another.
|
|
6
9
|
|
|
7
|
-
|
|
10
|
+
## Installation
|
|
8
11
|
|
|
9
|
-
|
|
10
|
-
|
|
11
|
-
```
|
|
12
|
-
CLI ──┐
|
|
13
|
-
├── @ai-zen/agents-sdk ──┐
|
|
14
|
-
Desktop ──┘ │
|
|
15
|
-
LLM API
|
|
12
|
+
```bash
|
|
13
|
+
pnpm add @ai-zen/agents-sdk
|
|
16
14
|
```
|
|
17
15
|
|
|
18
|
-
##
|
|
16
|
+
## What is in which half
|
|
19
17
|
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
18
|
+
| Half | Members |
|
|
19
|
+
|---|---|
|
|
20
|
+
| Capability face | `createAgent`, `SdkAgent`, `Scope` + its five capability sources (`allInOne`), `PermissionEvaluator`, `ConfigManager`, `AgentRepository`, `HandoffService` + `HandoffGuardPlugin`, `completeOnce` |
|
|
21
|
+
| Runtime | `AgentRuntime` (`wake` / `post` / `status` / `openPeer` / `kill` / `observe`), `Scopes`, `RuntimePeerSessions` |
|
|
22
|
+
|
|
23
|
+
The kernel itself (`@ai-zen/agents-core`) is underneath both: an `Agent`, its loop, its two gates, its
|
|
24
|
+
events and hooks. This package adds what one particular product needs around it — and nothing that
|
|
25
|
+
belongs to a host.
|
|
26
|
+
|
|
27
|
+
## Layering: what this package does not do
|
|
28
|
+
|
|
29
|
+
| Not here | Where it lives |
|
|
30
|
+
|---|---|
|
|
31
|
+
| storage, tables, migrations | the host |
|
|
32
|
+
| connections, discovery files, credentials | the host |
|
|
33
|
+
| user-visible copy, languages, i18n | the host |
|
|
34
|
+
| session rows | the host — a session is an opaque identity string here |
|
|
29
35
|
|
|
30
|
-
|
|
36
|
+
The rule the layering is measured by: this package never imports the host. A session is passed
|
|
37
|
+
around as a `string`; what that session is called is asked from a port, never stored. If a piece of
|
|
38
|
+
code needs to know "who is alive", "who knows whom", or "when to build and when to tear down", it
|
|
39
|
+
belongs to the runtime, not the host. If it reads or writes files, writes rows, relays events,
|
|
40
|
+
validates credentials or renders copy, it belongs to the host.
|
|
31
41
|
|
|
32
|
-
|
|
42
|
+
Conversely, an `as unknown as` cast that fakes an instance of something in this package means a port
|
|
43
|
+
is missing: the port should be declared here and implemented by the caller.
|
|
33
44
|
|
|
34
|
-
|
|
35
|
-
|--------|-------------|
|
|
36
|
-
| **Scope** | Orchestration container: global context (`config` / `cwd` / `agentsDir`) + the three-phase capability pipeline (discover → filter → instantiate) + plugin registry. Explicitly assembled via `scope.use(...)` |
|
|
37
|
-
| **ScopePlugin** | Capability plugin (the extension point): self-owns one capability source's discovery state, candidate names, and instantiation (`discover` / `candidates` / `instantiate` / `dispose`). 5 standard plugins ship out of the box, assembled via `allInOne()` |
|
|
38
|
-
| **ToolEnv** | Tool environment `{ cwd, config }`; injected when the built-in-tools plugin (`BuiltinToolsScopePlugin`) instantiates tools, serving as the base for relative path resolution and config reads |
|
|
39
|
-
| **SdkCallbackTool** | Abstract base for built-in tools: `env` constructor injection + subclass `call()` + `resolve()` relative path resolution |
|
|
40
|
-
| **SdkAgent** | Extends the Core Agent, carries SDK metadata, supports `use()` plugin registration |
|
|
41
|
-
| **AgentPlugin** | Plugin interface (`onInit`, `onBeforeSend`, `onAfterSend`, `onInnerLoopStart`, `onInnerLoopEnd`, `onInnerLoopsStart`, `onInnerLoopsEnd`, `onToolCall`, `onUnknownTool`, `onSubAgentStart`, `onSubAgentEnd`) |
|
|
42
|
-
| **Endpoint** | API endpoint (baseUrl + apiKey) |
|
|
43
|
-
| **Model** | Model config, bound to an Endpoint |
|
|
44
|
-
| **SubAgent** | An Agent with a `function` field, callable by other Agents as a tool |
|
|
45
|
+
### The four ports the runtime borrows
|
|
45
46
|
|
|
46
|
-
|
|
47
|
+
`AgentRuntime` does none of these itself, but each of them has to happen somewhere:
|
|
47
48
|
|
|
48
|
-
|
|
49
|
+
| Port | What the caller provides |
|
|
50
|
+
|---|---|
|
|
51
|
+
| `openScope(cwd, peers)` | build a capability container for that directory |
|
|
52
|
+
| `open(input)` | create a session: write the row, choose the identity, hand back `WakeMaterials` |
|
|
53
|
+
| `nameOf(sessionId)` | the session's current name, read from its row; `undefined` = no such session |
|
|
54
|
+
| `log` | a `LogSink`; omit it and nothing is logged |
|
|
49
55
|
|
|
56
|
+
`WakeMaterials` is everything needed to assemble one agent, given from above: `cwd`, `agentId`,
|
|
57
|
+
`modelId` / `modelParams`, `lineage`, `history` and the `waiting` entries not taken last time.
|
|
58
|
+
|
|
59
|
+
## The capability face
|
|
60
|
+
|
|
61
|
+
### Scope: one container per directory
|
|
62
|
+
|
|
63
|
+
A `Scope` holds the configuration, the working directory, the agent-definition directory, the
|
|
64
|
+
plugins, and the tools that came out of them. It runs a three-stage pipeline per agent
|
|
65
|
+
(`discover` → `candidates` → `instantiate`), so what an agent can use is decided when that agent is
|
|
66
|
+
built, not when each call arrives.
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
const scope = new Scope({ getConfig: () => config.read(), agentsDir, cwd })
|
|
70
|
+
.use(...allInOne({ toolsPaths, skillsPaths, subAgentsPaths, mcpPaths }));
|
|
71
|
+
await scope.init();
|
|
50
72
|
```
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
73
|
+
|
|
74
|
+
`getConfig` is a port rather than a snapshot: after a configuration change, `refresh()` reads it
|
|
75
|
+
again instead of rebuilding the container. `use()` must happen before `init()`.
|
|
76
|
+
|
|
77
|
+
### The five capability sources
|
|
78
|
+
|
|
79
|
+
`allInOne(options)` returns the five standard plugins in this order — built-in tools, user tools,
|
|
80
|
+
skills, MCP, sub-agents — so a later source wins when two of them offer the same name.
|
|
81
|
+
|
|
82
|
+
| Plugin | Source |
|
|
83
|
+
|---|---|
|
|
84
|
+
| `BuiltinToolsScopePlugin` | the built-in tool set; each tool declares its own availability (`isAvailable`) |
|
|
85
|
+
| `UserToolsScopePlugin` | tool scripts found on disk |
|
|
86
|
+
| `SkillsScopePlugin` | skill directories, plus the tools that load a skill |
|
|
87
|
+
| `McpScopePlugin` | MCP servers (see below) |
|
|
88
|
+
| `SubAgentsScopePlugin` | sub-agent definitions on disk, exposed as one delegation tool each |
|
|
89
|
+
|
|
90
|
+
`allInOne` options: `skillsPaths`, `toolsPaths`, `subAgentsPaths`, `mcpPaths`, `logger`,
|
|
91
|
+
`mcpTaskNotice`. To drop or replace one source, construct the plugins one by one and `use()` them.
|
|
92
|
+
|
|
93
|
+
### Permissions
|
|
94
|
+
|
|
95
|
+
Four dimensions, each independent, each `{ allow: [...] }` or `{ deny: [...] }`, with `*` supported.
|
|
96
|
+
No match means denied; a dimension with no policy at all means denied. Filters are applied to
|
|
97
|
+
candidate names before instantiation, so a denied capability is not merely refused when called — the
|
|
98
|
+
model never sees it.
|
|
99
|
+
|
|
100
|
+
```json
|
|
101
|
+
{
|
|
102
|
+
"permissions": {
|
|
103
|
+
"tools": { "allow": ["*"] },
|
|
104
|
+
"skills": { "deny": ["deploy"] },
|
|
105
|
+
"mcps": { "allow": ["github"] },
|
|
106
|
+
"subagents": { "allow": ["reviewer"] }
|
|
107
|
+
}
|
|
108
|
+
}
|
|
56
109
|
```
|
|
57
110
|
|
|
58
|
-
|
|
111
|
+
`PermissionEvaluator` is the only implementation of that rule (`filter`, `isAllowed`, `match`).
|
|
59
112
|
|
|
60
|
-
|
|
61
|
-
const scope = new Scope({
|
|
62
|
-
config,
|
|
63
|
-
cwd: "/path/to/workspace", // one working directory per Scope; parallel sessions don't interfere
|
|
64
|
-
agentsDir,
|
|
65
|
-
}).use(
|
|
66
|
-
...allInOne({ skillsPaths, toolsPaths, subAgentsPaths, mcpPaths }),
|
|
67
|
-
);
|
|
68
|
-
await scope.init();
|
|
113
|
+
### Definitions, configuration and models
|
|
69
114
|
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
agent
|
|
74
|
-
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
115
|
+
| Member | What it owns |
|
|
116
|
+
|---|---|
|
|
117
|
+
| `ConfigManager` | `config.json` and the directories beside it: read, write, factory defaults, recovery of a broken file, reasoning presets, factory skills, `mcp.json` |
|
|
118
|
+
| `AgentRepository` | one agent definition per file, `<agentsDir>/<id>.json` |
|
|
119
|
+
| `createAgent(scope, agentId, options)` | one assembled `SdkAgent`: definition read, model resolved, tools built from the filtered candidates |
|
|
120
|
+
| `resolveModel` / `resolveModelParams` | session override > definition > `config.defaultModel`, the only implementation |
|
|
121
|
+
| `createModel` / `createModelFromConfig` | the `OpenAI` client, the model name and the request parameters |
|
|
122
|
+
| `completeOnce` | one non-streaming call with no tools and no history |
|
|
78
123
|
|
|
79
|
-
|
|
80
|
-
|
|
124
|
+
`createAgent` options: `modelId` and `modelParams` (the session-level level), `lifetime`
|
|
125
|
+
(`"one-shot"` for an agent that runs once and dies), `canOpenPeers`, and the two interruption
|
|
126
|
+
strategies `abortedToolRoundStrategy` / `abortedMessageStrategy`, which fall back to the configuration
|
|
127
|
+
and then to the kernel defaults.
|
|
81
128
|
|
|
82
|
-
|
|
129
|
+
Model resolution never mixes levels: the parameters come from whichever level supplied the model, so
|
|
130
|
+
a session that switches model does not carry the previous model's parameters.
|
|
131
|
+
|
|
132
|
+
`SdkAgent` is an `Agent` that also carries `scope` and `definition` (the definition as it is in
|
|
133
|
+
effect, with the resolved model written into it), plus `useModel(modelId, modelParams?)` to change
|
|
134
|
+
model and parameters in place without killing the agent.
|
|
135
|
+
|
|
136
|
+
### Handoff
|
|
137
|
+
|
|
138
|
+
`HandoffService` writes a handoff document, and optionally replaces the memory with it.
|
|
139
|
+
|
|
140
|
+
| Method | What it does |
|
|
141
|
+
|---|---|
|
|
142
|
+
| `handoff(params)` | gives the agent one instruction to write the document, and changes nothing else about the session |
|
|
143
|
+
| `migrate(params)` | writes the document, then computes the new memory and commits it |
|
|
83
144
|
|
|
84
|
-
|
|
145
|
+
Two modes for who writes the document: `self` (the same agent, in its own session — the default) and
|
|
146
|
+
`summary` (one separate model call over a serialized history). Two strategies for what happens to the
|
|
147
|
+
old messages: `omit` (marked and kept out of later requests — the default) and `prune` (physically
|
|
148
|
+
removed). `commitMemory` decides where the new memory lands: without it the SDK splices
|
|
149
|
+
`agent.messages` in place, with it the caller stores it.
|
|
150
|
+
|
|
151
|
+
`HandoffGuardPlugin` is the guard for the handoff batch: during it, the only write that passes is the
|
|
152
|
+
one to the handoff document itself; every other write tool is refused with a sentence the model can
|
|
153
|
+
read and act on. It also observes whether that write happened (`arm` returns an outcome and a
|
|
154
|
+
"batch over" promise; `disarm` lets everything through again). It is a guard against mistakes in the
|
|
155
|
+
workspace, not a sandbox: a shell command can still write files. Cancellation surfaces as
|
|
156
|
+
`HandoffAbortedError`, and it is never silently retried with the other mode.
|
|
157
|
+
|
|
158
|
+
### Agent plugins
|
|
159
|
+
|
|
160
|
+
Mounted on an agent, not on the container: `AutoMigratePlugin` (hand off when usage crosses the soft
|
|
161
|
+
line), `AutoRefreshToolsPlugin`, `ContextGuardPlugin` (refuse a request that would cross the hard
|
|
162
|
+
line), `SubAgentGuardInstallerPlugin` (install the guard on sub-agents too), `HandoffGuardPlugin`,
|
|
163
|
+
`UnknownToolHintPlugin`, `AssetTransportPlugin`.
|
|
85
164
|
|
|
86
|
-
|
|
87
|
-
|------|-------------|
|
|
88
|
-
| `cwd` | Get the current working directory |
|
|
89
|
-
| `read` | Read a file (optional `range` for line/column slicing; oversized output warns and suggests batched reads) |
|
|
90
|
-
| `inspect_file` | Inspect a file's structural overview (line count, column distribution, etc.); streamed scan, not limited by the 300KB read threshold |
|
|
91
|
-
| `write` | Write a file |
|
|
92
|
-
| `exec` | Execute a command (supports `timeout`; oversized stdout+stderr is dumped to `stdout.log` / `stderr.log`) |
|
|
93
|
-
| `spawn` | Execute a command asynchronously, returns immediately without waiting |
|
|
94
|
-
| `mkdir` | Create a directory |
|
|
95
|
-
| `rm` | Delete a file or directory |
|
|
96
|
-
| `glob` | Scan and find files using glob patterns (oversized output dumped to `result.json`) |
|
|
97
|
-
| `ls` | List directory contents (oversized output dumped to `result.json`) |
|
|
98
|
-
| `exist` | Check whether a file or directory exists |
|
|
99
|
-
| `find_text` | Search for text or regex in files (oversized output dumped to `result.json`) |
|
|
100
|
-
| `download_file` | Download a file from a URL and save it locally |
|
|
101
|
-
| `rename` | Rename or move a file/directory |
|
|
102
|
-
| `copy` | Copy a file or directory |
|
|
103
|
-
| `batch_edit` | Batch-edit file text (only unmatched items are echoed back; successful ones are counted) |
|
|
104
|
-
| `edit` | Edit text in a file |
|
|
105
|
-
| `sleep` | Wait for a specified number of milliseconds |
|
|
165
|
+
## The runtime
|
|
106
166
|
|
|
107
|
-
|
|
167
|
+
`AgentRuntime` keeps one resident agent per session and forwards the kernel's facts.
|
|
108
168
|
|
|
109
|
-
|
|
|
110
|
-
|
|
111
|
-
| `
|
|
112
|
-
| `
|
|
169
|
+
| Member | What it does |
|
|
170
|
+
|---|---|
|
|
171
|
+
| `wake(sessionId, materials)` | assemble, register, start; idempotent, concurrent calls share one assembly |
|
|
172
|
+
| `post({ from, to, content })` | put one sentence in another session's inbox; answers `{ ok: true }` or a reason |
|
|
173
|
+
| `status(sessionId)` | whether it is working or idle, its name, an excerpt of the last thing it said |
|
|
174
|
+
| `openPeer({ from, prompt, agentId?, modelId?, label? })` | open a peer session, wake it, post the first prompt, return immediately |
|
|
175
|
+
| `kill(sessionId)` | unregister, kill, report that it is gone |
|
|
176
|
+
| `close()` | kill everything and tear every container down |
|
|
177
|
+
| `observe(listener)` | subscribe to the facts; returns an unsubscribe function |
|
|
178
|
+
| `get(sessionId)` / `sessionOf(agent)` / `aliveOn(cwd)` | the snapshots: which agent, which session, which sessions on that directory |
|
|
179
|
+
| `scopes` / `peerSessions` | the container registry, and the peer-session port this runtime implements |
|
|
113
180
|
|
|
114
|
-
|
|
181
|
+
Facts are a discriminated union: `resident:appeared` and `resident:gone` (the runtime's own two),
|
|
182
|
+
`scope:appeared` / `scope:refreshed` / `scope:gone` (from the container registry), and every kernel
|
|
183
|
+
event of every agent, unchanged in name and payload, with the `sessionId` added.
|
|
184
|
+
|
|
185
|
+
There is no "wait until it is done" on the runtime: a resident session is never done, it goes from
|
|
186
|
+
working to idle and can be pushed again at any moment. Nothing in the runtime waits for a caller; a
|
|
187
|
+
delivery is what wakes a session up.
|
|
188
|
+
|
|
189
|
+
### Scopes: containers live by directory
|
|
190
|
+
|
|
191
|
+
`Scopes` owns the container registry: one container per `cwd`, shared by every session working in
|
|
192
|
+
that directory.
|
|
193
|
+
|
|
194
|
+
| Member | What it does |
|
|
195
|
+
|---|---|
|
|
196
|
+
| `for(cwd)` | the container for that directory, built on first use |
|
|
197
|
+
| `dispose(cwd)` | tear it down — refuses while any session is still alive on that directory |
|
|
198
|
+
| `refreshAll()` | let every already-built container re-read the configuration; reports how many were refreshed and which failed |
|
|
199
|
+
| `disposeAll()` | tear down everything, for process shutdown |
|
|
200
|
+
|
|
201
|
+
There is no idle timer, no reference counting and no automatic collection: a container lives because
|
|
202
|
+
someone holds it, and it is torn down when someone tears it down. "Nobody is using it" is not a
|
|
203
|
+
decidable state. Tearing down refuses rather than cascading, because a cascade would silently kill
|
|
204
|
+
sessions that are in the middle of work.
|
|
205
|
+
|
|
206
|
+
## Peer sessions
|
|
207
|
+
|
|
208
|
+
A peer session is another session an agent opens for itself, with its own agent, its own context and
|
|
209
|
+
its own usage, and it stays in the session list afterwards.
|
|
210
|
+
|
|
211
|
+
The model side is three tools (`packages/sdk/src/scope/plugins/peers/`):
|
|
212
|
+
|
|
213
|
+
| Tool | What it does |
|
|
214
|
+
|---|---|
|
|
215
|
+
| `create_session` | open a peer session and return `{ sessionId, label }` at once |
|
|
216
|
+
| `read_session_status` | whether it is working or idle, whether it is alive, its name, an excerpt of its last message |
|
|
217
|
+
| `post_message` | put one message in that session's inbox |
|
|
218
|
+
|
|
219
|
+
They implement nothing themselves. `PeerSessionsScopePlugin` takes a `PeerSessionPort` with three
|
|
220
|
+
methods — `create`, `status`, `send` — and without a port it produces no tools at all. The runtime
|
|
221
|
+
implements that port (`RuntimePeerSessions`), which is why the three tools also work when no host is
|
|
222
|
+
around.
|
|
223
|
+
|
|
224
|
+
Two rules are structural rather than validated at call time:
|
|
225
|
+
|
|
226
|
+
- an agent that was itself opened as a peer has no `create_session` on its hands: `createAgent` is
|
|
227
|
+
called with `canOpenPeers: false` for it, so creating is one level deep and the model cannot even
|
|
228
|
+
try. `post_message` and `read_session_status` stay, because peers talk both ways.
|
|
229
|
+
- a one-shot agent has neither of the three nor the two background tools: it has no identity to sign
|
|
230
|
+
a message with, it can open nothing that anybody would own, and it is gone before a background
|
|
231
|
+
result comes back.
|
|
232
|
+
|
|
233
|
+
`post_message` does not depend on the relation between the two sessions, and its receipt says only
|
|
234
|
+
that the message was accepted. Refusals are structured: `gone` (no such session) and `dead` (the row
|
|
235
|
+
exists, no agent behind it, so nobody will take it). Creating can also be refused with
|
|
236
|
+
`depth_exceeded` (this session was itself opened as a peer, or the caller is not a session at all)
|
|
237
|
+
or `model_unresolved`; `PeerSessionRejectReason` also carries `too_many_peers`, for a port that
|
|
238
|
+
enforces a limit.
|
|
239
|
+
|
|
240
|
+
Neither an excerpt of a peer's history nor a message count is ever returned: an excerpt is all the
|
|
241
|
+
model gets, so it does not start treating another session's transcript as its own context.
|
|
242
|
+
|
|
243
|
+
## Background tools
|
|
244
|
+
|
|
245
|
+
Two built-in tools return immediately and report later:
|
|
246
|
+
|
|
247
|
+
| Tool | What it does |
|
|
248
|
+
|---|---|
|
|
249
|
+
| `async_exec` | run a shell command in the background; its output and exit status are pushed back into the session as a new message |
|
|
250
|
+
| `async_timeout` | a timer; when it fires, a message carrying the task id is pushed back |
|
|
251
|
+
|
|
252
|
+
Both are in `scope/plugins/builtin/` (`AsyncExecTool`, `AsyncTimeoutTool`, `asyncTasks`). The result
|
|
253
|
+
comes back through a delivery into the same session, at low priority, so it never lands inside the
|
|
254
|
+
batch that is currently running. Task ids come from one counter per agent (`async_exec-1`,
|
|
255
|
+
`async_timeout-2`), and everything still running is reaped when the agent is stopped or killed.
|
|
256
|
+
|
|
257
|
+
A one-shot agent gets neither of them (`ASYNC_TASK_TOOL_NAMES` is stripped at assembly): the result
|
|
258
|
+
arrives after its call stack has returned, so there would be nobody to deliver it to. This is the same
|
|
259
|
+
rule the kernel states for resident versus one-shot, enforced where the tools are chosen.
|
|
260
|
+
|
|
261
|
+
## MCP
|
|
262
|
+
|
|
263
|
+
Four things live in `scope/plugins/mcp/`.
|
|
264
|
+
|
|
265
|
+
Discovery merges an ordered list of `mcp.json` files, nearest first: an earlier file wins for the
|
|
266
|
+
same server id, and a `disabled: true` entry in a nearer file cancels the definition in a farther
|
|
267
|
+
one. The five locations of the standard chain are assembled by the caller and passed as `mcpPaths`
|
|
268
|
+
(the host is the one that knows them), so this package merges exactly what it is given.
|
|
269
|
+
|
|
270
|
+
Connections are lazy and belong to `McpConnectionManager`: `load_mcp` connects a server and returns
|
|
271
|
+
its manifest, an unused connection is dropped after an idle timeout (30 minutes for stdio, 5 for
|
|
272
|
+
http), and `disconnect` / `disconnectAll` close them explicitly. A dropped transport marks the server
|
|
273
|
+
disconnected instead of reconnecting on its own — reconnecting happens when the model asks for that
|
|
274
|
+
server again, and the stale manifest is never shown as current. When the configuration changes,
|
|
275
|
+
`McpScopePlugin` reconciles: removed and changed servers are disconnected, unchanged ones are left
|
|
276
|
+
untouched.
|
|
277
|
+
|
|
278
|
+
The model side is five tools: `load_mcp`, `call_mcp_tool`, `read_mcp_resource`,
|
|
279
|
+
`get_mcp_task_result`, `cancel_mcp_task`.
|
|
280
|
+
|
|
281
|
+
Tasks are the long-running shape of an MCP call. A tool declares its task support
|
|
282
|
+
(`forbidden` / `optional` / `required`); when a call produces a task, `call_mcp_tool` returns the task
|
|
283
|
+
id at once, the server pushes status notifications, and the manager remembers which session started
|
|
284
|
+
the task. A terminal status (`completed` / `failed` / `cancelled`, see `isTerminalTaskStatus`) is
|
|
285
|
+
handed to `McpTaskNoticePort`, which the host implements: `sessionOf(agent)` says which session a
|
|
286
|
+
caller belongs to, `deliver(sessionId, notice)` puts the notice in its inbox. The result itself is
|
|
287
|
+
fetched by task id with `get_mcp_task_result`.
|
|
288
|
+
|
|
289
|
+
## Example 1: one agent from the capability face
|
|
290
|
+
|
|
291
|
+
```ts
|
|
292
|
+
import { Message } from "@ai-zen/agents-core";
|
|
293
|
+
import { AgentRepository, ConfigManager, Scope, allInOne, createAgent } from "@ai-zen/agents-sdk";
|
|
294
|
+
|
|
295
|
+
const base = "/path/to/data"; // config.json and agents/ live here
|
|
296
|
+
|
|
297
|
+
const config = new ConfigManager(`${base}/config.json`);
|
|
298
|
+
await config.write({
|
|
299
|
+
endpoints: [{ id: "openai", name: "OpenAI", baseUrl: "https://api.openai.com/v1", apiKey: "sk-..." }],
|
|
300
|
+
models: [
|
|
301
|
+
{
|
|
302
|
+
id: "gpt-4o",
|
|
303
|
+
name: "GPT-4o",
|
|
304
|
+
endpointId: "openai",
|
|
305
|
+
tokenThresholds: { handoff: 500_000, guard: 750_000 },
|
|
306
|
+
},
|
|
307
|
+
],
|
|
308
|
+
defaultModel: "gpt-4o",
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
const agents = new AgentRepository(`${base}/agents`);
|
|
312
|
+
await agents.write({
|
|
313
|
+
id: "demo",
|
|
314
|
+
name: "Demo",
|
|
315
|
+
messages: [Message.System("Answer in one sentence.")],
|
|
316
|
+
modelId: "gpt-4o",
|
|
317
|
+
permissions: {
|
|
318
|
+
tools: { allow: ["*"] },
|
|
319
|
+
skills: { allow: ["*"] },
|
|
320
|
+
mcps: { allow: ["*"] },
|
|
321
|
+
subagents: { allow: ["*"] },
|
|
322
|
+
},
|
|
323
|
+
createdAt: new Date().toISOString(),
|
|
324
|
+
updatedAt: new Date().toISOString(),
|
|
325
|
+
});
|
|
115
326
|
|
|
116
|
-
|
|
327
|
+
const scope = new Scope({
|
|
328
|
+
getConfig: () => config.read(),
|
|
329
|
+
agentsDir: `${base}/agents`,
|
|
330
|
+
cwd: base,
|
|
331
|
+
}).use(
|
|
332
|
+
...allInOne({
|
|
333
|
+
toolsPaths: [`${base}/tools`],
|
|
334
|
+
skillsPaths: [`${base}/skills`],
|
|
335
|
+
subAgentsPaths: [`${base}/sub-agents`],
|
|
336
|
+
mcpPaths: [`${base}/mcp.json`],
|
|
337
|
+
}),
|
|
338
|
+
);
|
|
339
|
+
await scope.init();
|
|
340
|
+
|
|
341
|
+
const agent = await createAgent(scope, "demo");
|
|
117
342
|
|
|
118
|
-
|
|
343
|
+
const idle = new Promise<void>((resolve) => {
|
|
344
|
+
const offIdle = agent.on("state:idle", () => {
|
|
345
|
+
offIdle();
|
|
346
|
+
resolve();
|
|
347
|
+
});
|
|
348
|
+
});
|
|
119
349
|
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
| `AutoRefreshToolsPlugin` | Re-scans the file system before each `send()` to refresh the tool list |
|
|
124
|
-
| `ContextGuardPlugin` | Context safety guard — before each request, throws `ContextOverflowError` (interrupting the conversation) when the previous round's `usage.prompt_tokens` exceeds `guardTokens` (an absolute value: no multiplier, no looser tier), preventing context runaway from reading oversized files. `isSuspended()` lets the guard itself step aside for handoff/migration turns |
|
|
125
|
-
| `UnknownToolHintPlugin` | Smarter unknown-tool hints — when the LLM calls a nonexistent tool, guides it to `call_mcp_tool` / points out permission issues based on MCP config (opt-in via `agent.use`) |
|
|
350
|
+
agent.push({ content: "What is a Scope?", priority: "low", source: { kind: "user" } });
|
|
351
|
+
void agent.start();
|
|
352
|
+
await idle;
|
|
126
353
|
|
|
127
|
-
|
|
354
|
+
console.log(agent.messages.at(-1)?.content);
|
|
355
|
+
agent.stop();
|
|
356
|
+
await scope.dispose();
|
|
357
|
+
```
|
|
128
358
|
|
|
129
|
-
|
|
359
|
+
## Example 2: two sessions, one message between them
|
|
360
|
+
|
|
361
|
+
```ts
|
|
362
|
+
import {
|
|
363
|
+
AgentRuntime,
|
|
364
|
+
ConfigManager,
|
|
365
|
+
PeerSessionsScopePlugin,
|
|
366
|
+
Scope,
|
|
367
|
+
allInOne,
|
|
368
|
+
type RuntimeFact,
|
|
369
|
+
type WakeMaterials,
|
|
370
|
+
} from "@ai-zen/agents-sdk";
|
|
371
|
+
|
|
372
|
+
// config.json and the two definitions "lead" and "helper" already exist under `base`
|
|
373
|
+
const base = "/path/to/data";
|
|
374
|
+
const config = new ConfigManager(`${base}/config.json`);
|
|
375
|
+
const names = new Map<string, string>();
|
|
376
|
+
|
|
377
|
+
const runtime = new AgentRuntime({
|
|
378
|
+
openScope: async (cwd, peers) => {
|
|
379
|
+
const scope = new Scope({ getConfig: () => config.read(), agentsDir: `${base}/agents`, cwd })
|
|
380
|
+
.use(...allInOne({ mcpPaths: [`${base}/mcp.json`] }))
|
|
381
|
+
.use(new PeerSessionsScopePlugin(peers)); // the peer tools need the port from the runtime
|
|
382
|
+
await scope.init();
|
|
383
|
+
return scope;
|
|
384
|
+
},
|
|
385
|
+
open: async (input) => {
|
|
386
|
+
// a real host writes a session row here and decides the identity
|
|
387
|
+
const sessionId = `session-${names.size + 1}`;
|
|
388
|
+
names.set(sessionId, input.label ?? input.prompt);
|
|
389
|
+
const materials: WakeMaterials = {
|
|
390
|
+
cwd: base,
|
|
391
|
+
agentId: input.agentId,
|
|
392
|
+
modelId: input.modelId,
|
|
393
|
+
lineage: input.lineage,
|
|
394
|
+
history: [],
|
|
395
|
+
waiting: [],
|
|
396
|
+
};
|
|
397
|
+
return { ok: true, sessionId, materials };
|
|
398
|
+
},
|
|
399
|
+
nameOf: async (sessionId) => names.get(sessionId),
|
|
400
|
+
});
|
|
401
|
+
|
|
402
|
+
runtime.observe((fact: RuntimeFact) => {
|
|
403
|
+
if (fact.type === "messageFinished") console.log(fact.sessionId, fact.message.content);
|
|
404
|
+
});
|
|
405
|
+
|
|
406
|
+
names.set("lead", "lead");
|
|
407
|
+
names.set("helper", "helper");
|
|
408
|
+
await runtime.wake("lead", { cwd: base, agentId: "lead", lineage: null, history: [], waiting: [] });
|
|
409
|
+
await runtime.wake("helper", { cwd: base, agentId: "helper", lineage: null, history: [], waiting: [] });
|
|
410
|
+
|
|
411
|
+
// the helper is woken up by this delivery, runs on its own, and comes back to idle
|
|
412
|
+
console.log(await runtime.post({ from: "lead", to: "helper", content: "Say hi in one line." }));
|
|
413
|
+
console.log(await runtime.status("helper"));
|
|
414
|
+
|
|
415
|
+
await runtime.close();
|
|
416
|
+
```
|
|
130
417
|
|
|
131
|
-
|
|
418
|
+
`peerSessions` on the runtime is the port those three tools end up talking to; `Scopes` is the
|
|
419
|
+
container registry the runtime owns, so the example does not construct it.
|
|
132
420
|
|
|
133
|
-
|
|
134
|
-
- **Schema cost is paid every turn.** Description text is re-sent with every request, so a token delta is a standing cost in request size, context usage and spend rather than a one-off.
|
|
135
|
-
- **Cache prefixes stop being comparable.** Prompt caching matches on the prefix; letting language into the SDK multiplies the prefix shapes of one code path and removes the single variable that benchmarks rely on.
|
|
136
|
-
- **Diagnosis needs one shape.** Performance data, bug reproductions and tool-call success rates have to be comparable across users; once behaviour drifts with locale, every conclusion needs a "what language are you on?" qualifier first.
|
|
421
|
+
## Testing
|
|
137
422
|
|
|
138
|
-
|
|
423
|
+
```bash
|
|
424
|
+
npm run pretest # tsc --noEmit over src and the tests
|
|
425
|
+
npx vitest run # the suite that depends on nothing outside this repository
|
|
426
|
+
```
|
|
139
427
|
|
|
140
|
-
|
|
428
|
+
Both are run from `packages/sdk`. `npm run test:e2e` runs the cases that need an API key or a real
|
|
429
|
+
MCP server; `npm test` must never need either. The fake endpoint used by the suite lives in
|
|
430
|
+
`@ai-zen/agents-testing` (which re-exports `@ai-zen/fake-llm`).
|
|
141
431
|
|
|
142
|
-
|
|
432
|
+
## License
|
|
143
433
|
|
|
144
|
-
|
|
145
|
-
2. Design first, documentation as the source of truth
|
|
146
|
-
3. Symmetry and uniformity
|
|
147
|
-
4. No over-engineering
|
|
148
|
-
5. Occam's razor
|
|
149
|
-
6. Refactor as you go; keep clean layering
|
|
150
|
-
7. Tests are the foundation
|
|
434
|
+
MIT
|