@ai-zen/agents-sdk 1.2.0-alpha.2 → 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.
Files changed (131) hide show
  1. package/CHANGELOG.md +77 -0
  2. package/README.md +397 -113
  3. package/README.zh.md +314 -112
  4. package/dist/agent-plugins/AssetTransportPlugin.d.ts +51 -0
  5. package/dist/agent-plugins/AssetTransportPlugin.js +145 -0
  6. package/dist/agent-plugins/AutoMigratePlugin.d.ts +56 -6
  7. package/dist/agent-plugins/AutoMigratePlugin.js +64 -15
  8. package/dist/agent-plugins/AutoRefreshToolsPlugin.d.ts +12 -9
  9. package/dist/agent-plugins/AutoRefreshToolsPlugin.js +6 -7
  10. package/dist/agent-plugins/ContextGuardPlugin.d.ts +32 -24
  11. package/dist/agent-plugins/ContextGuardPlugin.js +37 -22
  12. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.d.ts +38 -46
  13. package/dist/agent-plugins/SubAgentGuardInstallerPlugin.js +37 -50
  14. package/dist/agent-plugins/UnknownToolHintPlugin.d.ts +15 -1
  15. package/dist/agent-plugins/UnknownToolHintPlugin.js +15 -1
  16. package/dist/config/ConfigManager.d.ts +13 -5
  17. package/dist/config/ConfigManager.js +58 -39
  18. package/dist/config/constants.d.ts +1 -1
  19. package/dist/config/constants.js +2 -2
  20. package/dist/config/factory-skills.js +2 -2
  21. package/dist/config/normalize.d.ts +93 -0
  22. package/dist/config/normalize.js +158 -0
  23. package/dist/crud/AgentRepository.d.ts +3 -1
  24. package/dist/crud/AgentRepository.js +4 -2
  25. package/dist/index.d.ts +22 -9
  26. package/dist/index.js +16 -6
  27. package/dist/runtime/AgentRuntime.d.ts +293 -0
  28. package/dist/runtime/AgentRuntime.js +457 -0
  29. package/dist/runtime/HandoffGuardPlugin.d.ts +85 -16
  30. package/dist/runtime/HandoffGuardPlugin.js +140 -19
  31. package/dist/runtime/HandoffService.d.ts +255 -91
  32. package/dist/runtime/HandoffService.js +392 -177
  33. package/dist/runtime/RuntimePeerSessions.d.ts +34 -0
  34. package/dist/runtime/RuntimePeerSessions.js +50 -0
  35. package/dist/runtime/Scopes.d.ts +123 -0
  36. package/dist/runtime/Scopes.js +169 -0
  37. package/dist/runtime/SdkAgent.d.ts +21 -11
  38. package/dist/runtime/SdkAgent.js +24 -8
  39. package/dist/runtime/completeOnce.d.ts +3 -3
  40. package/dist/runtime/completeOnce.js +3 -3
  41. package/dist/runtime/createAgent.d.ts +29 -7
  42. package/dist/runtime/createAgent.js +57 -12
  43. package/dist/runtime/createModel.d.ts +4 -4
  44. package/dist/runtime/createModel.js +6 -6
  45. package/dist/runtime/lastPromptTokens.d.ts +18 -0
  46. package/dist/runtime/lastPromptTokens.js +26 -0
  47. package/dist/runtime/resolveModel.d.ts +9 -9
  48. package/dist/runtime/resolveModel.js +8 -8
  49. package/dist/scope/Scope.d.ts +42 -14
  50. package/dist/scope/Scope.js +55 -16
  51. package/dist/scope/ScopePlugin.d.ts +2 -8
  52. package/dist/scope/disclosure.d.ts +1 -1
  53. package/dist/scope/disclosure.js +1 -1
  54. package/dist/scope/plugins/allInOne.d.ts +13 -1
  55. package/dist/scope/plugins/allInOne.js +9 -5
  56. package/dist/scope/plugins/builtin/AsyncExecTool.d.ts +12 -0
  57. package/dist/scope/plugins/builtin/AsyncExecTool.js +103 -0
  58. package/dist/scope/plugins/builtin/AsyncTimeoutTool.d.ts +10 -0
  59. package/dist/scope/plugins/builtin/AsyncTimeoutTool.js +90 -0
  60. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.d.ts +1 -1
  61. package/dist/scope/plugins/builtin/BuiltinToolsScopePlugin.js +1 -1
  62. package/dist/scope/plugins/builtin/DownloadFileTool.js +1 -1
  63. package/dist/scope/plugins/builtin/ExecTool.js +10 -199
  64. package/dist/scope/plugins/builtin/FindTextTool.d.ts +1 -1
  65. package/dist/scope/plugins/builtin/FindTextTool.js +1 -1
  66. package/dist/scope/plugins/builtin/GenerateImageTool.d.ts +1 -4
  67. package/dist/scope/plugins/builtin/GenerateImageTool.js +2 -8
  68. package/dist/scope/plugins/builtin/InspectFileTool.js +1 -1
  69. package/dist/scope/plugins/builtin/SdkCallbackTool.d.ts +4 -4
  70. package/dist/scope/plugins/builtin/SdkCallbackTool.js +3 -3
  71. package/dist/scope/plugins/builtin/SleepTool.js +2 -3
  72. package/dist/scope/plugins/builtin/ViewImageTool.d.ts +2 -4
  73. package/dist/scope/plugins/builtin/ViewImageTool.js +4 -6
  74. package/dist/scope/plugins/builtin/WriteTool.d.ts +7 -0
  75. package/dist/scope/plugins/builtin/WriteTool.js +8 -1
  76. package/dist/scope/plugins/builtin/asyncTasks.d.ts +41 -0
  77. package/dist/scope/plugins/builtin/asyncTasks.js +97 -0
  78. package/dist/scope/plugins/builtin/commandOutput.d.ts +22 -0
  79. package/dist/scope/plugins/builtin/commandOutput.js +55 -0
  80. package/dist/scope/plugins/builtin/commandRun.d.ts +48 -0
  81. package/dist/scope/plugins/builtin/commandRun.js +169 -0
  82. package/dist/scope/plugins/builtin/discover.d.ts +1 -3
  83. package/dist/scope/plugins/builtin/discover.js +1 -3
  84. package/dist/scope/plugins/builtin/index.d.ts +5 -7
  85. package/dist/scope/plugins/builtin/index.js +7 -7
  86. package/dist/scope/plugins/builtin/outputGuard.d.ts +1 -5
  87. package/dist/scope/plugins/builtin/outputGuard.js +1 -5
  88. package/dist/scope/plugins/mcp/McpConnectionManager.d.ts +61 -9
  89. package/dist/scope/plugins/mcp/McpConnectionManager.js +174 -72
  90. package/dist/scope/plugins/mcp/McpScopePlugin.d.ts +37 -4
  91. package/dist/scope/plugins/mcp/McpScopePlugin.js +100 -9
  92. package/dist/scope/plugins/mcp/discover.d.ts +9 -2
  93. package/dist/scope/plugins/mcp/discover.js +12 -14
  94. package/dist/scope/plugins/mcp/mcpTaskNotice.d.ts +52 -0
  95. package/dist/scope/plugins/mcp/mcpTaskNotice.js +8 -0
  96. package/dist/scope/plugins/mcp/mcpTools.d.ts +20 -2
  97. package/dist/scope/plugins/mcp/mcpTools.js +220 -39
  98. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.d.ts +25 -0
  99. package/dist/scope/plugins/peers/PeerSessionsScopePlugin.js +32 -0
  100. package/dist/scope/plugins/peers/peerSessionTools.d.ts +173 -0
  101. package/dist/scope/plugins/peers/peerSessionTools.js +292 -0
  102. package/dist/scope/plugins/skills/SkillsScopePlugin.d.ts +4 -0
  103. package/dist/scope/plugins/skills/SkillsScopePlugin.js +10 -4
  104. package/dist/scope/plugins/skills/discover.d.ts +15 -8
  105. package/dist/scope/plugins/skills/discover.js +15 -26
  106. package/dist/scope/plugins/skills/skillTools.d.ts +9 -8
  107. package/dist/scope/plugins/skills/skillTools.js +21 -13
  108. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.d.ts +4 -0
  109. package/dist/scope/plugins/subagents/SubAgentsScopePlugin.js +4 -1
  110. package/dist/scope/plugins/subagents/discover.d.ts +7 -1
  111. package/dist/scope/plugins/subagents/discover.js +7 -3
  112. package/dist/scope/plugins/subagents/subAgentTools.d.ts +0 -1
  113. package/dist/scope/plugins/subagents/subAgentTools.js +14 -1
  114. package/dist/scope/plugins/usertools/UserToolsScopePlugin.d.ts +4 -0
  115. package/dist/scope/plugins/usertools/UserToolsScopePlugin.js +4 -1
  116. package/dist/scope/plugins/usertools/discover.d.ts +7 -8
  117. package/dist/scope/plugins/usertools/discover.js +17 -27
  118. package/dist/shared/EntityRepository.d.ts +22 -5
  119. package/dist/shared/EntityRepository.js +45 -29
  120. package/dist/shared/content-blocks.d.ts +9 -3
  121. package/dist/shared/content-blocks.js +12 -19
  122. package/dist/shared/errors.d.ts +8 -3
  123. package/dist/shared/errors.js +9 -4
  124. package/dist/shared/logger.d.ts +21 -10
  125. package/dist/shared/logger.js +9 -15
  126. package/dist/types/index.d.ts +38 -13
  127. package/package.json +2 -2
  128. package/dist/config/migrate.d.ts +0 -115
  129. package/dist/config/migrate.js +0 -200
  130. package/dist/scope/plugins/builtin/test-helpers.d.ts +0 -3
  131. package/dist/scope/plugins/builtin/test-helpers.js +0 -4
package/CHANGELOG.md CHANGED
@@ -1,3 +1,80 @@
1
+ ## [2.0.0-alpha.1] - 2026-11-23
2
+
3
+ > Follows `@ai-zen/agents-core` `5.0.0-alpha.2`, and it is a major bump for the same reason the
4
+ > kernel's was one: this package used to be business logic sitting on `send()`. A handoff awaited
5
+ > the round it had started, a sub-agent awaited the agent it had built, auto-migration reacted to
6
+ > "this round ended". None of that survives — a resident session has no "deliver and wait" any
7
+ > more, because any other party can push it from idle to busy — so the same behaviour had to be
8
+ > rebuilt on facts instead of promises.
9
+ >
10
+ > Rebuilding it is what split the package in two. The **capability face** is what `1.1.0` already
11
+ > was: `Scope` with its five capability sources behind `allInOne()`, `PermissionEvaluator`, the
12
+ > configuration and definition repositories, model resolution, `createAgent` / `SdkAgent`, handoff.
13
+ > The **runtime** is what the package never had: the thing that keeps those agents alive and lets
14
+ > them talk to each other. The line between the two halves is the line the package is now measured
15
+ > by — the runtime is the only place that knows who is alive, who knows whom, and when to build and
16
+ > when to tear down, and it still imports no host.
17
+
18
+ ### Added
19
+
20
+ - **`AgentRuntime`** — one resident agent per session, with `wake(sessionId, materials)`
21
+ (idempotent; concurrent calls share one assembly), `post({ from, to, content })`,
22
+ `status(sessionId)`, `openPeer({ from, prompt, agentId?, modelId?, label? })`, `kill(sessionId)`,
23
+ `close()`, `observe(listener)` and the snapshots `get` / `sessionOf` / `aliveOn`. It waits for
24
+ nobody: a delivery is what wakes a session, and there is no "one run" object to settle. Its facts
25
+ are a discriminated union — `resident:appeared` / `resident:gone` of its own, `scope:appeared` /
26
+ `scope:refreshed` / `scope:gone` from the container registry, and every kernel event of every
27
+ agent unchanged in name and payload with the `sessionId` added.
28
+ - **`Scopes`** — containers live by directory: one per `cwd`, built on first use, shared by every
29
+ session working there, with `for(cwd)`, `dispose(cwd)`, `refreshAll()` and `disposeAll()`.
30
+ `dispose()` refuses while a session is still alive on that directory instead of cascading,
31
+ because a cascade would silently kill sessions that are in the middle of work. No idle timer, no
32
+ reference counting: "nobody is using it" is not a decidable state.
33
+ - **Four ports** the runtime borrows and never implements: `openScope(cwd, peers)`, `open(input)`
34
+ (write the session, choose the identity, hand back `WakeMaterials`), `nameOf(sessionId)` and
35
+ `log`. A session is an opaque `string` here; a cast that fakes an instance of something in this
36
+ package now means a port is missing.
37
+ - **Peer sessions** — three tools under `scope/plugins/peers/`: `create_session` answers
38
+ `{ sessionId, label }` at once, `read_session_status` answers working / idle, alive, name and an
39
+ excerpt of the last thing said, and `post_message` says only that the message was accepted. They
40
+ implement none of it themselves: `PeerSessionsScopePlugin` takes a `PeerSessionPort` (`create` /
41
+ `status` / `send`) and without a port it produces no tools at all. `RuntimePeerSessions` is that
42
+ port, which is why the three tools also work with no host around. A delegated one-shot agent has
43
+ none of the three: it has no identity to sign a message with and can open nothing that anybody
44
+ would own.
45
+ - **One level deep, structurally** — an agent that was itself opened as a peer is created with
46
+ `canOpenPeers: false`, so `create_session` is not among its tools at all and the model cannot even
47
+ try; `post_message` and `read_session_status` stay, because peers talk both ways. Refusals are
48
+ structured rather than sentences: `gone` / `dead` for a delivery, `depth_exceeded` /
49
+ `model_unresolved` for a creation.
50
+ - **`async_exec` / `async_timeout`** — two tools that return at once and report later. The result
51
+ is delivered back into the same session at low priority, so it never lands inside the batch that
52
+ is currently running, and whatever is still running is reaped when the agent stops. A one-shot
53
+ agent gets neither (`ASYNC_TASK_TOOL_NAMES` is stripped when the tools are chosen): its call
54
+ stack has returned by the time the result arrives.
55
+ - **MCP tasks** — `call_mcp_tool` hands back the task id at once and the server pushes status
56
+ notifications; a terminal status goes to `McpTaskNoticePort` (`sessionOf` / `deliver`), which the
57
+ caller implements, while `isTerminalTaskStatus` is the single test for "this task is over". The
58
+ result itself is fetched by task id with `get_mcp_task_result`; `cancel_mcp_task` cancels it.
59
+ - **`completeOnce`** — one non-streaming call with no tools and no history, the request shape both
60
+ the handoff summary and auto-naming need. **`lastPromptTokens`** is the read behind the context
61
+ guard: the last assistant message that carries usage, never a second copy of the count.
62
+
63
+ ### Changed
64
+
65
+ - Every plugin was re-seated on the seams the new kernel offers, and each had to justify the seam
66
+ it picked. `ContextGuardPlugin` refuses by **returning a string** from `onInnerLoopStart` instead
67
+ of throwing: throwing tears the whole loop down, while refusing leaves no placeholder behind and
68
+ reports `denied`. `AutoMigratePlugin` moved to `onIdle`, because migration means "nothing is
69
+ moving any more", not "this round ended".
70
+ - `HandoffService` judges a handoff round by one fact — whether the write to that path happened
71
+ inside that batch — instead of waiting for the agent to go idle, and there is no timer either: a
72
+ model that replies "done" without calling the tool is answered by the batch closing. Cancellation
73
+ surfaces as `HandoffAbortedError` and is never retried with the other writer.
74
+ - Sub-agents are built with `lifetime: "one-shot"`, and every `role: user` message injected from a
75
+ template carries a `source` naming the injecting tool, so a delegated task's history is never
76
+ mistaken for something the user said.
77
+
1
78
  ## [1.1.0] - 2026-11-09
2
79
 
3
80
  > Cancelling a handoff now means "go back to how it was". Before this release `Ctrl+C` only
package/README.md CHANGED
@@ -1,150 +1,434 @@
1
1
  # @ai-zen/agents-sdk
2
2
 
3
- AI-Zen SDK — shared business logic layer providing a unified Agent runtime for CLI and Desktop. Works out of the box, with preconfigured vendor settings, a default Agent, and a default SubAgent.
3
+ Two halves behind one package name.
4
4
 
5
- ## Source of Truth
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
- **[`docs/sdk-design-v1.md`](./docs/sdk-design-v1.md)** is the single source of truth for this package's design. All implementations must stay consistent with the document.
10
+ ## Installation
8
11
 
9
- ## Architecture
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
- ## Module Layering
16
+ ## What is in which half
19
17
 
20
- ```
21
- types ← pure types, zero business dependencies (incl. ToolEnv)
22
- config ← ConfigManager + constants: config.json read/write + directory setup + factory defaults
23
- crud ← capability-entity CRUD (Agent definitions; conversations/drafts are persisted by each consumer)
24
- runtime ← model factory + Agent assembly + task handoff/migration (cancellable via `AbortSignal`; createModel / createAgent / SdkAgent / HandoffService / HandoffGuardPlugin)
25
- scope ← Scope orchestration container + ScopePlugin contract + PermissionEvaluator / disclosure + plugins/ (5 self-contained capability sources: discovery + tools + plugin)
26
- agent-plugins ← Agent plugins (autoMigrate, autoRefreshTools, contextGuard, unknownToolHint, subAgentGuardInstaller)
27
- shared ← content blocks (file → content block transport), entity repository, logging, errors
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
- Dependency direction: `agent-plugins → runtime → scope`; `runtime → scope / crud / shared / types`, `scope → types / shared`. Upper layers depend on lower layers.
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
- ## Core Concepts
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
- | Entity | Description |
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
- ## Permission Model
47
+ `AgentRuntime` does none of these itself, but each of them has to happen somewhere:
47
48
 
48
- The four dimensions are independent; allow/deny are mutually exclusive, no match means deny, and permission is disclosure (denied items are completely invisible to the LLM).
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
- Agent.permissions
52
- ├── tools: { allow: string[] } | { deny: string[] }
53
- ├── skills: { allow: string[] } | { deny: string[] }
54
- ├── mcps: { allow: string[] } | { deny: string[] }
55
- └── subagents: { allow: string[] } | { deny: string[] }
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
- ## Consumption
111
+ `PermissionEvaluator` is the only implementation of that rule (`filter`, `isAllowed`, `match`).
59
112
 
60
- ```typescript
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
- const agent = await createAgent(scope, "my-agent");
71
- const handoffService = new HandoffService({ handoffDir: "/work/.ai-zen/handoffs", skillDirs });
72
- agent.use(new ContextGuardPlugin({ guardTokens, isSuspended: () => handoffService.busy }));
73
- agent.use(new AutoMigratePlugin({ service: handoffService, handoffTokens }));
74
- agent.use(new AutoRefreshToolsPlugin());
75
- agent.use(new UnknownToolHintPlugin({ scope }));
76
- await agent.init();
77
- await agent.send("Hello");
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
- await scope.dispose(); // disconnect MCP, release plugin resources
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
- ## Built-in Tools
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
- All built-in tools are classes (extending `SdkCallbackTool`), instantiated by the built-in-tools plugin (`BuiltinToolsScopePlugin`) with a `ToolEnv` — one set of instances per Scope, with `cwd` injected and relative paths resolved against `Scope.cwd`, never depending on the global `process.cwd()`.
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
- | Tool | Description |
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
- Conditionally injected based on the active model / config:
167
+ `AgentRuntime` keeps one resident agent per session and forwards the kernel's facts.
108
168
 
109
- | Tool | Injection Condition | Description |
110
- |------|---------------------|-------------|
111
- | `generate_image` | Only when `defaultImageModel` is configured | Generate an image from a text description |
112
- | `view_image` | Only for vision models (the agent's `modelId` resolves to a model with `vision: true`) | View / analyze an image: local images are auto-uploaded via the Files API, network URLs are referenced directly |
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
- Tool output protection: `AppConfig.maxToolOutput` (in characters, default 32768) is the unified ceiling for tool output. Each tool handles overflow itself — `exec` dumps `stdout.log` / `stderr.log` separately (returning head/tail previews per stream), `find_text` / `glob` / `ls` dump `result.json` (returning a head preview), and `read` only warns and suggests batched reads via `range`. Dumps go to `<tmpdir>/ai-zen/tool-output/<tool>-<timestamp>-<random>/`, one directory per call, with no self-cleanup. See [`docs/sdk-design-v1.md`](docs/sdk-design-v1.md).
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
- Interrupt strategies live in the config: `AppConfig.abortedMessageStrategy` (`keep` / `drop`, factory `keep` — the model can continue the half-sentence after an interrupt) and `AppConfig.abortedToolRoundStrategy` (`fill` / `drop`, factory `fill` — whole rounds go in or out, because `tool_calls` must pair with results). `createAgent()` reads them from `scope.config` when no explicit option is passed, keeping a single source of truth.
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
- ## Built-in Plugins
343
+ const idle = new Promise<void>((resolve) => {
344
+ const offIdle = agent.on("state:idle", () => {
345
+ offIdle();
346
+ resolve();
347
+ });
348
+ });
119
349
 
120
- | Plugin | Description |
121
- |--------|-------------|
122
- | `AutoMigratePlugin` | Automatically triggers task migration when `usage.prompt_tokens` exceeds `handoffTokens`; delegates the actual migration to the injected `HandoffService` (history handled per `strategy`: default `omit` keeps it auditable, optional `prune` drops it). `resolveMode` lets the caller pick the handoff executor or skip the round. Steps aside while `service.busy` to avoid the handoff→migrate→handoff recursion |
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
- ## Language
354
+ console.log(agent.messages.at(-1)?.content);
355
+ agent.stop();
356
+ await scope.dispose();
357
+ ```
128
358
 
129
- The SDK is **English-only**: every model-facing and user-facing string — tool schema descriptions, factory prompts, runtime-injected guidance, tool results, error messages, factory catalog data — is a fixed English literal. There is no locale field, no message catalog, and no runtime language switch. UI language belongs entirely to each consumer (the CLI's `i18n/`, the Desktop's language setting).
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
- This is a performance boundary, not a convenience choice — **SDK behaviour and performance must not vary by the user's language**:
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
- - **Thresholds are absolute.** `Model.tokenThresholds.handoff` / `guard` and `AppConfig.maxToolOutput` are absolute token / character counts. A localized tool schema is a different token count, so handoff and context-guard would trip at *different amounts of real content* for the same `config.json` — same config, different behaviour per language.
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
- Following the user's language is handled by one language-neutral instruction in the factory system prompt — `Always reply in the same language the user writes in.` — which adapts per **message** rather than per installation, and needs no locale plumbing in the SDK. Full rationale: [`docs/sdk-design-v1.md`](docs/sdk-design-v1.md).
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
- ## Design Principles
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
- See the project-root [`PRINCIPLES.md`](../../PRINCIPLES.md):
432
+ ## License
143
433
 
144
- 1. Logical consistency
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