kode-sdk 2.7.0

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 (169) hide show
  1. package/LICENSE +201 -0
  2. package/README.md +74 -0
  3. package/dist/core/agent/breakpoint-manager.d.ts +16 -0
  4. package/dist/core/agent/breakpoint-manager.js +36 -0
  5. package/dist/core/agent/message-queue.d.ts +26 -0
  6. package/dist/core/agent/message-queue.js +47 -0
  7. package/dist/core/agent/permission-manager.d.ts +9 -0
  8. package/dist/core/agent/permission-manager.js +32 -0
  9. package/dist/core/agent/todo-manager.d.ts +26 -0
  10. package/dist/core/agent/todo-manager.js +91 -0
  11. package/dist/core/agent/tool-runner.d.ts +9 -0
  12. package/dist/core/agent/tool-runner.js +45 -0
  13. package/dist/core/agent.d.ts +271 -0
  14. package/dist/core/agent.js +2334 -0
  15. package/dist/core/checkpointer.d.ts +96 -0
  16. package/dist/core/checkpointer.js +57 -0
  17. package/dist/core/checkpointers/file.d.ts +20 -0
  18. package/dist/core/checkpointers/file.js +153 -0
  19. package/dist/core/checkpointers/index.d.ts +3 -0
  20. package/dist/core/checkpointers/index.js +9 -0
  21. package/dist/core/checkpointers/redis.d.ts +35 -0
  22. package/dist/core/checkpointers/redis.js +113 -0
  23. package/dist/core/compression/ai-strategy.d.ts +53 -0
  24. package/dist/core/compression/ai-strategy.js +298 -0
  25. package/dist/core/compression/index.d.ts +12 -0
  26. package/dist/core/compression/index.js +27 -0
  27. package/dist/core/compression/prompts.d.ts +35 -0
  28. package/dist/core/compression/prompts.js +114 -0
  29. package/dist/core/compression/simple-strategy.d.ts +44 -0
  30. package/dist/core/compression/simple-strategy.js +240 -0
  31. package/dist/core/compression/token-estimator.d.ts +42 -0
  32. package/dist/core/compression/token-estimator.js +121 -0
  33. package/dist/core/compression/types.d.ts +140 -0
  34. package/dist/core/compression/types.js +9 -0
  35. package/dist/core/config.d.ts +10 -0
  36. package/dist/core/config.js +2 -0
  37. package/dist/core/context-manager.d.ts +115 -0
  38. package/dist/core/context-manager.js +107 -0
  39. package/dist/core/errors.d.ts +6 -0
  40. package/dist/core/errors.js +17 -0
  41. package/dist/core/events.d.ts +49 -0
  42. package/dist/core/events.js +312 -0
  43. package/dist/core/file-pool.d.ts +43 -0
  44. package/dist/core/file-pool.js +120 -0
  45. package/dist/core/hooks.d.ts +23 -0
  46. package/dist/core/hooks.js +71 -0
  47. package/dist/core/permission-modes.d.ts +31 -0
  48. package/dist/core/permission-modes.js +61 -0
  49. package/dist/core/pool.d.ts +31 -0
  50. package/dist/core/pool.js +87 -0
  51. package/dist/core/room.d.ts +15 -0
  52. package/dist/core/room.js +57 -0
  53. package/dist/core/scheduler.d.ts +33 -0
  54. package/dist/core/scheduler.js +58 -0
  55. package/dist/core/template.d.ts +69 -0
  56. package/dist/core/template.js +35 -0
  57. package/dist/core/time-bridge.d.ts +18 -0
  58. package/dist/core/time-bridge.js +100 -0
  59. package/dist/core/todo.d.ts +34 -0
  60. package/dist/core/todo.js +89 -0
  61. package/dist/core/types.d.ts +380 -0
  62. package/dist/core/types.js +3 -0
  63. package/dist/index.d.ts +51 -0
  64. package/dist/index.js +147 -0
  65. package/dist/infra/provider.d.ts +144 -0
  66. package/dist/infra/provider.js +294 -0
  67. package/dist/infra/sandbox-factory.d.ts +10 -0
  68. package/dist/infra/sandbox-factory.js +21 -0
  69. package/dist/infra/sandbox.d.ts +87 -0
  70. package/dist/infra/sandbox.js +255 -0
  71. package/dist/infra/store.d.ts +154 -0
  72. package/dist/infra/store.js +584 -0
  73. package/dist/skills/index.d.ts +12 -0
  74. package/dist/skills/index.js +36 -0
  75. package/dist/skills/injector.d.ts +29 -0
  76. package/dist/skills/injector.js +96 -0
  77. package/dist/skills/loader.d.ts +59 -0
  78. package/dist/skills/loader.js +215 -0
  79. package/dist/skills/manager.d.ts +85 -0
  80. package/dist/skills/manager.js +221 -0
  81. package/dist/skills/parser.d.ts +40 -0
  82. package/dist/skills/parser.js +107 -0
  83. package/dist/skills/types.d.ts +107 -0
  84. package/dist/skills/types.js +7 -0
  85. package/dist/skills/validator.d.ts +30 -0
  86. package/dist/skills/validator.js +121 -0
  87. package/dist/store.d.ts +1 -0
  88. package/dist/store.js +5 -0
  89. package/dist/tools/bash_kill/index.d.ts +1 -0
  90. package/dist/tools/bash_kill/index.js +35 -0
  91. package/dist/tools/bash_kill/prompt.d.ts +2 -0
  92. package/dist/tools/bash_kill/prompt.js +14 -0
  93. package/dist/tools/bash_logs/index.d.ts +1 -0
  94. package/dist/tools/bash_logs/index.js +40 -0
  95. package/dist/tools/bash_logs/prompt.d.ts +2 -0
  96. package/dist/tools/bash_logs/prompt.js +14 -0
  97. package/dist/tools/bash_run/index.d.ts +16 -0
  98. package/dist/tools/bash_run/index.js +61 -0
  99. package/dist/tools/bash_run/prompt.d.ts +2 -0
  100. package/dist/tools/bash_run/prompt.js +18 -0
  101. package/dist/tools/builtin.d.ts +9 -0
  102. package/dist/tools/builtin.js +27 -0
  103. package/dist/tools/define.d.ts +101 -0
  104. package/dist/tools/define.js +214 -0
  105. package/dist/tools/fs_edit/index.d.ts +1 -0
  106. package/dist/tools/fs_edit/index.js +62 -0
  107. package/dist/tools/fs_edit/prompt.d.ts +2 -0
  108. package/dist/tools/fs_edit/prompt.js +15 -0
  109. package/dist/tools/fs_glob/index.d.ts +1 -0
  110. package/dist/tools/fs_glob/index.js +60 -0
  111. package/dist/tools/fs_glob/prompt.d.ts +2 -0
  112. package/dist/tools/fs_glob/prompt.js +18 -0
  113. package/dist/tools/fs_grep/index.d.ts +1 -0
  114. package/dist/tools/fs_grep/index.js +66 -0
  115. package/dist/tools/fs_grep/prompt.d.ts +2 -0
  116. package/dist/tools/fs_grep/prompt.js +16 -0
  117. package/dist/tools/fs_multi_edit/index.d.ts +1 -0
  118. package/dist/tools/fs_multi_edit/index.js +106 -0
  119. package/dist/tools/fs_multi_edit/prompt.d.ts +2 -0
  120. package/dist/tools/fs_multi_edit/prompt.js +16 -0
  121. package/dist/tools/fs_read/index.d.ts +1 -0
  122. package/dist/tools/fs_read/index.js +40 -0
  123. package/dist/tools/fs_read/prompt.d.ts +2 -0
  124. package/dist/tools/fs_read/prompt.js +16 -0
  125. package/dist/tools/fs_rm/index.d.ts +1 -0
  126. package/dist/tools/fs_rm/index.js +41 -0
  127. package/dist/tools/fs_rm/prompt.d.ts +2 -0
  128. package/dist/tools/fs_rm/prompt.js +14 -0
  129. package/dist/tools/fs_write/index.d.ts +1 -0
  130. package/dist/tools/fs_write/index.js +40 -0
  131. package/dist/tools/fs_write/prompt.d.ts +2 -0
  132. package/dist/tools/fs_write/prompt.js +15 -0
  133. package/dist/tools/index.d.ts +9 -0
  134. package/dist/tools/index.js +56 -0
  135. package/dist/tools/mcp.d.ts +73 -0
  136. package/dist/tools/mcp.js +198 -0
  137. package/dist/tools/registry.d.ts +29 -0
  138. package/dist/tools/registry.js +26 -0
  139. package/dist/tools/skill_activate/index.d.ts +5 -0
  140. package/dist/tools/skill_activate/index.js +63 -0
  141. package/dist/tools/skill_list/index.d.ts +5 -0
  142. package/dist/tools/skill_list/index.js +48 -0
  143. package/dist/tools/skill_resource/index.d.ts +5 -0
  144. package/dist/tools/skill_resource/index.js +82 -0
  145. package/dist/tools/task_run/index.d.ts +7 -0
  146. package/dist/tools/task_run/index.js +60 -0
  147. package/dist/tools/task_run/prompt.d.ts +5 -0
  148. package/dist/tools/task_run/prompt.js +29 -0
  149. package/dist/tools/todo_read/index.d.ts +1 -0
  150. package/dist/tools/todo_read/index.js +29 -0
  151. package/dist/tools/todo_read/prompt.d.ts +2 -0
  152. package/dist/tools/todo_read/prompt.js +18 -0
  153. package/dist/tools/todo_write/index.d.ts +1 -0
  154. package/dist/tools/todo_write/index.js +42 -0
  155. package/dist/tools/todo_write/prompt.d.ts +2 -0
  156. package/dist/tools/todo_write/prompt.js +23 -0
  157. package/dist/tools/tool.d.ts +43 -0
  158. package/dist/tools/tool.js +104 -0
  159. package/dist/tools/toolkit.d.ts +69 -0
  160. package/dist/tools/toolkit.js +98 -0
  161. package/dist/tools/type-inference.d.ts +127 -0
  162. package/dist/tools/type-inference.js +207 -0
  163. package/dist/utils/agent-id.d.ts +1 -0
  164. package/dist/utils/agent-id.js +28 -0
  165. package/dist/utils/session-id.d.ts +21 -0
  166. package/dist/utils/session-id.js +64 -0
  167. package/dist/utils/unicode.d.ts +17 -0
  168. package/dist/utils/unicode.js +62 -0
  169. package/package.json +117 -0
package/LICENSE ADDED
@@ -0,0 +1,201 @@
1
+ Apache License
2
+ Version 2.0, January 2004
3
+ http://www.apache.org/licenses/
4
+
5
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
6
+
7
+ 1. Definitions.
8
+
9
+ "License" shall mean the terms and conditions for use, reproduction,
10
+ and distribution as defined by Sections 1 through 9 of this document.
11
+
12
+ "Licensor" shall mean the copyright owner or entity authorized by
13
+ the copyright owner that is granting the License.
14
+
15
+ "Legal Entity" shall mean the union of the acting entity and all
16
+ other entities that control, are controlled by, or are under common
17
+ control with that entity. For the purposes of this definition,
18
+ "control" means (i) the power, direct or indirect, to cause the
19
+ direction or management of such entity, whether by contract or
20
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
21
+ outstanding shares, or (iii) beneficial ownership of such entity.
22
+
23
+ "You" (or "Your") shall mean an individual or Legal Entity
24
+ exercising permissions granted by this License.
25
+
26
+ "Source" form shall mean the preferred form for making modifications,
27
+ including but not limited to software source code, documentation
28
+ source, and configuration files.
29
+
30
+ "Object" form shall mean any form resulting from mechanical
31
+ transformation or translation of a Source form, including but
32
+ not limited to compiled object code, generated documentation,
33
+ and conversions to other media types.
34
+
35
+ "Work" shall mean the work of authorship, whether in Source or
36
+ Object form, made available under the License, as indicated by a
37
+ copyright notice that is included in or attached to the work
38
+ (an example is provided in the Appendix below).
39
+
40
+ "Derivative Works" shall mean any work, whether in Source or Object
41
+ form, that is based on (or derived from) the Work and for which the
42
+ editorial revisions, annotations, elaborations, or other modifications
43
+ represent, as a whole, an original work of authorship. For the purposes
44
+ of this License, Derivative Works shall not include works that remain
45
+ separable from, or merely link (or bind by name) to the interfaces of,
46
+ the Work and Derivative Works thereof.
47
+
48
+ "Contribution" shall mean any work of authorship, including
49
+ the original version of the Work and any modifications or additions
50
+ to that Work or Derivative Works thereof, that is intentionally
51
+ submitted to Licensor for inclusion in the Work by the copyright owner
52
+ or by an individual or Legal Entity authorized to submit on behalf of
53
+ the copyright owner. For the purposes of this definition, "submitted"
54
+ means any form of electronic, verbal, or written communication sent
55
+ to the Licensor or its representatives, including but not limited to
56
+ communication on electronic mailing lists, source code control systems,
57
+ and issue tracking systems that are managed by, or on behalf of, the
58
+ Licensor for the purpose of discussing and improving the Work, but
59
+ excluding communication that is conspicuously marked or otherwise
60
+ designated in writing by the copyright owner as "Not a Contribution."
61
+
62
+ "Contributor" shall mean Licensor and any individual or Legal Entity
63
+ on behalf of whom a Contribution has been received by Licensor and
64
+ subsequently incorporated within the Work.
65
+
66
+ 2. Grant of Copyright License. Subject to the terms and conditions of
67
+ this License, each Contributor hereby grants to You a perpetual,
68
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
69
+ copyright license to reproduce, prepare Derivative Works of,
70
+ publicly display, publicly perform, sublicense, and distribute the
71
+ Work and such Derivative Works in Source or Object form.
72
+
73
+ 3. Grant of Patent License. Subject to the terms and conditions of
74
+ this License, each Contributor hereby grants to You a perpetual,
75
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
76
+ (except as stated in this section) patent license to make, have made,
77
+ use, offer to sell, sell, import, and otherwise transfer the Work,
78
+ where such license applies only to those patent claims licensable
79
+ by such Contributor that are necessarily infringed by their
80
+ Contribution(s) alone or by combination of their Contribution(s)
81
+ with the Work to which such Contribution(s) was submitted. If You
82
+ institute patent litigation against any entity (including a
83
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
84
+ or a Contribution incorporated within the Work constitutes direct
85
+ or contributory patent infringement, then any patent licenses
86
+ granted to You under this License for that Work shall terminate
87
+ as of the date such litigation is filed.
88
+
89
+ 4. Redistribution. You may reproduce and distribute copies of the
90
+ Work or Derivative Works thereof in any medium, with or without
91
+ modifications, and in Source or Object form, provided that You
92
+ meet the following conditions:
93
+
94
+ (a) You must give any other recipients of the Work or
95
+ Derivative Works a copy of this License; and
96
+
97
+ (b) You must cause any modified files to carry prominent notices
98
+ stating that You changed the files; and
99
+
100
+ (c) You must retain, in the Source form of any Derivative Works
101
+ that You distribute, all copyright, patent, trademark, and
102
+ attribution notices from the Source form of the Work,
103
+ excluding those notices that do not pertain to any part of
104
+ the Derivative Works; and
105
+
106
+ (d) If the Work includes a "NOTICE" text file as part of its
107
+ distribution, then any Derivative Works that You distribute must
108
+ include a readable copy of the attribution notices contained
109
+ within such NOTICE file, excluding those notices that do not
110
+ pertain to any part of the Derivative Works, in at least one
111
+ of the following places: within a NOTICE text file distributed
112
+ as part of the Derivative Works; within the Source form or
113
+ documentation, if provided along with the Derivative Works; or,
114
+ within a display generated by the Derivative Works, if and
115
+ wherever such third-party notices normally appear. The contents
116
+ of the NOTICE file are for informational purposes only and
117
+ do not modify the License. You may add Your own attribution
118
+ notices within Derivative Works that You distribute, alongside
119
+ or as an addendum to the NOTICE text from the Work, provided
120
+ that such additional attribution notices cannot be construed
121
+ as modifying the License.
122
+
123
+ You may add Your own copyright statement to Your modifications and
124
+ may provide additional or different license terms and conditions
125
+ for use, reproduction, or distribution of Your modifications, or
126
+ for any such Derivative Works as a whole, provided Your use,
127
+ reproduction, and distribution of the Work otherwise complies with
128
+ the conditions stated in this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work
132
+ by You to the Licensor shall be under the terms and conditions of
133
+ this License, without any additional terms or conditions.
134
+ Notwithstanding the above, nothing herein shall supersede or modify
135
+ the terms of any separate license agreement you may have executed
136
+ with Licensor regarding such Contributions.
137
+
138
+ 6. Trademarks. This License does not grant permission to use the trade
139
+ names, trademarks, service marks, or product names of the Licensor,
140
+ except as required for reasonable and customary use in describing the
141
+ origin of the Work and reproducing the content of the NOTICE file.
142
+
143
+ 7. Disclaimer of Warranty. Unless required by applicable law or
144
+ agreed to in writing, Licensor provides the Work (and each
145
+ Contributor provides its Contributions) on an "AS IS" BASIS,
146
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
147
+ implied, including, without limitation, any warranties or conditions
148
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
149
+ PARTICULAR PURPOSE. You are solely responsible for determining the
150
+ appropriateness of using or redistributing the Work and assume any
151
+ risks associated with Your exercise of permissions under this License.
152
+
153
+ 8. Limitation of Liability. In no event and under no legal theory,
154
+ whether in tort (including negligence), contract, or otherwise,
155
+ unless required by applicable law (such as deliberate and grossly
156
+ negligent acts) or agreed to in writing, shall any Contributor be
157
+ liable to You for damages, including any direct, indirect, special,
158
+ incidental, or consequential damages of any character arising as a
159
+ result of this License or out of the use or inability to use the
160
+ Work (including but not limited to damages for loss of goodwill,
161
+ work stoppage, computer failure or malfunction, or any and all
162
+ other commercial damages or losses), even if such Contributor
163
+ has been advised of the possibility of such damages.
164
+
165
+ 9. Accepting Warranty or Additional Liability. While redistributing
166
+ the Work or Derivative Works thereof, You may choose to offer,
167
+ and charge a fee for, acceptance of support, warranty, indemnity,
168
+ or other liability obligations and/or rights consistent with this
169
+ License. However, in accepting such obligations, You may act only
170
+ on Your own behalf and on Your sole responsibility, not on behalf
171
+ of any other Contributor, and only if You agree to indemnify,
172
+ defend, and hold each Contributor harmless for any liability
173
+ incurred by, or claims asserted against, such Contributor by reason
174
+ of your accepting any such warranty or additional liability.
175
+
176
+ END OF TERMS AND CONDITIONS
177
+
178
+ APPENDIX: How to apply the Apache License to your work.
179
+
180
+ To apply the Apache License to your work, attach the following
181
+ boilerplate notice, with the fields enclosed by brackets "[]"
182
+ replaced with your own identifying information. (Don't include
183
+ the brackets!) The text should be enclosed in the appropriate
184
+ comment syntax for the file format. We also recommend that a
185
+ file or class name and description of purpose be included on the
186
+ same "printed page" as the copyright notice for easier
187
+ identification within third-party archives.
188
+
189
+ Copyright [yyyy] [name of copyright owner]
190
+
191
+ Licensed under the Apache License, Version 2.0 (the "License");
192
+ you may not use this file except in compliance with the License.
193
+ You may obtain a copy of the License at
194
+
195
+ http://www.apache.org/licenses/LICENSE-2.0
196
+
197
+ Unless required by applicable law or agreed to in writing, software
198
+ distributed under the License is distributed on an "AS IS" BASIS,
199
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
200
+ See the License for the specific language governing permissions and
201
+ limitations under the License.
package/README.md ADDED
@@ -0,0 +1,74 @@
1
+ # KODE SDK · Event-Driven Agent Runtime
2
+
3
+ > **就像和资深同事协作**:发消息、批示、打断、分叉、续上 —— 一套最小而够用的 API,驱动长期在线的多 Agent 系统。
4
+
5
+ ## Why KODE
6
+
7
+ - **Event-First**:UI 只订阅 Progress(文本/工具流);审批与治理走 Control & Monitor 回调,默认不推噪音事件。
8
+ - **长时运行 + 可分叉**:七段断点恢复(READY → POST_TOOL),Safe-Fork-Point 天然存在于工具结果与纯文本处,一键 fork 继续。
9
+ - **同事式协作心智**:Todo 管理、提醒、Tool 手册自动注入,工具并发可限流,默认配置即安全可用。
10
+ - **高性能且可审计**:统一 WAL、零拷贝文本流、工具拒绝必落审计、Monitor 事件覆盖 token 用量、错误与文件变更。
11
+ - **可扩展生态**:原生接入 MCP 工具、Sandbox 驱动、模型 Provider、Store 后端、Scheduler DSL,支持企业级自定义。
12
+
13
+ ## 60 秒上手:跑通第一个“协作收件箱”
14
+
15
+ ```bash
16
+ npm install kode-sdk
17
+ export ANTHROPIC_API_KEY=sk-... # 或 ANTHROPIC_API_TOKEN
18
+ export ANTHROPIC_BASE_URL=https://... # 可选,默认为官方 API
19
+ export ANTHROPIC_MODEL_ID=claude-sonnet-4.5-20250929 # 可选
20
+
21
+ npm run example:agent-inbox
22
+ ```
23
+
24
+ 输出中你会看到:
25
+
26
+ - Progress 渠道实时流式文本 / 工具生命周期事件
27
+ - Control 渠道的审批请求(示例中默认拒绝 `bash_run`)
28
+ - Monitor 渠道的工具审计日志(耗时、审批结果、错误)
29
+
30
+ 想自定义行为?修改 `examples/01-agent-inbox.ts` 内的模板、工具与事件订阅即可。
31
+
32
+ ## 示例游乐场
33
+
34
+ | 示例 | 用例 | 涵盖能力 |
35
+ | --- | --- | --- |
36
+ | `npm run example:getting-started` | 最小对话循环 | Progress 流订阅、Anthropic 模型直连 |
37
+ | `npm run example:agent-inbox` | 事件驱动收件箱 | Todo 管理、工具并发、Monitor 审计 |
38
+ | `npm run example:approval` | 工具审批工作流 | Control 回调、Hook 策略、自动拒绝/放行 |
39
+ | `npm run example:room` | 多 Agent 协作 | AgentPool、Room 消息、Safe Fork、Lineage |
40
+ | `npm run example:scheduler` | 长时运行 & 提醒 | Scheduler 步数触发、系统提醒、FilePool 监控 |
41
+ | `npm run example:nextjs` | API + SSE | Resume-or-create、Progress 流推送(无需安装 Next) |
42
+
43
+ 每个示例都位于 `examples/` 下,对应 README 中的学习路径,展示事件驱动、审批、安全、调度、协作等核心能力的组合方式。
44
+
45
+ ## 构建属于你的协作型 Agent
46
+
47
+ 1. **理解三通道心智**:详见 [`docs/events.md`](./docs/events.md)。
48
+ 2. **跟着 Quickstart 实战**:[`docs/quickstart.md`](./docs/quickstart.md) 从 “依赖注入 → Resume → SSE” 手把手搭建服务。
49
+ 3. **扩展用例**:[`docs/playbooks.md`](./docs/playbooks.md) 涵盖审批治理、多 Agent 小组、调度提醒等典型场景。
50
+ 4. **查阅 API**:[`docs/api.md`](./docs/api.md) 枚举 `Agent`、`EventBus`、`ToolRegistry` 等核心类型与事件。
51
+ 5. **深挖能力**:Todo、ContextManager、Scheduler、Sandbox、Hook、Tool 定义详见 `docs/` 目录。
52
+
53
+ ## 基础设计一图流
54
+
55
+ ```
56
+ Client/UI ── subscribe(['progress']) ──┐
57
+ Approval service ── Control 回调 ─────┼▶ EventBus(三通道)
58
+ Observability ── Monitor 事件 ────────┘
59
+
60
+
61
+
62
+ MessageQueue → ContextManager → ToolRunner
63
+ │ │ │
64
+ ▼ ▼ ▼
65
+ Store (WAL) FilePool PermissionManager
66
+ ```
67
+
68
+ ## 下一步
69
+
70
+ - 使用 `examples/` 作为蓝本接入你自己的工具、存储、审批系统。
71
+ - 将 Monitor 事件接入现有 observability 平台,沉淀治理与审计能力。
72
+ - 参考 `docs/` 中的扩展指南,为企业自定义 Sandbox、模型 Provider 或多团队 Agent 协作流程。
73
+
74
+ 欢迎在 Issue / PR 中分享反馈与场景诉求,让 KODE SDK 更贴近真实协作团队的需求。
@@ -0,0 +1,16 @@
1
+ import { BreakpointState } from '../types';
2
+ export interface BreakpointEntry {
3
+ state: BreakpointState;
4
+ timestamp: number;
5
+ note?: string;
6
+ }
7
+ export declare class BreakpointManager {
8
+ private readonly onChange?;
9
+ private current;
10
+ private history;
11
+ constructor(onChange?: ((previous: BreakpointState, next: BreakpointState, entry: BreakpointEntry) => void) | undefined);
12
+ getCurrent(): BreakpointState;
13
+ getHistory(): ReadonlyArray<BreakpointEntry>;
14
+ set(state: BreakpointState, note?: string): void;
15
+ reset(state?: BreakpointState): void;
16
+ }
@@ -0,0 +1,36 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.BreakpointManager = void 0;
4
+ class BreakpointManager {
5
+ constructor(onChange) {
6
+ this.onChange = onChange;
7
+ this.current = 'READY';
8
+ this.history = [];
9
+ }
10
+ getCurrent() {
11
+ return this.current;
12
+ }
13
+ getHistory() {
14
+ return this.history;
15
+ }
16
+ set(state, note) {
17
+ if (this.current === state)
18
+ return;
19
+ const entry = {
20
+ state,
21
+ timestamp: Date.now(),
22
+ note,
23
+ };
24
+ const previous = this.current;
25
+ this.current = state;
26
+ this.history.push(entry);
27
+ if (this.onChange) {
28
+ this.onChange(previous, state, entry);
29
+ }
30
+ }
31
+ reset(state = 'READY') {
32
+ this.current = state;
33
+ this.history = [];
34
+ }
35
+ }
36
+ exports.BreakpointManager = BreakpointManager;
@@ -0,0 +1,26 @@
1
+ import { Message } from '../types';
2
+ import { ReminderOptions } from '../types';
3
+ export type PendingKind = 'user' | 'reminder';
4
+ export interface PendingMessage {
5
+ message: Message;
6
+ kind: PendingKind;
7
+ metadata?: Record<string, any>;
8
+ }
9
+ export interface SendOptions {
10
+ kind?: PendingKind;
11
+ metadata?: Record<string, any>;
12
+ reminder?: ReminderOptions;
13
+ }
14
+ export interface MessageQueueOptions {
15
+ wrapReminder(content: string, options?: ReminderOptions): string;
16
+ addMessage(message: Message, kind: PendingKind): void;
17
+ persist(): Promise<void>;
18
+ ensureProcessing(): void;
19
+ }
20
+ export declare class MessageQueue {
21
+ private readonly options;
22
+ private pending;
23
+ constructor(options: MessageQueueOptions);
24
+ send(text: string, opts?: SendOptions): string;
25
+ flush(): Promise<void>;
26
+ }
@@ -0,0 +1,47 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.MessageQueue = void 0;
4
+ class MessageQueue {
5
+ constructor(options) {
6
+ this.options = options;
7
+ this.pending = [];
8
+ }
9
+ send(text, opts = {}) {
10
+ const kind = opts.kind ?? 'user';
11
+ const payload = kind === 'reminder' ? this.options.wrapReminder(text, opts.reminder) : text;
12
+ const id = `msg-${Date.now()}-${Math.random().toString(36).slice(2, 9)}`;
13
+ this.pending.push({
14
+ message: {
15
+ role: 'user',
16
+ content: [{ type: 'text', text: payload }],
17
+ },
18
+ kind,
19
+ metadata: { id, ...(opts.metadata || {}) },
20
+ });
21
+ if (kind === 'user') {
22
+ this.options.ensureProcessing();
23
+ }
24
+ return id;
25
+ }
26
+ async flush() {
27
+ if (this.pending.length === 0)
28
+ return;
29
+ const queue = this.pending;
30
+ try {
31
+ // 先添加到消息历史
32
+ for (const entry of queue) {
33
+ this.options.addMessage(entry.message, entry.kind);
34
+ }
35
+ // 持久化成功后才清空队列
36
+ await this.options.persist();
37
+ // 成功:从队列中移除已处理的消息
38
+ this.pending = this.pending.filter(item => !queue.includes(item));
39
+ }
40
+ catch (err) {
41
+ // 失败:保留队列,下次重试
42
+ console.error('[MessageQueue] Flush failed, messages retained:', err);
43
+ throw err; // 重新抛出让调用者知道失败
44
+ }
45
+ }
46
+ }
47
+ exports.MessageQueue = MessageQueue;
@@ -0,0 +1,9 @@
1
+ import { PermissionConfig } from '../template';
2
+ import { ToolDescriptor } from '../../tools/registry';
3
+ import { PermissionDecision } from '../permission-modes';
4
+ export declare class PermissionManager {
5
+ private readonly config;
6
+ private readonly descriptors;
7
+ constructor(config: PermissionConfig, descriptors: Map<string, ToolDescriptor>);
8
+ evaluate(toolName: string): PermissionDecision;
9
+ }
@@ -0,0 +1,32 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.PermissionManager = void 0;
4
+ const permission_modes_1 = require("../permission-modes");
5
+ class PermissionManager {
6
+ constructor(config, descriptors) {
7
+ this.config = config;
8
+ this.descriptors = descriptors;
9
+ }
10
+ evaluate(toolName) {
11
+ if (this.config.denyTools?.includes(toolName)) {
12
+ return 'deny';
13
+ }
14
+ if (this.config.allowTools && this.config.allowTools.length > 0 && !this.config.allowTools.includes(toolName)) {
15
+ return 'deny';
16
+ }
17
+ if (this.config.requireApprovalTools?.includes(toolName)) {
18
+ return 'ask';
19
+ }
20
+ const handler = permission_modes_1.permissionModes.get(this.config.mode || 'auto') || permission_modes_1.permissionModes.get('auto');
21
+ if (!handler) {
22
+ return 'allow';
23
+ }
24
+ const context = {
25
+ toolName,
26
+ descriptor: this.descriptors.get(toolName),
27
+ config: this.config,
28
+ };
29
+ return handler(context);
30
+ }
31
+ }
32
+ exports.PermissionManager = PermissionManager;
@@ -0,0 +1,26 @@
1
+ import { TodoService, TodoInput, TodoItem } from '../todo';
2
+ import { TodoConfig } from '../template';
3
+ import { ReminderOptions } from '../types';
4
+ import { EventBus } from '../events';
5
+ export interface TodoManagerOptions {
6
+ service?: TodoService;
7
+ config?: TodoConfig;
8
+ events: EventBus;
9
+ remind: (content: string, options?: ReminderOptions) => void;
10
+ }
11
+ export declare class TodoManager {
12
+ private readonly opts;
13
+ private stepsSinceReminder;
14
+ constructor(opts: TodoManagerOptions);
15
+ get enabled(): boolean;
16
+ list(): TodoItem[];
17
+ setTodos(todos: TodoInput[]): Promise<void>;
18
+ update(todo: TodoInput): Promise<void>;
19
+ remove(id: string): Promise<void>;
20
+ handleStartup(): void;
21
+ onStep(): void;
22
+ private publishChange;
23
+ private sendReminder;
24
+ private sendEmptyReminder;
25
+ private formatTodoReminder;
26
+ }
@@ -0,0 +1,91 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.TodoManager = void 0;
4
+ class TodoManager {
5
+ constructor(opts) {
6
+ this.opts = opts;
7
+ this.stepsSinceReminder = 0;
8
+ }
9
+ get enabled() {
10
+ return !!this.opts.service && !!this.opts.config?.enabled;
11
+ }
12
+ list() {
13
+ return this.opts.service ? this.opts.service.list() : [];
14
+ }
15
+ async setTodos(todos) {
16
+ if (!this.opts.service)
17
+ throw new Error('Todo service not enabled for this agent');
18
+ const prev = this.opts.service.list();
19
+ await this.opts.service.setTodos(todos);
20
+ this.publishChange(prev, this.opts.service.list());
21
+ }
22
+ async update(todo) {
23
+ if (!this.opts.service)
24
+ throw new Error('Todo service not enabled for this agent');
25
+ const prev = this.opts.service.list();
26
+ await this.opts.service.update(todo);
27
+ this.publishChange(prev, this.opts.service.list());
28
+ }
29
+ async remove(id) {
30
+ if (!this.opts.service)
31
+ throw new Error('Todo service not enabled for this agent');
32
+ const prev = this.opts.service.list();
33
+ await this.opts.service.delete(id);
34
+ this.publishChange(prev, this.opts.service.list());
35
+ }
36
+ handleStartup() {
37
+ if (!this.enabled || !this.opts.config?.reminderOnStart)
38
+ return;
39
+ const todos = this.list().filter((todo) => todo.status !== 'completed');
40
+ if (todos.length === 0) {
41
+ this.sendEmptyReminder();
42
+ }
43
+ else {
44
+ this.sendReminder(todos, 'startup');
45
+ }
46
+ }
47
+ onStep() {
48
+ if (!this.enabled)
49
+ return;
50
+ if (!this.opts.config?.remindIntervalSteps)
51
+ return;
52
+ if (this.opts.config.remindIntervalSteps <= 0)
53
+ return;
54
+ this.stepsSinceReminder += 1;
55
+ if (this.stepsSinceReminder < this.opts.config.remindIntervalSteps)
56
+ return;
57
+ const todos = this.list().filter((todo) => todo.status !== 'completed');
58
+ if (todos.length === 0)
59
+ return;
60
+ this.sendReminder(todos, 'interval');
61
+ }
62
+ publishChange(previous, current) {
63
+ if (!this.opts.events)
64
+ return;
65
+ this.stepsSinceReminder = 0;
66
+ this.opts.events.emitMonitor({ channel: 'monitor', type: 'todo_changed', previous, current });
67
+ if (current.length === 0) {
68
+ this.sendEmptyReminder();
69
+ }
70
+ }
71
+ sendReminder(todos, reason) {
72
+ this.stepsSinceReminder = 0;
73
+ this.opts.events.emitMonitor({ channel: 'monitor', type: 'todo_reminder', todos, reason });
74
+ this.opts.remind(this.formatTodoReminder(todos), { category: 'todo', priority: 'medium' });
75
+ }
76
+ sendEmptyReminder() {
77
+ this.opts.remind('当前 todo 列表为空,如需跟踪任务请使用 todo_write 建立清单。', {
78
+ category: 'todo',
79
+ priority: 'low',
80
+ });
81
+ }
82
+ formatTodoReminder(todos) {
83
+ const bulletList = todos
84
+ .slice(0, 10)
85
+ .map((todo, index) => `${index + 1}. [${todo.status}] ${todo.title}`)
86
+ .join('\n');
87
+ const more = todos.length > 10 ? `\n… 还有 ${todos.length - 10} 项` : '';
88
+ return `Todo 列表仍有未完成项:\n${bulletList}${more}\n请结合 todo_write 及时更新进度,不要向用户直接提及本提醒。`;
89
+ }
90
+ }
91
+ exports.TodoManager = TodoManager;
@@ -0,0 +1,9 @@
1
+ export declare class ToolRunner {
2
+ private readonly concurrency;
3
+ private active;
4
+ private readonly queue;
5
+ constructor(concurrency: number);
6
+ run<T>(task: () => Promise<T>): Promise<T>;
7
+ clear(): void;
8
+ private flush;
9
+ }
@@ -0,0 +1,45 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.ToolRunner = void 0;
4
+ class ToolRunner {
5
+ constructor(concurrency) {
6
+ this.concurrency = concurrency;
7
+ this.active = 0;
8
+ this.queue = [];
9
+ if (!Number.isFinite(concurrency) || concurrency <= 0) {
10
+ throw new Error('ToolRunner requires a positive concurrency limit');
11
+ }
12
+ }
13
+ run(task) {
14
+ return new Promise((resolve, reject) => {
15
+ const execute = () => {
16
+ this.active += 1;
17
+ task()
18
+ .then(resolve, reject)
19
+ .finally(() => {
20
+ this.active -= 1;
21
+ this.flush();
22
+ });
23
+ };
24
+ if (this.active < this.concurrency) {
25
+ execute();
26
+ }
27
+ else {
28
+ this.queue.push(execute);
29
+ }
30
+ });
31
+ }
32
+ clear() {
33
+ this.queue.length = 0;
34
+ }
35
+ flush() {
36
+ if (this.queue.length === 0)
37
+ return;
38
+ if (this.active >= this.concurrency)
39
+ return;
40
+ const next = this.queue.shift();
41
+ if (next)
42
+ next();
43
+ }
44
+ }
45
+ exports.ToolRunner = ToolRunner;