@geminilight/mindos 0.6.25 → 0.6.28

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 (45) hide show
  1. package/README.md +19 -3
  2. package/README_zh.md +19 -3
  3. package/app/app/api/a2a/discover/route.ts +23 -0
  4. package/app/components/CreateSpaceModal.tsx +1 -0
  5. package/app/components/ImportModal.tsx +3 -0
  6. package/app/components/OnboardingView.tsx +1 -0
  7. package/app/components/RightAskPanel.tsx +4 -2
  8. package/app/components/SidebarLayout.tsx +11 -2
  9. package/app/components/agents/AgentDetailContent.tsx +48 -1
  10. package/app/components/agents/AgentsContentPage.tsx +3 -0
  11. package/app/components/agents/AgentsOverviewSection.tsx +11 -0
  12. package/app/components/agents/DiscoverAgentModal.tsx +149 -0
  13. package/app/components/ask/AskContent.tsx +29 -9
  14. package/app/components/ask/SessionTabBar.tsx +70 -0
  15. package/app/components/echo/EchoInsightCollapsible.tsx +4 -0
  16. package/app/components/help/HelpContent.tsx +65 -9
  17. package/app/components/panels/AgentsPanel.tsx +25 -2
  18. package/app/components/panels/AgentsPanelAgentListRow.tsx +10 -1
  19. package/app/components/renderers/workflow/WorkflowRenderer.tsx +5 -0
  20. package/app/components/settings/AiTab.tsx +1 -0
  21. package/app/components/settings/KnowledgeTab.tsx +2 -0
  22. package/app/components/settings/SyncTab.tsx +2 -0
  23. package/app/components/setup/StepDots.tsx +5 -1
  24. package/app/data/skills/mindos/SKILL.md +186 -0
  25. package/app/data/skills/mindos-zh/SKILL.md +185 -0
  26. package/app/hooks/useA2aRegistry.ts +53 -0
  27. package/app/hooks/useAskSession.ts +44 -25
  28. package/app/lib/a2a/a2a-tools.ts +212 -0
  29. package/app/lib/a2a/client.ts +207 -0
  30. package/app/lib/a2a/index.ts +8 -0
  31. package/app/lib/a2a/orchestrator.ts +255 -0
  32. package/app/lib/a2a/types.ts +54 -0
  33. package/app/lib/agent/tools.ts +6 -4
  34. package/app/lib/i18n-en.ts +52 -0
  35. package/app/lib/i18n-zh.ts +52 -0
  36. package/app/next-env.d.ts +1 -1
  37. package/bin/cli.js +180 -171
  38. package/bin/commands/agent.js +110 -18
  39. package/bin/commands/api.js +5 -3
  40. package/bin/commands/ask.js +3 -3
  41. package/bin/commands/file.js +13 -13
  42. package/bin/commands/search.js +2 -2
  43. package/bin/commands/space.js +64 -10
  44. package/bin/lib/command.js +10 -0
  45. package/package.json +1 -1
@@ -0,0 +1,185 @@
1
+ ---
2
+ name: mindos-zh
3
+ description: >
4
+ 操作 MindOS 知识库:更新笔记, 搜索知识库, 整理文件, 执行SOP/工作流, 复盘, 追加CSV, 跨Agent交接,
5
+ 路由非结构化输入到对应文件, 提炼经验, 同步关联文档.
6
+ update notes, search knowledge base, organize, SOP, retrospective, CSV, handoff, route notes, distill experience.
7
+ 仅 mindRoot 知识库内任务。不用于:改代码仓库/项目文档/KB 外路径。
8
+ 核心概念:空间、指令(INSTRUCTION.md)、技能(SKILL.md);笔记可承载指令与技能。
9
+ ---
10
+
11
+ # MindOS Skill
12
+
13
+ <!-- version: 1.3.0 -->
14
+
15
+ **每次任务前,内化这 5 条规则:**
16
+
17
+ 1. **bootstrap 目录树是首要索引** — 先从目录名和层级推断,再搜索。大多数定位不需要工具调用。
18
+ 2. **默认只读。** 只有用户明确要求保存、记录、整理、修改时才调写入工具。查阅/总结/引用 = 不写。
19
+ 3. **规则优先级**(越上越优先):用户当轮指令 → `user-skill-rules.md` → 就近目录 `INSTRUCTION.md` → 根 `INSTRUCTION.md` → 本 SKILL 默认。
20
+ 4. **多文件编辑必须先出计划。** 展示完整变更清单,确认后再执行。
21
+ 5. 增删/移动/重命名后 → **自动同步受影响 README**。
22
+
23
+ ---
24
+
25
+ ## 绝对不要(踩坑清单)
26
+
27
+ - **绝不写入 KB 根目录**,除非用户明确要求。根目录只放治理文件(`README.md`、`INSTRUCTION.md`、`CONFIG`)。新内容放语义最合适的子目录。
28
+ - **绝不假设目录名。** 不要写死 `Workflows/`、`Projects/`、`Contacts/` — 必须从实际收到的 bootstrap 目录树推断。用户可能用中文名、扁平结构或独特层级。
29
+ - **绝不用 `mindos_write_file` 做小修改。** 用 `update_section`、`update_lines` 或 `insert_after_heading` — 整文件覆写破坏 git diff,变更无法审计。
30
+ - **绝不单关键词搜索。** 必须并行 2-4 条搜索(同义词、缩写、中英文变体)。单条命中率太低。
31
+ - **绝不未经确认就改 `INSTRUCTION.md` 或 `README.md`。** 它们是治理文档,即使看起来只是修个错别字。
32
+ - **绝不在没看过邻居文件的情况下创建新文件。** 至少读 1-2 个同目录文件,学习本地命名/标题/CSV 格式。自创新规是不一致的常见根源。
33
+ - **绝不留孤链。** 重命名/移动后必须 `get_backlinks` 并更新每一个引用方。这是知识库断链的首因。
34
+ - **绝不跳过多文件写入的路由确认。** 即使目标看起来很明显——用户的心智模型可能和你不同。
35
+
36
+ ---
37
+
38
+ ## MindOS 核心概念
39
+
40
+ - **空间(Space)** — 按你的思维方式组织的知识分区。Agent 遵循同样的结构。
41
+ - **指令(Instruction)** — 所有接入 Agent 都遵守的规则文件。写一次,全局生效。
42
+ - **技能(Skill)** — 教 Agent 如何读写、整理知识库。Agent 按安装的 Skill 执行,不是瞎猜。
43
+
44
+ **笔记即指令 / 技能** — `INSTRUCTION.md` 和 `SKILL.md` 就是目录树里的 Markdown 文件。笔记可以是随笔,也可以是 Agent 必须遵守的治理规则,或 Agent 按步骤执行的程序包。
45
+
46
+ ---
47
+
48
+ ## 思维框架
49
+
50
+ 动手前,问自己:
51
+
52
+ 1. **用户意图属于哪类?** → 只读查阅 | 单文件编辑 | 多文件路由 | 结构变更 | SOP 执行。决定走下面哪条路径。
53
+ 2. **这个内容该放哪?** → 扫目录树。如果看名字 5 秒内定不下来,大概率要问用户确认。
54
+ 3. **附近有什么?** → 写之前读 1-2 个同级文件,照它们的风格。
55
+ 4. **改这里会打断什么?** → 重命名/移动:`get_backlinks`。内容修改:想想谁引用了这个事实。
56
+ 5. **用户让我写了吗,还是我自作主张?** → 没让你写就别写。
57
+
58
+ ---
59
+
60
+ ## 任务路由决策树
61
+
62
+ ```
63
+ 用户请求
64
+
65
+ ├─ 只是查找 / 总结 / 引用?
66
+ │ └─ 是 → [只读路径]:搜索 + 读取 + 标注来源。不写入。跳过 Hooks。
67
+
68
+ ├─ 要求保存 / 记录 / 更新 / 整理具体内容?
69
+ │ ├─ 单文件目标? → [单文件编辑]:启动协议 → 读取 → 最小化修改 → 验证
70
+ │ └─ 多文件或目标不明? → [多文件路由]:解析 → 出计划 → 确认 → 编辑
71
+
72
+ ├─ 结构变更(重命名 / 移动 / 删除 / 重组)?
73
+ │ └─ [结构路径]:get_backlinks → 影响报告 → 确认 → 执行 → 更新引用 → 同步 README
74
+
75
+ ├─ 流程性 / 可重复的任务?
76
+ │ └─ [SOP 路径]:搜索匹配 SOP(关键词 + 目录树扫描)→ 读取 → 逐步执行 → 偏差则提议更新 SOP
77
+
78
+ ├─ 复盘 / 提炼 / 交接?
79
+ │ └─ [复盘路径]:确认范围 → 抽取产物 → 路由 → 汇总变更
80
+
81
+ └─ 模糊或范围过大?
82
+ └─ 先问清楚。基于 KB 状态提出 2-3 个具体选项。不要开始编辑。
83
+ ```
84
+
85
+ ---
86
+
87
+ ## 启动协议(仅写入任务)
88
+
89
+ 只读路径跳过。所有写入任务:
90
+
91
+ 1. **Bootstrap** — `mindos_bootstrap`(首选),或手动读根 `INSTRUCTION.md` + `README.md`。
92
+ 2. **发现结构** — `mindos_list_spaces`(顶层分区与 README 摘要)和/或 `mindos_list_files` + 按需 `mindos_search_notes`。不假设一级目录名。
93
+ 3. **加载局部治理** — 读取目标路径附近的 `README.md` / `INSTRUCTION.md`。局部约定覆盖全局假设。
94
+ 4. **匹配已有 SOP** — 任务偏流程时:从树中识别存放流程的目录(`Workflows/`、`SOPs/`、`流程/` 等仅为常见名,不假设一定存在)。用关键词 + `<!-- keywords: -->` 元数据搜索。找到则读取并执行;偏差则任务后提议更新。
95
+ 5. **写前检查** — 确认:路径存在或应创建;位置在子目录下(非根);现有内容已读;修改范围最小;路径变更的反链影响已评估。
96
+ 6. **执行编辑。**
97
+
98
+ 上下文缺失时,按最佳努力继续并明确写出假设。
99
+
100
+ ---
101
+
102
+ ## 工具选型
103
+
104
+ | 意图 | 推荐工具 | 避免 |
105
+ |------|----------|------|
106
+ | 启动时加载上下文 | `mindos_bootstrap` | 不 bootstrap 就随机读文件 |
107
+ | 列出顶层心智空间 | `mindos_list_spaces` | 只需分区概览却拉整棵 `list_files` |
108
+ | 找文件 | `mindos_search_notes`(2-4 条并行关键词变体)| 单关键词搜索 |
109
+ | 读内容 | `mindos_read_file` 或 `mindos_read_lines`(大文件) | 只需 10 行却读整文件 |
110
+ | 小范围文字修改 | `mindos_update_section` / `update_lines` / `insert_after_heading` | 小修改用 `write_file` |
111
+ | 追加到末尾 | `mindos_append_to_file` | 为了加一行重写整文件 |
112
+ | 整文件替换 | `mindos_write_file` | 用它做章节级编辑 |
113
+ | 新建文件 | `mindos_create_file` | 自动创建父目录,但不会生成空间脚手架文件 |
114
+ | 新建心智空间(目录 + README + INSTRUCTION)| `mindos_create_space` | 创建空间的唯一方式。`create_file` 只创建普通目录 |
115
+ | 重命名空间目录 | `mindos_rename_space` | `rename_file`(仅文件,不能重命名文件夹)|
116
+ | 追加 CSV | `mindos_append_csv`(校验表头)| 手动拼字符串不校验 |
117
+ | 重命名前查影响 | `mindos_get_backlinks` | 不查引用就重命名 |
118
+ | 查看近期变动 | `mindos_get_recent` | 猜最近改了什么 |
119
+ | 恢复历史版本 | `mindos_get_file_at_version` | 让用户回忆之前内容 |
120
+
121
+ ### 回退
122
+
123
+ - `mindos_bootstrap` 不可用 → 手动读根 `INSTRUCTION.md` + `README.md`。
124
+ - 行级/章节级工具不可用 → 读 + 受限 `mindos_write_file`(模拟最小修改)。
125
+ - 搜索无结果 → 不放弃:(1) 扫上下文中的树;(2) 直接读候选文件;(3) `mindos_list_files` 细化子目录;(4) 用同义词/中英文变体重试。
126
+
127
+ ---
128
+
129
+ ## 执行模式
130
+
131
+ ### 单文件编辑
132
+ 搜索 → 读目标 + 局部约定 → 最小化修改 → 验证风格匹配 → 总结。
133
+
134
+ ### 基于上下文的问答(只读)
135
+ 目录树推断 → 搜索 → 读取 → 回答并标注来源 → 信息缺失时明确说。
136
+
137
+ ### 多文件路由
138
+ 解析非结构化输入为语义单元 → 为每个单元搜候选文件 → **展示路由表**(信息 → 文件 → 位置)→ 确认 → 编辑 → 汇总全部变更。
139
+
140
+ ### 对话复盘
141
+ 确认范围 → 抽取决策、理由、踩坑、下一步 → 路由到最合适的现有文件 → 补变更说明。
142
+
143
+ ### SOP 执行
144
+ 完整读取 SOP → 分步执行 → 仅更新过时章节 → 偏差则提议更新。
145
+ **创建新 SOP 时** → 必须先读 [references/sop-template.md](./references/sop-template.md)。
146
+
147
+ ### 结构变更
148
+ `get_backlinks` → 影响报告 → 确认 → 执行 → 更新所有引用 → 同步 README。
149
+
150
+ ### 速查模式表
151
+
152
+ | 模式 | 关键步骤 |
153
+ |------|----------|
154
+ | CSV 追加 | 读表头 → 校验字段 → `mindos_append_csv` |
155
+ | TODO 管理 | 定位列表 → 读格式 → 最小化编辑保持约定 |
156
+ | 跨 Agent 接力 | 读任务状态+决策 → 无需重复探索直接接续 → 回写进度 |
157
+ | 知识冲突联动 | 多关键词搜索 → 列受影响文件 → 展示计划 → 确认 → 更新 |
158
+ | 周期性回顾 | `get_recent`/`get_history` → 读变动文件 → 结构化总结 |
159
+ | 交接文档 | 读来源 → 合成(背景、决策、状态、待办)→ 放项目目录 |
160
+
161
+ ---
162
+
163
+ ## 交互规则
164
+
165
+ - **模糊请求?** 先问。基于 KB 现状提出 2-3 个选项。不要在没理解范围前开始编辑。
166
+ - **标注来源。** KB 中的事实附带文件路径,便于验证。
167
+ - **简洁优先。** 展示最可能的匹配,不列全部。
168
+
169
+ ---
170
+
171
+ ## 任务后 Hooks
172
+
173
+ **写入任务**完成后,读 [references/post-task-hooks.md](./references/post-task-hooks.md) 查看是否有一句话跟进提议(经验沉淀、一致性同步、SOP 偏差等)。
174
+ **只读任务:跳过。** 用户要求安静模式时,本会话跳过所有 Hooks。
175
+ **不要读** post-task-hooks 用于简单单文件修改或只读查阅。
176
+
177
+ ## 偏好捕获
178
+
179
+ 用户表达要长期记住的偏好(「以后不要…」「这个该放在…」)时,读 [references/preference-capture.md](./references/preference-capture.md) 并按确认后写入流程存入 `user-skill-rules.md`。
180
+ **不要读** preference-capture 除非用户真的表达了要持久化的偏好。
181
+
182
+ ## SOP 编写
183
+
184
+ 创建或改写工作流 SOP 时,**必须 — 读 [references/sop-template.md](./references/sop-template.md)**(前置条件、分支步骤、退出条件、踩坑记录)。
185
+ **不要读** sop-template 用于 SOP 执行(仅用于 SOP 创建/编辑)。
@@ -0,0 +1,53 @@
1
+ 'use client';
2
+
3
+ import { useState, useCallback } from 'react';
4
+ import type { RemoteAgent } from '@/lib/a2a/types';
5
+
6
+ interface A2aRegistry {
7
+ agents: RemoteAgent[];
8
+ discovering: boolean;
9
+ error: string | null;
10
+ discover: (url: string) => Promise<RemoteAgent | null>;
11
+ refresh: () => void;
12
+ }
13
+
14
+ export function useA2aRegistry(): A2aRegistry {
15
+ const [agents, setAgents] = useState<RemoteAgent[]>([]);
16
+ const [discovering, setDiscovering] = useState(false);
17
+ const [error, setError] = useState<string | null>(null);
18
+
19
+ const discover = useCallback(async (url: string): Promise<RemoteAgent | null> => {
20
+ setDiscovering(true);
21
+ setError(null);
22
+ try {
23
+ const res = await fetch('/api/a2a/discover', {
24
+ method: 'POST',
25
+ headers: { 'Content-Type': 'application/json' },
26
+ body: JSON.stringify({ url }),
27
+ });
28
+ const data = await res.json();
29
+ if (data.agent) {
30
+ setAgents(prev => {
31
+ const exists = prev.some(a => a.id === data.agent.id);
32
+ if (exists) return prev.map(a => a.id === data.agent.id ? data.agent : a);
33
+ return [...prev, data.agent];
34
+ });
35
+ return data.agent as RemoteAgent;
36
+ }
37
+ setError(data.error || 'Discovery failed');
38
+ return null;
39
+ } catch (err) {
40
+ setError((err as Error).message);
41
+ return null;
42
+ } finally {
43
+ setDiscovering(false);
44
+ }
45
+ }, []);
46
+
47
+ const refresh = useCallback(() => {
48
+ setAgents([]);
49
+ setError(null);
50
+ }, []);
51
+
52
+ return { agents, discovering, error, discover, refresh };
53
+ }
@@ -78,13 +78,19 @@ export function useAskSession(currentFile?: string) {
78
78
  const [activeSessionId, setActiveSessionId] = useState<string | null>(null);
79
79
  const persistTimerRef = useRef<ReturnType<typeof setTimeout> | null>(null);
80
80
 
81
- /** Load sessions from server, pick the matching one or create fresh. */
81
+ /** Load sessions from server, pick the matching one or create fresh. Prunes stale empty sessions. */
82
82
  const initSessions = useCallback(async () => {
83
- const sorted = (await fetchSessions())
83
+ const all = (await fetchSessions())
84
84
  .sort((a, b) => b.updatedAt - a.updatedAt)
85
85
  .slice(0, MAX_SESSIONS);
86
- setSessions(sorted);
87
86
 
87
+ // Prune any empty sessions that leaked to server (from older versions)
88
+ const emptyIds = all.filter((s) => s.messages.length === 0).map((s) => s.id);
89
+ const sorted = emptyIds.length > 0 ? all.filter((s) => !emptyIds.includes(s.id)) : all;
90
+ if (emptyIds.length > 0) void removeSessions(emptyIds);
91
+
92
+ // Always prepend a fresh empty session in memory (never persisted until first message)
93
+ const fresh = createSession(currentFile);
88
94
  const matched = currentFile
89
95
  ? sorted.find((sess) => sess.currentFile === currentFile)
90
96
  : sorted[0];
@@ -92,20 +98,19 @@ export function useAskSession(currentFile?: string) {
92
98
  if (matched) {
93
99
  setActiveSessionId(matched.id);
94
100
  setMessages(matched.messages);
101
+ setSessions([...sorted]);
95
102
  } else {
96
- const fresh = createSession(currentFile);
97
103
  setActiveSessionId(fresh.id);
98
104
  setMessages([]);
99
- const next = [fresh, ...sorted].slice(0, MAX_SESSIONS);
100
- setSessions(next);
101
- await upsertSession(fresh);
105
+ // Empty session lives only in memory — no upsertSession call
106
+ setSessions([fresh, ...sorted].slice(0, MAX_SESSIONS));
102
107
  }
103
108
  }, [currentFile]);
104
109
 
105
- /** Persist current session (debounced). */
110
+ /** Persist current session (debounced). Only persists if session has messages. */
106
111
  const persistSession = useCallback(
107
112
  (msgs: Message[], sessionId: string | null) => {
108
- if (!sessionId) return;
113
+ if (!sessionId || msgs.length === 0) return;
109
114
  let sessionToPersist: ChatSession | null = null;
110
115
  setSessions((prev) => {
111
116
  const now = Date.now();
@@ -135,35 +140,48 @@ export function useAskSession(currentFile?: string) {
135
140
  }
136
141
  }, []);
137
142
 
138
- /** Create a brand-new session. */
143
+ /** Create a brand-new session (memory only). If current session is already empty, reuse it. */
139
144
  const resetSession = useCallback(() => {
140
- const fresh = createSession(currentFile);
141
- setActiveSessionId(fresh.id);
142
- setMessages([]);
143
145
  setSessions((prev) => {
144
- const next = [fresh, ...prev]
146
+ const active = prev.find((s) => s.id === activeSessionId);
147
+ // Already on an empty session — just clear input, don't create another
148
+ if (active && active.messages.length === 0) return prev;
149
+
150
+ const fresh = createSession(currentFile);
151
+ setActiveSessionId(fresh.id);
152
+ setMessages([]);
153
+ // Memory only — no upsertSession call. Will be persisted on first message.
154
+ return [fresh, ...prev]
145
155
  .sort((a, b) => b.updatedAt - a.updatedAt)
146
156
  .slice(0, MAX_SESSIONS);
147
- void upsertSession(fresh);
148
- return next;
149
157
  });
150
- }, [currentFile]);
158
+ }, [currentFile, activeSessionId]);
151
159
 
152
- /** Switch to an existing session. */
160
+ /** Switch to an existing session. Auto-drops abandoned empty sessions from memory. */
153
161
  const loadSession = useCallback(
154
162
  (id: string) => {
155
163
  const target = sessions.find((s) => s.id === id);
156
164
  if (!target) return;
165
+
166
+ // Drop the session we're leaving if it's empty (it was never persisted, just remove from memory)
167
+ const leaving = activeSessionId ? sessions.find((s) => s.id === activeSessionId) : null;
168
+ if (leaving && leaving.messages.length === 0 && leaving.id !== id) {
169
+ setSessions((prev) => prev.filter((s) => s.id !== leaving.id));
170
+ }
171
+
157
172
  setActiveSessionId(target.id);
158
173
  setMessages(target.messages);
159
174
  },
160
- [sessions],
175
+ [sessions, activeSessionId],
161
176
  );
162
177
 
163
- /** Delete a session. If it's the active one, create fresh. */
178
+ /** Delete a session. If it's the active one, create fresh (memory only). */
164
179
  const deleteSession = useCallback(
165
180
  (id: string) => {
166
- void removeSession(id);
181
+ const target = sessions.find((s) => s.id === id);
182
+ // Only call removeSession if the session has messages (i.e. was persisted)
183
+ if (target && target.messages.length > 0) void removeSession(id);
184
+
167
185
  const remaining = sessions.filter((s) => s.id !== id);
168
186
  setSessions(remaining);
169
187
 
@@ -172,21 +190,22 @@ export function useAskSession(currentFile?: string) {
172
190
  setActiveSessionId(fresh.id);
173
191
  setMessages([]);
174
192
  setSessions([fresh, ...remaining].slice(0, MAX_SESSIONS));
175
- void upsertSession(fresh);
193
+ // No upsertSession — memory only
176
194
  }
177
195
  },
178
196
  [activeSessionId, currentFile, sessions],
179
197
  );
180
198
 
181
199
  const clearAllSessions = useCallback(() => {
182
- const allIds = sessions.map(s => s.id);
183
- void removeSessions(allIds);
200
+ // Only delete sessions that have messages (were persisted)
201
+ const persistedIds = sessions.filter(s => s.messages.length > 0).map(s => s.id);
202
+ if (persistedIds.length > 0) void removeSessions(persistedIds);
184
203
 
185
204
  const fresh = createSession(currentFile);
186
205
  setActiveSessionId(fresh.id);
187
206
  setMessages([]);
188
207
  setSessions([fresh]);
189
- void upsertSession(fresh);
208
+ // No upsertSession — memory only
190
209
  }, [currentFile, sessions]);
191
210
 
192
211
  return {
@@ -0,0 +1,212 @@
1
+ /**
2
+ * A2A Agent Tools — Expose A2A client capabilities as tools
3
+ * for the MindOS built-in agent to discover and delegate to external agents.
4
+ */
5
+
6
+ import { Type, type Static } from '@sinclair/typebox';
7
+ import type { AgentTool } from '@mariozechner/pi-agent-core';
8
+ import {
9
+ discoverAgent,
10
+ discoverAgents,
11
+ delegateTask,
12
+ checkRemoteTaskStatus,
13
+ getDiscoveredAgents,
14
+ } from './client';
15
+ import { createPlan, executePlan } from './orchestrator';
16
+
17
+ function textResult(text: string) {
18
+ return { content: [{ type: 'text' as const, text }], details: {} };
19
+ }
20
+
21
+ /* ── Parameter Schemas ─────────────────────────────────────────────────── */
22
+
23
+ const DiscoverAgentParams = Type.Object({
24
+ url: Type.String({ description: 'Base URL of the agent to discover (e.g. http://localhost:3456)' }),
25
+ });
26
+
27
+ const DiscoverMultipleParams = Type.Object({
28
+ urls: Type.Array(Type.String(), { description: 'List of base URLs to discover agents from' }),
29
+ });
30
+
31
+ const DelegateParams = Type.Object({
32
+ agent_id: Type.String({ description: 'ID of the target agent (from list_remote_agents)' }),
33
+ message: Type.String({ description: 'Natural language message to send to the agent' }),
34
+ });
35
+
36
+ const CheckStatusParams = Type.Object({
37
+ agent_id: Type.String({ description: 'ID of the agent that owns the task' }),
38
+ task_id: Type.String({ description: 'Task ID returned by delegate_to_agent' }),
39
+ });
40
+
41
+ const OrchestrateParams = Type.Object({
42
+ request: Type.String({ description: 'The complex request to decompose and execute across multiple agents' }),
43
+ subtasks: Type.Optional(Type.Array(Type.String(), { description: 'Pre-decomposed subtask descriptions. If omitted, auto-decomposition is used.' })),
44
+ strategy: Type.Optional(Type.Union([
45
+ Type.Literal('parallel'),
46
+ Type.Literal('sequential'),
47
+ ], { description: 'Execution strategy: parallel (default) or sequential', default: 'parallel' })),
48
+ });
49
+
50
+ /* ── Tool Implementations ──────────────────────────────────────────────── */
51
+
52
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
53
+ export const a2aTools: AgentTool<any>[] = [
54
+ {
55
+ name: 'list_remote_agents',
56
+ label: 'List Remote Agents',
57
+ description: 'List all discovered remote A2A agents and their capabilities. Shows agent ID, name, skills, and reachability status. Call discover_agent first to add agents.',
58
+ parameters: Type.Object({}),
59
+ execute: async (_id: string) => {
60
+ const agents = getDiscoveredAgents();
61
+ if (agents.length === 0) {
62
+ return textResult('No remote agents discovered yet. Use discover_agent with a URL to find agents.');
63
+ }
64
+ const lines = agents.map(a => {
65
+ const skills = a.card.skills.map(s => s.name).join(', ');
66
+ const status = a.reachable ? 'reachable' : 'unreachable';
67
+ return `- **${a.card.name}** (id: ${a.id}, ${status})\n Skills: ${skills || 'none declared'}`;
68
+ });
69
+ return textResult(`Discovered agents:\n\n${lines.join('\n\n')}`);
70
+ },
71
+ },
72
+
73
+ {
74
+ name: 'discover_agent',
75
+ label: 'Discover Remote Agent',
76
+ description: 'Discover a remote A2A agent by fetching its agent card from the given URL. The agent card describes the agent\'s capabilities and skills.',
77
+ parameters: DiscoverAgentParams,
78
+ execute: async (_id: string, params: Static<typeof DiscoverAgentParams>) => {
79
+ try {
80
+ const agent = await discoverAgent(params.url);
81
+ if (!agent) {
82
+ return textResult(`No A2A agent found at ${params.url}. The server may not support the A2A protocol.`);
83
+ }
84
+ const skills = agent.card.skills.map(s => ` - ${s.name}: ${s.description}`).join('\n');
85
+ return textResult(
86
+ `Discovered agent: **${agent.card.name}** (v${agent.card.version})\n` +
87
+ `ID: ${agent.id}\n` +
88
+ `Description: ${agent.card.description}\n` +
89
+ `Endpoint: ${agent.endpoint}\n` +
90
+ `Skills:\n${skills || ' (none declared)'}`
91
+ );
92
+ } catch (err) {
93
+ return textResult(`Failed to discover agent at ${params.url}: ${(err as Error).message}`);
94
+ }
95
+ },
96
+ },
97
+
98
+ {
99
+ name: 'discover_agents',
100
+ label: 'Discover Multiple Agents',
101
+ description: 'Discover multiple remote A2A agents by fetching their agent cards concurrently. Returns all successfully discovered agents.',
102
+ parameters: DiscoverMultipleParams,
103
+ execute: async (_id: string, params: Static<typeof DiscoverMultipleParams>) => {
104
+ try {
105
+ const agents = await discoverAgents(params.urls);
106
+ if (agents.length === 0) {
107
+ return textResult(`No A2A agents found at any of the ${params.urls.length} URLs.`);
108
+ }
109
+ const lines = agents.map(a =>
110
+ `- **${a.card.name}** (id: ${a.id}) — ${a.card.skills.length} skills`
111
+ );
112
+ return textResult(`Discovered ${agents.length}/${params.urls.length} agents:\n\n${lines.join('\n')}`);
113
+ } catch (err) {
114
+ return textResult(`Discovery failed: ${(err as Error).message}`);
115
+ }
116
+ },
117
+ },
118
+
119
+ {
120
+ name: 'delegate_to_agent',
121
+ label: 'Delegate Task to Agent',
122
+ description: 'Send a task to a remote A2A agent. The agent will process the message and return a result. Use list_remote_agents to see available agents and their skills first.',
123
+ parameters: DelegateParams,
124
+ execute: async (_id: string, params: Static<typeof DelegateParams>) => {
125
+ try {
126
+ const task = await delegateTask(params.agent_id, params.message);
127
+
128
+ if (task.status.state === 'TASK_STATE_COMPLETED') {
129
+ const result = task.artifacts?.[0]?.parts?.[0]?.text
130
+ ?? task.history?.find(m => m.role === 'ROLE_AGENT')?.parts?.[0]?.text
131
+ ?? 'Task completed (no text result)';
132
+ return textResult(`Agent completed task (id: ${task.id}):\n\n${result}`);
133
+ }
134
+
135
+ if (task.status.state === 'TASK_STATE_FAILED') {
136
+ const errMsg = task.status.message?.parts?.[0]?.text ?? 'Unknown error';
137
+ return textResult(`Agent failed task (id: ${task.id}): ${errMsg}`);
138
+ }
139
+
140
+ // Task is still in progress (non-blocking)
141
+ return textResult(
142
+ `Task submitted (id: ${task.id}, state: ${task.status.state}).\n` +
143
+ `Use check_task_status to poll for completion.`
144
+ );
145
+ } catch (err) {
146
+ return textResult(`Delegation failed: ${(err as Error).message}`);
147
+ }
148
+ },
149
+ },
150
+
151
+ {
152
+ name: 'check_task_status',
153
+ label: 'Check Remote Task Status',
154
+ description: 'Check the status of a task previously delegated to a remote agent. Returns the current state, any results, or error information.',
155
+ parameters: CheckStatusParams,
156
+ execute: async (_id: string, params: Static<typeof CheckStatusParams>) => {
157
+ try {
158
+ const task = await checkRemoteTaskStatus(params.agent_id, params.task_id);
159
+
160
+ const state = task.status.state;
161
+ if (state === 'TASK_STATE_COMPLETED') {
162
+ const result = task.artifacts?.[0]?.parts?.[0]?.text ?? 'Completed (no text)';
163
+ return textResult(`Task ${params.task_id} completed:\n\n${result}`);
164
+ }
165
+ if (state === 'TASK_STATE_FAILED') {
166
+ const errMsg = task.status.message?.parts?.[0]?.text ?? 'Unknown error';
167
+ return textResult(`Task ${params.task_id} failed: ${errMsg}`);
168
+ }
169
+
170
+ return textResult(`Task ${params.task_id} state: ${state}`);
171
+ } catch (err) {
172
+ return textResult(`Status check failed: ${(err as Error).message}`);
173
+ }
174
+ },
175
+ },
176
+
177
+ {
178
+ name: 'orchestrate',
179
+ label: 'Orchestrate Multi-Agent Task',
180
+ description: 'Decompose a complex request into subtasks and execute them across multiple remote agents. Auto-matches subtasks to the best available agent based on skills. Use discover_agent first to register agents.',
181
+ parameters: OrchestrateParams,
182
+ execute: async (_id: string, params: Static<typeof OrchestrateParams>) => {
183
+ try {
184
+ const strategy = params.strategy ?? 'parallel';
185
+ const plan = createPlan(params.request, strategy, params.subtasks);
186
+
187
+ const assigned = plan.subtasks.filter(st => st.assignedAgentId);
188
+ if (assigned.length === 0) {
189
+ return textResult(
190
+ `Created plan with ${plan.subtasks.length} subtasks but no agents matched any skill.\n` +
191
+ `Subtasks: ${plan.subtasks.map(st => st.description).join(', ')}\n\n` +
192
+ 'Discover agents first using discover_agent, then retry.'
193
+ );
194
+ }
195
+
196
+ const result = await executePlan(plan);
197
+
198
+ const summary = plan.subtasks.map(st => {
199
+ const icon = st.status === 'completed' ? '[OK]' : st.status === 'failed' ? '[FAIL]' : '[?]';
200
+ return `${icon} ${st.description}`;
201
+ }).join('\n');
202
+
203
+ return textResult(
204
+ `Orchestration ${result.status} (${strategy}, ${plan.subtasks.length} subtasks):\n\n` +
205
+ `${summary}\n\n---\n\n${result.aggregatedResult ?? '(no result)'}`
206
+ );
207
+ } catch (err) {
208
+ return textResult(`Orchestration failed: ${(err as Error).message}`);
209
+ }
210
+ },
211
+ },
212
+ ];