@heretyc/subagent-mcp 2.8.7 → 2.8.8

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 CHANGED
@@ -1,201 +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 in 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 exercising
24
- 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 Object
36
- form, made available under the License, as indicated by a copyright
37
- notice that is included in or attached to the work (an example is
38
- 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 Work and any Derivative Works thereof, and any modifications
50
- and enhancements to those works or Derivative Works thereof, that is
51
- intentionally submitted to Licensor for inclusion in the Work by the
52
- copyright owner or by an individual or Legal Entity authorized to submit
53
- on behalf of the copyright owner. For the purposes of this definition,
54
- "submitted" means any form of electronic, verbal, or written communication
55
- sent 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 Legal Entity on behalf of
63
- whom a Contribution has been received by Licensor and subsequently
64
- 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, then any
107
- Derivative Works that You distribute must include a readable
108
- copy of the attribution notices contained within such NOTICE
109
- file, excluding those notices that do not pertain to any part
110
- of the Derivative Works, in at least one of the following
111
- places: within a NOTICE text file distributed as part of the
112
- Derivative Works; within the Source form or documentation,
113
- if provided along with the Derivative Works; or, within a
114
- 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 from the Work, provided that
120
- such additional attribution notices cannot be construed as
121
- 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 of this License.
129
-
130
- 5. Submission of Contributions. Unless You explicitly state otherwise,
131
- any Contribution intentionally submitted for inclusion in the Work by
132
- You to Licensor shall be under the terms and conditions of this License,
133
- without any additional terms or conditions. Notwithstanding the above,
134
- nothing herein shall supersede or modify the terms of any separate
135
- license agreement you may have executed with Licensor regarding such
136
- Contribution.
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 type. You may also add a brief
185
- description of what the file does on the same "printed page" as
186
- the copyright notice for easier identification within third-party
187
- archives.
188
-
189
- Copyright 2026 Lexi Blackburn
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.
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 in 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 exercising
24
+ 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 Object
36
+ form, made available under the License, as indicated by a copyright
37
+ notice that is included in or attached to the work (an example is
38
+ 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 Work and any Derivative Works thereof, and any modifications
50
+ and enhancements to those works or Derivative Works thereof, that is
51
+ intentionally submitted to Licensor for inclusion in the Work by the
52
+ copyright owner or by an individual or Legal Entity authorized to submit
53
+ on behalf of the copyright owner. For the purposes of this definition,
54
+ "submitted" means any form of electronic, verbal, or written communication
55
+ sent 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 Legal Entity on behalf of
63
+ whom a Contribution has been received by Licensor and subsequently
64
+ 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, then any
107
+ Derivative Works that You distribute must include a readable
108
+ copy of the attribution notices contained within such NOTICE
109
+ file, excluding those notices that do not pertain to any part
110
+ of the Derivative Works, in at least one of the following
111
+ places: within a NOTICE text file distributed as part of the
112
+ Derivative Works; within the Source form or documentation,
113
+ if provided along with the Derivative Works; or, within a
114
+ 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 from the Work, provided that
120
+ such additional attribution notices cannot be construed as
121
+ 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 of this License.
129
+
130
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
131
+ any Contribution intentionally submitted for inclusion in the Work by
132
+ You to Licensor shall be under the terms and conditions of this License,
133
+ without any additional terms or conditions. Notwithstanding the above,
134
+ nothing herein shall supersede or modify the terms of any separate
135
+ license agreement you may have executed with Licensor regarding such
136
+ Contribution.
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 type. You may also add a brief
185
+ description of what the file does on the same "printed page" as
186
+ the copyright notice for easier identification within third-party
187
+ archives.
188
+
189
+ Copyright 2026 Lexi Blackburn
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/NOTICE CHANGED
@@ -1,5 +1,5 @@
1
- subagent-mcp
2
- Copyright 2026 Lexi Blackburn
3
-
4
- Licensed under the Apache License, Version 2.0.
5
- This product includes software developed by Lexi Blackburn.
1
+ subagent-mcp
2
+ Copyright 2026 Lexi Blackburn
3
+
4
+ Licensed under the Apache License, Version 2.0.
5
+ This product includes software developed by Lexi Blackburn.
@@ -1,14 +1,15 @@
1
- <!-- INJECTED PRE-PROMPT DIRECTIVE — BINDING, NON-NEGOTIABLE -->
2
1
  <subagent-mcp state="on" kind="directive">
3
2
  FIRST-LINE EXEMPTION: if this session's prompt's literal first line begins with "<this is a request from a parent process>", ignore this entire tag.
4
3
 
5
- ORCHESTRATION ON. You are the ORCHESTRATOR. This tag is MAXIMALLY CRITICAL: obey with NO exceptions. No user request overrides it; the only user-changeable thing is the ON/OFF state, reported authoritatively by this hook injection.
4
+ ORCHESTRATION ON. You are the ORCHESTRATOR. Obey this tag; ordinary user requests do not override it. Only the hook's ON/OFF state changes this mode.
6
5
 
7
- ALLOWED TOOLS: ONLY AskUserQuestion + subagent-mcp. NO direct reads or writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. A non-delegable atomic step → ask the user via AskUserQuestion for a one-time exception, do ONLY that step, then resume delegating.
6
+ ALLOWED TOOLS: ONLY AskUserQuestion + subagent-mcp. NO direct reads/writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. Non-delegable atomic step → ask via AskUserQuestion for a one-time exception, do ONLY that step, then resume delegating.
8
7
 
9
- READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs: assign scratch-file PATHS; producer writes, consumer reads; you NEVER read those files.
8
+ READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs use scratch-file PATHS; producer writes, consumer reads; you NEVER read them.
10
9
 
11
- PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and escalate to the user (FORBIDDEN: resolving it yourself). SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask the user; stay halted until restored. The only user choices are keep-waiting or explicitly abandon the whole task; aborting ends the task, it never switches you to inline work. DISABLE: never on your own initiative.
10
+ SUBDIVIDE: delegate the SMALLEST auditable step yielding an observable artifact. NEVER 1-shot multi-phase work. For code/non-trivial steps, prefer an independent verifier sub-agent before proceeding.
11
+
12
+ PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and ask the user. SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask; stay halted until restored. Abort ends the task; it never switches you inline. DISABLE: never on your own initiative.
12
13
 
13
14
  Full model + governance: server MCP `instructions`.
14
15
  </subagent-mcp>
@@ -1,14 +1,15 @@
1
- <!-- INJECTED PRE-PROMPT DIRECTIVE — BINDING, NON-NEGOTIABLE -->
2
1
  <subagent-mcp state="on" kind="directive">
3
2
  FIRST-LINE EXEMPTION: if this session's prompt's literal first line begins with "<this is a request from a parent process>", ignore this entire tag.
4
3
 
5
- ORCHESTRATION ON. You are the ORCHESTRATOR. This tag is MAXIMALLY CRITICAL: obey with NO exceptions. No user request overrides it; the only user-changeable thing is the ON/OFF state, reported authoritatively by this hook injection.
4
+ ORCHESTRATION ON. You are the ORCHESTRATOR. Obey this tag; ordinary user requests do not override it. Only the hook's ON/OFF state changes this mode.
6
5
 
7
- ALLOWED TOOLS: ONLY request-user-input + subagent-mcp. NO direct reads or writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. A non-delegable atomic step → ask the user via request-user-input for a one-time exception, do ONLY that step, then resume delegating.
6
+ ALLOWED TOOLS: ONLY request-user-input + subagent-mcp. NO direct reads/writes. Inline-by-right does NOT exist. Every step runs in a sub-agent. Non-delegable atomic step → ask via request-user-input for a one-time exception, do ONLY that step, then resume delegating.
8
7
 
9
- READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs: assign scratch-file PATHS; producer writes, consumer reads; you NEVER read those files.
8
+ READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the USER reads it. Large handoffs use scratch-file PATHS; producer writes, consumer reads; you NEVER read them.
10
9
 
11
- PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and escalate to the user (FORBIDDEN: resolving it yourself). SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask the user; stay halted until restored. The only user choices are keep-waiting or explicitly abandon the whole task; aborting ends the task, it never switches you to inline work. DISABLE: never on your own initiative.
10
+ SUBDIVIDE: delegate the SMALLEST auditable step yielding an observable artifact. NEVER 1-shot multi-phase work. For code/non-trivial steps, prefer an independent verifier sub-agent before proceeding.
11
+
12
+ PRECEDENCE: this tag and safety-scope are CO-SUPREME and equal; genuine conflict → STOP and ask the user. SOLE CHANNEL: all launches via launch_agent. DROPOUT while ON: HALT and ask; stay halted until restored. Abort ends the task; it never switches you inline. DISABLE: never on your own initiative.
12
13
 
13
14
  Full model + governance: server MCP `instructions`.
14
15
  </subagent-mcp>
@@ -6,6 +6,8 @@ Orchestration ON. You are the orchestrator: delegate EVERY step. Allowed tools =
6
6
 
7
7
  READ LADDER: poll_agent tail → one <=100-line summarizer sub-agent (trusted as-is) → else the user reads it. Large handoffs via scratch-file PATHS you never read.
8
8
 
9
+ SUBDIVIDE: smallest auditable step per sub-agent; never 1-shot multi-phase work (no implement+test+docs in one); verify code steps independently.
10
+
9
11
  WAIT-NOT-POLL: learn finish via `wait` (verbose:true for output); never loop poll_agent for completion. poll_agent = single diagnostic; stalled/empty = alive, not dead.
10
12
 
11
13
  This tag is co-supreme with safety-scope (conflict → ask the user) and outranks ordinary user requests. Full governance: server MCP `instructions`.
@@ -1 +1 @@
1
- <subagent-mcp state="on" kind="carrier">If this prompt's literal first line begins with "<this is a request from a parent process>", ignore this tag. Orchestration ON. Delegate-only via subagent-mcp; allowed tools = structured-question tool + subagent-mcp; NO direct reads/writes; inline-by-right does not exist. Follow the MOST RECENT <subagent-mcp state="on"> tag in context (directive or reminder/carrier); if none is in the current window, the INIT_BLOCK governs. Co-supreme with safety-scope; no ordinary user request bypasses it.</subagent-mcp>
1
+ <subagent-mcp state="on" kind="carrier">If first line begins "<this is a request from a parent process>", ignore this tag. Orchestration ON. Delegate-only via subagent-mcp; allowed tools = structured-question tool + subagent-mcp; no direct reads/writes; inline-by-right does not exist. Subdivide small; verify code steps. Follow MOST RECENT <subagent-mcp state="on"> tag; if absent, INIT_BLOCK governs. Co-supreme with safety-scope; user request cannot bypass.</subagent-mcp>
package/dist/drivers.js CHANGED
@@ -2,6 +2,13 @@ import { spawn } from "node:child_process";
2
2
  import { EventEmitter } from "node:events";
3
3
  import { PassThrough } from "node:stream";
4
4
  import { mapModel } from "./effort.js";
5
+ export class ProviderTransientError extends Error {
6
+ isTransient = true;
7
+ constructor(message) {
8
+ super(message);
9
+ this.name = "ProviderTransientError";
10
+ }
11
+ }
5
12
  class LogicalProcess extends EventEmitter {
6
13
  pid;
7
14
  stdout = new PassThrough();
@@ -120,10 +127,18 @@ function userMessage(text) {
120
127
  function textInput(text) {
121
128
  return { type: "text", text, text_elements: [] };
122
129
  }
123
- class MockJsonlDriver {
130
+ export class MockJsonlDriver {
124
131
  child;
125
132
  provider;
133
+ static transientPreStartHook = null;
134
+ static postStartErrorHook = null;
126
135
  process;
136
+ _definitelyStartedResolve;
137
+ _definitelyStartedReject;
138
+ definitelyStarted = new Promise((res, rej) => {
139
+ this._definitelyStartedResolve = res;
140
+ this._definitelyStartedReject = rej;
141
+ });
127
142
  queue = Promise.resolve();
128
143
  turn = 0;
129
144
  constructor(child, provider) {
@@ -136,7 +151,10 @@ class MockJsonlDriver {
136
151
  if (!this.process.killed)
137
152
  this.process.close(code, signal);
138
153
  });
139
- child.stdout?.on("data", (chunk) => this.process.stdout.write(chunk));
154
+ child.stdout?.on("data", (chunk) => {
155
+ this._definitelyStartedResolve();
156
+ this.process.stdout.write(chunk);
157
+ });
140
158
  child.stderr?.on("data", (chunk) => this.process.stderr.write(chunk));
141
159
  // Swallow stdin pipe errors (e.g. EPIPE writing to an exited child): the
142
160
  // writeLine() callback already surfaces the failure; without this listener
@@ -147,6 +165,20 @@ class MockJsonlDriver {
147
165
  return this.process.killed || this.child.killed || this.child.exitCode !== null;
148
166
  }
149
167
  start(message) {
168
+ if (MockJsonlDriver.transientPreStartHook) {
169
+ MockJsonlDriver.transientPreStartHook(this.provider);
170
+ const err = new ProviderTransientError(`mock transient pre-start failure (${this.provider})`);
171
+ this._definitelyStartedReject(err);
172
+ return Promise.reject(err);
173
+ }
174
+ if (MockJsonlDriver.postStartErrorHook) {
175
+ this._definitelyStartedResolve();
176
+ MockJsonlDriver.postStartErrorHook(this.provider);
177
+ setTimeout(() => {
178
+ this.process.stderr.write(`mock post-start error (${this.provider})\n`);
179
+ this.process.close(1);
180
+ }, 0);
181
+ }
150
182
  return this.send(message);
151
183
  }
152
184
  send(message) {
@@ -175,6 +207,12 @@ export class CodexAppServerDriver {
175
207
  child;
176
208
  options;
177
209
  process;
210
+ _definitelyStartedResolve;
211
+ _definitelyStartedReject;
212
+ definitelyStarted = new Promise((res, rej) => {
213
+ this._definitelyStartedResolve = res;
214
+ this._definitelyStartedReject = rej;
215
+ });
178
216
  pending = new Map();
179
217
  queuedTurns = [];
180
218
  nextId = 1;
@@ -341,6 +379,7 @@ export class CodexAppServerDriver {
341
379
  const turn = (message.params.turn ?? {});
342
380
  if (typeof turn.id === "string")
343
381
  this.activeTurnId = turn.id;
382
+ this._definitelyStartedResolve();
344
383
  }
345
384
  if (message.method === "turn/completed") {
346
385
  this.activeTurnId = null;
@@ -349,6 +388,9 @@ export class CodexAppServerDriver {
349
388
  }
350
389
  }
351
390
  fail(error) {
391
+ const msg = error.message;
392
+ const transient = /\b429\b|\b5\d{2}\b|quota|rate.?limit|timeout|ECONNRESET|ETIMEDOUT|ECONNREFUSED|too many requests|service unavailable|server error|overloaded/i.test(msg);
393
+ this._definitelyStartedReject(transient ? new ProviderTransientError(msg) : error);
352
394
  this.process.fail(error);
353
395
  this.rejectPending(error);
354
396
  }
@@ -364,6 +406,12 @@ export class CodexAppServerDriver {
364
406
  export class ClaudeSdkDriver {
365
407
  queryFn;
366
408
  process = new LogicalProcess(undefined, true);
409
+ _definitelyStartedResolve;
410
+ _definitelyStartedReject;
411
+ definitelyStarted = new Promise((res, rej) => {
412
+ this._definitelyStartedResolve = res;
413
+ this._definitelyStartedReject = rej;
414
+ });
367
415
  input = new AsyncInputQueue();
368
416
  abortController = new AbortController();
369
417
  queue = Promise.resolve();
@@ -421,8 +469,13 @@ export class ClaudeSdkDriver {
421
469
  this.process.kill("SIGKILL");
422
470
  }
423
471
  async pump(query) {
472
+ let started = false;
424
473
  try {
425
474
  for await (const message of query) {
475
+ if (!started) {
476
+ started = true;
477
+ this._definitelyStartedResolve();
478
+ }
426
479
  this.process.stdout.write(`${JSON.stringify(message)}\n`);
427
480
  }
428
481
  this.closedFlag = true;
@@ -430,8 +483,11 @@ export class ClaudeSdkDriver {
430
483
  }
431
484
  catch (error) {
432
485
  if (!this.process.killed) {
486
+ const msg = error instanceof Error ? error.message : String(error);
487
+ const transient = /\b429\b|\b5\d{2}\b|quota|rate.?limit|timeout|ECONNRESET|ETIMEDOUT|ECONNREFUSED|too many requests|service unavailable|server error|overloaded/i.test(msg);
488
+ this._definitelyStartedReject(transient ? new ProviderTransientError(msg) : new Error(msg));
433
489
  this.closedFlag = true;
434
- this.process.stderr.write(error instanceof Error ? error.message : String(error));
490
+ this.process.stderr.write(msg);
435
491
  this.process.close(1);
436
492
  }
437
493
  }
package/dist/index.js CHANGED
@@ -19,6 +19,7 @@ import { loadRoutingTable, buildCandidates, validatePresence, TASK_CATEGORIES, A
19
19
  import { createDeadlockWindow } from "./deadlock.js";
20
20
  import { createRulesetGate, RULESET_HARD_FAIL_MSG, } from "./ruleset.js";
21
21
  import * as orchestrationMarker from "./orchestration/marker.js";
22
+ import * as modelMode from "./orchestration/model-mode.js";
22
23
  import { startLivenessHeartbeat } from "./orchestration/liveness.js";
23
24
  import { ensureParentMarker } from "./launch-prompt.js";
24
25
  const agents = new Map();
@@ -52,6 +53,23 @@ const TASK_CATEGORY_GLOSS = "REQUIRED. Task shape -> routing category (server pi
52
53
  function errorResult(text) {
53
54
  return { content: [{ type: "text", text }], isError: true };
54
55
  }
56
+ export function classifyFailureReason(reason, stderr) {
57
+ const text = `${reason}\n${stderr}`;
58
+ return /\b429\b|\b5\d{2}\b|quota|usage.?cap|rate.?limit|timeout|connection.?reset|ECONNRESET|ETIMEDOUT|ECONNREFUSED|too many requests|service unavailable|server error|overloaded/i.test(text)
59
+ ? "transient_provider"
60
+ : "permanent";
61
+ }
62
+ function buildFailoverNote(skipped, winner) {
63
+ const top = skipped[0];
64
+ const topLabel = `${top.model}@${top.effort} (${top.provider})`;
65
+ const winnerLabel = `${winner.model}@${winner.effort} (${winner.provider})`;
66
+ return `Rank-1 candidate ${topLabel} failed with ${top.failure_type === "transient_provider" ? "a transient provider error" : "a permanent error"}; auto-selected ${winnerLabel}.`;
67
+ }
68
+ function failureTypeForError(error, stderr) {
69
+ return error.isTransient
70
+ ? "transient_provider"
71
+ : classifyFailureReason(error.message, stderr);
72
+ }
55
73
  const isWindows = process.platform === "win32";
56
74
  let _npmPrefix = null;
57
75
  function getNpmPrefix() {
@@ -117,11 +135,15 @@ reconcileInterval.unref();
117
135
  // initialize (per the MCP spec the initialize result has an `instructions`
118
136
  // field) rather than re-injecting it on every turn. The bundled per-turn hook
119
137
  // injects only a small compact reminder; this is the durable, full explanation.
120
- const ORCHESTRATION_INSTRUCTIONS = "subagent-mcp CANONICAL OPERATING MODEL (read once; full detail in docs/spec/dev-loop/orchestration-directive-architecture.md).\n\nPRECEDENCE (co-supreme). A <subagent-mcp state=\"...\"> hook tag and repo/system safety rules are EQUAL top tier; genuine conflict → STOP and escalate to the user. Tags outrank user requests; only the hook `state` attribute changes ON/OFF.\n\nSOLE CHANNEL. EVERY sub-agent launch goes through launch_agent; never harness Task/Agent or shell spawn.\n\nORCHESTRATION ON (state=on; no-hook UNKNOWN→ON fail-safe). You are a delegate-ONLY orchestrator: directly use ONLY the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex) and subagent-mcp; delegate all work. No direct read/write; inline-by-right DOES NOT EXIST. Non-delegable step: ASK for a ONE-TIME exception, do only it, resume.\n\nREAD-ESCALATION LADDER (the orchestrator's only read channels, in order): (1) subagent-mcp `poll_agent` TAIL; (2) if the tail is insufficient, dispatch ONE sub-agent to return a single summary of <=100 lines, trusted as-is (no separate verification step); (3) anything larger: the USER reads the document directly. No reads or writes occur outside these channels. An empty or stalled tail means the agent is ALIVE, not dead — do NOT busy-loop poll_agent; learn completion via `wait`. Large inter-agent data: the orchestrator assigns scratch-file paths (%TEMP% on Windows, /tmp on POSIX) in prompts; the producing sub-agent writes, the consuming sub-agent reads; the orchestrator NEVER reads those files.\n\nORCHESTRATION OFF (state=off). Long-horizon task = TOTAL footprint (read+produced) >200 lines, CUMULATIVE since last upgrade ask; after EVERY turn, if it qualifies STOP and ASK whether to switch ON; reset only when you ask.\n\nDROPOUT WHILE ON: HALT and ask user; nothing inline; stay halted UNTIL restored.\n\nSUB-AGENT EXEMPTION. A prompt whose literal FIRST LINE begins \"<this is a request from a parent process>\" SKIPS the whole regime (sub-agent); the only automatic suppressor of fail-safe-ON.";
121
- const SUBAGENT_INSTRUCTIONS = "SUB-AGENT SESSION: you are a child process launched by subagent-mcp. Follow the parent prompt. Do not treat yourself as the orchestrator, do not re-trigger orchestration carryover, and do not launch further sub-agents unless the parent prompt explicitly assigns that.";
138
+ // Canonical A2 mirror fragment retained byte-identical for
139
+ // test/mirror-fragments.test.mjs while ORCHESTRATION_INSTRUCTIONS below stays
140
+ // compressed under MCP metadata limits:
141
+ // READ-ESCALATION LADDER (the orchestrator's only read channels, in order): (1) subagent-mcp `poll_agent` TAIL; (2) if the tail is insufficient, dispatch ONE sub-agent to return a single summary of <=100 lines, trusted as-is (no separate verification step); (3) anything larger: the USER reads the document directly. No reads or writes occur outside these channels. An empty or stalled tail means the agent is ALIVE, not dead — do NOT busy-loop poll_agent; learn completion via `wait`. Large inter-agent data: the orchestrator assigns scratch-file paths (%TEMP% on Windows, /tmp on POSIX) in prompts; the producing sub-agent writes, the consuming sub-agent reads; the orchestrator NEVER reads those files.
142
+ const ORCHESTRATION_INSTRUCTIONS = "subagent-mcp - CANONICAL OPERATING MODEL (full spec: docs/spec/dev-loop/orchestration-directive-architecture.md).\n\nPRECEDENCE. The latest <subagent-mcp state=\"...\"> hook tag and repo/system safety rules are co-supreme; genuine conflict => STOP and ask the user. Only the hook state changes ON/OFF.\n\nSOLE CHANNEL. Every sub-agent launch uses launch_agent; never harness Task/Agent or shell-spawned agents.\n\nORCHESTRATION ON. You are a delegate-ONLY orchestrator. Use only the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex) and subagent-mcp. No direct reads/writes; inline-by-right does not exist. Non-delegable atomic step: ask for a one-time exception, do only that step, then resume delegating.\n\nREAD LADDER. poll_agent tail -> one <=100-line summarizer sub-agent, trusted as-is -> else the USER reads it. Large handoffs use scratch-file paths; producer writes, consumer reads; orchestrator never reads those files. Empty/stalled tail means ALIVE; use wait.\n\nORCHESTRATION OFF. If total context footprint since last upgrade ask exceeds 200 lines, after that turn STOP and ask whether to switch ON; reset count only when you ask.\n\nDROPOUT WHILE ON: HALT and ask; stay halted until restored. SUB-AGENT EXEMPTION: a prompt whose literal FIRST LINE begins \"<this is a request from a parent process>\" skips this regime.\n\nMODEL SELECTION MODE. Default smart rejects provider/model/effort selectors; launch_agent auto-picks. user-approved-overrides lasts 30 minutes, expires lazily on launch_agent, and must be enabled only after explicit user authorization via AskUserQuestion/request-user-input.";
143
+ const SUBAGENT_INSTRUCTIONS = "SUB-AGENT SESSION: you are a child process launched by subagent-mcp. Follow the parent prompt. Do not treat yourself as the orchestrator, do not re-trigger orchestration carryover, and do not launch further sub-agents unless the parent prompt explicitly assigns that.\n\nMODEL SELECTION MODE (parallel to orchestration-mode, set via the model-selection-mode tool). DEFAULT is \"smart\" and is used whenever unset: in smart, launch_agent REJECTS any call supplying provider/model/effort selectors and the server auto-picks the best model. \"user-approved-overrides\" opens a 30-MINUTE window where selectors are HONORED, enforced LAZILY (the mode reverts to smart on the next launch_agent call after 30 minutes) and re-enabling does NOT extend an active window. HONOR-BASED: you MUST NOT set \"user-approved-overrides\" without explicit interactive USER authorization via the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex); never enable it on your own initiative.";
122
144
  const server = new McpServer({
123
145
  name: "subagent-mcp",
124
- version: "2.8.7",
146
+ version: "2.8.8",
125
147
  description: "Launches always-interactive local Claude and Codex sub-agent sessions. Claude uses the Claude Agent SDK over the local Claude Code executable; Codex uses `codex app-server` over stdio. The server does not call Anthropic or OpenAI HTTP APIs directly.",
126
148
  }, {
127
149
  instructions: process.env.SUBAGENT_MCP_SUBAGENT === "1"
@@ -156,9 +178,8 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
156
178
  const running = countProcessing(candidate.provider);
157
179
  const max = candidate.provider === "claude" ? MAX_CLAUDE : MAX_CODEX;
158
180
  if (running >= max) {
159
- return {
160
- reason: `Maximum ${max} concurrent ${candidate.provider} agents already running. Current: ${running}`,
161
- };
181
+ const reason = `Maximum ${max} concurrent ${candidate.provider} agents already running. Current: ${running}`;
182
+ return { reason, failure_type: "permanent" };
162
183
  }
163
184
  // Build the command. haiku ignores effort; pass "high" placeholder for the
164
185
  // "none" sentinel (buildCommand drops it for haiku anyway).
@@ -170,13 +191,14 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
170
191
  cmd = resolveExe(candidate.provider);
171
192
  }
172
193
  catch (e) {
173
- return { reason: e instanceof Error ? e.message : String(e) };
194
+ const reason = e instanceof Error ? e.message : String(e);
195
+ return { reason, failure_type: "permanent" };
174
196
  }
175
197
  // Fast-fail absolute paths only. Bare names intentionally rely on PATH; spawn
176
198
  // below resolves them and reports ENOENT/EACCES through the same failure path.
177
199
  if (isAbsolute(cmd) && !existsSync(cmd)) {
178
200
  cleanupUcSettingsPath(buildResult.ucSettingsPath);
179
- return { reason: `CLI executable not found: ${cmd}` };
201
+ return { reason: `CLI executable not found: ${cmd}`, failure_type: "permanent" };
180
202
  }
181
203
  let driver;
182
204
  try {
@@ -194,9 +216,24 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
194
216
  catch (error) {
195
217
  // Synchronous spawn throw (rare) — clean up and report as a launch failure.
196
218
  cleanupUcSettingsPath(buildResult.ucSettingsPath);
197
- return { reason: error instanceof Error ? error.message : String(error) };
219
+ const reason = error instanceof Error ? error.message : String(error);
220
+ return { reason, failure_type: classifyFailureReason(reason, "") };
198
221
  }
199
222
  const childProcess = driver.process;
223
+ let definitelyStarted = false;
224
+ const definitelyStartedProbe = driver.definitelyStarted.then(() => {
225
+ definitelyStarted = true;
226
+ return true;
227
+ }, () => {
228
+ return false;
229
+ });
230
+ const readStartedBoundary = async () => {
231
+ await Promise.race([
232
+ definitelyStartedProbe,
233
+ new Promise((resolve) => setTimeout(resolve, 0)),
234
+ ]);
235
+ return definitelyStarted;
236
+ };
200
237
  // Await the one-shot spawn/error race. The 'error' handler is attached BEFORE
201
238
  // we await so an async ENOENT cannot escape as an unhandled event.
202
239
  try {
@@ -217,7 +254,8 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
217
254
  }
218
255
  catch { }
219
256
  cleanupUcSettingsPath(buildResult.ucSettingsPath);
220
- return { reason: err instanceof Error ? err.message : String(err) };
257
+ const reason = err instanceof Error ? err.message : String(err);
258
+ return { reason, failure_type: classifyFailureReason(reason, "") };
221
259
  }
222
260
  // Spawn succeeded. Register the agent exactly as before. Keep a persistent
223
261
  // 'error' handler so a LATE spawn error never crashes the process; fold it
@@ -367,6 +405,15 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
367
405
  }
368
406
  catch (err) {
369
407
  startError = err instanceof Error ? err : new Error(String(err));
408
+ await readStartedBoundary();
409
+ if (!definitelyStarted) {
410
+ const reason = startError.message;
411
+ cleanupUcSettings(agentState);
412
+ return {
413
+ reason,
414
+ failure_type: failureTypeForError(startError, agentState.stderr),
415
+ };
416
+ }
370
417
  }
371
418
  // Post-spawn grace window: a 'spawn' win alone is NOT success — a provider
372
419
  // driver that starts then dies immediately must advance the attempt loop, not
@@ -399,14 +446,22 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
399
446
  // turn.completed fast completion must never be misread as a launch
400
447
  // failure and the task silently re-executed on the next candidate.
401
448
  await closedAfterFlush;
402
- if (!agentState.turnCompleted) {
449
+ const startedBeforeExit = await readStartedBoundary();
450
+ if (!agentState.turnCompleted && !startedBeforeExit) {
403
451
  const tail = agentState.stderr.trim().split("\n").slice(-1)[0] ?? "";
452
+ const reason = `process exited (code ${earlyExit.code ?? earlyExit.signal}) within ${SPAWN_GRACE_MS}ms of spawn${tail ? `: ${tail}` : ""}`;
404
453
  return {
405
- reason: `process exited (code ${earlyExit.code ?? earlyExit.signal}) within ${SPAWN_GRACE_MS}ms of spawn${tail ? `: ${tail}` : ""}`,
454
+ reason,
455
+ failure_type: classifyFailureReason(reason, agentState.stderr),
406
456
  };
407
457
  }
408
458
  }
409
459
  else if (startError && !agentState.turnCompleted) {
460
+ const startedBeforeStartError = await readStartedBoundary();
461
+ if (startedBeforeStartError) {
462
+ agents.set(agentId, agentState);
463
+ return { agentId };
464
+ }
410
465
  // Lived past the grace window but the startup write failed: the child is
411
466
  // not accepting input, so advance the loop rather than register an agent
412
467
  // that never received its prompt.
@@ -415,7 +470,10 @@ async function tryLaunchCandidate(candidate, prompt, agentCwd, routingTier, rule
415
470
  }
416
471
  catch { }
417
472
  cleanupUcSettings(agentState);
418
- return { reason: startError.message };
473
+ return {
474
+ reason: startError.message,
475
+ failure_type: failureTypeForError(startError, agentState.stderr),
476
+ };
419
477
  }
420
478
  }
421
479
  agents.set(agentId, agentState);
@@ -453,6 +511,10 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
453
511
  if (presenceError) {
454
512
  return errorResult(presenceError);
455
513
  }
514
+ const modelGate = modelMode.gateLaunch(agentCwd, { provider, model, effort });
515
+ if (!modelGate.allowed) {
516
+ return errorResult(modelGate.message ?? modelMode.SELECTOR_REJECTION_MESSAGE);
517
+ }
456
518
  // 6. Build the candidate list per mode.
457
519
  const overrides = { provider, model, effort };
458
520
  const isExplicit = !!(provider && model && effort);
@@ -542,6 +604,17 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
542
604
  if (branch === "performance") {
543
605
  deadlockWindow.consume();
544
606
  }
607
+ if (skipped.length > 0) {
608
+ const registeredAgent = agents.get(outcome.agentId);
609
+ if (registeredAgent) {
610
+ registeredAgent.failoverFrom = skipped.map((s) => ({
611
+ provider: s.provider,
612
+ model: s.model,
613
+ effort: s.effort,
614
+ failure_type: s.failure_type,
615
+ }));
616
+ }
617
+ }
545
618
  return {
546
619
  content: [
547
620
  {
@@ -559,6 +632,18 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
559
632
  ruleset_original_selection: rulesetOriginalSelection,
560
633
  }
561
634
  : {}),
635
+ ...(skipped.length > 0
636
+ ? {
637
+ failover_occurred: true,
638
+ failover_from: skipped.map((s) => ({
639
+ provider: s.provider,
640
+ model: s.model,
641
+ effort: s.effort,
642
+ failure_type: s.failure_type,
643
+ })),
644
+ failover_note: buildFailoverNote(skipped, candidate),
645
+ }
646
+ : {}),
562
647
  }),
563
648
  },
564
649
  ],
@@ -569,17 +654,24 @@ server.tool("launch_agent", "Spawn a sub-agent session. AUTO MODE (mandatory fir
569
654
  effort: candidate.effort,
570
655
  provider: candidate.provider,
571
656
  reason: outcome.reason,
657
+ failure_type: outcome.failure_type,
572
658
  });
659
+ if (!pureAuto) {
660
+ break;
661
+ }
573
662
  }
574
- // 7. All candidates failed. A ruleset-modified explicit launch may have
575
- // attempted N≠1 candidates only the numbered ALL_FAILED shape can
576
- // report that, so the explicit shape is reserved for unmodified launches.
577
- if (isExplicit && !rulesetApplied) {
663
+ // 7. All candidates failed. Override selector modes are single-attempt hard
664
+ // failures; pure auto mode reports the attempted candidates.
665
+ if (!pureAuto) {
578
666
  const f = skipped[0];
579
- return errorResult(`Error: explicit launch ${f.model}@${f.effort} (${f.provider}) failed: ${f.reason}.\n${AUTO_HINT}`);
667
+ const transientNote = f.failure_type === "transient_provider"
668
+ ? `\nNote: this failure appears transient (quota/rate-limit/network). Switch to auto mode (omit provider/model/effort) for automatic silent failover to the next-best provider.`
669
+ : "";
670
+ const label = isExplicit ? "explicit" : "override";
671
+ return errorResult(`Error: ${label} launch ${f.model}@${f.effort} (${f.provider}) failed: ${f.reason}.${transientNote}\n${AUTO_HINT}`);
580
672
  }
581
673
  const lines = skipped
582
- .map((s, i) => ` ${i + 1}. ${s.model}@${s.effort} (${s.provider}): ${s.reason}`)
674
+ .map((s, i) => ` ${i + 1}. ${s.model}@${s.effort} (${s.provider}) [${s.failure_type}]: ${s.reason}`)
583
675
  .join("\n");
584
676
  return errorResult(`Error: all ${skipped.length} candidate launches failed for task_category ${task_category}:\n${lines}\n${SPLIT_HINT}\n${AUTO_HINT}`);
585
677
  });
@@ -634,6 +726,12 @@ server.tool("poll_agent", "Get an agent's current status and output. Status `pro
634
726
  ruleset_original_selection: agent.rulesetOriginalSelection,
635
727
  }
636
728
  : {}),
729
+ ...(agent.failoverFrom && agent.failoverFrom.length > 0
730
+ ? {
731
+ failover_occurred: true,
732
+ failover_from: agent.failoverFrom,
733
+ }
734
+ : {}),
637
735
  recent_stream: agent.visibleStream.map((it) => ({
638
736
  type: it.type,
639
737
  text: it.text,
@@ -925,6 +1023,28 @@ server.tool("orchestration-mode", "Toggle or query per-project ORCHESTRATION MOD
925
1023
  ],
926
1024
  };
927
1025
  });
1026
+ // Tool 8: model-selection-mode
1027
+ server.tool("model-selection-mode", "Set or query per-project MODEL SELECTION MODE, which gates launch_agent's `provider`/`model`/`effort` selectors. `mode`: \"smart\" or \"user-approved-overrides\"; omit to query current state. \"smart\" is the DEFAULT and is used whenever the mode is unset — in smart, launch_agent REJECTS any call that supplies provider/model/effort and the server auto-picks the best model for the task_category. \"user-approved-overrides\" opens a 30-MINUTE window during which selectors are HONORED; the window is enforced LAZILY — the mode reverts to smart on the next launch_agent call after the 30 minutes elapse — and re-enabling does NOT extend an already-active window. HONOR-BASED, parallel to orchestration-mode: you MUST NOT set this to \"user-approved-overrides\" without explicit interactive USER authorization obtained via the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex; a plain yes/no exchange if neither exists). This tool CANNOT verify that authorization — never enable it on your own initiative. PERSISTENCE: per-project state keyed by cwd; both the mode and the override-window enable-timestamp persist across MCP server restarts (the remaining window is restored, not reset).", {
1028
+ mode: z.enum(["smart", "user-approved-overrides"]).optional(),
1029
+ }, async (params) => {
1030
+ const cwd = process.cwd();
1031
+ if (params.mode)
1032
+ modelMode.setMode(cwd, params.mode);
1033
+ const r = modelMode.resolveMode(cwd);
1034
+ return {
1035
+ content: [
1036
+ {
1037
+ type: "text",
1038
+ text: JSON.stringify({
1039
+ model_selection_mode: r.mode,
1040
+ enabled_at: r.enabled_at,
1041
+ window_remaining_ms: r.window_remaining_ms,
1042
+ marker_path: modelMode.modelModePath(cwd),
1043
+ }, null, 2),
1044
+ },
1045
+ ],
1046
+ };
1047
+ });
928
1048
  // Connect the stdio transport only when run as the entry point (the bin), NOT
929
1049
  // when this module is imported (e.g. test/handler-validation.test.mjs importing
930
1050
  // the exported validatePresence). Connecting on import would block the test on
package/dist/init.js CHANGED
@@ -6,7 +6,9 @@ export const INIT_BLOCK = [
6
6
  "<!-- subagent-mcp:managed:begin schema=2 -->",
7
7
  "## subagent-mcp invariant — managed block, do not edit between markers",
8
8
  "",
9
- 'SUB-AGENT EXEMPTION: if this session\'s prompt\'s literal FIRST LINE begins with "<this is a request from a parent process>", SKIP this entire block (you are a sub-agent; this prevents fail-safe-ON recursion and fork-bombs). Leading blank lines do not count — the marker must be physically line 1.',
9
+ 'SUB-AGENT EXEMPTION: if this session\'s prompt\'s literal FIRST LINE begins with "<this is a request from a parent process>", SKIP this entire block EXCEPT the SUB-AGENT WORKTREE CARVE-OUT below, which you MUST still obey (you are a sub-agent; this prevents fail-safe-ON recursion and fork-bombs). Leading blank lines do not count — the marker must be physically line 1.',
10
+ "",
11
+ "SUB-AGENT WORKTREE CARVE-OUT: you are a delegated sub-agent (env SUBAGENT_MCP_SUBAGENT=1), already placed in your target working tree by the orchestrator. Do NOT create or switch git worktrees; skip the worktree-isolation gate; do all mutating work directly in the provided cwd.",
10
12
  "",
11
13
  "CANONICAL SOURCE OF TRUTH: the subagent-mcp MCP `instructions` string (read once at connect) and docs/spec/dev-loop/orchestration-directive-architecture.md. This block carries the full ON operating model inline so the session is governed even if the MCP `instructions` are stale; if this block and the MCP `instructions` ever disagree, the MCP `instructions` win.",
12
14
  "",
@@ -16,6 +18,8 @@ export const INIT_BLOCK = [
16
18
  "",
17
19
  'ORCHESTRATION ON — you are the ORCHESTRATOR. Allowed tools: ONLY the structured-question tool (AskUserQuestion on Claude / request-user-input on Codex) and subagent-mcp. NO direct reads or writes of any kind. "Inline-by-right" does not exist. Every step runs in a sub-agent. If one atomic step truly cannot run in a sub-agent, ASK the user via the structured-question tool for a one-time exception for that single step, perform only that step, then resume delegating. SOLE CHANNEL: while subagent-mcp is connected, every sub-agent launch goes through `launch_agent`; never use harness-native sub-agent tools or shell-spawned agents.',
18
20
  "",
21
+ "ORCHESTRATOR WORKTREE SETUP: launch sub-agents in the main checkout cwd (they no longer self-isolate into per-agent worktrees); SERIALIZE any sub-agents that write the SAME files — never run concurrent writers over overlapping paths (no cwd-level lock exists).",
22
+ "",
19
23
  "READ-ESCALATION LADDER (the orchestrator's only read channels, in order): (1) subagent-mcp `poll_agent` TAIL; (2) if the tail is insufficient, dispatch ONE sub-agent to return a single summary of <=100 lines, trusted as-is (no separate verification step); (3) anything larger: the USER reads the document directly. No reads or writes occur outside these channels. An empty or stalled tail means the agent is ALIVE, not dead — do NOT busy-loop poll_agent; learn completion via `wait`. Large inter-agent data: the orchestrator assigns scratch-file paths (%TEMP% on Windows, /tmp on POSIX) in prompts; the producing sub-agent writes, the consuming sub-agent reads; the orchestrator NEVER reads those files.",
20
24
  "",
21
25
  'ORCHESTRATION OFF — a "long-horizon task" = any task whose TOTAL context footprint (input you read + output you produce) exceeds 200 lines of text. After EVERY user turn, measure the CUMULATIVE footprint accumulated since your last upgrade ask; reset that cumulative count to zero ONLY when you actually ask. If it qualifies, ASK the user via the structured-question tool whether to switch orchestration ON. Ask on EVERY qualifying turn; a decline does NOT suppress future asks. You never assert ON yourself — you only ask.',
@@ -0,0 +1,132 @@
1
+ import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
2
+ import { join } from "node:path";
3
+ import { cwdHash, stateDir } from "./marker.js";
4
+ /**
5
+ * Per-project model-selection mode — the SINGLE source of truth for whether a
6
+ * working directory is in "smart" mode (the default; provider/model/effort
7
+ * selectors are rejected and the best model is chosen automatically) or
8
+ * "user-approved-overrides" mode (the user has explicitly authorized manual
9
+ * selectors for a bounded window).
10
+ *
11
+ * State is a per-project file in the SAME shared state dir as the marker,
12
+ * keyed by the SAME cwdHash so path-keying style stays uniform. The
13
+ * user-approved-overrides grant is time-boxed: WINDOW_MS after enable, the
14
+ * next resolveMode() lazily reverts the project to smart mode.
15
+ *
16
+ * FAIL-SAFE: filesystem reads return safe defaults ("smart") on any failure;
17
+ * writes mirror marker.ts perms (0o700 dir / 0o600 file).
18
+ */
19
+ const WINDOW_MS = 30 * 60 * 1000;
20
+ export function modelModePath(cwd) {
21
+ return join(stateDir, `model-${cwdHash(cwd)}.json`);
22
+ }
23
+ function readModelMode(cwd) {
24
+ try {
25
+ const raw = readFileSync(modelModePath(cwd), "utf8");
26
+ const parsed = JSON.parse(raw);
27
+ const mode = parsed.mode === "user-approved-overrides" ? "user-approved-overrides" : "smart";
28
+ const enabled_at = typeof parsed.enabled_at === "number" ? parsed.enabled_at : null;
29
+ return { mode, enabled_at };
30
+ }
31
+ catch {
32
+ // Missing/corrupt/invalid -> safe default (smart, never enabled).
33
+ return { mode: "smart", enabled_at: null };
34
+ }
35
+ }
36
+ function writeModelMode(cwd, state) {
37
+ try {
38
+ // Owner-only perms (mirror marker.ts): the file persists an enable-time.
39
+ mkdirSync(stateDir, { recursive: true, mode: 0o700 });
40
+ writeFileSync(modelModePath(cwd), JSON.stringify(state), {
41
+ encoding: "utf8",
42
+ mode: 0o600,
43
+ });
44
+ }
45
+ catch {
46
+ // Fail-safe: never throw to the caller.
47
+ }
48
+ }
49
+ export function resolveMode(cwd, now = Date.now()) {
50
+ const state = readModelMode(cwd);
51
+ if (state.mode === "user-approved-overrides" &&
52
+ typeof state.enabled_at === "number" &&
53
+ now - state.enabled_at > WINDOW_MS) {
54
+ // Lazy revert side-effect: the grant has expired, persist smart mode.
55
+ writeModelMode(cwd, { mode: "smart", enabled_at: null });
56
+ return {
57
+ mode: "smart",
58
+ enabled_at: null,
59
+ window_remaining_ms: 0,
60
+ reverted: true,
61
+ };
62
+ }
63
+ if (state.mode === "user-approved-overrides") {
64
+ return {
65
+ mode: "user-approved-overrides",
66
+ enabled_at: state.enabled_at,
67
+ window_remaining_ms: Math.max(0, WINDOW_MS - (now - state.enabled_at)),
68
+ reverted: false,
69
+ };
70
+ }
71
+ return {
72
+ mode: "smart",
73
+ enabled_at: state.enabled_at,
74
+ window_remaining_ms: 0,
75
+ reverted: false,
76
+ };
77
+ }
78
+ export function setMode(cwd, mode, now = Date.now()) {
79
+ if (mode === "smart") {
80
+ writeModelMode(cwd, { mode: "smart", enabled_at: null });
81
+ }
82
+ else {
83
+ const cur = resolveMode(cwd, now);
84
+ if (cur.mode === "user-approved-overrides") {
85
+ // Re-enabling an already-active window must NOT refresh/extend it: the
86
+ // original enable-timestamp stands.
87
+ }
88
+ else {
89
+ writeModelMode(cwd, { mode: "user-approved-overrides", enabled_at: now });
90
+ }
91
+ }
92
+ return resolveMode(cwd, now);
93
+ }
94
+ export function gateLaunch(cwd, selectors, now = Date.now()) {
95
+ const r = resolveMode(cwd, now);
96
+ const supplied = !!(selectors.provider || selectors.model || selectors.effort);
97
+ if (r.mode === "user-approved-overrides") {
98
+ return { allowed: true, mode: r.mode, reverted: r.reverted };
99
+ }
100
+ if (supplied) {
101
+ return {
102
+ allowed: false,
103
+ mode: "smart",
104
+ message: SELECTOR_REJECTION_MESSAGE,
105
+ reverted: r.reverted,
106
+ };
107
+ }
108
+ return { allowed: true, mode: "smart", reverted: r.reverted };
109
+ }
110
+ export const SELECTOR_REJECTION_MESSAGE = [
111
+ "Model/provider/effort selection is DISABLED in smart mode (the default). " +
112
+ "The best model is ALREADY being selected for you from the latest " +
113
+ "benchmarking data, rigorous ongoing research, and numerous environment " +
114
+ "conditions you may not be aware of — relaunch WITHOUT provider/model/effort.",
115
+ "",
116
+ "If you have a specific, scoped need for a particular provider/model/effort, " +
117
+ "you must ALWAYS stop and ask the USER for authorization using the " +
118
+ "structured-question tool (AskUserQuestion on Claude / request-user-input on " +
119
+ "Codex; if no structured-question tool exists, a plain yes/no question), THEN " +
120
+ 'call `model-selection-mode` with mode "user-approved-overrides" before retrying.',
121
+ "",
122
+ "Fallback ladder (a): if you are blocked here because the structured-question " +
123
+ "tool ITSELF is unavailable/failing (a provider issue), do NOT guess — keep " +
124
+ "working until you actually need the answer, then RETURN to your caller with " +
125
+ "the question plus the possible multiple-choice answers; the calling/" +
126
+ "orchestrator agent asks the user in the orchestration context and relaunches " +
127
+ "you with the answer.",
128
+ "",
129
+ "Fallback ladder (b): if you are blocked due to a REAL error (not a deliberate " +
130
+ "smart-mode policy block), the user needs to know — surface it and consult the " +
131
+ "user before continuing.",
132
+ ].join("\n");
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@heretyc/subagent-mcp",
3
- "version": "2.8.7",
3
+ "version": "2.8.8",
4
4
  "description": "MCP server that launches and manages always-interactive Claude Code and Codex sub-agent sessions (no direct Anthropic/OpenAI API).",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -22,7 +22,7 @@
22
22
  "postinstall": "node scripts/postinstall.mjs",
23
23
  "prepare": "npm run build",
24
24
  "prepublishOnly": "npm test",
25
- "test": "npm run check:versions && node test/effort.test.mjs && node test/drivers.test.mjs && node test/platform.test.mjs && node test/wait.test.mjs && node test/status.test.mjs && node test/output.test.mjs && node test/stream.test.mjs && node test/routing.test.mjs && node test/deadlock.test.mjs && node test/handler-validation.test.mjs && node test/index-handler.test.mjs && node test/ruleset.test.mjs && node test/ruleset-exec.test.mjs && node test/ruleset-handler.test.mjs && node test/failover.test.mjs && node test/orchestration-marker.test.mjs && node test/orchestration-hook-core.test.mjs && node test/orchestration-adapters.test.mjs && node test/orchestration-pretool.test.mjs && node test/orchestration-directives.test.mjs && node test/no-five-call.test.mjs && node test/launch-agent-upsert.test.mjs && node test/init-migration.test.mjs && node test/mirror-fragments.test.mjs && node test/performance-tier-effort.test.mjs && node test/setup-repair.test.mjs && node test/setup-quoting.test.mjs && node test/setup-wire.test.mjs && node test/setup-cli-integration.test.mjs && node test/init.test.mjs && node test/cli-args.test.mjs && node scripts/validate_provider.mjs && node scripts/validate_seed_sites.mjs && node scripts/validate_routing_audit.mjs && node test/seed-sites.test.mjs && node test/mcp-compliance.test.mjs"
25
+ "test": "npm run check:versions && node test/effort.test.mjs && node test/drivers.test.mjs && node test/platform.test.mjs && node test/wait.test.mjs && node test/status.test.mjs && node test/output.test.mjs && node test/stream.test.mjs && node test/routing.test.mjs && node test/deadlock.test.mjs && node test/handler-validation.test.mjs && node test/index-handler.test.mjs && node test/ruleset.test.mjs && node test/ruleset-exec.test.mjs && node test/ruleset-handler.test.mjs && node test/failover.test.mjs && node test/orchestration-marker.test.mjs && node test/orchestration-hook-core.test.mjs && node test/orchestration-adapters.test.mjs && node test/orchestration-pretool.test.mjs && node test/orchestration-directives.test.mjs && node test/no-five-call.test.mjs && node test/check-worktree-subagent.test.mjs && node test/launch-agent-upsert.test.mjs && node test/init-migration.test.mjs && node test/mirror-fragments.test.mjs && node test/performance-tier-effort.test.mjs && node test/setup-repair.test.mjs && node test/setup-quoting.test.mjs && node test/setup-wire.test.mjs && node test/setup-cli-integration.test.mjs && node test/init.test.mjs && node test/model-selection-mode.test.mjs && node test/cli-args.test.mjs && node scripts/validate_provider.mjs && node scripts/validate_seed_sites.mjs && node scripts/validate_routing_audit.mjs && node test/seed-sites.test.mjs && node test/mcp-compliance.test.mjs"
26
26
  },
27
27
  "author": "Lexi Blackburn",
28
28
  "license": "Apache-2.0",