@jetcrab/pi-desk-subagent 0.0.0-stage → 1.0.1-dev.9001

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/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 CHANGED
@@ -1,3 +1,5 @@
1
- # Temporary Holding Version
1
+ # Pi Desk — pi-desk-subagent
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ 包名:`@jetcrab/pi-desk-subagent`。插件接口以源码导出为准,个人配置不随包分发。
4
+
5
+ 许可与第三方来源见本目录的 LICENSE 及适用的归属说明。
package/agents/dev.md ADDED
@@ -0,0 +1,13 @@
1
+ ---
2
+ description: 执行派发的开发任务,修改文件和代码,并返回改动与验证结果。
3
+ tools: read, grep, find, ls, bash, edit, write
4
+ thinking: medium
5
+ ---
6
+
7
+ # 职责
8
+
9
+ 按派发目标和范围修改文件与代码,并完成相关验证。
10
+
11
+ # 返回结果
12
+
13
+ 修改文件、改动摘要、验证结果和未解决事项。
@@ -0,0 +1,83 @@
1
+ ---
2
+ description: 快速初步探索现有代码库的执行路径、架构分层和依赖关系,为开发提供线索。仅限代码分析,不用于开发完成后的代码审查或网络调研。使用能力较弱的模型,核心代码逻辑可由主代理复核。
3
+ tools: read, grep, find, ls
4
+ thinking: medium
5
+ ---
6
+
7
+ # 代码探索 Agent
8
+
9
+ 在新开发开始前,快速初步探索派发范围内的代码库,说明关键入口、执行路径、架构分层和依赖关系,为主代理提供开发线索。
10
+
11
+ ## 分析流程
12
+
13
+ ### 1. 发现入口点
14
+
15
+ - 找到功能或代码区域的主要入口点
16
+ - 从用户操作或外部触发开始,沿调用栈向下追踪
17
+
18
+ ### 2. 追踪执行路径
19
+
20
+ - 跟踪从入口到完成的调用链
21
+ - 记录分支逻辑与异步边界
22
+ - 梳理数据转换过程与错误路径
23
+
24
+ ### 3. 映射架构分层
25
+
26
+ - 识别代码涉及的层级
27
+ - 理解这些层级之间如何通信
28
+ - 记录可复用边界与反模式
29
+
30
+ ### 4. 识别现有模式
31
+
32
+ - 识别项目中已经使用的模式与抽象
33
+ - 记录命名约定与代码组织原则
34
+
35
+ ### 5. 记录依赖关系
36
+
37
+ - 梳理外部库与外部服务
38
+ - 梳理内部模块依赖
39
+ - 识别值得复用的共享工具
40
+
41
+ ## 输出格式
42
+
43
+ 以下格式仅供参考;以清楚说明派发范围内的主要逻辑、关键位置和待主代理复核项为目标。
44
+
45
+ ```markdown
46
+ ## 探索:[功能/区域名称]
47
+
48
+ ### 入口点
49
+
50
+ - [入口点]:[触发方式]
51
+
52
+ ### 执行流程
53
+
54
+ 1. [步骤]
55
+ 2. [步骤]
56
+
57
+ ### 架构洞察
58
+
59
+ - [模式]:[使用位置与原因]
60
+
61
+ ### 关键文件
62
+
63
+ #### <作用>
64
+
65
+ <文件路径>
66
+
67
+ <关键代码段>
68
+
69
+ ### 依赖关系
70
+
71
+ - 外部依赖: [...]
72
+ - 内部依赖: [...]
73
+
74
+ ### 新开发建议
75
+
76
+ - 遵循 [...]
77
+ - 复用 [...]
78
+ - 避免 [...]
79
+
80
+ ### 补充说明
81
+
82
+ <其他补充说明,按照实际需求任意格式输出>
83
+ ```
@@ -0,0 +1,40 @@
1
+ # Research Worker
2
+
3
+ 你是由 Root research 间接派发、但归属于当前主会话的叶子子代理。
4
+
5
+ ## 边界
6
+
7
+ - 只研究当前派发的独立轨道,不扩大到其他 Worker 的范围。
8
+ - 不启动、建议或编排其他子代理。
9
+ - 不修改项目文件。
10
+ - 证据足以支持、反驳或判定证据不足后立即汇总,不继续扩展相邻问题。
11
+
12
+ ## 研究方式
13
+
14
+ 1. 使用 `external_research` 搜索网页、GitHub 和缓存证据。
15
+ 2. GitHub 项目确认相关后使用 `github_clone`,再通过 `read`、`grep`、`find`、`ls` 阅读本地源码。
16
+ 3. 网页结论优先引用官方正文;较长正文通过 `cache_read` 回读。
17
+ 4. 明确区分事实、推断和无法验证的内容。
18
+
19
+ ## 输出
20
+
21
+ ```markdown
22
+ # Research Worker 结果
23
+
24
+ ## 结论
25
+
26
+ - <支持、反驳或证据不足>
27
+
28
+ ## 证据
29
+
30
+ - 网页:<URL>;缓存键、时间、Hash、字符范围和摘录
31
+ - GitHub:<owner/repo> @ <commit>;<路径:行号>:<说明>
32
+
33
+ ## 观察限制
34
+
35
+ - <无法验证的边界>
36
+
37
+ ## 未解决项
38
+
39
+ - <需要 Root research 决定是否继续的问题>
40
+ ```
@@ -0,0 +1,44 @@
1
+ ---
2
+ description: 专注网络调研,检索外部网页、GitHub 项目与缓存证据,用于技术选型和外部源码调研;不承担开发实现、错误排查或代码审查。
3
+ tools: research_delegate, external_research, read, grep, find, ls
4
+ thinking: medium
5
+ ---
6
+
7
+ # 职责
8
+
9
+ 负责外部研究的范围判断、证据获取和结果汇总,不修改项目文件;不承担开发实现、错误排查或代码审查。
10
+
11
+ 当已知或经表层探索发现至少两个互不依赖的研究对象或问题时,优先使用 `research_delegate` 启动叶子 Research Worker 并等待全部结果。
12
+
13
+ 拆分到每个 Worker 只负责一个明确对象或一个单一可交付问题。避免把可以独立研究的多个对象打包给同一个 Worker;一个对象内部仍有多个工作量明显且可独立取证的问题时,可以继续按问题细分。只拆分自然独立的研究轨道,不机械切碎同一个不可分问题。
14
+
15
+ ## 工作流程
16
+
17
+ 1. 先识别任务中的研究对象和独立问题。对于对象或范围未知的模糊需求,先做表层探索;只搜索到足以形成候选清单、排除明显无关项和确定分片,不在这一阶段逐项深入取证。
18
+ 2. 一旦已知或发现至少两个互不依赖的研究对象或问题,立即细分。默认一个 Worker 负责一个对象或一个单一可交付问题;只有对象强绑定、证据高度重叠且无法独立得出结论时才合并。
19
+ 3. 为每个 Worker 提供完整目标、范围、已有表层结论、研究问题、证据要求和禁止扩展项,然后调用 `research_delegate`。
20
+ 4. `research_delegate` 运行期间停止重复研究,等待全部 Worker 进入终态;个别 Worker 失败时保留其他结果。
21
+ 5. 汇总 Worker 的支持、反驳和证据不足项;只对明确冲突或缺口做针对性补查,随后输出最终结论。
22
+ 6. 只有最终确认任务仅有一个不可再分的研究轨道时,才由 Root 直接使用 `external_research` 完成详细研究。同一问题与二次验证优先读取返回的 `cacheKey`,仅任务明确要求最新信息时传 `refresh: true`。
23
+ 7. GitHub 项目确认相关后立即使用 `github_clone`,后续通过本地路径的 `read`、`grep`、`find`、`ls` 阅读源码。不要以搜索摘要代替源码证据。
24
+ 8. 网页结论先使用搜索结果定位来源,必要时通过 `fetch_url` 读取正文;较长正文用 `cache_read` 按范围回读。
25
+ 9. 证据不足时明确说明,不推测未读取的事实。
26
+
27
+ ## 输出要求
28
+
29
+ ```markdown
30
+ # 外部调研结果
31
+
32
+ ## 结论
33
+
34
+ - <结论;二次验证时标记为支持、反驳或证据不足>
35
+
36
+ ## 证据
37
+
38
+ - 网页:<URL>;缓存键 `<cacheKey>`;获取时间 <time>;Hash `<sha256>`;字符 <start>-<end>:<摘录>
39
+ - GitHub:<owner/repo> @ <commit>;`<本地路径>:<行号范围>`:<说明>
40
+
41
+ ## 缓存
42
+
43
+ - <cacheKey>:<命中或新建、后续如何复用>
44
+ ```
@@ -0,0 +1,30 @@
1
+ import type { CapabilityOption } from '@jetcrab/pi-desk-sdk/capabilities';
2
+ import type { ThinkingLevel } from '@earendil-works/pi-agent-core';
3
+ export type SubagentName = string;
4
+ export interface SubagentConfig {
5
+ name: SubagentName;
6
+ description: string;
7
+ tools: string[];
8
+ model?: string;
9
+ thinking?: ThinkingLevel;
10
+ systemPrompt: string;
11
+ }
12
+ export interface DiscoverSubagentConfigsOptions {
13
+ cwd: string;
14
+ projectTrusted: boolean;
15
+ agentDir?: string;
16
+ builtinAgentsDir?: string | null;
17
+ }
18
+ export interface DiscoverSubagentConfigsResult {
19
+ configs: Map<SubagentName, SubagentConfig>;
20
+ diagnostics: string[];
21
+ }
22
+ export declare function isSubagentName(value: unknown): value is SubagentName;
23
+ export declare function discoverSubagentConfigs(options: DiscoverSubagentConfigsOptions): DiscoverSubagentConfigsResult;
24
+ export declare function listGlobalSubagentSettings(agentDir?: string): Array<{
25
+ name: string;
26
+ model: string;
27
+ thinking: ThinkingLevel | null;
28
+ disabled: boolean;
29
+ }>;
30
+ export declare function collectSubagentCapabilityOptions(cwds: readonly string[], signal?: AbortSignal, agentDir?: string): CapabilityOption[];
@@ -0,0 +1,236 @@
1
+ import { existsSync, readdirSync, readFileSync } from 'node:fs';
2
+ import { dirname, join, resolve } from 'node:path';
3
+ import { fileURLToPath } from 'node:url';
4
+ import { CONFIG_DIR_NAME, getAgentDir, parseFrontmatter } from '@earendil-works/pi-coding-agent';
5
+ const BUILTIN_AGENTS_DIR = fileURLToPath(new URL('../agents/', import.meta.url));
6
+ const AGENT_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
7
+ const TOOL_NAME_PATTERN = /^[A-Za-z][A-Za-z0-9_-]{0,63}$/;
8
+ const THINKING_LEVELS = new Set([
9
+ 'off',
10
+ 'minimal',
11
+ 'low',
12
+ 'medium',
13
+ 'high',
14
+ 'xhigh',
15
+ 'max'
16
+ ]);
17
+ export function isSubagentName(value) {
18
+ return typeof value === 'string' && AGENT_NAME_PATTERN.test(value);
19
+ }
20
+ function nonEmptyString(value) {
21
+ return typeof value === 'string' && value.trim() ? value.trim() : undefined;
22
+ }
23
+ function parseTools(value, name) {
24
+ const text = nonEmptyString(value);
25
+ if (!text)
26
+ throw new Error(`Agent "${name}" must define a tools allowlist`);
27
+ const tools = [
28
+ ...new Set(text
29
+ .split(',')
30
+ .map((tool) => tool.trim())
31
+ .filter(Boolean))
32
+ ];
33
+ const invalid = tools.filter((tool) => !TOOL_NAME_PATTERN.test(tool));
34
+ if (invalid.length > 0) {
35
+ throw new Error(`Agent "${name}" has invalid tool names: ${invalid.join(', ')}`);
36
+ }
37
+ return tools;
38
+ }
39
+ function parseThinking(value, name) {
40
+ const thinking = nonEmptyString(value);
41
+ if (!thinking)
42
+ return undefined;
43
+ if (!THINKING_LEVELS.has(thinking)) {
44
+ throw new Error(`Agent "${name}" has unsupported thinking level: ${thinking}`);
45
+ }
46
+ return thinking;
47
+ }
48
+ function findProjectConfigDir(cwd) {
49
+ let current = cwd;
50
+ while (true) {
51
+ const candidate = join(current, CONFIG_DIR_NAME);
52
+ if (existsSync(candidate))
53
+ return candidate;
54
+ const parent = dirname(current);
55
+ if (parent === current)
56
+ return undefined;
57
+ current = parent;
58
+ }
59
+ }
60
+ // model 只表示 provider/modelId,模型 ID 自身可能含 "/",因此在第一个分隔符处切分后整段保留。
61
+ // thinking 是独立字段,避免用字符串后缀表达,防止模型 ID 与 thinking 相互歧义。
62
+ function parseModelSelection(selection, name) {
63
+ const separator = selection.indexOf('/');
64
+ if (separator <= 0 || separator === selection.length - 1) {
65
+ throw new Error(`Agent "${name}" setting must use provider/model format`);
66
+ }
67
+ return { model: selection };
68
+ }
69
+ function readAgentSetting(settingsPath, name) {
70
+ if (!settingsPath || !existsSync(settingsPath))
71
+ return undefined;
72
+ const settings = JSON.parse(readFileSync(settingsPath, 'utf8'));
73
+ if (settings.agents === undefined)
74
+ return undefined;
75
+ if (!settings.agents || typeof settings.agents !== 'object' || Array.isArray(settings.agents)) {
76
+ throw new Error(`Agent settings must be an object: ${settingsPath}`);
77
+ }
78
+ const value = settings.agents[name];
79
+ if (value === undefined)
80
+ return undefined;
81
+ if (typeof value === 'string') {
82
+ const selection = nonEmptyString(value);
83
+ if (!selection)
84
+ throw new Error(`Agent "${name}" model cannot be empty: ${settingsPath}`);
85
+ return { modelSelection: parseModelSelection(selection, name) };
86
+ }
87
+ if (!value || typeof value !== 'object' || Array.isArray(value)) {
88
+ throw new Error(`Agent "${name}" setting must be a model string or object: ${settingsPath}`);
89
+ }
90
+ const setting = value;
91
+ let modelSelection;
92
+ if (setting.model !== undefined) {
93
+ const model = nonEmptyString(setting.model);
94
+ if (!model)
95
+ throw new Error(`Agent "${name}" model cannot be empty: ${settingsPath}`);
96
+ modelSelection = parseModelSelection(model, name);
97
+ if (setting.thinking !== undefined) {
98
+ modelSelection.thinking = parseThinking(setting.thinking, name);
99
+ }
100
+ }
101
+ let disabled;
102
+ if (setting.disabled !== undefined) {
103
+ if (typeof setting.disabled !== 'boolean') {
104
+ throw new Error(`Agent "${name}" disabled must be boolean: ${settingsPath}`);
105
+ }
106
+ disabled = setting.disabled;
107
+ }
108
+ return { modelSelection, disabled };
109
+ }
110
+ function listAgentFiles(directory, diagnostics) {
111
+ const files = new Map();
112
+ if (!directory || !existsSync(directory))
113
+ return files;
114
+ let entries;
115
+ try {
116
+ entries = readdirSync(directory, { withFileTypes: true });
117
+ }
118
+ catch (error) {
119
+ diagnostics.push(`Unable to read Agent directory "${directory}": ${error instanceof Error ? error.message : String(error)}`);
120
+ return files;
121
+ }
122
+ for (const entry of entries) {
123
+ if (!entry.isFile() || !entry.name.endsWith('.md'))
124
+ continue;
125
+ const name = entry.name.slice(0, -3);
126
+ const filePath = join(directory, entry.name);
127
+ if (!isSubagentName(name)) {
128
+ diagnostics.push(`Agent file has an invalid agent name: ${filePath}`);
129
+ continue;
130
+ }
131
+ files.set(name, { name, filePath });
132
+ }
133
+ return files;
134
+ }
135
+ function loadConfig(params) {
136
+ const content = readFileSync(params.filePath, 'utf8');
137
+ const { frontmatter, body } = parseFrontmatter(content);
138
+ const description = nonEmptyString(frontmatter.description);
139
+ if (!description)
140
+ throw new Error(`Agent "${params.name}" must define a description`);
141
+ const systemPrompt = body.trim();
142
+ if (!systemPrompt)
143
+ throw new Error(`Agent "${params.name}" has an empty system prompt`);
144
+ return {
145
+ name: params.name,
146
+ description,
147
+ tools: parseTools(frontmatter.tools, params.name),
148
+ model: params.modelSelection?.model ?? nonEmptyString(frontmatter.model),
149
+ thinking: params.modelSelection?.thinking ?? parseThinking(frontmatter.thinking, params.name),
150
+ systemPrompt
151
+ };
152
+ }
153
+ export function discoverSubagentConfigs(options) {
154
+ const agentDir = options.agentDir ?? getAgentDir();
155
+ const projectConfigDir = options.projectTrusted ? findProjectConfigDir(options.cwd) : undefined;
156
+ const globalSettingsPath = join(agentDir, 'settings.json');
157
+ const projectSettingsPath = projectConfigDir ? join(projectConfigDir, 'settings.json') : undefined;
158
+ const diagnostics = [];
159
+ const selectedFiles = new Map();
160
+ const builtinAgentsDir = options.builtinAgentsDir === undefined ? BUILTIN_AGENTS_DIR : options.builtinAgentsDir;
161
+ for (const file of listAgentFiles(builtinAgentsDir ?? undefined, diagnostics).values()) {
162
+ selectedFiles.set(file.name, file);
163
+ }
164
+ for (const file of listAgentFiles(join(agentDir, 'agents'), diagnostics).values()) {
165
+ selectedFiles.set(file.name, file);
166
+ }
167
+ if (projectConfigDir) {
168
+ for (const file of listAgentFiles(join(projectConfigDir, 'agents'), diagnostics).values()) {
169
+ selectedFiles.set(file.name, file);
170
+ }
171
+ }
172
+ const configs = new Map();
173
+ for (const name of [...selectedFiles.keys()].sort()) {
174
+ const file = selectedFiles.get(name);
175
+ if (!file)
176
+ continue;
177
+ try {
178
+ const globalSetting = readAgentSetting(globalSettingsPath, name);
179
+ const projectSetting = readAgentSetting(projectSettingsPath, name);
180
+ if (projectSetting?.disabled ?? globalSetting?.disabled ?? false)
181
+ continue;
182
+ const modelSelection = projectSetting?.modelSelection ?? globalSetting?.modelSelection;
183
+ configs.set(name, loadConfig({
184
+ name,
185
+ filePath: file.filePath,
186
+ modelSelection
187
+ }));
188
+ }
189
+ catch (error) {
190
+ diagnostics.push(error instanceof Error ? error.message : String(error));
191
+ }
192
+ }
193
+ return { configs, diagnostics };
194
+ }
195
+ export function listGlobalSubagentSettings(agentDir = getAgentDir()) {
196
+ const names = new Set([
197
+ ...listAgentFiles(BUILTIN_AGENTS_DIR, []).keys(),
198
+ ...listAgentFiles(join(agentDir, 'agents'), []).keys()
199
+ ]);
200
+ const settingsPath = join(agentDir, 'settings.json');
201
+ return [...names].sort().map((name) => {
202
+ const setting = readAgentSetting(settingsPath, name);
203
+ return {
204
+ name,
205
+ model: setting?.modelSelection?.model ?? '',
206
+ thinking: setting?.modelSelection?.thinking ?? null,
207
+ disabled: setting?.disabled ?? false
208
+ };
209
+ });
210
+ }
211
+ export function collectSubagentCapabilityOptions(cwds, signal, agentDir = getAgentDir()) {
212
+ const uniqueCwds = new Map();
213
+ for (const cwd of cwds) {
214
+ const path = resolve(cwd);
215
+ uniqueCwds.set(process.platform === 'win32' ? path.toLowerCase() : path, path);
216
+ }
217
+ const sources = [
218
+ { cwd: agentDir, projectTrusted: false, agentDir },
219
+ ...[...uniqueCwds.values()].map((cwd) => ({ cwd, projectTrusted: true, agentDir }))
220
+ ];
221
+ const options = new Map();
222
+ for (const source of sources) {
223
+ signal?.throwIfAborted();
224
+ // A settings catalog only reads definitions; it does not grant project execution trust.
225
+ const { configs } = discoverSubagentConfigs(source);
226
+ for (const config of configs.values()) {
227
+ const description = config.description.slice(0, 1000);
228
+ const previous = options.get(config.name);
229
+ if (!previous)
230
+ options.set(config.name, { value: config.name, description });
231
+ else if (previous.description !== description)
232
+ options.set(config.name, { value: config.name });
233
+ }
234
+ }
235
+ return [...options.values()].sort((left, right) => left.value.localeCompare(right.value));
236
+ }